从另一个活动返回MainActivity并显示错误消息

时间:2016-06-01 09:03:23

标签: android android-activity

我在android中有点新,我想从当前活动返回主活动,并在对话框中显示错误消息。

我编写了一个脚本来调用rest api,如果没有响应的数据或错误,那么我想在对话框中返回带有该错误的主活动。

这就是我正在做的事情

txtScan.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                selectImage();
            }
        });

     private void selectImage(){
        final CharSequence[] items = { "Take Photo", "Choose from Library",
                "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 item) {
                if (items[item].equals("Take Photo")) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, REQUEST_CAMERA);
                } else if (items[item].equals("Choose from Library")) {
                    Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(
                            Intent.createChooser(intent, "Select File"),
                            SELECT_FILE);


   } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_FILE)
                onSelectFromGalleryResult(data);
            else if (requestCode == REQUEST_CAMERA)
                onCaptureImageResult(data);
        }
    }


private void onCaptureImageResult(Intent data) {
        byte[] b;

        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
        String fileName =  File.separator + System.currentTimeMillis() + ".jpg";
        filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + fileName;
        System.out.println(filePath);
        File destination = new File(Environment.getExternalStorageDirectory(),
                System.currentTimeMillis() + ".jpg");
        /*FileInputStream fis = null;
        try{
            fis = new FileInputStream(filePath);
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }*/

        b = bytes.toByteArray();
        encode_string = Base64.encodeToString(b, Base64.DEFAULT);
        System.out.println(b);
        System.out.println(encode_string);
        FileOutputStream fo;
        try {
            destination.createNewFile();
            fo = new FileOutputStream(destination);
            fo.write(bytes.toByteArray());
            fo.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try{
            obj =  new JSONObject();
            obj.put("image",encode_string);
            obj.put("api_key",API_SECRET);
            System.out.println(obj.toString());
        }catch (Throwable t){
            t.printStackTrace();
        }

       new Image().execute();
        //new LongRunningGetIO().execute();

        //ivImage.setImageBitmap(thumbnail);
    }

此功能在图像类

@Override
        protected void onPostExecute(Void r) {
            progressDialog.dismiss();
            if(responseBody == "Api key does not found/match"){
                //here i want to return to main activity with error
            }else {

                byte[] imageAsBytes = Base64.decode(encode_string.getBytes(), Base64.DEFAULT);
                //System.out.println(imageAsBytes);
                Intent intent = new Intent(getActivity().getApplicationContext(), ViewActivity.class);
                intent.putExtra("filePath", imageAsBytes);
                //intent.putExtra("data", text);
                startActivity(intent);

            }
        }

提前感谢任何想法

1 个答案:

答案 0 :(得分:1)

使用startActivityForResults将值从当前活动传递到之前的活动

致电活动

Intent intent=new Intent(MainActivity.this,CurrentActivity.class);  
                startActivityForResult(intent, 2);

处理MainActivity上的结果

@Override  
       protected void onActivityResult(int requestCode, int resultCode, Intent data)  
       {  
                 super.onActivityResult(requestCode, resultCode, data);  
                  // check if the request code is same as what is passed  here it is 2  
                   if(requestCode==2)  
                         {  
                            String error=data.getStringExtra("MESSAGE");   
                           //display error
                         }  
     }  

<强>异步

@Override
        protected void onPostExecute(Void r) {
            progressDialog.dismiss();
            if(responseBody == "Api key does not found/match"){

               Intent intent=new Intent();  
                    intent.putExtra("Error",message);  
                    setResult(2,intent);  
                    finish();
            }else {

                byte[] imageAsBytes = Base64.decode(encode_string.getBytes(), Base64.DEFAULT);
                //System.out.println(imageAsBytes);
                Intent intent = new Intent(getActivity().getApplicationContext(), ViewActivity.class);
                intent.putExtra("filePath", imageAsBytes);
                //intent.putExtra("data", text);
                startActivity(intent);

            }
        }