问题如下,imageview有一个按钮,单击按钮,对话框打开,并要求图库中的图像或来自相机的图像。 一旦我选择了库,我选择图像并设置图像,
BUT
有时界面会挂起并冻结,给我一个没有响应的警报。 我试图调试,但有时调试不遵循应用程序,所以我看不出有什么问题。
public class ProfileFragment extends Fragment implements View.OnClickListener
{
private static final int CAMERA_REQUEST = 1888;
private static int RESULT_LOAD_IMAGE = 1;
View view;
SessionManager manager;
private ImageView profilePicture;
int countrySpinnerIndex=0,citySpinnerIndex=0,areaSpinnerIndex=0;
String userName = "";
String pictureDirectory = "";
String encodedImage;
private EditText firstName_et;
private EditText lastName_et;
private EditText email_et;
private Spinner countriesSpinner;
private Spinner citiesSpinner;
private Spinner areaSpinner;
private EditText contactNumber_et;
private EditText street_et;
private EditText areaCode_et;
private AppCompatImageButton imageEdit_btn;
private Button acceptTemp_btn;
private ArrayList<String> countriesList;
private ArrayList<String> citiesList;
private ArrayList<String> areaList;
public ProfileFragment() {
// Required empty public constructor
}
/ * 没关系旋转器,这是另一个麻烦,但现在不担心 * /
这是我的问题开始我认为,在这里我称为Asynctask编码图像
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK && null != data) {
// Determine which bmp user selected in gallery and store path
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePath, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePath[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
profilePicture.setImageBitmap(BitmapFactory.decodeFile(picturePath));
pictureDirectory = picturePath;
Bitmap image = ((BitmapDrawable) profilePicture.getDrawable()).getBitmap();
new EncodeImage(image).execute();
}
else if(requestCode == CAMERA_REQUEST && resultCode == getActivity().RESULT_OK){
Bitmap photo = (Bitmap) data.getExtras().get("data");
profilePicture.setImageBitmap(photo);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getContext(), photo);
// CALL THIS METHOD TO GET THE ACTUAL PATH OF BITMAP WITHIN STORAGE
File finalFile = new File(getRealPathFromURI(tempUri));
//Temporary for display of filepath
pictureDirectory = finalFile.toString();
Toast.makeText(getActivity(),pictureDirectory , Toast.LENGTH_LONG).show();
//Glide.with(this).load(photo).into(profilePicture);
}
} catch (Exception ex) {
ex.getMessage();
}
}
@Override
public void onClick(View v) {
int id = v.getId();
if(id == R.id.imageEdit_btn){
final CharSequence[] items ={"Take Photo","Choose from Gallery","Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add Photo");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (items[which].equals("Take Photo")) {
//Open camera to user
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
} else if (items[which].equals("Choose from Gallery")) {
//open gallery to user to select image
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
} else if (items[which].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
else if (id==R.id.accept_btn) {
try {
//Bitmap image = ((BitmapDrawable)((LayerDrawable)profilePicture.getDrawable()).getDrawable(0)).getBitmap();
Bitmap image = ((BitmapDrawable) profilePicture.getDrawable()).getBitmap();
String[] profileServerList = new String[10];
profileServerList[0] = userName;
profileServerList[1] = firstName_et.getText().toString();
profileServerList[2] = lastName_et.getText().toString();
profileServerList[3] = email_et.getText().toString();
profileServerList[4] = contactNumber_et.getText().toString();
profileServerList[5] = street_et.getText().toString();
profileServerList[6] = "BWB";
profileServerList[7] = "PE";
profileServerList[8] = "ZA";
//logParams[6] = areaSpinner.getSelectedItem().toString();
// logParams[7] = citiesSpinner.getSelectedItem().toString();
// logParams[8] = countriesSpinner.getSelectedItem().toString();
profileServerList[9] = areaCode_et.getText().toString();
new AsyncUploadToServer(image, profileServerList).execute();
//while (SyncTask.getStatus() == AsyncTask.Status.RUNNING || SyncTask.getStatus()== AsyncUploadToServer.Status.PENDING) {
// if(SyncTask.getStatus() == AsyncTask.Status.FINISHED){
// SaveLocal();}
// }
}catch (Exception e){
e.printStackTrace();
}
}
}
我的Asynctask将图像加载到图像视图以及共享首选项 公共类LoadImage扩展AsyncTask { 布尔结果;
@Override
protected Void doInBackground(Void... params) {
try {
ArrayList<String> list = new ArrayList<String>();
manager = new SessionManager(getActivity().getApplicationContext());
list.add(encodedImage);
result = manager.SetSharedPreferences(list, "ProfilePicture");
}
catch (Exception ex)
{
ex.getMessage();
}
}
@Override
protected void onPostExecute(Void aVoid) {
if (result) {
Toast.makeText(getActivity(), "Image was successfully stored", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "Image was not stored", Toast.LENGTH_LONG).show();
}
}
}
public class EncodeImage extends AsyncTask<Void,Void,String> {
Bitmap img;
public EncodeImage(Bitmap image)
{
img = image;
}
@Override
protected String doInBackground(Void... params) {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
img.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
return encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
}catch (Exception ex){
return ex.getMessage();
}
}
@Override
protected void onPostExecute(String s) {
new LoadImage().execute();
}
}
//Used to load default profile picture
private void Load(View view) {
profilePicture = (ImageView) view.findViewById(R.id.profileImageView);
profilePicture.setImageResource(R.drawable.default_profile);
//Glide.with(this).load(R.drawable.default_profile).into(profilePicture);
}
//get image uri from camera
private Uri getImageUri(Context inContext, Bitmap inPhoto) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inPhoto.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(),inPhoto,"Title",null);
return Uri.parse(path);
}
//get actual path of image store on device
private String getRealPathFromURI(Uri uri) {
Cursor cursor = getContext().getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
public class AsyncUploadToServer extends AsyncTask<String, String, String> {
String[] list;
public AsyncUploadToServer(Bitmap image,String... list)
{
this.list = list;
// new EncodeImage(image).execute();
// SaveLocal();
}
@Override
protected String doInBackground(String... params) {
//Background worker handling connection to database
try
{
//Make an instance of the api;
eyeWatchApi api = new eyeWatchApi();
//Create an instance of the jason parser;
Parser pass = new Parser();
ArrayList<String> UpdateProfile= new ArrayList<String>();
UpdateProfile.add(list[0]);
UpdateProfile.add(list[1]);
UpdateProfile.add(list[2]);
UpdateProfile.add(list[3]);
UpdateProfile.add(list[4]);
UpdateProfile.add(list[5]);
UpdateProfile.add(list[6]);
UpdateProfile.add(list[7]);
UpdateProfile.add(list[8]);
UpdateProfile.add(list[9]);
UpdateProfile.add(encodedImage);
return pass.StringValue(api.UpdateMemberProfile(UpdateProfile));
}
catch (Exception ex)
{
return ex.getMessage();
}
}
@Override
protected void onPostExecute(String result) {
if(result=="Success")
{
}
}
}
public class AsyncPopulateCountrySpinner extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... params) {
countriesList = new ArrayList<String>();
eyeWatchApi api = new eyeWatchApi();
Parser parser = new Parser();
try{
countriesList = parser.CountriesArray(api.GetAllCountries());}
catch (Exception e)
{
}
return "Success";
}
protected void onPostExecute(String result) {
if(result == "Success") {
ArrayAdapter<String> countriesAdapter;
countriesAdapter = new ArrayAdapter<String>(getActivity(), R.layout.countries_spinner_item, countriesList);
countriesAdapter.setDropDownViewResource(R.layout.countries_spinner_item_droplist);
countriesSpinner.setBackgroundColor(Color.parseColor("#141414"));
countriesSpinner.setAdapter(countriesAdapter);
/*countriesSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
countrySpinnerIndex = position;
}
});*/
}
else
{
Toast.makeText(getActivity(), "Could not pull Country spinner data", Toast.LENGTH_LONG).show();
}
//super.onPostExecute(aVoid);
}
}
public class AsyncPopulateCitySpinner extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... params) {
citiesList = new ArrayList<String>();
eyeWatchApi api = new eyeWatchApi();
Parser parser = new Parser();
try{
citiesList = parser.CitiesArray(api.GetAllCities());
}
catch (Exception e)
{
}
return "Success";
}
protected void onPostExecute(String result) {
if(result == "Success") {
ArrayAdapter<String> cityAdapter;
cityAdapter = new ArrayAdapter<String>(getActivity(), R.layout.neighborhoods_spinner_item_droplist, citiesList);
cityAdapter.setDropDownViewResource(R.layout.neighborhoods_spinner_item_droplist);
areaSpinner.setBackgroundColor(Color.parseColor("#141414"));
citiesSpinner.setAdapter(cityAdapter);
/*citiesSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
citySpinnerIndex = position;
}
});*/
}
else
{
Toast.makeText(getActivity(), "Could not pull City spinner data", Toast.LENGTH_LONG).show();
}
//super.onPostExecute(aVoid);
}
}
public class AsyncPopulateSuburbSpinner extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... params) {
areaList = new ArrayList<String>();
eyeWatchApi api = new eyeWatchApi();
Parser parser = new Parser();
try{
areaList =parser.SuburbArray(api.GetAllSuburbs());}
catch (Exception e)
{
}
return "Success";
}
protected void onPostExecute(String result) {
if(result == "Success") {
/* ArrayAdapter<String> neighAdapter;
neighAdapter = new ArrayAdapter<String>(getActivity(), R.layout.neighborhood_spinner_item, areaList);
neighAdapter.setDropDownViewResource(R.layout.neighborhoods_spinner_item_droplist);
areaSpinner.setBackgroundColor(Color.parseColor("#141414"));
areaSpinner.setAdapter(neighAdapter);
areaSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
areaSpinnerIndex = position;
}
});*/
}
else
{
Toast.makeText(getActivity(), "Could not pull spinner data", Toast.LENGTH_LONG).show();
}
//super.onPostExecute(aVoid);
}
}
//Save profile information locally
private void SaveLocal() {
boolean result;
manager = new SessionManager(getActivity().getApplicationContext());
ArrayList<String> list = new ArrayList<String>();
/*0*/list.add(firstName_et.getText().toString());
/*1*/list.add(lastName_et.getText().toString());
/*2*/list.add(email_et.getText().toString());
/*3*/list.add(contactNumber_et.getText().toString());
/*4*/list.add(street_et.getText().toString());
/*5*/list.add("Sunridge Park");
/*6*/list.add("Port Elizabeth");
/*7*/list.add("South Africa");
/*8*/list.add(areaCode_et.getText().toString());
/*9*/list.add(encodedImage);
/*10*/list.add("False");
//Add to sharedpreferences local
result = manager.SetSharedPreferences(list,"Profile");
if (result) {
Toast.makeText(getActivity(), "Data was successfully stored", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "Data was not stored", Toast.LENGTH_LONG).show();
}
}
private void GetProfileData() {
manager = new SessionManager(getActivity().getApplicationContext());
ArrayList<String> list = new ArrayList<String>();
list = manager.GetSharedPreferences();
try {
firstName_et.setText(list.get(0));
lastName_et.setText(list.get(1));
email_et.setText(list.get(2));
contactNumber_et.setText(list.get(3));
street_et.setText(list.get(4));
//area (5)
//city (5)
//country (7)
areaCode_et.setText(list.get(8));
if (list.get(10).equals("TRUE")){
Load(view);
}else
{
String imageCode = list.get(9);
byte[] imageBytes = Base64.decode(imageCode.getBytes(),Base64.DEFAULT);
Bitmap image = BitmapFactory.decodeByteArray(imageBytes,0,imageBytes.length);
//Bitmap image = BitmapFactory.decodeFile(list.get(11));
profilePicture.setImageBitmap(image);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}