app crashes when going back from gallery without s

2020-05-09 18:38发布

when ever i am not selecting any image after opening the gallery and goin back my app crashes. plz help me out guys. this is a program to upload image to server selecting from a gallery

public class FragmentAskFitindya extends Fragment {

private AskJSON obj;
private EditText subject,question;
private Spinner category; 
private TextView messageText,tv;
private CheckBox privacyBox;
private Button uploadButton, btnselectpic,uploadButton2;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
public String user_id,sub,quest,cat_id,privacy;      
private String upLoadServerUri = null;
private String imagepath=null;
public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";
public static String getUrlData= new Sql_connect().url();

public FragmentAskFitindya()
{

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View view=inflater.inflate(R.layout.fragment_layout_askfitindya,container, false);
    category=(Spinner)view.findViewById(R.id.spinner1);
    privacyBox=(CheckBox) view.findViewById(R.id.item_check);
    subject=(EditText) view.findViewById(R.id.subject_text);
    question=(EditText) view.findViewById(R.id.your_question_text);
        uploadButton = (Button)view.findViewById(R.id.uploadButton);
        uploadButton2=(Button) view.findViewById(R.id.uploadButton2);
        privacyBox=(CheckBox) view.findViewById(R.id.item_check);
        btnselectpic = (Button)view.findViewById(R.id.button_selectpic);
        imageview = (ImageView)view.findViewById(R.id.imageView_pic);
        uploadButton.setVisibility(View.GONE);
        btnselectpic.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
            }
        });
        uploadButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dialog = ProgressDialog.show(getActivity(), "", "Uploading file...", true);
            //   messageText.setText("uploading started.....");
                 new Thread(new Runnable() {
                     public void run() {
                         if(privacyBox.isChecked()){
                             privacy="1";   
                         }
                         if(privacyBox.isChecked()){

                         }else{
                             privacy="0";   
                         }
                         cat_id=category.getSelectedItem().toString();

                         if(cat_id.equals("Weight Loss")){
                             cat_id="1"; 
                         }
                         if(cat_id.equals("Muscle Gain")){
                             cat_id="2"; 
                         }

                         sub=subject.getText().toString();
                         quest=question.getText().toString(); 
                         upLoadServerUri = getUrlData+"windex.php?itfpage=addquestion" +
                                "&user_id=3" +
                                "&subject=" +sub+
                                "&quest="+quest+
                                "&cat_id="+cat_id+
                                "&privacy="+privacy;

                          uploadFile(imagepath);

                     }
                   }).start();     
            }
        });

            }
        });


    return view;
}




    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //&& resultCode == RESULT_OK
        if (requestCode == 1 ) {
            //Bitmap photo = (Bitmap) data.getData().getPath(); 

            Uri selectedImageUri = data.getData();
            imagepath = getPath(selectedImageUri);
            Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
            imageview.setImageBitmap(bitmap);
         //   messageText.setText("Uploading file path:" +imagepath);

        }
    }
         public String getPath(Uri uri) {
             String[] projection = { MediaStore.Images.Media.DATA };
                Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            }

    public int uploadFile(String sourceFileUri) {


          String fileName = sourceFileUri;

          HttpURLConnection conn = null;
          DataOutputStream dos = null;  
          String lineEnd = "\r\n";
          String twoHyphens = "--";
          String boundary = "*****";
          int bytesRead, bytesAvailable, bufferSize;
          byte[] buffer;
          int maxBufferSize = 1 * 1024 * 1024; 
          File sourceFile = new File(sourceFileUri); 

          if (!sourceFile.isFile()) {

              dialog.dismiss(); 

               Log.e("uploadFile", "Source File not exist :"+imagepath);

               getActivity().runOnUiThread(new Runnable() {
                   public void run() {
                    //   messageText.setText("Source File not exist :"+ imagepath);
                       Log.v("img path", ""+imagepath);
                   }
               }); 

               return 0;

          }
          else
          {
               try { 

                     // open a URL connection to the Servlet
                   FileInputStream fileInputStream = new FileInputStream(sourceFile);
                   URL url = new URL(upLoadServerUri);

                   // Open a HTTP  connection to  the URL
                   conn = (HttpURLConnection) url.openConnection(); 
                   conn.setDoInput(true); // Allow Inputs
                   conn.setDoOutput(true); // Allow Outputs
                   conn.setUseCaches(false); // Don't use a Cached Copy
                   conn.setRequestMethod("POST");
                   conn.setRequestProperty("Connection", "Keep-Alive");
                   conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                   conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                   conn.setRequestProperty("askimage", fileName); 

                   dos = new DataOutputStream(conn.getOutputStream());

                   dos.writeBytes(twoHyphens + boundary + lineEnd); 
                   dos.writeBytes("Content-Disposition: form-data; name=\"askimage\";filename=\""
                                             + fileName + "\"" + lineEnd);

                   dos.writeBytes(lineEnd);

                   // create a buffer of  maximum size
                   bytesAvailable = fileInputStream.available(); 

                   bufferSize = Math.min(bytesAvailable, maxBufferSize);
                   buffer = new byte[bufferSize];

                   // read file and write it into form...
                   bytesRead = fileInputStream.read(buffer, 0, bufferSize);  

                   while (bytesRead > 0) {

                     dos.write(buffer, 0, bufferSize);
                     bytesAvailable = fileInputStream.available();
                     bufferSize = Math.min(bytesAvailable, maxBufferSize);
                     bytesRead = fileInputStream.read(buffer, 0, bufferSize);   

                    }

                   // send multipart form data necesssary after file data...
                   dos.writeBytes(lineEnd);
                   dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                   // Responses from the server (code and message)
                   serverResponseCode = conn.getResponseCode();
                   String serverResponseMessage = conn.getResponseMessage();

                   Log.i("uploadFile", "HTTP Response is : " 
                           + serverResponseMessage + ": " + serverResponseCode);

                   if(serverResponseCode == 200){

                       getActivity().runOnUiThread(new Runnable() {
                            public void run() {
                                dialog.dismiss();  
                                Toast.makeText(getActivity(), "File Upload Complete.", Toast.LENGTH_SHORT).show();

                            }
                        });                   
                   }    

                   //close the streams //
                   fileInputStream.close();
                   dos.flush();
                   dos.close();

              } catch (MalformedURLException ex) {

                  dialog.dismiss();  
                  ex.printStackTrace();

                  getActivity().runOnUiThread(new Runnable() {
                      public void run() {
                          messageText.setText("MalformedURLException Exception : check script url.");
                          Toast.makeText(getActivity(), "MalformedURLException", Toast.LENGTH_SHORT).show();
                      }
                  });

                  Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
              } catch (Exception e) {
                  dialog.dismiss();  
                  e.printStackTrace();

                  getActivity().runOnUiThread(new Runnable() {
                      public void run() {
                          messageText.setText("Got Exception : see logcat ");
                      //    Toast.makeText(getActivity(), "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                      }
                  });
                  Log.e("Upload file to server Exception", "Exception : "  + e.getMessage(), e);  
              }
             // dialog.dismiss();       
              return serverResponseCode; 

           } // End else block 
         }

}

3条回答
别忘想泡老子
2楼-- · 2020-05-09 19:07

Add below line in your code. If the operation is cancelled, you will not get RESULT_OK

public void onActivityResult(int requestCode, int resultCode, Intent data) {

if (resultCode != RESULT_OK) 
      return;
查看更多
神经病院院长
3楼-- · 2020-05-09 19:18

You can handle it this way:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
        //your code
    }
    else {
        //alert of "No image was selected"
    }
}

Don't perform any operation on data if its null. So it won't give a crash.

Hope it helps.

查看更多
▲ chillily
4楼-- · 2020-05-09 19:25

Try this, add if(resultCode == RESULT_OK) :

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == RESULT_OK){ //<-- Add this
        if (requestCode == 1 ) {
            //Bitmap photo = (Bitmap) data.getData().getPath(); 

            Uri selectedImageUri = data.getData();
            imagepath = getPath(selectedImageUri);
            Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
            imageview.setImageBitmap(bitmap);
         //   messageText.setText("Uploading file path:" +imagepath);
        }
        }
    }

In your current code , even if the result code is not OK its executing data.getData() which is null

查看更多
登录 后发表回答