2014-07-11 5 views
0

이미 문제를 해결하기 위해 정확한 검색을 수행했지만, 불행히도 제공된 솔루션 중 어느 것도 내 문제를 해결하지 못했습니다. 내 문제는 캡처 한 이미지가 이미지 뷰에 나타나지 않는다는 것입니다. onActivityResult() 메서드를 수정하려고했지만 여전히 작동하지 않습니다. 관련 XML캡처 된 이미지가 이미지보기에 표시되지 않습니다.

public class EditProfileActivity extends Activity { 

    /** 
    * JSON Response node names. 
    **/ 
    private static String KEY_SUCCESS = "success"; 
    private static String KEY_UID = "uid"; 
    private static String KEY_FIRSTNAME = "fname"; 
    private static String KEY_LASTNAME = "lname"; 
    private static String KEY_USERNAME = "uname"; 
    private static String KEY_EMAIL = "email"; 
    private static String KEY_CREATED_AT = "created_at"; 
    private static String KEY_ERROR = "error"; 
    private static String KEY_RESIDENCE = "residence"; 

    TextView inputfname, inputlname, inputemail; 
    PlacesTask placesTask; 
    ParserTask parserTask; 
    AutoCompleteTextView inputresidence; 
    ImageView imgFavorite; 
    private ActionBar actionBar; 
    private static final int CAMERA_REQUEST = 1888; 
    private ImageView imageView; 

    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.edit_profile_layout); 

     this.imageView = (ImageView)this.findViewById(R.id.imageView1); 
     Button photoButton = (Button) this.findViewById(R.id.button1); 
     photoButton.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
       startActivityForResult(cameraIntent, CAMERA_REQUEST); 
      } 
     }); 



     // actionBar = getActionBar(); 
     // actionBar.setDisplayHomeAsUpEnabled(true); 
     // getActionBar().setHomeButtonEnabled(true); 

     DatabaseHandler db = new DatabaseHandler(getApplicationContext()); 

     // Hashmap to load data from the Sqlite database 
     HashMap<String, String> user = new HashMap<String, String>(); 
     user = db.getUserDetails(); 

     inputfname = (TextView) findViewById(R.id.fname); 
     inputlname = (TextView) findViewById(R.id.lname); 
     inputemail = (TextView) findViewById(R.id.email); 
     inputresidence = (AutoCompleteTextView) findViewById(R.id.atv_places); 

     // inputfname.setText(""); 
     inputfname.setText(user.get("fname")); 
     inputlname.setText(user.get("lname")); 
     inputemail.setText(user.get("email")); 
     inputresidence.setText(user.get("residence")); 

     inputresidence = (AutoCompleteTextView) findViewById(R.id.atv_places); 
     inputresidence.setThreshold(1); 

     inputresidence.addTextChangedListener(new TextWatcher() { 

      @Override 
      public void onTextChanged(CharSequence s, int start, int before, 
        int count) { 
       placesTask = new PlacesTask(); 
       placesTask.execute(s.toString()); 
      } 

      @Override 
      public void beforeTextChanged(CharSequence s, int start, int count, 
        int after) { 
       // TODO Auto-generated method stub 
      } 

      @Override 
      public void afterTextChanged(Editable s) { 
       // TODO Auto-generated method stub 
      } 
     }); 

    } 

    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
      if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) { 
       Bitmap photo = (Bitmap) data.getExtras().get("data"); 
       imageView.setImageBitmap(photo); 
       //imageView.invalidate(); 
      } 
     } 

    /** A method to download json data from url */ 
    private String downloadUrl(String strUrl) throws IOException { 
     String data = ""; 
     InputStream iStream = null; 
     HttpURLConnection urlConnection = null; 
     try { 
      URL url = new URL(strUrl); 

      // Creating an http connection to communicate with url 
      urlConnection = (HttpURLConnection) url.openConnection(); 

      // Connecting to url 
      urlConnection.connect(); 

      // Reading data from url 
      iStream = urlConnection.getInputStream(); 

      BufferedReader br = new BufferedReader(new InputStreamReader(
        iStream)); 

      StringBuffer sb = new StringBuffer(); 

      String line = ""; 
      while ((line = br.readLine()) != null) { 
       sb.append(line); 
      } 

      data = sb.toString(); 

      br.close(); 

     } catch (Exception e) { 
      Log.d("Exception while downloading url", e.toString()); 
     } finally { 
      iStream.close(); 
      urlConnection.disconnect(); 
     } 
     return data; 
    } 

    // Fetches all places from GooglePlaces AutoComplete Web Service 
    private class PlacesTask extends AsyncTask<String, Void, String> { 

     @Override 
     protected String doInBackground(String... place) { 
      // For storing data from web service 
      String data = ""; 
      // Obtain browser key from https://code.google.com/apis/console 
      String key = "key=AIzaSyDP-e-LqaAQ5NsJMffT68ed5o0ZnpyHG_c"; 
      String input = ""; 

      try { 
       input = "input=" + URLEncoder.encode(place[0], "utf-8"); 
      } catch (UnsupportedEncodingException e1) { 
       e1.printStackTrace(); 
      } 

      // place type to be searched 
      String types = "types=geocode"; 

      // Sensor enabled 
      String sensor = "sensor=false"; 

      // Building the parameters to the web service 
      String parameters = input + "&" + types + "&" + sensor + "&" + key; 

      // Output format 
      String output = "json"; 

      // Building the url to the web service 
      String url = "https://maps.googleapis.com/maps/api/place/autocomplete/" 
        + output + "?" + parameters; 

      try { 
       // Fetching the data from we service 
       data = downloadUrl(url); 
      } catch (Exception e) { 
       Log.d("Background Task", e.toString()); 
      } 
      return data; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      super.onPostExecute(result); 

      // Creating ParserTask 
      parserTask = new ParserTask(); 

      // Starting Parsing the JSON string returned by Web Service 
      parserTask.execute(result); 
     } 
    } 

    /** A class to parse the Google Places in JSON format */ 
    private class ParserTask extends 
      AsyncTask<String, Integer, List<HashMap<String, String>>> { 

     JSONObject jObject; 

     @Override 
     protected List<HashMap<String, String>> doInBackground(
       String... jsonData) { 

      List<HashMap<String, String>> places = null; 

      PlaceJSONParser placeJsonParser = new PlaceJSONParser(); 

      try { 
       jObject = new JSONObject(jsonData[0]); 

       // Getting the parsed data as a List construct 
       places = placeJsonParser.parse(jObject); 

      } catch (Exception e) { 
       Log.d("Exception", e.toString()); 
      } 
      return places; 
     } 

     @Override 
     protected void onPostExecute(List<HashMap<String, String>> result) { 

      String[] from = new String[] { "description" }; 
      int[] to = new int[] { android.R.id.text1 }; 

      // Creating a SimpleAdapter for the AutoCompleteTextView 
      SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, 
        android.R.layout.simple_list_item_1, from, to); 

      // Setting the adapter 
      inputresidence.setAdapter(adapter); 
     } 

    } 

    /** 
    * Async Task to check whether internet connection is working 
    **/ 

    private class NetCheck extends AsyncTask<String, String, Boolean> { 
     private ProgressDialog nDialog; 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      nDialog = new ProgressDialog(EditProfileActivity.this); 
      nDialog.setMessage("Loading.."); 
      nDialog.setTitle("Checking Network"); 
      nDialog.setIndeterminate(false); 
      nDialog.setCancelable(true); 
      nDialog.show(); 
     } 

     @Override 
     protected Boolean doInBackground(String... args) { 

      /** 
      * Gets current device state and checks for working internet 
      * connection by trying Google. 
      **/ 
      ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
      NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
      if (netInfo != null && netInfo.isConnected()) { 
       try { 
        URL url = new URL("http://www.google.com"); 
        HttpURLConnection urlc = (HttpURLConnection) url 
          .openConnection(); 
        urlc.setConnectTimeout(3000); 
        urlc.connect(); 
        if (urlc.getResponseCode() == 200) { 
         return true; 
        } 
       } catch (MalformedURLException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
      return false; 

     } 

     @Override 
     protected void onPostExecute(Boolean th) { 

      if (th == true) { 
       nDialog.dismiss(); 
       new ProcessUpdateProfile().execute(); 
      } else { 
       nDialog.dismiss(); 
       Toast toast = Toast.makeText(getApplicationContext(), 
         "Error in Network Connection", Toast.LENGTH_SHORT); 
       toast.show(); 
      } 
     } 
    } 

    private class ProcessUpdateProfile extends 
      AsyncTask<String, String, JSONObject> { 

     /** 
     * Defining Process dialog 
     **/ 
     private ProgressDialog pDialog; 

     String uid, fname, lname, email, residence; 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 

      DatabaseHandler db = new DatabaseHandler(getApplicationContext()); 

      // Hashmap to load data from the Sqlite database 

      HashMap<String, String> user = new HashMap<String, String>(); 
      user = db.getUserDetails(); 
      uid = user.get("uid"); 
      fname = inputfname.getText().toString(); 
      lname = inputlname.getText().toString(); 
      email = inputemail.getText().toString(); 
      residence = inputresidence.getText().toString(); 

      pDialog = new ProgressDialog(EditProfileActivity.this); 
      pDialog.setTitle("Server"); 
      pDialog.setMessage("Registrierung.."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
     } 

     @Override 
     protected JSONObject doInBackground(String... args) { 

      UserFunctions userFunction = new UserFunctions(); 

      JSONObject json = userFunction.updateProfile(uid, fname, lname, 
        email, residence); 

      return json; 

     } 

     @Override 
     protected void onPostExecute(JSONObject json) { 
      /** 
      * Checks for success message. 
      **/ 
      try { 
       if (json.getString(KEY_SUCCESS) != null) { 
        // registerErrorMsg.setText(""); 
        // inputEmail.setBackgroundColor(Color.WHITE); 
        // inputUsername.setBackgroundColor(Color.WHITE); 

        String res = json.getString(KEY_SUCCESS); 

        String red = json.getString(KEY_ERROR); 

        if (Integer.parseInt(res) == 1) { 
         pDialog.setTitle("Daten"); 
         pDialog.setMessage("Laden.."); 

         DatabaseHandler db = new DatabaseHandler(
           getApplicationContext()); 
         JSONObject json_user = json.getJSONObject("user"); 

         /** 
         * Clear all previous data in SQlite database. 
         **/ 
         UserFunctions logout = new UserFunctions(); 
         logout.logoutUser(getApplicationContext()); 

         db.addUser(json_user.getString(KEY_FIRSTNAME), 
           json_user.getString(KEY_LASTNAME), 
           json_user.getString(KEY_EMAIL), 
           json_user.getString(KEY_USERNAME), 
           json_user.getString(KEY_UID), 
           json_user.getString(KEY_CREATED_AT), 
           json_user.getString(KEY_RESIDENCE)); 

         // json_user.getString(KEY_LAST_LOGIN)); 

         /** 
         * Stores registered data in SQlite Database Launch 
         * Registered screen 
         **/ 

         /* 
         * Intent dashboard = new 
         * Intent(getApplicationContext(), 
         * ProfileFragment.class); 
         */ 

         pDialog.dismiss(); 

         Intent intent = new Intent(EditProfileActivity.this, 
           MainActivity.class); 
         intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
         startActivity(intent); 

         Toast toast = Toast.makeText(getApplicationContext(), 
           "Ihre Daten wurden erfolgreich aktualisiert!", 
           Toast.LENGTH_SHORT); 
         toast.setGravity(Gravity.CENTER 
           | Gravity.CENTER_HORIZONTAL, 0, 0); 
         toast.show(); 

        } else if (Integer.parseInt(red) == 2) { 
         pDialog.dismiss(); 
         inputemail.setBackgroundColor(Color.RED); 

         Toast.makeText(getApplicationContext(), 
           "E-Mail existiert bereits!", Toast.LENGTH_LONG) 
           .show(); 
         // registerErrorMsg.setText("E-Mail existiert bereits"); 

        } else if (Integer.parseInt(red) == 3) { 
         pDialog.dismiss(); 
         inputemail.setBackgroundColor(Color.RED); 

         Toast.makeText(getApplicationContext(), 
           "Ungültige E-Mail", Toast.LENGTH_LONG).show(); 

         // registerErrorMsg.setText("Ungültige E-Mail"); 
        } 
       } 

       else { 
        pDialog.dismiss(); 

        Toast.makeText(getApplicationContext(), 
          "Fehler aufgetreten, bitte nochmal versuchen", 
          Toast.LENGTH_LONG).show(); 

       } 

      } catch (JSONException e) { 
       e.printStackTrace(); 

      } 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     MenuInflater inflater = getMenuInflater(); 

     inflater.inflate(R.menu.edit_profile_save, menu); 
     return super.onCreateOptionsMenu(menu); 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle presses on the action bar items 
     switch (item.getItemId()) { 
     case R.id.action_save: 

      if ((!inputfname.getText().toString().equals("")) 
        && (!inputlname.getText().toString().equals("")) 
        && (!inputemail.getText().toString().equals("")) 
        && (!inputresidence.getText().toString().equals(""))) { 

       NetAsync(item); 

      } else { 
       Toast.makeText(getApplicationContext(), 
         "Bitte alle Felder füllen", Toast.LENGTH_SHORT).show(); 
      } 

      return true; 
     default: 
      return super.onOptionsItemSelected(item); 

     } 
    } 

    public void NetAsync(MenuItem item) { 
     new NetCheck().execute(); 
    } 

    @Override 
    protected void onResume() { 

     super.onResume(); 
     this.onCreate(null); 
    } 
} 

그리고 여기에 있습니다 : :

<?xml version="1.0" encoding="utf-8"?> 
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context=".EditProfileActivity" > 

    <LinearLayout 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" > 

     <TextView 
      android:id="@+id/text_change_profilePic" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_marginTop="25dp" 
      android:hint="@string/text_change_avatar" /> 

     <View 
      android:id="@+id/divider1" 
      android:layout_width="fill_parent" 
      android:layout_height="1dp" 
      android:background="@android:color/darker_gray" /> 

     <Button 
      android:id="@+id/button1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="take image" > 
     </Button> 

     <ImageView 
      android:id="@+id/imageView1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center_horizontal" 
      android:layout_marginTop="30dp" 
      android:contentDescription="test" 
      android:src="@drawable/ic_action_camera" > 
     </ImageView> 

     <TextView 
      android:id="@+id/text_change_data" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_marginTop="100dp" 
      android:hint="@string/btn_upload_avatar" /> 

     <View 
      android:id="@+id/divider2" 
      android:layout_width="fill_parent" 
      android:layout_height="1dp" 
      android:background="@android:color/darker_gray" /> 

     <EditText 
      android:id="@+id/fname" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_marginTop="10dp" 
      android:drawableLeft="@drawable/ic_user" 
      android:drawablePadding="10dip" 
      android:hint="@string/EditText_firstname" 
      android:textSize="15sp" /> 

     <EditText 
      android:id="@+id/lname" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_marginTop="10dp" 
      android:drawableLeft="@drawable/ic_user" 
      android:drawablePadding="10dip" 
      android:hint="@string/EditText_lastname" 
      android:textSize="15sp" /> 

     <EditText 
      android:id="@+id/email" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_marginTop="10dp" 
      android:drawableLeft="@drawable/ic_email" 
      android:drawablePadding="10dip" 
      android:hint="@string/EditText_email" 
      android:inputType="textEmailAddress" 
      android:textSize="15sp" /> 

     <com.Sinan_Kalkan.sinis.CustomAutoCompleteTextView 
      android:id="@+id/atv_places" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_marginTop="10dp" 
      android:drawableLeft="@drawable/ic_location" 
      android:drawablePadding="10dp" 
      android:hint="@string/EditText_residence" 
      android:textSize="15sp" /> 
    </LinearLayout> 

</ScrollView> 

********

은 여기 내 전체 활동 클래스 느릅 나무 카메라 의도를 호출입니다 * 업데이트 : 내 활동 클래스에서 다음과 같은 방법을 삭제하여 나의 문제를 해결했습니다 :

@Override 
    protected void onResume() { 

     super.onResume(); 
     this.onCreate(null); 
    } 

분명히 onResume() 메서드가 문제를 일으켰습니다. 어쨌든 당신 도움을 주셔서 감사합니다!

답변

0
Button bt_camera=(Button)dialog.findViewById(R.id.button1); 
bt_camera.setOnClickListener(new OnClickListener() { 

    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 
     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 

     intent.putExtra(MediaStore.EXTRA_OUTPUT, 
     MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString()); 
     // ******** code for crop image 
     intent.putExtra("crop", "true"); 
     intent.putExtra("aspectX", 0); 
     intent.putExtra("aspectY", 0); 
     intent.putExtra("outputX", 200); 
     intent.putExtra("outputY", 150); 

     try { 

     intent.putExtra("return-data", true); 
     startActivityForResult(intent, PICK_FROM_CAMERA); 

     } catch (ActivityNotFoundException e) { 
     // Do nothing for now 
     } 

+0

불행히도 귀하의 제공 코드가 NullPointerException을 던집니다. 나는 genymotion 에뮬레이터를 사용합니다. 카메라 미리보기는 항상 가로 모드입니다. 아마 이것이 이미지 뷰의 미리보기가 작동하지 않는 이유에 대한 힌트일까요? –

0

이 방법을 시도

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

if (requestCode == PICK_FROM_CAMERA) { 
try 
{ 
    Bundle extras = data.getExtras(); 
    System.out.println("frome the PICK_FROM_CAMERA "); 
    Bitmap photo = extras.getParcelable("data"); 
    img.setImageBitmap(photo); 
} 
catch(NullPointerException ex) 
{ 
    ex.printStackTrace(); 
    Toast.makeText(getApplicationContext(), "User Canclled", 3000).show(); 
} 

} onResult, 이것은 당신이 당신의 문제를 해결하는 데 도움이되기를 바랍니다.

private String imgPath; 

public Uri setImageUri() { 
    // Store image in dcim 
    File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new  Date().getTime() + ".png"); 
    Uri imgUri = Uri.fromFile(file); 
    this.imgPath = file.getAbsolutePath(); 
    return imgUri; 
} 

public String getImagePath() { 
    return imgPath; 
} 

public Bitmap decodeFile(String path) { 
    try { 
    // Decode image size 
    BitmapFactory.Options o = new BitmapFactory.Options(); 
     o.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(path, o); 
    // The new size we want to scale to 
    final int REQUIRED_SIZE = 1024; 
    // Find the correct scale value. It should be the power of 2. 
    int scale = 1; 
    while (o.outWidth/scale/2 >= REQUIRED_SIZE && o.outHeight/scale/2 >= REQUIRED_SIZE) 
    scale *= 2; 
     // Decode with inSampleSize 
    BitmapFactory.Options o2 = new BitmapFactory.Options(); 
    o2.inSampleSize = scale; 
    return BitmapFactory.decodeFile(path, o2); 
    } catch (Throwable e) { 
    e.printStackTrace(); 
    } 
    return null; 
} 

photoButton.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
     intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri()); 
     startActivityForResult(cameraIntent, CAMERA_REQUEST);  
    } 
}); 


@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     switch (requestCode) { 
     case CAMERA_REQUEST: 
     if (resultCode == RESULT_OK) {      
      Bitmap photo = decodeFile(getImagePath); 
      imageView.setImageBitmap(photo);        
     } 
     break; 
     default: 
     break; 
    }   
} 
0

안녕 당신은 친절하게 아래를 찾을 수 .. 당신이 사용하는 경우에, 당신은 이미지를 표시하기 위해 동일한 경로를 사용할 수 있습니다 .. 당신의 촬영 영상이 저장되는 경로를 제공하는

을 가질 수있다 사진을 촬영하기위한 코드 :

Intent intent = new Intent(
      android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 

File photo = new File("sd card path where should be stored" 
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); 
intent.putExtra("exit", "false"); 
intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, 
      ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo)); 

그런 다음 요청 코드를 기반으로하여 onActivityResult에서 해당 경로에서 이미지를 표시 할 수 있습니다 .. sdcard에 허가를, 카메라를 사용하여 읽기와 쓰기에 대한 매니페스트에 권한을 부여 할 수 있습니다. .

질문이 있으시면 친절하게 알려주십시오.

관련 문제