Reputation: 277
why when i choose image from gallery using my device getting error but if using emulator not? note * the emulator using api 17, and my device using api 19
and after i get error i tried remove this part code from WC_Activity.java and it's working normally
how i can fix that?
if (Build.VERSION.SDK_INT < 11)
realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(this, data.getData());
// SDK >= 11 && SDK < 19
else if (Build.VERSION.SDK_INT < 19)
realPath = RealPathUtil.getRealPathFromURI_API11to18(this, data.getData());
// SDK > 19 (Android 4.4)
else
realPath = RealPathUtil.getRealPathFromURI_API19(this, data.getData());
full code
WC_Activity.java
package com.emergency.e_place;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Eggy on 5/3/2016.
*/
public class WC_Activity extends AppCompatActivity {
final String TAG = "DEBUG";
private ImageSwitcher imageview;
private int PICK_IMAGE_REQUEST = 1;
private int ACTION_IMAGE_CAPTURE=1;
Button b;
Button Camera;
int serverResponseCode = 0;
ProgressDialog dialog = null;
String realPath;
String Latitude;
String Longitude;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wc);
b = (Button) findViewById(R.id.btnSimpanWC);
Camera = (Button) findViewById(R.id.Camera);
Toolbar toolbar=(Toolbar)findViewById(R.id.toolbarWC);
setSupportActionBar(toolbar);
//ambil lokasi dari MainActivity
Intent myIntent = getIntent(); // gets the previously created intent
Latitude = myIntent.getStringExtra("Latitude"); // will return "FirstKeyValue"
Longitude= myIntent.getStringExtra("Longitude"); // will return "SecondKeyValue"
Log.d(TAG, "onLocationChanged: " + Longitude);
//ambil lokasi dari MainActivity
Button ChooseFile = (Button) findViewById(R.id.ChooseFile);
ChooseFile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
});
Button Camera = (Button) findViewById(R.id.Camera);
Camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,ACTION_IMAGE_CAPTURE);
}
});
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(WC_Activity.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
}
});
int response= uploadFile(realPath);
System.out.println("RES : " + response);
}
}).start();
}
});
}
public int uploadFile(String sourceFileUri) {
String upLoadServerUri = "http://192.168.1.101/e_place/android/upload_image_wc.php";
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File Does not exist");
return 0;
}
try { // open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
//ubah nama gambar menjadi data dari latitude_longitude
String namafoto = "/"+Latitude+"_"+Longitude+".";
String namafile = fileName.substring(0,fileName.lastIndexOf("/")) +namafoto+(fileName.substring(fileName.lastIndexOf(".")+1));
conn.setRequestProperty("uploaded_file", namafile);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ namafile + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(WC_Activity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
Toast.makeText(WC_Activity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
Toast.makeText(WC_Activity.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ImageView imageView = (ImageView) findViewById(R.id.imageView);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
if (Build.VERSION.SDK_INT < 11)
realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(this, data.getData());
// SDK >= 11 && SDK < 19
else if (Build.VERSION.SDK_INT < 19)
realPath = RealPathUtil.getRealPathFromURI_API11to18(this, data.getData());
// SDK > 19 (Android 4.4)
else
realPath = RealPathUtil.getRealPathFromURI_API19(this, data.getData());
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
Log.d(TAG, "niiih : " + realPath);
imageView.setImageBitmap(bitmap);
imageView.getLayoutParams().height = 300;
imageView.getLayoutParams().width = 300;
} catch (IOException e) {
e.printStackTrace();
}
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
RealPathUtil.java
package com.emergency.e_place;
/**
* Created by Eggy on 6/6/2016.
*/
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
public class RealPathUtil {
@SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
String filePath = "";
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ id }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
@SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null){
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index
= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
logcat
06-07 18:37:54.324 5168-5168/com.emergency.e_place E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.emergency.e_place, PID: 5168
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/12513 (has extras) }} to activity {com.emergency.e_place/com.emergency.e_place.WC_Activity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3601)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3644)
at android.app.ActivityThread.access$1400(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5511)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.emergency.e_place.WC_Activity.getImageUri(WC_Activity.java:244)
at com.emergency.e_place.WC_Activity.onActivityResult(WC_Activity.java:209)
at android.app.Activity.dispatchActivityResult(Activity.java:5514)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3597)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3644)
at android.app.ActivityThread.access$1400(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5511)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
[ 06-07 18:37:54.334 212: 362 D/ ]
RIL_onMultiClientUnsolicitedResponse:
[ 06-07 18:37:54.334 212: 362 E/ ]
unsupported multiclient unsolicited response code 1009
Upvotes: 0
Views: 470
Reputation: 1049
Try to use Intent.ACTION_PICK instead of Intent.ACTION_GET_CONTENT to pick a photo from the gallery.
Upvotes: 1