android使用onActivityResult()将值传递给类

时间:2013-11-08 07:18:53

标签: java android

仍然是android / java dev的新手,但是到了那里,我已经创建了一个将图像上传到php服务器但是图像当前是硬编码的类,我想通过选择图库中的图像来更进一步然后上传它。

我不确定如何使用onActivityResult()并将结果传递给类?希望你能帮忙。

onClick事件在profile.java上,上传脚本在ImageUpload.java上,所以需要从profile到ImageUpload获取结果

另外,我如何将以下内容更改为正确的代码?

       Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);           
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
    byte [] byte_arr = stream.toByteArray();
    String image_str = Base64.encodeBytes(byte_arr);
    final ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();

    nameValuePairs.add(new BasicNameValuePair("image",image_str));
    nameValuePairs.add(new BasicNameValuePair("username",IMService.USERNAME));

     Thread t = new Thread(new Runnable() {              
    public void run() {
          try{
                 HttpClient httpclient = new DefaultHttpClient();
                 HttpPost httppost = new HttpPost("http://127.0.0.1/upimage.php");
                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                 HttpResponse response = httpclient.execute(httppost);
                 final String the_string_response = convertResponseToString(response);
                 runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            Toast.makeText(UserProfile.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();                          
                        }
                    });

             }catch(final Exception e){


                   System.out.println("Error in http connection "+e.toString());
             }  
    }

2 个答案:

答案 0 :(得分:0)

// try this way
final private int PICK_IMAGE_USER_AVATAR = 1;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE_USER_AVATAR);

private String selectedImagePathPhotoUpload;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
       if (requestCode == PICK_IMAGE_UPLOAD_PHOTO) {
            selectedImagePathPhotoUpload = getAbsolutePath(data.getData());
            imgUploadPhoto.setVisibility(View.VISIBLE);
            imgUploadPhoto.setImageBitmap(decodeFile(selectedImagePathPhotoUpload));
        }
     }

}

public String getAbsolutePath(Uri uri) {
    String[] projection = { MediaColumns.DATA };
        @SuppressWarnings("deprecation")
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if (cursor != null) {
        int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } else
    return null;
}

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 = 70;

            // 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;

}

答案 1 :(得分:0)

请参阅此示例代码ImageGalleryDemoActivity有一个按钮Loadimage,在其click事件中,它激活一个意图,从图库中选择图片并将结果返回到activityResult方法。

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class ImageGalleryDemoActivity extends Activity {


    private static int RESULT_LOAD_IMAGE = 1;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
    }


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

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

        }


    }
}