问候,
我正在尝试在Android设备上上传图片。
我有以下代码导致图像选择器出现并检查SD卡(这就是我想要的)。
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
但接下来我该怎么办?是否有一些我可以覆盖的类来处理被点击的图像?我试过谷歌搜索但找不到任何东西。我希望有人能指出我正确的方向。
尝试了willytate的建议,但现在我不断收到以下错误:
02-08 16:58:01.574: ERROR/AndroidRuntime(16962): FATAL EXCEPTION: WebViewCoreThread
02-08 16:58:01.574: ERROR/AndroidRuntime(16962): java.lang.NullPointerException
02-08 16:58:01.574: ERROR/AndroidRuntime(16962): at android.app.Activity.startActivityForResult(Activity.java:2890)
02-08 16:58:01.574: ERROR/AndroidRuntime(16962): at prestocab.driver.Main$Uploader.upload(Main.java:172)
02-08 16:58:01.574: ERROR/AndroidRuntime(16962): at android.webkit.WebViewCore.nativeTouchUp(Native Method)
02-08 16:58:01.574: ERROR/AndroidRuntime(16962): at android.webkit.WebViewCore.access$3300(WebViewCore.java:66)
02-08 16:58:01.574: ERROR/AndroidRuntime(16962): at android.webkit.WebViewCore$EventHub$1.handleMessage(WebViewCore.java:1226)
02-08 16:58:01.574: ERROR/AndroidRuntime(16962): at android.os.Handler.dispatchMessage(Handler.java:99)
02-08 16:58:01.574: ERROR/AndroidRuntime(16962): at android.os.Looper.loop(Looper.java:143)
02-08 16:58:01.574: ERROR/AndroidRuntime(16962): at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:642)
02-08 16:58:01.574: ERROR/AndroidRuntime(16962): at java.lang.Thread.run(Thread.java:1102)
这是我的班级:
public class Uploader extends Activity{ //uploader
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
public void upload(){
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent,0);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
String selectedImagePath = data.getDataString();
Toast.makeText(Main.this, selectedImagePath, 2000);
}
}
}
非常感谢,
答案 0 :(得分:3)
Eamorr,
您需要在onActivityResult()
中捕获返回的图像。您将检查requestCode
值以确保它是您想要返回的意图。在你的情况下你放了一个1
。然后处理图像上传...就像这样:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch(requestCode) {
case 1:
imageUri = data.getData(); //get the Uri of the image from the returned data
//upload imageUri
break;
}
}
}
编辑: Eamorr。
使用此函数获取data.getDataString()
的ImagePath字符串。只需传入imageUri
。
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
startManagingCursor(cursor);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
我实际上在我的应用程序中具有相同的功能,所以我遇到了所有这些障碍><