我已經做了一個精確的搜索來解決我的問題,但不幸的是沒有提供的解決方案解決了我的問題。我的問題是捕獲的圖像不顯示在圖像視圖中。我試圖修改onActivityResult()方法,但它仍然不起作用。捕獲的圖像不會顯示在圖像視圖
這裏是我的完整活動類至極調用相機意圖:
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:
<?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()方法導致了這個問題。非常感謝您的幫助!
不幸的是,您提供的代碼會拋出一個NullPointerException異常。我使用genymotion模擬器,並且相機預覽始終處於橫向模式,也許這是暗示爲什麼imageview上的預覽不起作用? –