选择新图片后,为什么“userProfilePic”id中的imageView会快速更改为存储在数据库中的旧图像

时间:2016-02-20 19:02:40

标签: java android xml android-studio

我想将imageView id“userProfilePic”中的图片更改为用户选择的新图片,并将该图片更新到数据库。但是一旦我选择了一张新图片,“userProfilePic”id下的图片会快速更改为新图片并再次更改为旧图片(已经在数据库中),因此我无法为“userProfilePic”上传新图片ID。我是Android开发的初学者,我只知道少量的android,所以请帮我解决这个问题。这是我的EditUserProfile.java file

 package com.example.kasun.timetable;

    import android.app.DatePickerDialog;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.drawable.BitmapDrawable;
    import android.net.Uri;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.provider.MediaStore;
    import android.support.v7.app.ActionBarActivity;
    import android.util.Base64;
    import android.view.View;
    import android.widget.Button;
    import android.widget.DatePicker; 
    import android.widget.EditText;
    import android.widget.ImageView;
    import android.widget.Toast;

    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.params.BasicHttpParams;
    import org.apache.http.params.HttpConnectionParams;
    import org.apache.http.params.HttpParams;

    import java.io.ByteArrayOutputStream;
    import java.io.InputStream;
    import java.net.URL;
    import java.net.URLConnection;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Locale;

    public class EditYourProfile extends ActionBarActivity implements View.OnClickListener {
        private static final int Result_Load_Image=1;
        private Button bSave2,bBack2,bImageUpload;
        private EditText etUsernameEdit,etFirstNameEdit,etLastNameEdit,etPasswordEdit,etPositionEdit,etBirthDateEdit,etQualificationEdit,etEmailEdit;
        private Calendar myCalendar = Calendar.getInstance();
        private UserLocalDatabase userLocalDatabase;
        private ImageView userProfilePic;

        private static final String SERVER_ADDRESS="http://172.21.18.170/Timetable/";

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_edit_your_profile);

            bBack2=(Button)findViewById(R.id.bBack2);
            bSave2=(Button)findViewById(R.id.bSave2);
            etUsernameEdit=(EditText)findViewById(R.id.etUserNameEdit);
            etFirstNameEdit=(EditText)findViewById(R.id.etFirstNameEdit);
            etLastNameEdit=(EditText)findViewById(R.id.etLastNameEdit);
            etPasswordEdit=(EditText)findViewById(R.id.etPasswordEdit);
            etEmailEdit=(EditText)findViewById(R.id.etEmailEdit);
            etQualificationEdit=(EditText)findViewById(R.id.etQualificationEdit);
            etPositionEdit=(EditText)findViewById(R.id.etPositionEdit);
            etBirthDateEdit=(EditText)findViewById(R.id.etBirthDateEdit);
            userProfilePic=(ImageView)findViewById(R.id.userProfilePic);
            bImageUpload=(Button)findViewById(R.id.bImageUpload);

            bSave2.setOnClickListener(this);
            bBack2.setOnClickListener(this);
            userProfilePic.setOnClickListener(this);
            bImageUpload.setOnClickListener(this);
            userLocalDatabase = new UserLocalDatabase(this);



            final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear,
                                      int dayOfMonth) {
                    // TODO Auto-generated method stub

                    myCalendar.set(Calendar.YEAR, year);
                    myCalendar.set(Calendar.MONTH, monthOfYear);
                    myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    updateLabel();
                }

            };

            etBirthDateEdit.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    new DatePickerDialog(EditYourProfile.this, date, myCalendar
                            .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                            myCalendar.get(Calendar.DAY_OF_MONTH)).show();


                }
            });






        }
        private void updateLabel() {

            String myFormat = "MM/dd/yy"; 
            SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

            etBirthDateEdit.setText(sdf.format(myCalendar.getTime()));
        }

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

            if(authenticate()==true){
                showDetails();


            }
            else {
                startActivity(new Intent(this, MainActivity.class));
                finish();

            }

        }

        public boolean authenticate(){

            return userLocalDatabase.getUserStatus();
        }

        public void showDetails(){
            User user=userLocalDatabase.getLoggedInUser();

            etFirstNameEdit.setText(user.firstName);
            etLastNameEdit.setText(user.lastName);
            etUsernameEdit.setText(user.userName);
            etQualificationEdit.setText(user.qualification);
            etPositionEdit.setText(user.position);
            etPasswordEdit.setText(user.password);
            etEmailEdit.setText(user.email);

            new downloadImage(etUsernameEdit.getText().toString()).execute();

        }



        @Override
        public void onClick(View v) {

            switch(v.getId()){

                case R.id.bSave2:



                    break;

                case R.id.bBack2:
                    startActivity(new Intent(this,SelectTask.class));
                    break;
                case R.id.userProfilePic:

                    Intent galleryIntent= new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(galleryIntent,Result_Load_Image);




                    break;
                case R.id.bImageUpload:

                    Bitmap image=((BitmapDrawable) userProfilePic.getDrawable()).getBitmap();

                    new uploadImage(image,etUsernameEdit.getText().toString()).execute();



                    break;

            }


        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            if(requestCode==Result_Load_Image && resultCode==RESULT_OK && data!=null){

                Uri selectedImage= data.getData();

                userProfilePic.setImageURI(selectedImage);

            }

        }

        public class uploadImage extends AsyncTask<Void,Void,Void> {


            private Bitmap image;
            private String name;



            public uploadImage(Bitmap image,String name){
                this.image=image;
                this.name=name;

            }

            @Override
            protected Void doInBackground(Void... params) {

                ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();

                image.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
                String encodedImage= Base64.encodeToString(byteArrayOutputStream.toByteArray(),Base64.DEFAULT);

                ArrayList<NameValuePair> dataToSend1= new ArrayList<>();
                dataToSend1.add(new BasicNameValuePair("image",encodedImage));
                dataToSend1.add(new BasicNameValuePair("name",name));

                HttpParams httpRequestParams= getHttpRequestParams();

                HttpClient httpClient = new DefaultHttpClient(httpRequestParams);
                HttpPost post= new HttpPost(SERVER_ADDRESS + "savePicture.php");

                try{
                    post.setEntity(new UrlEncodedFormEntity(dataToSend1));
                    httpClient.execute(post);

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

                }

                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                Toast.makeText(getApplicationContext(),"Image is uploaded",Toast.LENGTH_SHORT).show();
            }


        }
        //----------------------------------------------------------------------------------------------

        private HttpParams getHttpRequestParams(){
            HttpParams httpRequestParams= new BasicHttpParams();

            HttpConnectionParams.setConnectionTimeout(httpRequestParams, 1000 * 30);
            HttpConnectionParams.setSoTimeout(httpRequestParams,1000 * 30);
            return httpRequestParams;






        }
        public class downloadImage extends AsyncTask<Void,Void,Bitmap>{

            private String name;



            public downloadImage(String name){

                this.name=name;
            }


            @Override
            protected Bitmap doInBackground(Void... params) {


                String url= SERVER_ADDRESS+"proPictures/"+name+".JPG";


                try{
                    URLConnection connection= new URL(url).openConnection();

                    connection.setConnectTimeout(1000*30); 
                    connection.setReadTimeout(1000 * 30); 

                    return BitmapFactory.decodeStream((InputStream) connection.getContent(), null, null);






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





                return null;
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                super.onPostExecute(bitmap);



                if(bitmap!=null){

                    userProfilePic.setImageBitmap(bitmap);


                }

            }
        }




    }

这是我的相关xml文件

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.kasun.timetable.EditYourProfile"
    android:background="#303030">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="1000dp"
        android:id="@+id/scroll">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

    <ImageView
        android:layout_width="110dp"
        android:layout_height="100dp"
        android:id="@+id/userProfilePic"
        android:layout_marginTop="34dp"
        android:background="#c6c4c4"

        android:layout_marginBottom="10dp"/>

    <Button
        android:layout_width="110dp"
        android:layout_height="wrap_content"
        android:text="Upload "
        android:id="@+id/bImageUpload"

        android:layout_marginBottom="10dp"
        android:textColor="#ffffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/userNameText"
        android:id="@+id/textView18"

        android:layout_marginBottom="10dp"
        android:textColor="#ffffffff" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/etUserNameEdit"
        android:layout_marginBottom="10dp"
        android:textColor="#ffffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/FirstNameText"
        android:id="@+id/textView19"

        android:layout_marginBottom="10dp"
        android:textColor="#ffffffff" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/etFirstNameEdit"

        android:layout_marginBottom="10dp"
        android:textColor="#ffffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/LastNameText"
        android:id="@+id/textView20"

        android:layout_marginBottom="10dp"
        android:textColor="#ffffffff" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/etLastNameEdit"

        android:layout_marginBottom="10dp"
        android:textColor="#ffffffff" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="@string/Password"
            android:id="@+id/textView21"
            android:layout_marginTop="16dp"


            android:layout_marginBottom="10dp"
            android:textColor="#ffffffff" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:ems="10"
            android:id="@+id/etPasswordEdit"

            android:layout_marginBottom="10dp"
            android:textColor="#ffffffff" />

        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/Position"
        android:id="@+id/textView23"

        android:layout_marginTop="12dp"
        android:layout_marginBottom="10dp"
        android:textColor="#ffffffff" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/etPositionEdit"

        android:layout_marginBottom="10dp"
        android:textColor="#ffffffff" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="@string/Email"
            android:id="@+id/textView24"

            android:layout_marginTop="12dp"
            android:layout_marginBottom="10dp"
            android:textColor="#ffffffff" />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/etEmailEdit"

            android:layout_marginBottom="10dp"
            android:textColor="#ffffffff" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="@string/Telephone"
            android:id="@+id/textView25"

            android:layout_marginTop="12dp"
            android:layout_marginBottom="10dp"
            android:textColor="#ffffffff" />


        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/etTelephoneEdit"

            android:layout_marginBottom="10dp"
            android:textColor="#ffffffff" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="@string/BDate"
            android:id="@+id/textView26"
            android:layout_marginTop="16dp"
            android:layout_marginBottom="10dp"
            android:textColor="#ffffffff" />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/etBirthDateEdit"
            android:textColor="#ffffffff" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="@string/qualification"
            android:id="@+id/textView26"
            android:layout_marginTop="16dp"
            android:layout_marginBottom="10dp"
            android:textColor="#ffffffff" />


        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/etQualificationEdit"/>

        <!--<DatePicker-->
            <!--android:layout_width="wrap_content"-->
            <!--android:layout_height="wrap_content"-->
            <!--android:id="@+id/datePicker"-->
            <!--android:layout_alignBottom="@+id/scroll"-->
            <!--android:layout_centerHorizontal="true"-->
            <!--android:layout_marginBottom="85dp" />-->






    </LinearLayout>

    </ScrollView>




    <Button
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="@string/LogoutButtonText"
        android:id="@+id/bLogout2"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:gravity="center" />
        <!--android:layout_alignParentRight="@+id/bBack2"-->
    <!--android:layout_alignBottom="@+id/scroll"-->

    <Button
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="@string/BackButtonText"
        android:id="@+id/bBack2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentBottom="true"
        android:gravity="center" />

    <Button
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="@string/SaveButtonText"
        android:id="@+id/bSave2"
        android:layout_alignTop="@+id/bBack2"
        android:layout_centerHorizontal="true"
        android:gravity="center" />





</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

我认为这可能来自于你在onstart方法上调用showDetail这个事实,当你回到你的活动时会调用它。也许它做的是这样的:     activityToPickUpAPic - &gt; PickUpAPic - &gt;返回该活动 - &gt;     Onstart - &gt;可以开始下载您的图片 - &gt;开始活动结果 - &gt;为您的新图像充电 - >完成从服务器下载图像

当您再次调用onStart时,再次调用onStart,因此您可能希望更改此方法并仅使用Oncreate方法调用下载图片。

让我知道这是问题;)

编辑:

boolean isImageSet = false;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode==Result_Load_Image && resultCode==RESULT_OK && data!=null){

        Uri selectedImage= data.getData();

        userProfilePic.setImageURI(selectedImage);
        isImageSet = true;
    }
}

if(bitmap!=null && !isImageSet){
    userProfilePic.setImageBitmap(bitmap);
}

对于测试,你可以发表评论

//userProfilePic.setImageBitmap(bitmap);