NullPointerException when user choose the background from gallery [duplicate] - android

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Good Day, I would like to allow user to change background in my app. Try to make it, but face with that problem:
12-09 06:22:15.874 20413-20413/com.vadimsleonovs.horoscope E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.vadimsleonovs.horoscope, PID: 20413
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/20 flg=0x1 }} to activity {com.vadimsleonovs.horoscope/com.vadimsleonovs.horoscope.activities.SettingsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.setBackground(android.graphics.drawable.Drawable)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3539)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582)
at android.app.ActivityThread.access$1300(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.setBackground(android.graphics.drawable.Drawable)' on a null object reference
at com.vadimsleonovs.horoscope.activities.SettingsActivity.onActivityResult(SettingsActivity.java:76)
at android.app.Activity.dispatchActivityResult(Activity.java:6135)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3535)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582) 
at android.app.ActivityThread.access$1300(ActivityThread.java:144) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5221) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
The code is that:
public class SettingsActivity extends AppCompatActivity {
Button mBcgBtn;
private static int RESULT_LOAD_IMAGE = 1;
String picturePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mBcgBtn = (Button) findViewById(R.id.bcg_clr_btn);
mBcgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
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 };
try {
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
}catch(NullPointerException e){
e.printStackTrace();
}
LinearLayout mHomeLayout = (LinearLayout) findViewById(R.id.activity_home);
LinearLayout mDetailsPageLayout = (LinearLayout) findViewById(R.id.activity_details_page);
Drawable d = new BitmapDrawable(getResources(), BitmapFactory.decodeFile(picturePath));
mHomeLayout.setBackground(d);
}
}
}
Also, I added write external storage permission, and this code works perfectly in "blank project", but in my project not working at all.

It says mHomeLayout is null. ie, There is no LinearLayout with id activity_home in activity_settings layout.
So what you need to do is save the selected drawable path in storage preferences from Settings Activity. And load it when you open the other activity which has the Linearlayout with id activity_home. And then set it as it's background.
I hope that's your problem.

Related

Blank Screen showing up after Image Selected from Gallery

I am trying to get an image into the ImageView but whenever I click a picture on the Gallery the app shows a blank screen and closes down.
This ImageView is in a fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_auction_add, container, false);
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_imageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageSelectAction(v);
}
});
dateTimeAction(v);
return v;
}
private void imageSelectAction(View v) {
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_image = v.findViewById(R.id.auction_add_imageView);
choosePicture();
}
private void choosePicture() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
if (data != null && data.getData() != null) {
Uri selectedImageUri = data.getData();
auction_add_image.setImageURI(selectedImageUri);
}
}
}
}
The Inital Declaration
public class auction_add extends Fragment {
private static final int SELECT_PICTURE = 10;
private static final int PERMISSION_CODE = 11;
ImageButton auction_add_imageViewButton;
//References to all Auction Add Page EditText
EditText auction_add_itemNameTxt;
EditText auction_add_descriptionTxt;
EditText auction_add_initialPriceTxt;
EditText auction_add_startTimeTxt;
EditText auction_add_endTimeTxt;
//Reference to ImageView
private ImageView auction_add_image;
final Calendar myCalendar = Calendar.getInstance();
Would Appreciate the help thanks!
Edit:
Followed is the error on the Run tab of Android Studio
W/System: A resource failed to call close.
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.projectcrest, PID: 5618
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=242868079, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:31 flg=0x1 }} to activity {com.example.projectcrest/com.example.projectcrest.pages.LandingPage}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:5015)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference
at com.example.projectcrest.fragments.auction_add.onActivityResult(auction_add.java:155)
at androidx.fragment.app.FragmentManager$9.onActivityResult(FragmentManager.java:2905)
at androidx.fragment.app.FragmentManager$9.onActivityResult(FragmentManager.java:2885)
at androidx.activity.result.ActivityResultRegistry.doDispatch(ActivityResultRegistry.java:377)
at androidx.activity.result.ActivityResultRegistry.dispatchResult(ActivityResultRegistry.java:336)
at androidx.activity.ComponentActivity.onActivityResult(ComponentActivity.java:624)
at androidx.fragment.app.FragmentActivity.onActivityResult(FragmentActivity.java:164)
at android.app.Activity.dispatchActivityResult(Activity.java:8310)
at android.app.ActivityThread.deliverResults(ActivityThread.java:5008)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056) 
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
I/Process: Sending signal. PID: 5618 SIG: 9
By looking into the exception it seems that the App is crashing in #onActivityResult function at line auction_add_image.setImageURI(selectedImageUri); due to NPE (Null Pointer Exception). This expection/crash is caused since the auction_add_image object has null value instead of an ImageView.
After taking an close look into your code, I think the issue has occured due to following code:
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_imageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageSelectAction(v);
}
});
Note that in #onClick function you are passing view v on which you are going to perform the #findViewById operation. Here the passed view v refers to the auction_add_imageViewButton instead of the v you have captured above.
I would suggest to modify the code as below (just rename the v variable in #onClick function):
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_imageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View buttonView) {
imageSelectAction(v);
}
});
This way the variable name collision could be avoided and the error would be resolved.
Also, in case this does not solve your problem, then please check whether the #findViewById is returning an ImageView instead of null. In case the Id provided to #findViewById is not present on the screen or in the child views of view (on which the #findViewById) is being performed then the #findViewById will return null value.
Also, check whether you have assigned null value to auction_add_image in anywhere your code.

Set an image on imageview using arraylist strings and strings

Brief Description: This is a speech to text app, if the word they spoken is also a word in the database file then it will also have an image of that word spoken.
So I attempted to use imageResource to set the image but it failed, as it is using an ArrayList and a String for the first part of the imageResoruce function. which is assumed to be causing the error message as it crashes when i open the application.
Main.java
public class Main extends Activity {
private static final int VR_Request = 100;
private final String pathname = ".png"; //path name of an image file stored in the drawable folder
TextView speechInput;
TextView matchOrNot;
String[] wordBank; //
ArrayList<String> wordBANK;
ImageButton speechBtn;
ImageView image;
Resources res = getResources();
int resID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reverse_pictionary);
speechInput = (TextView) findViewById(R.id.english_word);
matchOrNot = (TextView) findViewById(R.id.matchOrNot);
wordBank = getResources().getStringArray(R.array.Words);
speechBtn = (ImageButton) findViewById(R.id.mic_pic_button);
wordBANK = new ArrayList<String>(Arrays.asList(wordBank));
image = (ImageView) findViewById(R.id.imageOfword);
}
public void onMic(View view) {
promptSpeechInput();
}
public void promptSpeechInput() {
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == VR_Request && resultCode == RESULT_OK) {
ArrayList<String> result = intent.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if(wordBANK.contains(result.get(0).toLowerCase())){
speechInput.setText(result.get(0).toUpperCase());
matchOrNot.setText("MATCH");
resID = res.getIdentifier(result.get(0).toLowerCase()+pathname, "drawable", getPackageName());
image.setImageResource(resID);
}else {
speechInput.setText(result.get(0));
matchOrNot.setText("NO MATCH");
}
}
super.onActivityResult(requestCode, resultCode, intent);
}
}
RunTime Error Message:
08-10 21:07:37.678 2344-2344/com.example.speechtotext E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.speechtotext, PID: 2344
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.speechtotext/com.example.speechtotext.Main}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at com.example.speechtotext.Main.<init>(Main.java:38)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Any Ideas? Thank you in advance!
Move the code :
Resources res = getResources();
into the onCreate() method.
You can not use getResources() before the activity created.

NullPointer with using Facebook SDK

I using Facebook SKD in my app and I have next error:
My callBackmanager in onActivityResult() method is null and I get NullPointerException
This is my code:
parent.findViewById(R.id.fb_login_button).setOnClickListener(this);
Where
R.id.fb_login_button - my custom button for fb.
When I click this button, my listener call this method:
private void onFacebookButtonClick() {
initFacebook(getView());
mFacebookLoginButton.performClick(); // this is button from SDK, Visibility - GONE
}
And this initFacebook(View parent) method:
callbackManager = CallbackManager.Factory.create();
mFacebookLoginButton = (LoginButton) parent.findViewById(R.id.login_button);
mFacebookLoginButton.setReadPermissions("public_profile");
mFacebookLoginButton.setFragment(this);
mFacebookLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
String userId = loginResult.getAccessToken().getUserId();
trySocialLogin(userId, Constants.PROVIDER_FACEBOOK);
}
#Override
public void onCancel() {
Log.e("FB", "onCancel()");
}
#Override
public void onError(FacebookException exception) {
exception.printStackTrace();
}
});
And this code from onActivityResult():
callbackManager.onActivityResult(requestCode, resultCode, data); // callbackManager is null here - why?
Add logcat:
Fatal Exception: java.lang.RuntimeException: Unable to resume activity {com.nashkvartal/com.nashkvartal.StartScreenActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=129742, result=0, data=null} to activity {com.nashkvartal/com.nashkvartal.StartScreenActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'boolean com.facebook.CallbackManager.onActivityResult(int, int, android.content.Intent)' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3287)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3318)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2661)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1512)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5691)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
Caused by java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=129742, result=0, data=null} to activity {com.nashkvartal/com.nashkvartal.StartScreenActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'boolean com.facebook.CallbackManager.onActivityResult(int, int, android.content.Intent)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3887)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3269)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3318)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2661)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1512)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5691)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
Caused by java.lang.NullPointerException: Attempt to invoke interface method 'boolean com.facebook.CallbackManager.onActivityResult(int, int, android.content.Intent)' on a null object reference
at com.nashkvartal.fragments.LoginFragment.onActivityResult(LoginFragment.java:105)
at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:176)
at com.nashkvartal.StartScreenActivity.onActivityResult(StartScreenActivity.java:74)
at android.app.Activity.dispatchActivityResult(Activity.java:6344)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3883)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3269)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3318)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2661)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1512)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5691)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
UPD - added onActivityResult() full code
#Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if (currentProvider == Constants.PROVIDER_FACEBOOK) {
callbackManager.onActivityResult(requestCode, resultCode, data); // I catch NullPointer here
}
super.onActivityResult(requestCode, resultCode, data);
}
As per newer Facebook SDK. You should override onActivityResult with super.
For newer SDK use:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode,
resultCode, data);
}
And make sure For the login to work, Your onActivityResult() method should be outside the FacebookCallback anonymous class.
EDIT 1
As from your code you need to init SDK before setContentView. Currently in your code it is called below setContentView so change it.
Like this.
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_start_screen);

how to set the image to imageview from gallery ? Please tell me how to achieve it ? Thanks advance

Here is my MainActivity.java
public class MainActivity extends AppCompatActivity {
int PICK_IMAGE_REQUEST=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn= (Button) findViewById(R.id.btnImgGet);
btn.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 Picture"), PICK_IMAGE_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK){
if(requestCode==PICK_IMAGE_REQUEST && null != data)
{
//Toast.makeText(getApplicationContext(),"onActivityResult working",Toast.LENGTH_SHORT).show();
try {
Uri uri = data.getData();
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri,projection,null,null,null);
cursor.moveToFirst();
int column_index=cursor.getColumnIndex(projection[0]);
String path = getString(column_index);
cursor.close();
// Log.d("Image Path is->",path);
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(path));
}catch (NullPointerException ex){ex.printStackTrace();}
}
}
}
}
here is the Logcat..
01-23 18:13:41.767 7528-7528/com.example.manpreetsingh.gridviewimages W/ResourceType: No package identifier when getting value for resource number 0x00000000
01-23 18:13:41.778 7528-7528/com.example.manpreetsingh.gridviewimages D/AndroidRuntime: Shutting down VM
01-23 18:13:41.834 7528-7528/com.example.manpreetsingh.gridviewimages E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.manpreetsingh.gridviewimages, PID: 7528
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:21776 flg=0x1 }} to activity {com.example.manpreetsingh.gridviewimages/com.example.manpreetsingh.gridviewimages.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.app.ActivityThread.deliverResults(ActivityThread.java:3659)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3702)
at android.app.ActivityThread.access$1300(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1366)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:299)
at android.content.res.Resources.getString(Resources.java:385)
at android.content.Context.getString(Context.java:377)
at com.example.manpreetsingh.gridviewimages.MainActivity.onActivityResult(MainActivity.java:68)
at android.app.Activity.dispatchActivityResult(Activity.java:6218)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3655)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3702)
at android.app.ActivityThread.access$1300(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1366)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
01-23 18:13:44.494 7528-7528/? I/Process: Sending signal. PID: 7528 SIG: 9
You have multiple problems here.
Tactically, you are calling getString() on the Activity, not the Cursor, which will not work.
Beyond that, almost everything inside onActivityResult() is incorrect. The Uri you get is not necessarily in the MediaStore, and MediaStore does not have to offer you a path that you can read.
Please use an image loading library, like Picasso, to take the Uri and put the image in your ImageView.
If you insist upon doing this yourself, fork a background thread, and use getInputStream() on a ContentResolver, passing that stream to decodeStream() on BitmapFactory.

onActivityResult in ViewPager fragment crash

I have 4 fragments in a ViewPager in an activity. In one of the fragments I start an activity for result, and always get a crash when coming back to the first activity. The error is:
Process: com.mycom.android.myapp.debug, PID: 13505
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=196610, result=0, data=Intent { }} to activity {com.mycom.android.myapp.debug/com.mycom.android.myapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.Fragment.onActivityResult(int, int, android.content.Intent)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3539)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582)
at android.app.ActivityThread.access$1300(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.Fragment.onActivityResult(int, int, android.content.Intent)' on a null object reference
at com.mycom.android.myapp.fragment.AgendaFragment.onActivityResult(AgendaFragment.java:415)
Although I tried commenting out the body of onActivityResult function of the fragment, still happens. It looks like the fragment is not restored in time.
How should I go about dealing with this? tks
Update: this is my onActivityResult in the problematic fragment. There are child fragments and I'm sure there are #Override in those fragments as well. I try commenting the body of the loop, still no luck. Any more ideas? thanks.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
LOGD(TAG, "onActivityResult called BEFORE calling super");
super.onActivityResult(requestCode, resultCode, data);
LOGD(TAG, "onActivityResult called AFTER calling super");
/**we need to broadcast this event to nested child fragments */
List<Fragment> fragments = getChildFragmentManager().getFragments();
if (!CollectionUtils.isEmpty(fragments)) {
for (Fragment fragment : fragments) {
if(fragment!=null){
LOGD(TAG, "fragment not null");
fragment.onActivityResult(requestCode, resultCode, data);
}else
LOGD(TAG,"fragment IS null");
}
}
}
Update 2: since I startActivity() in a nested fragment of AgendaFragment, following pvshnik's answer at onActivityResult() not called in new nested fragment API
Inside ListFragment, which is a child fragment of AgendaFragment, I did
getParentFragment().startActivityForResult(intent, requestCode);
You can try like this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
List<Fragment> listOfFragments = getChildFragmentManager().getFragments();
if(listOfFragments.size()>=1){
for (Fragment fragment : listOfFragments) {
if(fragment instanceof yourFragmentName){
fragment.onActivityResult(requestCode, resultCode, data);
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}

Categories

Resources