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 !!
Related
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;
}
}
The value of walletBalance is a string, eg "150.0".
I am trying to display an error message in form of a toast in another activity(SuccessActivity) is the amount to be withdrawn from the user is less than the wallet balance. I keep getting NumberFormatException error for the value of i, so i decided to use a try catch block but it still doesnt work. Here is the method below.
private void checkWalletBalance(int amount, Context context){
String walletBalance = Preferences.getBalance(context);
try {
int i = Integer.parseInt(walletBalance.trim());
if(amount < i){
Intent intent = new Intent(getBaseContext(), SuccessActivity.class);
startActivity(intent);
Toast. makeText(ActivityHome.this,"Insufficient Wallet Balance",Toast. LENGTH_LONG).show();
}
}
catch (NumberFormatException nfe){
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
Alos, I want to display a toast in the success Activity, If the condition i true. here is the code in success activity to display the toast message.
private void insufficientError(){
Intent intent = getIntent();
intent.getExtras();
Toast.makeText(SuccessActivity.this,"Insufficient Balance",Toast.LENGTH_LONG).show();
}
Like #Blackbelt commented, you are trying to parse a double string and not an integer.
Therefore, you need to do the following:
double amount = Double.parseDouble(walletBalance.trim());
You could use either of the following-
Double.valueOf(walletBalance.trim());
Double.parseDouble(walletBalance.trim());
And then if you want to convert them to Integer/int like this -
Integer i = Double.valueOf(walletBalance.trim()).intValue();
int i = (int) Double.parseDouble(walletBalance.trim());
NumberFormatException - Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
Don't
int i = Integer.parseInt(walletBalance.trim()); //walletBalance.trim() ==150.0
Do
int i = (int) Double.parseDouble(walletBalance.trim());
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");
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.
I am trying to convert a value from Double to String in an Android Activity.I can get this to work with my first example here below (working in the sense of no squigly error from Eclipse). However I am curious as to why the second example is not working.
First example
balance = (TextView) findViewById(R.id.textViewCardBalance);
Intent intent = getIntent();
if (intent.getExtras() != null) {
balance.setText(String.valueOf((long)intent.getDoubleExtra("balance", 0.00)));
}
Second example below not working (Error: "Cannot cast from Double to Long"
balance = (TextView) findViewById(R.id.textViewCardBalance);
Double cardBalance;
Intent intent = getIntent();
if (intent.getExtras() != null) {
cardBalance = intent.getDoubleExtra("balance", 0.00);
balance.setText(String.valueOf((long)cardBalance);
}
Would anyone know how I can get the second example to work as I need to log the value retrieved from the intent before passing it to the TextView.
Thanks
Why can't you do this?
balance.setText(cardBalance + "");
String yourDoubleString = String.valueOf(yourDouble);
in your case:
String yourDoubleString = String.valueOf(intent.getDoubleExtra("balance", 0.00));
using String v = ""+String.valueOf((long)cardBalance) not work?