在Android中,我想从我的画廊获得的图像,并将其转换为Base64,但该文件路径为空引用
问题描述:
这是我在那里的活动,这是在发生的事情:在Android中,我想从我的画廊获得的图像,并将其转换为Base64,但该文件路径为空引用
package com.example.alexlevine.guestify;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
public class ProfileActivity extends AppCompatActivity implements View.OnClickListener, NavigationView.OnNavigationItemSelectedListener {
TextView t3;
Button chooseImg, uploadImg;
ImageView imgView;
int PICK_IMAGE_REQUEST = 1;
Uri filePath;
String path;
String encodedString;
// private FirebaseUser user;
private FirebaseAuth fbAuth;
/*private TextView textViewUserEmail;
private Button buttonLogout;
private DatabaseReference dbRef;*/
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
public static String b64;
/**
* message : enrollment processed successfully
* data : {"enrollment_id":"ahBzfmNodWlzcGRldGVjdG9ychcLEgpFbnJvbGxtZW50GICAgID5r4YKDA"}
* success : true
*/
private String message;
//private DataBean data;
private boolean success;
//FirebaseDatabase storage = FirebaseDatabase.getInstance();
public ProfileActivity() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
b64 = null;
mDrawerLayout = (DrawerLayout) findViewById(R.id.nav);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
setNavigationViewListner();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
chooseImg = (Button)findViewById(R.id.chooseImg);
uploadImg = (Button)findViewById(R.id.uploadImg);
imgView = (ImageView)findViewById(R.id.imgView);
chooseImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
}
});
EnrollImg ei = new EnrollImg();
new EnrollImg().execute();
String r = EnrollImg.resulttouse;
//t3.setText(r);
Gson gson = new Gson();
// DataBean db = gson.fromJson(r, DataBean.class);
//String enrollid = db.getEnrollment_id();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
try {
final Uri imageUri = data.getData();
path = getPath(imageUri);
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imageUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
path = cursor.getString(columnIndex);
cursor.close();
//Toast.makeText(PersonalDetails.this,imagepath, Toast.LENGTH_SHORT).show();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
b64 = BitMapToString(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
private void saveUserInformation() {
//FirebaseUser user = fbAuth.getCurrentUser();
//dbRef.child(user.getUid()).setValue("exp");
}
private void setNavigationViewListner() {
NavigationView navigationView = (NavigationView) findViewById(R.id.navdrawer);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_account: {
break;
}
case R.id.create: {
break;
}
case R.id.org_manage: {
break;
}
case R.id.join: {
break;
}
case R.id.history: {
break;
}
case R.id.logout: {
fbAuth.signOut();
finish();;
startActivity(new Intent(this, LoginActivity.class));
break;
}
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View view) {
}
public String BitMapToString(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos);
byte[] b = baos.toByteArray();
String temp = Base64.encodeToString(b, Base64.DEFAULT);
return temp;
}
String encodeImage(Bitmap bitmap) {
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 3;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload
// easy
try {
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
} catch (Exception e1) {
// TODO Auto-generated catch block
}
//System.out.println("SIZE OF BITMAP " + sizeOf(bitmap));
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
try {
encodedString = Base64.encodeToString(byte_arr, 0);
} catch (Exception e) {
// TODO Auto-generated catch block
}
return encodedString;
}
}
这里是logcat的:
08-20 21:24:53.147 26753-26753/com.example.alexlevine.guestify
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.alexlevine.guestify, PID: 26753
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null,
request=1, result=-1, data=Intent {
dat=content://com.google.android.apps.docs.storage/document/acc=1;doc=1715
flg=0x1 }} to activity
{com.example.alexlevine.guestify/com.example.alexlevine.guestify.
ProfileActivity}: java.lang.NullPointerException: Attempt to invoke virtual
method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a
null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4323)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4366)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1649)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.TextView.setText(java.lang.CharSequence)' on a null
object reference
at com.example.alexlevine.guestify.ProfileActivity.onActivityResult
(ProfileActivity.java:143)
at android.app.Activity.dispatchActivityResult(Activity.java:7237)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4319)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4366)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1649)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
08-20 21:24:53.147 26753-26753/com.example.alexlevine.guestify
E/UncaughtException: java.lang.RuntimeException: Failure delivering result
ResultInfo{who=null, request=1, result=-1, data=Intent {
dat=content://com.google.android.apps.docs.storage/document/acc=1;doc=1715
flg=0x1 }} to activity
{com.example.alexlevine.guestify/com.example.alexlevine.guestify.
ProfileActivity}: java.lang.NullPointerException: Attempt to invoke virtual
method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a
null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4323)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4366)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1649)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.TextView.setText(java.lang.CharSequence)' on a null
object reference
at com.example.alexlevine.guestify.ProfileActivity.onActivityResult
(ProfileActivity.java:143)
at android.app.Activity.dispatchActivityResult(Activity.java:7237)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4319)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4366)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1649)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
我看了几个网上论坛和尝试了我使用来获取和转换图像并没有什么方法很多变化似乎是工作。我也不确定null是否与我在特定或我的代码中测试的图像有关;可能是代码,因为它甚至在主页上也有错误。 有人可以看看这个吗?谢谢!
答
请看看
{com.example.alexlevine.guestify/com.example.alexlevine.guestify。 ProfileActivity}:显示java.lang.NullPointerException:尝试调用 虚拟方法 '无效 android.widget.TextView.setText(java.lang.CharSequence中)' 上的空 对象引用
我认为该错误与图像无关,但当您将文本设置为文本视图时,文本视图为空。
答
您需要初始化您的TextView.It为您的TextView引发NullPointerException而不是图像相关的代码。首先初始化你的textview然后尝试setText进去。