2014-09-30 57 views
-1

當我沒有選擇任何圖像後打開畫廊和布萊恩回我的應用程序崩潰。 plz幫助我出去。這是從畫廊應用程序崩潰時,從圖庫回來沒有選擇任何圖像

公共類FragmentAskFitindya擴展片段{

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

你必須檢查是否'resultCode爲== RESULT_OK' – 2014-09-30 08:00:29

+0

檢查data.getData()爲空或不是 – 2014-09-30 08:02:32

+1

一般的經驗法則,以避免越來越下降表決提高您獲得良好答案的機會:crash =發佈LogCat !!! – 2Dee 2014-09-30 08:07:13

回答

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

如果空不要data進行任何操作。所以它不會發生崩潰。

希望它有幫助。

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

1

在代碼中添加以下行。如果操作被取消,你不會得到RESULT_OK

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

if (resultCode != RESULT_OK) 
     return; 
+0

謝謝親愛的。非常感謝您的幫助。你真正的MVP – 2014-09-30 09:33:52

相關問題