Android: NullPointerException when using Extras in Intents - android

Please I get a NullPoiterException when I try to get the extras form the intent.
The error is thrown exactly when I call
int posizione2 =Integer.parseInt((getIntent().getExtras().getString(Intent.EXTRA_TEXT)));
Any help very much appreciated!
private void aggiungiImm(View arg1, int arg2) {
Intent i=newintent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
i.putExtra(Intent.EXTRA_TEXT, Integer.toString(arg2));
startActivityForResult(i, PICK_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent data) {
Uri contactData=null;
if (requestCode==PICK_REQUEST) {
if (resultCode==RESULT_OK) {
contactData=data.getData();
int posizione2 =Integer.parseInt((getIntent().getExtras().getString(Intent.EXTRA_TEXT)));
EDITED:
No solution so far.
Can it be that the problem is related to the fact that this is an Implicit Intent??

Try to use data.getStringExtra(Intent.EXTRA_TEXT)

instead of
int posizione2 =Integer.parseInt((getIntent().getExtras().getString(Intent.EXTRA_TEXT)));
Try that:
Bundle extras = getIntent().getExtras();
if (extras==null) {
Log.e( "", "No extras provided" );
return;
}
String myText = extras.getString(Intent.EXTRA_TEXT);
if (myText==null) {
Log.e( "", "No text provided" );
return;
}
int posizione2 = Integer.parseInt(myText);
Should help you to see what is giving the exception...
By the way, your returned text (if that text is comming as result from the other activity) will be available in the Intent passed to the function. So you should be doing:
if (data.getString(Intent.EXTRA_TEXT)==null) {
Log.e( "", "No text provided" );
return;
}
int posizione2 = Integer.parseInt(data.getString(Intent.EXTRA_TEXT));
The getIntent() method will give you the intent with which the calling activity had been started. No the intent holding the result of the called activity.
If you are getting the No text provided message, that means you have not properly returned the result in the activity that computes it.

Related

Random signal 11 (SIGSEGV)

For few days now i got SIGSEGV errors at random points in my app. It crashed when i do nothing.
I started taking apart code to see which line was causing this segmentation, and was most shocked when i found out that it was: ( drum roll, please )
Activity.setResult(Activity.OK,intent)
WHAT? This still doesn't make ANY sense to me at all! In the line below i will show you my code before and after and can anyone tell me WHY the SIGSEGV was happening?
Before
CommentActivity:
val comments = ArrayList<Comment>()
comments.add(comment)
/*Set the results*/
val intent = Intent()
intent.putExtra("comment_result", Utils.General.serializeToJson(comments))
this.setResult(Activity.RESULT_OK, intent)
this.finish()
MainActivity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
//catch data from CommentActivity
case (INTENT_COMMENT): {
if (resultCode == RESULT_OK) {
String comments = intent.getExtras().getString("comment_result");
if (comments != null && !comments.isEmpty()) {
/*Save the instance to the database and expect the database observable to call the upload thread*/
Type type = new TypeToken<ArrayList<Comment>>() {}.getType();
ArrayList<Comment> list = Utils.General.Companion.deserializeFromJson(comments, type);
/*Save the instance to the database and expect the database observable to call the upload thread*/
DataSource.INSTANCE.saveComments(list);
} else {
showToast(getResources().getString(R.string.picture_lost), Toast.LENGTH_SHORT);
}
}
break;
}
==== This crashed in MainActivity after between 10secs and 1 minute =====
After - No Crash
CommentActivity:
/*Set the results*/
DataSource.saveComments(comments)
this.finish()

getIntent().getExtras() is some times null in API level 21?

As per some google crash report of my app i am seeing NullPointerException,
"Attempt to invoke virtual method int android.os.Bundle.getInt(java.lang.String) on a null object reference" but i have made sure and cross checked that intent to that activity always some Extras is set. Can some one suggest me what might be wrong, i am suspecting not overriding onNewIntent, is causing problem but my activity is launched with "noHistory =true" flag so onNewIntent is never called?
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_alert_dialog);
mBackToMain = false;
mDoExit = false;
int stringMessageId = getIntent().getExtras().getInt(name);
String stringMessage = getIntent().getExtras().getString(fullName);
initFields(name,fullName);
}
#Override
protected void onNewIntent(Intent intent)
{
mLog.d("WarningActivity","on new Intent triggered "+ intent.getExtras());
super.onNewIntent(intent);
int stringMessageId = getIntent().getExtras().getInt(name);
String stringMessage = getIntent().getExtras().getString(fullName);
initFields(name,fullName);
}
You may be putting extras right and something else goes wrong so make sure that the extras is not null by checking it first like so:
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if(extras != null) {
if(extras.containsKey("your key here")) {
int x = extras.getInt("your key here");
}
else {
Log.d("extras", "No Key");
}
} else {
Log.d("extras", "Null Extras");
}
and then check your logcat and you should see what's really going on

in app billing i get response in response handler class so how I check it in activity?

i am facing problem since two day, i get response RESULT_OK but how can i check it into activity. after this i have to go to download window function, it is not showing dialog.please help me out thanks in advance...:(
ResponseHandler rep = new ResponseHandler();
String ecase=rep.responsecheck;
rep.register(mDungeonsPurchaseObserver);
System.out.println(ecase);
if(ecase!=null){
if(ecase.matches("RESULT_OK")){/
Toast.makeText(this,ecase, Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(this,ecase, Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(this,ecase, Toast.LENGTH_LONG).show();
}`
but this working is in oncreate and get null.
Try this
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode)
{
case REQUEST_CONNECT_DEVICE:
//Body what ever u want to do....
}}

onactivityforresult not called after contactscontract action_edit

I have a ListActivity which displays all the aggregate contacts. When the user clicks one, my code calls startActivityForResult. All this works properly. When the user finishes editing, I want my ListActivity to be displayed again. Instead, the "people" activity gets displayed. Similarly, my onActivityResult function never gets called.
Here is the code handling the click:
#Override
public void onItemClick (AdapterView<?> parent, View view, int position, long id)
{
Cursor cur = ((SimpleCursorAdapter)parent.getAdapter()).getCursor();
cur.moveToPosition (position);
String key = cur.getString (2); // "2" is the col containing the LOOKUP_KEY
System.out.println ("clicked " + key);
// make intent to edit contact
Intent intent = new Intent (Intent.ACTION_EDIT);
intent.setData (Uri.parse (ContactsContract.Contacts.CONTENT_LOOKUP_URI + "/" + key));
startActivityForResult (intent, 2);
}
And I also have an onActivityResult function:
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
System.out.println ("request " + requestCode + ", result " + resultCode);
}
Any suggestions?
I filed a bug to android about this. Someone looked at it and responded that there is an undocumented workaround. From the bug report:
The undocumented workaround is to call putExtra("finishActivityOnSaveCompleted", true); on the ACTION_EDIT Intent.
However, as this is undocumented, I have no idea which Android version(s) will use it.
I tried it and it works for the version of Android I'm using: 4.1.2. See issue 39262 for more info.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == 2) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
// Do something with the contact here (bigger example below)
}
}
}
Replace your onActivity result to this. for request code get after
they will work
Add
super.onActivityResult(requestCode, resultCode, data);
in OnActivtyResult().
Make sure you are calling startActivityForResult from an activity, then only your onActivityResult will be called. For example, if you have the similar code in an fragment, the onActivityResult will never be called.

How to go back from calling intent

I call camera to take a picture. But I cannot go back to my own original activity after taking the picture. What's the problem? Thank you.
public void addEntry(View view)
{
String EntryName=RegisterName.toString();
Toast.makeText(this, EntryName, Toast.LENGTH_LONG);
Intent addEntryintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(getFilesDir(),EntryName);
registeryFileUri = Uri.fromFile(file);
addEntryintent.putExtra(MediaStore.EXTRA_OUTPUT, registeryFileUri);
startActivityForResult(addEntryintent,TAKE_PICTURE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PICTURE)
{
if (data != null)
{
Toast.makeText(this, "Successfully Registered!", Toast.LENGTH_LONG);
ImageView Registerimage= (ImageView)findViewById(R.id.RegisterPicture);
Registerimage.setImageURI(registeryFileUri);
}
}
}
It took me a while to get it working and I have made several things and finally it works. I can't tell certainly which of the things I did is the solution to the problem, but they all together form the working solution.
There are multiple reasons why the camera activity does not return back. Two major ones are:
path for the new picture is invalid, or non-existing, or it can't be created
application got suspended and saved path get lost.
So here is my code solving all these problems, all together working.
First I created helper class ImageServices:
class ImageServices {
private static String getTempDirectoryPath(Context ctx) {
File cache;
// SD Card Mounted
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
cache = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
"/Android/data/" + ctx.getPackageName() + "/cache/");
}
// Use internal storage
else {
cache = ctx.getCacheDir();
}
// Create the cache directory if it doesn't exist
if (!cache.exists()) {
cache.mkdirs();
}
return cache.getAbsolutePath();
}
public static Uri getOutputImageFileUri(Context ctx) {
// TODO: check the presence of SDCard
String tstamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File file = new File(getTempDirectoryPath(ctx), "IMG_" + tstamp + ".jpg");
return Uri.fromFile(file);
}
}
The code is partially inspired by developer.android.com and partially by CameraLauncher class of Apache Cordova project.
In my activity the event handler for button to take a picture looks like this:
private Uri imageFileUri;
private static final int MAKE_PHOTO_RESULT_CODE = 100;
private static final int PICK_PHOTO_RESULT_CODE = 101;
public void onMakePhoto(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageFileUri = ImageServices.getOutputImageFileUri(this);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri);
Log.i("babies", "Taking picture: requested " + imageFileUri);
startActivityForResult(intent, MAKE_PHOTO_RESULT_CODE);
}
Method onActivityResult does not really contain much, as imageFileUri already points to the existing file and necessary rendering is done in onResume method, which is called when the activity gets back into foreground:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch(requestCode) {
case MAKE_PHOTO_RESULT_CODE:
assert imageFileUri != null;
break;
case ...
...other cases...
break;
}
}
}
But this is still not sufficient, as imageFileUri gets lost as your app gets suspended. And on regular device the chances are close to 100%. So next you need to store the value of imageFileUri to instance state:
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (imageFileUri == null) {
outState.putString("file-uri", "");
}
else {
outState.putString("file-uri", imageFileUri.toString());
}
};
and load it again in - easiest is directly in onCreate:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (savedInstanceState != null) {
String fileUri = savedInstanceState.getString("file-uri");
if (!fileUri.equals("")) imageFileUri = Uri.parse(fileUri);
}
}
So, again, on top of many other solutions presented on this site as well as elsewhere, there are two major differences:
smarter getTempDirectoryPath inspired by Apache Cordova
allowing imageFileUri to survive suspended application
And now - at least for me - everything works fine.
Answer
Use appContext.getExternalCacheDir() and don't forget to mention permissons.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PICTURE)
{
if(resultCode==Activity.RESULT_OK)
{ //if (data != null)
//{
Toast.makeText(this, "Successfully Registered!", Toast.LENGTH_LONG);
ImageView Registerimage= (ImageView)findViewById(R.id.RegisterPicture);
Registerimage.setImageURI(registeryFileUri);
//}
}
else
Toast.makeText(this, "Not Registered!", Toast.LENGTH_LONG);
}
**"android.permission.CAMERA"**
Check whether the above permission is specified in your manifest or not
Note: It's better to use getExternalCacheDir() than getFilesDir() if you still dont get the
image then use that. Dont forgot to specify the permission "android.permission.WRITE_EXTERNAL_STORAGE" if you use the getExternalCacheDir().
On some devices data will unfortunately be null in onActivityResult after calling the camera activity. So you may need to save your state in your activity's variables, and them read them in onActivityResult. Be sure to save these variables in onSaveInstanceState and restore them in onCreate.

Categories

Resources