我试图从图库上传图片。
以下是我正在使用的代码。
xml文件中的图像视图 -
<ImageView
android:id="@+id/imgView"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_marginLeft="260dp"
android:layout_weight="1"/>
java文件中的代码 -
public class AddLabReport02 extends ActionBarActivity {
private static int RESULT_LOAD_IMAGE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_lab_report02);
uploadLabReport = (Button) findViewById(R.id.uploadLabReport);
uploadLabReport.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));
}
}
}
在这里,当我点击uploadLabReport按钮时,我可以转到图库并选择图像。但是,之后图像未在imageView中设置。
我的代码中没有任何错误。有人可以看一下吗?
提前致谢:)
已编辑的代码 -
package myayubo.com.healthier;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import java.util.ArrayList;
import java.util.List;
public class AddLabReport02 extends ActionBarActivity {
private Spinner IllnessType;
private Spinner testReportType;
private Button uploadLabReport;
private static int GALLERY_PHOTO = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_lab_report02);
IllnessType = (Spinner) findViewById(R.id.selectIllnessType);
testReportType = (Spinner) findViewById(R.id.selectTest);
uploadLabReport = (Button) findViewById(R.id.uploadLabReport);
addItemsOnSpinnerIllnessType();
addTestReportType();
uploadLabReport.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
pickImage();
}
});
}
private void pickImage(){
Intent chooserIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
chooserIntent.setType("image/*");
startActivityForResult(chooserIntent, GALLERY_PHOTO);
}
// add Illness Type into spinner dynamically
public void addItemsOnSpinnerIllnessType() {
List<String> list = new ArrayList<String>();
list.add("Illness Type");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
IllnessType.setAdapter(dataAdapter);
}
// add Test Report Type into spinner dynamically
public void addTestReportType() {
List<String> list = new ArrayList<String>();
list.add("Test Report Type");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
testReportType.setAdapter(dataAdapter);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == GALLERY_PHOTO && data.getData() != null) {
String filePath = GetFilePathFromDevice.getPath(AddLabReport02.this, data.getData());
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(filePath));
}
}
@SuppressLint("NewApi")
public static final class GetFilePathFromDevice {
/**
* Get file path from URI
*
* @param context context of Activity
* @param uri uri of file
* @return path of given URI
*/
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_add_lab_report02, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(AddLabReport02.this, AddLabReport01.class));
finish();
}
}
答案 0 :(得分:2)
在按钮点击事件中调用以下方法。
private static final int GALLERY_PHOTO = 111;
private void pickImage(){
Intent chooserIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
chooserIntent.setType("image/*");
startActivityForResult(chooserIntent, GALLERY_PHOTO);
}
这是我用过的代码。根据您的需要使用它
onActivityResult()
在你的 if (resultCode == GALLERY_PHOTO && data.getData() != null) {
String filePath = GetFilePathFromDevice.getPath(AddLabReport02.this, data.getData());
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(filePath));
}
中你应该这样使用。
URI
以下是用于从public final class GetFilePathFromDevice {
/**
* Get file path from URI
*
* @param context context of Activity
* @param uri uri of file
* @return path of given URI
*/
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}
获取文件路径的类。
class SomeClass {
fooBar = (new class {
foo = 1;
inc = () => this.foo++;
}).inc
}
let foo = new SomeClass();
console.log(foo.fooBar()); // 1
console.log(foo.fooBar()); // 2
答案 1 :(得分:2)
此代码工作正常。自己搞清楚了。 :)
public class AddPrescription02 extends ActionBarActivity implements View.OnClickListener {
private ImageView imageView;
private Spinner illnessType;
private Button uploadPrescription;
private static int RESULT_LOAD_IMAGE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_prescription02);
illnessType = (Spinner) findViewById(R.id.selectIllnessType);
uploadPrescription = (Button) findViewById(R.id.uploadPrescription);
imageView = (ImageView) findViewById(R.id.imgView);
addItemsOnSpinnerIllnessType();
uploadPrescription.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, 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 && data!=null)
{
Uri selectedImage = data.getData();
imageView.setImageURI(selectedImage);
}
}
}
答案 2 :(得分:1)
1- fire意图:
startActivityForResult(new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI),
GALLERY_PIC_REQUEST);
onActivityResulr中的2-编写此代码:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == GALLERY_PIC_REQUEST) {
Uri selectedImage = data.getData();
if (selectedImage != null) {
Cursor cursor = mContext.getContentResolver().query(selectedImage, new String[]
{MediaStore.Images.ImageColumns.DATA},
null, null, null);
cursor.moveToFirst();
String path = cursor.getString(0);
Log.e("","$$$$$$$$$$ path of gallery " + path);
cursor.close();
setImageUser(path,true);
}
}
}
}
希望这会对你有帮助。
答案 3 :(得分:1)
使用这种方式可以提供帮助
private void uploadImage(){
class UploadImage extends AsyncTask<Bitmap,Void,String>{
ProgressDialog loading;
RequestHandler rh = new RequestHandler();
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Uploading Image", "Please wait...",true,true);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(Bitmap... params) {
Bitmap bitmap = params[0];
String uploadImage = getStringImage(bitmap);
HashMap<String,String> data = new HashMap<>();
data.put(UPLOAD_KEY, uploadImage);
String result = rh.sendPostRequest(UPLOAD_URL,data);
return result;
}
}
了解更多信息,请参阅here
答案 4 :(得分:1)
我使用下面的代码在ImageView上显示图像
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, CHOOSE_FROM_GALLERY);
内部onActivityResult:
if (requestCode == CHOOSE_FROM_GALLERY){
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
img_profile.setImageBitmap(thumbnail);
} else {
img_profile.setBackgroundResource(R.drawable.defaultImage);
}