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;
}
}
Related
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");
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 !!
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'm creating an android chat app.. The main screen will be a list of messages.. I get the messages and the friends from the database then show it in my list which contains two textviews and 1 imageview.. every thing works fine, but when i get my friends from database(not the same size of messages) and I need to get Imagepath of each friend.. that works fine also when i log it.. but when I try to get it in the adapter i get my list with only one unit..
messages_iv = (ImageView) row.findViewById(R.id.imageView1);
final String name = items.get(position).getTitle();
final String photoUrl = friends.get(1).getPhotoUrl();
new Thread(new Runnable() {
public void run() {
Log.d("Button Clicked", "Name: " + name);
Log.d("Button Clicked", "URL: " + photoUrl);
getPhoto(messages_iv, photoUrl);
}
}).start();
when I try friends.get(0) it works fine.. but when I try friends.get(1) I get :
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
Any Idea ??
Thanks.
I have an odd problem, (see shorter version at the bottom first please)
When my activity starts for the first time, the listview shows the dataset fine. The adapter is a custom adapter which shows 2 rows of text and an image. I call an asynctask upon a click event to the listview, the dataset updates in accordance with whatever was clicked on in the listview - more specifically the arrays which are associated with the adapter become rewritten with the parsings of some xml, and then notifyachapterdatasetchanged method is called to update the listview in the onPostExecute function. However I always get NullPointerException when I am iterating through some xml (which is very well formed and validates). ALso its worth mentioing that the algorithm that parses the desired values is good, because as mentioned above, if i write to just 1 element of the array then I dont get the error I just get the last node value so its looping in the correct places. i.e If I simple try to copy the current node value I am parsing during the loop into, say, producyTypes[0] then the last value from within the loop actually makes it to the listview as it constantly overwrites this elemet of the array
Here is my code.`
public class main extends Activity implements OnItemClickListener
{
String selectedType="";
ListView lview3;
ImageView iv;
ListViewCustomAdapter adapter;
String test = "";
List<String> ls;
String productTypes[] = {"Monitor","Components","Systems","Laptops","Flash / Usb Memory",
"Networking","Cables","Peripherals","Sound and Vision", "Software"};
String productsIncluded[] = {"Sizes (inches) 17, 19, 20",
"Motherboards, PSU, Cases, Fans/Heatsinks/Coolers, Barebones Systems, Blue-Ray/DVD. Card Readers, Controller Cards, Drive Enclosures, Sound Cards",
"Bundles, Switches and Hubs, Print Servers, Accessories/Modules",
"Cables for: Drives, Networking, HDMI/Monitor, Audio/Video, USB/Firewire, Power, Miscellaneous",
"Mice, Connectors, Bluetooth Devices",
"Mp3/Mp4 Solar Panel",
"Anti-Virus, Internet Security, Operating Systems, Office,,
"",
""};
private static int images[] = {R.drawable.monitor, R.drawable.components, R.drawable.systems,
R.drawable.laptops, R.drawable.flashusb, R.drawable.networking, R.drawable.cables, R.drawable.
peripherals, R.drawable.soundandvision, R.drawable.software};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iv = (ImageView)findViewById(R.id.ImageView01);
iv.setImageResource(R.drawable.logo);
iv.setVisibility(View.VISIBLE);
lview3 = (ListView) findViewById(R.id.listView3);
adapter = new ListViewCustomAdapter(main.this, productTypes, productsIncluded, images);
lview3.setAdapter(adapter);
lview3.setOnItemClickListener(main.this);
}
#Override
public void onItemClick(AdapterView arg0, View arg1, int position, long id) {
selectedType = "";
if(position == 0)
{
selectedType= "Monitors";
}
if(position == 1)
{
selectedType= "Hard Drives";
}
Toast.makeText(this, Integer.toString(position), Toast.LENGTH_SHORT).show();
new async().execute();
/*
Intent intent = new Intent(getApplicationContext(),activitywo.class);
Bundle bundle =new Bundle();
bundle.putString("selectedType",selectedType);
intent.putExtras(bundle);
startActivity(intent);
//Toast.makeText(this, "Title => "+productTypes[position]+" \n Description => "+productsIncluded[position], Toast.LENGTH_SHORT).show();
*/
}
private class async extends AsyncTask<String, Void, Void> {
// UI Thread
protected void onPreExecute() {
}
// automatically done on worker thread (separate from UI thread)
protected Void doInBackground(final String... args) {
try{
Resources res = getResources();
InputStream in;
in = res.openRawResource(R.raw.core);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(in);
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("entry");
count=0;
for(int i =0;i<items.getLength();i++){
Node item = items.item(i);
NodeList properties = item.getChildNodes();
//productsDefinedByTypeArray = new String[properties.getLength()];
for(int j = 0;j<properties.getLength();j++){
Node property = properties.item(j);
String name = property.getNodeName();
if(name.equalsIgnoreCase("g:product_type")){//everytime we hit g:product_type grab the value
String strText = property.getFirstChild().getNodeValue();
if(strText.contains(selectedType)){
//
for(int k = 0;k<properties.getLength();k++){
Node propertysecond = properties.item(k);
String namesecond = propertysecond.getNodeName();
if(namesecond.equalsIgnoreCase("title")){//everytime we hit title grab the value
String strTextsecond = propertysecond.getFirstChild().getNodeValue();
productTypes[0] = strTextsecond;
yo = strTextsecond;
count++;
}
}
}
}
}
}
The code crashes at the point where I am trying to copy the value of a "title" node that I parse out of my xml file into the list-String-. I am using a list-string- to show that even if you try and copy the value into the array itself (the array that is associated with the adapter), even if you comment out the notifydatasetchanged () line the program still crashes. The xml is well formed and very consistent. I know this because (aecept the fact its really small and I have read it all) ! Why can I not copy every node value into my array/list whilst the loop is in progress?
Any help is massively appreciated. Thank you.
Shorter version:
I cannot write to the List
if(strText.contains(selectedType)){
//
for(int k = 0;k<properties.getLength();k++){
property = properties.item(k);
name = property.getNodeName();
if(name.equalsIgnoreCase("title")){//everytime we hit title grab the value
String strTextsecond = property.getFirstChild().getNodeValue().toString();
ls.add(strTextsecond.toString());
//test = strTextsecond;
}
}
}
Maybe you forget initialize ls? I don't find in your code something like:
ls = new List<String>();