从图库返回而不选择任何图像时,应用程序崩溃

时间:2014-09-30 07:58:03

标签: android image-uploading

当我打开画廊后我没有选择任何图像并回到我的应用程序崩溃时。 PLZ帮帮我们。这是一个将图像上传到服务器的程序,从库中选择

公共类FragmentAskFitindya扩展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 个答案:

答案 0 :(得分:2)

在代码中添加以下行。如果操作被取消,您将无法获得RESULT_OK

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

if (resultCode != RESULT_OK) 
      return;

答案 1 :(得分:1)

你可以这样处理:

@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"
    }
}

如果{null},则不要对data执行任何操作。所以它不会发生崩溃。

希望它有所帮助。

答案 2 :(得分:0)

试试这个,添加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);
        }
        }
    }

在您当前的代码中,即使结果代码不是OK,其执行data.getData()也是null