简体   繁体   中英

How to pass image path as parameter for an image to be taken from camera

I am passing Image as parameter in this function:

twitt.shareToTwitter(string_msg, casted_image); (void chintan.khetiya.android.Twitter_code.Twitt_Sharing.shareToTwitter(String msg, File Image_url))

Now here I am selecting image from gallery, but now I want to take pic from cam and pass it. How to do it.?

Here is the full code:

public class MainActivity extends Activity {

// Replace your KEY here and Run ,
public final String consumer_key = "trWwomp0b09ER2A8H1cQg";
public final String secret_key = "PAC3E3CtcPcTuPl9VpCuzY6eDD8hPZPwp6gRDCviLs";
File casted_image;

String string_img_url = null, string_msg = null;
Button btn, pick, cam;
EditText et;
ImageView iv;
private static int RESULT_LOAD_IMAGE = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    try {
        setContentView(R.layout.main);

        iv = (ImageView) findViewById(R.id.imageView1);

        pick = (Button) findViewById(R.id.button1);
        pick.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, 1);
            }
        });

        cam = (Button) findViewById(R.id.button2);
        cam.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent takePicture = new Intent(
                        MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(takePicture, 0);
            }
        });

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

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                onClickTwitt();
            }
        });
    } catch (Exception e) {
        // TODO: handle exception
        runOnUiThread(new Runnable() {
            public void run() {
                showToast("View problem");
            }
        });

    }
}

public void Call_My_Blog(View v) {
    Intent intent = new Intent(MainActivity.this, My_Blog.class);
    startActivity(intent);

}

// Here you can pass the string message & image path which you want to share
// in Twitter.
public void onClickTwitt() {
    if (isNetworkAvailable()) {
        Twitt_Sharing twitt = new Twitt_Sharing(MainActivity.this,
                consumer_key, secret_key);

        et = (EditText) findViewById(R.id.editText1);
        string_msg = et.getText().toString();

        twitt.shareToTwitter(string_msg, casted_image);

    } else {
        showToast("No Network Connection Available !!!");
    }
}

// when user will click on twitte then first that will check that is
// internet exist or not
public boolean isNetworkAvailable() {
    ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity == null) {
        return false;
    } else {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
    }
    return false;
}

private void showToast(String msg) {
    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();

}

protected void onActivityResult(int requestCode, int resultCode,
        Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    switch (requestCode) {
    case 0:
        if (resultCode == RESULT_OK) {
            Uri selectedImage = imageReturnedIntent.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            // file path of captured image
            String filePath = cursor.getString(columnIndex);
            // file path of captured image
            casted_image = new File(filePath);

        }
        break;
    case 1:
        if (requestCode == 1 && resultCode == RESULT_OK
                && null != imageReturnedIntent) {
            Uri selectedImage = imageReturnedIntent.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);
            casted_image = new File(picturePath);
            cursor.close();
            iv.setImageURI(selectedImage);
            // String picturePath contains the path of selected Image
            break;
        }
    }
}
}

Log.txt:

09-10 16:42:26.672: E/AndroidRuntime(1888): FATAL EXCEPTION: main
09-10 16:42:26.672: E/AndroidRuntime(1888): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=inline-data (has extras) }} to activity {chintan.khetiya.android.Twitter_sharing/chintan.khetiya.android.Twitter_sharing.MainActivity}: java.lang.NullPointerException
09-10 16:42:26.672: E/AndroidRuntime(1888):     at android.app.ActivityThread.deliverResults(ActivityThread.java:2532)
09-10 16:42:26.672: E/AndroidRuntime(1888):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:2574)
09-10 16:42:26.672: E/AndroidRuntime(1888):     at android.app.ActivityThread.access$2000(ActivityThread.java:117)
09-10 16:42:26.672: E/AndroidRuntime(1888):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:961)
09-10 16:42:26.672: E/AndroidRuntime(1888):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-10 16:42:26.672: E/AndroidRuntime(1888):     at android.os.Looper.loop(Looper.java:123)
09-10 16:42:26.672: E/AndroidRuntime(1888):     at android.app.ActivityThread.main(ActivityThread.java:3683)
09-10 16:42:26.672: E/AndroidRuntime(1888):     at java.lang.reflect.Method.invokeNative(Native Method)
09-10 16:42:26.672: E/AndroidRuntime(1888):     at java.lang.reflect.Method.invoke(Method.java:507)
09-10 16:42:26.672: E/AndroidRuntime(1888):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
09-10 16:42:26.672: E/AndroidRuntime(1888):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
09-10 16:42:26.672: E/AndroidRuntime(1888):     at dalvik.system.NativeStart.main(Native Method)
09-10 16:42:26.672: E/AndroidRuntime(1888): Caused by: java.lang.NullPointerException
09-10 16:42:26.672: E/AndroidRuntime(1888):     at android.content.ContentResolver.acquireProvider(ContentResolver.java:743)
09-10 16:42:26.672: E/AndroidRuntime(1888):     at android.content.ContentResolver.query(ContentResolver.java:256)
09-10 16:42:26.672: E/AndroidRuntime(1888):     at chintan.khetiya.android.Twitter_sharing.MainActivity.onActivityResult(MainActivity.java:155)
09-10 16:42:26.672: E/AndroidRuntime(1888):     at android.app.Activity.dispatchActivityResult(Activity.java:3908)
09-10 16:42:26.672: E/AndroidRuntime(1888):     at android.app.ActivityThread.deliverResults(ActivityThread.java:2528)
09-10 16:42:26.672: E/AndroidRuntime(1888):     ... 11 more

Intent:

Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);

To fetch that result:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
   super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

   switch(requestCode) {
   case 0:
       if (requestCode == 0 && resultCode == RESULT_OK) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");           
        // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
        Uri tempUri = getImageUri(getApplicationContext(), photo);
        // CALL THIS METHOD TO GET THE ACTUAL PATH
        casted_image = new File(getRealPathFromURI(tempUri));
        System.out.println(tempUri);
    }  
   break;
   case 1:
       //handle gallery code here

        break;
  }
}

public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}

public String getRealPathFromURI(Uri uriTemp) {
    Cursor cursor = getContentResolver().query(uriTemp, null, null, null, null); 
    cursor.moveToFirst(); 
    int mIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
    return cursor.getString(mIndex); 
}

Add this in your manifest.xml.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

to ask for a specific file location to the camera you have to do like this:

     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
     cameraCaptureLocation = new File("... location goes here ...");
     intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraCaptureLocation));
     startActivityForResult(intent, REQUEST_CAMERA);

But there is a problem, since I am using both cam and gallery at the same place, the function onActivityResult is already there. What to do now.?

then you have to use the requestCode to filter where that activity result come from. You pass one integer for REQUEST_CAMERA and another for REQUEST_GALLERY

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM