Android:当第二个活动中的方法成功执行并关闭时,在主活动中重新加载方法

时间:2017-01-02 15:40:35

标签: android android-intent android-activity

我正在尝试构建一个可让您更改个人资料照片的应用。当应用程序第一次打开时,它包含当前配置文件pic的Networkimageview和更改图片的按钮。按下按钮后,将启动一个新的Activity,使用户可以从图库中选择图像并上传到服务器。

上传完成后,新的Activity会关闭,应用会返回MainActivity。当图像从新活动成功上传并关闭时,如何让MainActivity重新加载刚刚上传到服务器的图像?这是我的代码

这里是MainActivity.java

public class MainActivity extends AppCompatActivity {
    ImageLoader mImageLoader;
    NetworkImageView mNetworkImageView;
    private Button buttonChoose;
    static final int PROFILE_PICTURE_REQUEST = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        buttonChoose = (Button) findViewById(R.id.buttonChoose);

        mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView);

        loadImage();
    }

    private String url = "http://10.0.2.2/images/0.jpg";

    private void loadImage() {
        mImageLoader = CustomVolleyRequest.getInstance(this).getImageLoader();
        mNetworkImageView.setImageUrl(url, mImageLoader);
    }

    public void newActivity(View view) {
        Intent profileIntent = new Intent(this, Activity2.class);
        startActivityForResult(profileIntent, PROFILE_PICTURE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PROFILE_PICTURE_REQUEST) {
            if (resultCode == RESULT_OK) {
                loadImage();
            }
        }
    }
}

第二项活动Activity2.java

public class Activity2 extends AppCompatActivity implements View.OnClickListener {
    private Bitmap bitmap;
    private ImageView imageView;
    private int PICK_IMAGE_REQUEST = 1;
    private String UPLOAD_URL ="http://10.0.2.2/uploadd.php";
    private String KEY_IMAGE = "image";
    private Button buttonUpload;

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

        imageView  = (ImageView) findViewById(R.id.imageView);
        buttonUpload = (Button) findViewById(R.id.buttonUpload);
        buttonUpload.setOnClickListener(this);

        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }

    public String getStringImage(Bitmap bmp) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }

    public void uploadImage() {
        //Showing the progress dialog
        final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        loading.dismiss();
                        Toast.makeText(Activity2.this, s, Toast.LENGTH_LONG).show();
                        Intent returnIntent = new Intent();

                        setResult(RESULT_OK,returnIntent);
                        finish();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        //Dismissing the progress dialog
                        loading.dismiss();
                        //Showing toast
                        Toast.makeText(Activity2.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                //Converting Bitmap to String
                String image = getStringImage(bitmap);
                //Creating parameters
                Map<String, String> params = new Hashtable<String, String>();
                //Adding parameters
                params.put(KEY_IMAGE, image);

                //returning parameters
                return params;
            }
        };

        //Creating a Request Queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue.add(stringRequest);
    }

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

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri filePath = data.getData();
            try {
                //Getting the Bitmap from Gallery
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                //Setting the Bitmap to ImageView
                imageView.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onClick(View v) {
        if(v == buttonUpload){
            uploadImage();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

如果您在成功上传图像后完成Activity2,则需要在意图中添加一些额外内容,这些附加内容将传递给MainActivity启动器活动。

因此onResponse函数的uploadImage()段应如下所示。将filePath变量声明为public,以便您也可以在此处使用它。

// Declare filePath as public 
Uri filePath;

@Override
public void onResponse(String s) {
    loading.dismiss();
    Toast.makeText(Activity2.this, s, Toast.LENGTH_LONG).show();
    Intent returnIntent = new Intent();
    returnIntent.putExtra("UPDATED_PIC", filePath.toString());

    setResult(RESULT_OK,returnIntent);
    finish();
}

现在从MainActivity处理retuneIntent以获取filePath并从中加载图片。所以onActivityResult可能看起来像 -

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PROFILE_PICTURE_REQUEST) {
        if (resultCode == RESULT_OK) {
            if(data != null) {
              Uri filePath = Uri.parse(extras.getString("UPDATED_PIC"));
              try {
                  //Getting the Bitmap from Gallery
                  Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                  // Setting the Bitmap to ImageView
                  mNetworkImageView.setImageBitmap(bitmap);
              } catch (IOException e) {
                  e.printStackTrace();
              }
            }
        }
    }
}