Problems with multiple myIntent.putExtra/myIntent.getExtra in Android - java

Ok, so I am trying to get two different String arrays from one activity, through an alarmManager to a BroadcastReceiver (called AlarmReceiver), and so far have been using myIntentName.putExtra() and the relevant .getExtra() on the broadcastReceiver side of things. Here's my relevant code:
In the first activity (this is called and the code gets to the AlarmReceiver):
private void setAlarmManager() {
Intent intent = new Intent(this, AlarmReceiver.class);
//I have already defined askArray and answerArray (they aren't null, but are dynamic
//and exactly how I define them is quite complex so not included here)
intent.putExtra("askArray", askArray);
intent.putExtra("answerArray", answerArray);
PendingIntent sender = PendingIntent.getBroadcast(this, 2, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, 5000, 61000, sender);
}
At the top of the AlarmReceiver(which extends BroadcastReceiver):
String[] askArray = new String[2];
String[] answerArray = new String[2];
In the broadcastReceiver, in the onReceive():
askArray = intent.getExtras().getStringArray("askArray");
answerArray = intent.getExtras().getStringArray("answerArray");
for (int i = 0; i < askArray.length; i++){ //I get a NullPointerException on this line
Log.i("L3R", "AskArray["+i+"]: " + askArray[i]);
}

use this
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
ContactItem contactData = (ContactItem) listView.getItemAtPosition(position);
Intent intent = new Intent(getActivity(), ContactDetail.class);
intent.putExtra("DATA_KEY", contactData);
startActivity(intent);
}
});
for details
Intent i = getIntent();
Bundle b = i.getExtras();
// getting attached intent data
ContactItem contact = (ContactItem) b.getSerializable("DATA_KEY");
// displaying selected contact name
txtName.setText(contact.getName());
txtPhone.setText(contact.getPhone());
txtMobile.setText(contact.getMobile());
txtEmail.setText(contact.getEmail());

you need to get array from intent using following code
askArray = intent.getStringArrayExtra("askArray");
answerArray = intent.getStringArrayExtra("answerArray");

You're presumably getting a NullPointerException when accessing askArray.length, which means it's a good idea to check if askArray == null before attempting to iterate through the array. This will prevent your app from crashing if an error occurs passing these values to the BroadcastReceiver.
It's also common practice to check if getExtras() returned anything useful, like so:
Bundle extras = intent.getExtras();
if(extras != null) {
askArray = extras.getStringArray("askArray");
answerArray = extras.getStringArray("answerArray");
if(askArray != null) {
for (int i = 0; i < askArray.length; i++) {
Log.i("L3R", "AskArray["+i+"]: " + askArray[i]);
}
}
} else {
Log.e("L3R", "Failed to getExtras()");
// deal with missing values here
}
If this logs the failure message every time, then the problem might be related to how you're setting the intent variable. It appears you're setting it correctly before "putting" the arrays, but it's not apparent how you're setting it when "getting" the arrays. This should be your code in the BroadcastReceiver:
Intent intent = getIntent();

Ok, sorry but it turns out that the problem wasn't with the part of the code I posted. I was using an alarm manager that had a quirk I wasn't aware of, but thanks for all the answers, here is the link: Android cannot pass intent extras though AlarmManager
And here is the relevant information(copied from the link):
Haresh's code is not the complete answer... I used a Bundle and I tried without Bundle but I got null's either way when I attempting to obtain the strings from the extra's !!
The exact problem, in your code, is with the PendingIntent !
This is wrong if you're trying to pass extra's :
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, uniqueRequestCode, intent, 0);
Because the 0 for the flags is what will cause you a headache
This is the right way to do it - specify a flag !
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, uniqueRequestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
This is probably such a popular problem because Google's sample code neglected to include Extra's in an Alarm.

Maybe this solve your problem:
At the top of the broadcast-receiver change fields to this:
String[] askArray;
String[] answerArray;
That's all. Good luck.

Related

How can I set more than one alarm with AlarmManager in Android?

This is my first app using AlarmManager, I´m triyng to set multiple alarms from an array of dates. For the array of dates I am occupying a String format
String[] date = new String[3];
date[0] = "2022-01-11 13:10";
date[1] = "2022-01-11 12:30";
date[2] = "2022-01-12 12:30";
And I convert it to Date(long) to set it to the alarmManager:
#RequiresApi(api = Build.VERSION_CODES.O)
public Long parseDateLong(String myDate){
long millisSinceEpoch = LocalDateTime.parse(myDate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))
.atOffset(ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
return millisSinceEpoch;
}
This is the service that does the onRecive,
#Override
public void onReceive(Context context, Intent intent) {
Intent service1 = new Intent(context, NotificationService.class);
service1.setData((Uri.parse("custom://" + System.currentTimeMillis())));
ContextCompat.startForegroundService(context, service1 );
Log.i("ALARM", " ALARM RECEIVED!!!");
}
I am using code I found to iterate over the array, and set the alarm:
AlarmManager[] alarmManager=new AlarmManager[date.length];
ArrayList intentArray = new ArrayList<PendingIntent>();
for(int i=0; i<date.length; i++){
Intent intent = new Intent(AddMedication.this, AlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(AddMedication.this, i ,intent, 0);
Log.i("dates", "dates"+date[i]);
alarmManager[i] = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager[i].set(AlarmManager.RTC_WAKEUP, parseDateLong(date[i]),pi);
intentArray.add(pi);
}
The problem is when I set the date array, all the alarms are executed instantly, without respecting the dates and times indicated.
How can I set multiple alarms and they run at the times indicated in the array?
you are initialising AlarmManager in a very wrong way. this component can't be created by developer using new keyword (I'm surprised that this is even possible with some public constructor), only obtained from system/Context
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
and there is only one instance of it, all alarms should be sheduled to this single one instead of items in array

Intent from multiple Activities

I have problem about getting data from multiple activities.
Here's my problem.
I made 3 Activities to get data from each other.(Let me say 3 Activities A,B,C)
A, B execute different method but their results are same type, the ArrayList.
I have a purpose to get both results in C from A,B.
Activity-A
Intent intent = new Intent(RouteInfoDebug1.this, LiveLocationInfo.class);
Bundle bundle = new Bundle();
bundle.putStringArrayList("stdid", (ArrayList<String>) list);
intent.putExtras(bundle);
Log.d("LLNC", "Passed Value:" + (ArrayList<String>) list +"\n");
startActivity(intent);
Activity-B
Intent intent = new Intent(LowBusInfo.this, LiveLocationInfo.class);
Bundle bundle = new Bundle();
bundle.putStringArrayList("lowStdid", (ArrayList<String>) list);
intent.putExtras(bundle);
Log.d("LLLC", "Passed Value:" + (ArrayList<String>) list +"\n");
startActivity(intent);
Activity-C
Bundle bundle = getIntent().getExtras();
ArrayList<String> list = bundle.getStringArrayList("stdid");
Log.d("LLNC", "Received Value: " + bundle.getStringArrayList("stdid")+"\n");
ArrayList<String> lowList = bundle.getStringArrayList("lowStdid");
Log.d("LLLC", "Received Value: " + bundle.getStringArrayList("lowStdid")+"\n");
I coded like this.
When I checked each values(Passed Value from Log.d) from different Activities A,B, it was perfect.
From A list: [null, 305001086, 305001087]
From B list: [null, 305001233, 305001241, 305001010, 305001123, 305001239, 305001273, 305001340, 305001143, 305001352, 305200048, 305001269, 305001275, 305001345, 305001167, 305001237, 305001434, 305001235, 305001354, 305001136, 305001227, 305001094, 305001243, 305001380, 305000887, 305001159, 305001347, 305001247, 305001353, 305001346, 305001171, 305001231, 305001169, 305001086, 305001127, 305200003, 305001341, 305001274, 305001245, 305001155, 305001088, 305001342, 305001271, 305200054, 305001229, 305300257, 305001137, 305001165, 305001153, 305001163]
But the problem is in Activity-C.
I keep getting null from one activity. For example, I get null from B list when I get full A list Value or the opposite situation happens.
I googled whole day finally I found someone says two activities can't be started at once so I matched key the same. But the result was miserably same thing.
Here's the detail purpose:
I wanted to get each data from A,B in C after that I wanted to make condition between A List and B List, refine it and use the code to get other data.
Actually I divided activities because of my convenience. If I combine two activities(A,B) into one(but different classes), could be the solution? This is my first question sorry for too long. Thanks in advance.
This runs Activity A then play Activity B.
public void mOnClick(View view){
switch(view.getId()){
case R.id.btnSearch:
new Thread(new Runnable(){
#Override
public void run(){
data = getRouteInfo();
/*Activity B's Method will be executed here*/
LowBusInfo lowBusInfo = (LowBusInfo)getApplication();
lowBusInfo.getLowBusInfo();
lowBusInfo.thread.start();
thread.start();
runOnUiThread(new Runnable(){
#Override
public void run(){
textView.setText(data);
}
});
}
}).start();
break;
}
}

putExtra ("int", value) but getIntent wrong

Please help with this code
I have a button in the first activite I want when I press it to send text and number to another activity
But I want to display the text in TextView 1 and the number in TextView2
I succeeded in sending the text to its specified location but I have a problem sending the number
I experimented with many of the codes and the failures persisted.
This is the last code you used to successfully send the text but failed to send the number
The code from the first activity:
Intent intent = new Intent( this, Order.class );
String keyIdentifer = null;
intent.putExtra( "String", text );
intent.putExtra( "Int", price );
startActivity( intent );
The code from the second Activity:
TextView userName = (TextView)findViewById(R.id.the_order);
Intent iin= getIntent();
Bundle b = iin.getExtras();
if(b!=null)
{
String j =(String) b.get("String");
userName.setText(j);
}
TextView userName1 = (TextView)findViewById(R.id.price);
Intent ii= getIntent();
Bundle bb = ii.getExtras();
if(bb!=null)
{
int jj =(int) bb.get("Int");
userName1.setText(jj);
}
get the int as:
int jj = yourintent.getIntExtra("Int");
You don't need to get the bundle first, this way is a wrap around the thing that you are doing and gives you the same value
One other error is that you are setting an int value inside the setText method.
This method accepts int but it expects the int value to be a resource identifier. Since you are passing a value which is not a resource id, it will crash saying resource not found.
try
userName1.setText(String.valueOf(jj));
Basically if you want to set the TextView value as an int, never forget to convert it to string. The error thrown is horrendously worded and doesn't remotely indicate that this is the actual issue.
Intent intent = new Intent(this, Activity.class);
intent.putExtra("Int", 4);
startActivity(intent);
In the activity its going to...
Intent intent = getIntent;
int getInt = intent.getIntExtra("Int");
System.out.println(getInt);
set a testview:
textView.setText(String.valueOf(getInt);
Your issue is you are setting an Int value in editText:
int jj =(int) bb.get("Int");
userName1.setText(jj);
Just do this when setting int value:
int jj =(int) bb.get("Int");
userName1.setText(jj+"");
just change
bb.get("Int");
to
bb.getInt("Int");

Format exeption errors

I have 2 activities. Activity A sends a Number to activity B and activity recieves and uses the Number. The problem is that activity B produces FormatExeption errors.
Activty A code:
EditText set_limit = findViewById(R.id.editText2);
Bundle set_limit_basic = new Bundle();
set_limit_basic.putString("limit_basic", String.valueOf(set_limit));
Intent Aintent = new Intent(A.this, B.class);
Aintent.putExtras(set_limit_basic);
startActivity(Aintent);
Activity B code:
Bundle set_limit_basic = getIntent().getExtras();
if (set_limit_basic != null) {
String B_string = set_limit_basic.getString("limit_basic");
if ( B_string .trim().length() == 0){
limit_number = Integer.parseInt(B_string);
Several points:
You shouldn't be converting set_limit to a string; set_limit is an EditText widget. Instead, you should be putting the contents of the view (the text it is displaying).
There's no reason to explicitly construct your own extras bundle. Just use one of the putExtra methods defined in the Intent class.
The error checking is probably better handled in activity A instead of activity B.
You seem to have a logic error in activity B, in that you are only attempting to parse the limit number when the trimmed text is empty. That seems backwards.
Putting all this together, I'd rewrite your code as follows:
Activity A:
EditText set_limit = findViewById(R.id.editText2);
CharSequence text = set_limit.getText();
if (TextUtils.isEmpty(text)) {
// handle case of no text
} else {
try {
int limit_number = Integer.parseInt(text.toString());
Intent intent = new Intent(A.this, B.class);
intent.putExtra("limit_basic", limit_number);
startActivity(intent);
} catch (NumberFormatException e) {
// handle case of improperly formatted text
}
}
Activity B:
limit_number = getIntExtra("limit_basic", -1 /* or other default value */);
// or, if you want to explicitly check for presence of the extra:
if (hasExtra("limit_basic")) {
limit_number = getIntExtra("limit_basic", -1);
}
In 1st Activity you are trying to use String.valueOf(edittext);
( set_limit is a variable of type EditText so the string value will be #djfjckckc78 something like this...which is surely not a number)
try
String.valueOf(set_limit.getText().toString());
i.e,
set_limit_basic.putString("limit_basic",String.valueOf(set_limit.getText().toString()));
and also in Activity B,
if ( B_string .trim().length() > 0){
}
If you try to convert String.valueOf(variable) to a number it will throw a NumberFormatException at runtime because that string aint a number !!

passing GPS coordinates to activity

I am trying to pass longitude and latitude variables into another activity for the Google maps fragment. So far I have managed to do this
Intent i = new Intent(Main.this, Main2.class);
i.putExtra(Double.toString(gettextLong), xLocation.getLongitude());
i.putExtra(Double.toString(gettextLat), xLocation.getLatitude());'
How do I receive it in the other activity?
Give relevant key like
Intent i = new Intent(Main.this, Main2.class);
i.putExtra("longitude", xLocation.getLongitude());
i.putExtra("latitude", xLocation.getLatitude());
and in Main2 Activity
Bundle extras = getIntent().getExtras();
if(extras !=null && extras.getDouble("latitude") != null && extras.getDouble("longitude") != null) {
double lat = extras.getDouble("latitude");
double lng = extras.getDouble("longitude");
}
Try:
Intent i = new Intent(Main.this, Main2.class);
i.putExtra("lon", xLocation.getLongitude());
i.putExtra("lat", xLocation.getLatitude());
Like this:
int lat = getIntent().getExtras().getDouble("lat");
int lon = getIntent().getExtras().getDouble("lon");
Use getIntent() and getDoubleExtra() in yours second activity. But pass it in different way. First argument in putExtra should be some String but you have to know him, it is needed to use later in second activity. Like:
public static final String FIRST = "firstArgument";
i.putExtra(FIRST, xLocation.getLongitude());
And in Main2:
double i = getIntent().getDoubleExtra(Main.FIRST, 0);

Categories

Resources