我已经进行了精确搜索以解决我的问题,但遗憾的是,所提供的解决方案都没有解决我的问题。我的问题是捕获的图像没有出现在imageview中。我试图修改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>
********* UPDATE: 通过在我的活动类中删除以下方法解决了我的问题:
@Override
protected void onResume() {
super.onResume();
this.onCreate(null);
}
显然onResume()方法导致了这个问题。不管怎样,谢谢你的帮助!
答案 0 :(得分: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
}
onResult
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();
}
}
答案 1 :(得分:0)
试试这种方式,希望这可以帮助您解决问题。
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;
}
}
答案 2 :(得分: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));
您可能必须在清单中授予使用相机,sdcard读取和写入权限的权限..然后在您的onActivityResult中根据请求代码,您可以显示该路径中的图像..
如果您有任何疑问,请告诉我