I'm trying to print a string from ArrayList in my another Activity using ListView. I passed a key and values in my intent variable. Using this.
MainActivity
ArrayList<String> arrayList = new ArrayList<String>();
Intent intent = new Intent(getApplicationContext(), ViewCart.class);
mealOneIncrement++;
quantityOne.setText(Integer.toString(mealOneIncrement));
mealOneCost = mealOneIncrement * mealOnePrice;
price.setText(Double.toString(mealOneCost));
String mealOneSummayName = name.toString();
String mealOneSummaryDescription = description.toString();
String mealOneSummaryQuantity = String.valueOf(mealOneIncrement);
String mealOneSummaryCost = String.valueOf(mealOneCost);
arrayList.add(mealOneSummayName);
arrayList.add(mealOneSummaryDescription);
arrayList.add(mealOneSummaryQuantity);
arrayList.add(mealOneSummaryCost);
intent.putExtra("data", arrayList);
As you can see here I passed arrayList variable as value for able to passed this from another Activity.
SecondActivity
ListView listView = (ListView) findViewById(R.id.listView);
String[] mealSummary = {};
ArrayAdapter adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, mealSummary);
Bundle bundle = getIntent().getExtras();
String data = bundle.getString("data");
listView.setAdapter(adapter);
I'm little bit confuse in this part String data = bundle.getString("data"); I'm not sure if I'm passing a correct variable to my ListView so I can able to show the arrayList variable in my ListView. Am I doing it wrong? Any help would appreciated :)
There are some problems with your code:
intent.putExtra("data", arrayList);
you are putting inside the bundle an arrayList of String, but then
String data = bundle.getString("data");
you are getting just a String. You need to use bundle.getStringArrayList("data").
ArrayList<String> data = bundle.getStringArrayList("data")
Also (not related to your problem), I recommend to use
Intent intent = new Intent(this, ViewCart.class);
instead of
Intent intent = new Intent(getApplicationContext(), ViewCart.class);
Pass Arraylist as putStringArrayListExtra,
Intent intent = new Intent(this, ViewCart.class);
intent.putStringArrayListExtra("data", arrayList);
startActivity(intent);
Get your ArrayList using getStringArrayListExtra,
arrayList = getIntent().getStringArrayListExtra("data");
You could modify this a bit.
In your secondActivity get the data like
ArrayList<String> data = getIntent().getSerializableExtra("data");
Now you got your data in an arrayList. If you wish to add this data to mealSummary then use,
mealSummary = (String[]) data.toArray();
Don't forget to call adapter.notifyDataSetChanged()
Related
In my app you can create a work project, you add client name, budget etc.
for UI purposes a staff member addition is on a seprate activity
Now My problem is that I pass the data in a Array between the activities via INTENT
that data is then displayed in a listview
Now the thing I am struggling with is that every time I want to add NEW data to the Array, The Array goes back to blank and then only displays the new data
So basically you add the Staff member data to an array, it goes to the other activity and passes that array via intent and Displays in a ListView
But it only displays the new data in the array
What I want to achieve is that the older data in the array must not disapear and the new data must just be added to the array and not create a new array
therby displaying the old and the new data
Activity 1 Code
This Passes the data to the other activity aswell as starts the other activity
AddStaff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MemberBudgetPassData= MemberBudget.getText().toString();
BudgetHoursPassData = budgetHours.getText().toString();
StaffList = Client + Rates + Staff + BudgetHoursPassData + MemberBudgetPassData;
StaffArray.add(StaffList);
PassData();
}
});
public void PassData(){
Intent GoToReport=new Intent(getApplicationContext(), createProject.class);
MemberBudgetPassData= MemberBudget.getText().toString();
BudgetHoursPassData = budgetHours.getText().toString();
Toasty.info(popupActivity.this, StaffArray.toString(),Toasty.LENGTH_LONG).show();
GoToReport.putStringArrayListExtra("Array",StaffArray);
startActivity(GoToReport);
Animatoo.animateCard(popupActivity.this);
}
Activity 2
Here it retrieves the data and diplays it in a listview
Array = new ArrayList<>();
Array = getIntent().getStringArrayListExtra("Array");
final ArrayAdapter arrayAdapter =new ArrayAdapter<>
(this, android.R.layout.simple_list_item_1, Array);
if (Array == null)
{
Toasty.info(createProject.this,"Select a Staff Memebr",Toasty.LENGTH_LONG).show();
}
else
{
StaffListView.setAdapter(arrayAdapter);
}
I use Gson library like this situation. Firstly, you should use model class and then pass model class or Arraylist object as String. For example;
Activity 1
public void PassData(){
Intent GoToReport=new Intent(getApplicationContext(), createProject.class);
MemberBudgetPassData= MemberBudget.getText().toString();
BudgetHoursPassData = budgetHours.getText().toString();
Toasty.info(popupActivity.this, StaffArray.toString(),Toasty.LENGTH_LONG).show();
GoToReport.putString("Array",new Gson.toJson(StaffArray));
startActivity(GoToReport);
Animatoo.animateCard(popupActivity.this);
}
Activity 2
Type listType = new TypeToken<ArrayList<StaffArray>>(){}.getType();
Array = new ArrayList<>();
Array = new Gson.fromJson(getIntent().getString("Array", listType));
final ArrayAdapter arrayAdapter =new ArrayAdapter<>
(this, android.R.layout.simple_list_item_1, Array);
if (Array == null)
{
Toasty.info(createProject.this,"Select a Staff Memebr",Toasty.LENGTH_LONG).show();
}
else
{
StaffListView.setAdapter(arrayAdapter);
}
Finally, don't remember add Gson library in gradle file.
implementation 'com.google.code.gson:gson:2.8.6'
Github: https://github.com/jjvang/PassIntentDemo
I've been following this tutorial about passing object by intent: https://www.javacodegeeks.com/2014/01/android-tutorial-two-methods-of-passing-object-by-intent-serializableparcelable.html
I understand from the tutorial how to send an Arraylist implementing Parcelable if you have only 1 set of values like this:
public void PacelableMethod(){
Book mBook = new Book();
mBook.setBookName("Android Developer Guide");
mBook.setAuthor("Leon");
mBook.setPublishTime(2014);
Intent mIntent = new Intent(this,ObjectTranDemo2.class);
Bundle mBundle = new Bundle();
mBundle.putParcelable(PAR_KEY, mBook);
mIntent.putExtras(mBundle);
startActivity(mIntent);
}
I have arranged the code so I can continue to add to the ArrayList to size 2 or greater but notice that the ArrayList I pass to the next activity is null.
I would like to understand if I would have to add to the ArrayList differently or if I am just sending/catching the Arraylist incorrectly.
Trying code change like this:
public void PacelableMethod(){
ArrayList<Book> words = new ArrayList<Book>();
words.add(new Book("red", "yes", 1));
words.add(new Book("mustard", "yes", 1));
Toast.makeText(this, "" + words, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this,ObjectTranDemo2.class);
intent.putExtra("Contact_list", words);
Bundle mBundle = new Bundle();
intent.putExtras(mBundle);
startActivity(intent);
}
public class ObjectTranDemo2 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<Book> myList = getIntent().getParcelableExtra("Contact_list");
Toast.makeText(this, "" + myList, Toast.LENGTH_SHORT).show();
}
}
Please advise, thank you!
I believe you need to add your array list to the intent extras using putParcelableArrayListExtra:
intent.putParcelableArrayListExtra(Contact_list", words)
then receive it with getParcelableArrayListExtra
I am trying to send a string and a int type data from one activity to another but due to lack of knowledge i don't know how to do it.
With the particular coding given below now i can only send any one of the data type.
searched a lot but not found any answer appropriate for my question. If i have asked any thing wrong plzz notify me as i am new to android Dev.
Any help may be appreciated.
this is my java coding of the two activities :
First.java
public class QM extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qm);
}
public void FLG(View view) {
// Do something in response to button
EditText mEditText= (EditText)findViewById(R.id.editText1);
String str = mEditText.getText().toString();
Intent intent = new Intent(this, Q1.class);
intent.putExtra("myExtra", str);
startActivity(intent);
finish();
}
}
Second.java
public class Q1 extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_q1);
Intent intent = getIntent();
if (intent.hasExtra("myExtra")){
TextView mText = (TextView)findViewById(R.id.textView1);
mText.setText("user name "+intent.getStringExtra("myExtra")+"!"); }
}
}
You can send 2 extras or even more as long you have different keys for it, so in your problem you need 2 extras one for String and one for Integer.
sample:
pass:
Intent intent = new Intent(this, Q1.class);
intent.putExtra("myExtra", str);
intent.putExtra("myExtraInt", yourInt);
get:
Intent intent = getIntent();
if (intent.hasExtra("myExtra") && intent.hasExtra("myExtraInt")){
TextView mText = (TextView)findViewById(R.id.textView1);
mText.setText("user name "+intent.getStringExtra("myExtra")+"!");
int extraInt = intent.getIntExtra(myExtraInt);
}
I'd like to give you some information.
Imagine the Intent's extras to be a (theoretically) infinitely sized bagpack. You can put certain type of data into it in an infinite number as long as each of the data has a unique name which is a string.
Internally it's a table that maps names to values.
So: Yes you can put String and Int simultaneously into the Intent's extras like this.
String str = "Test";
int val = 2933;
Intent i = new Intent(MyActivity.this, NewActivity.class);
i.putExtra("MyStringExtraUniqueName", str);
i.putExtra("MyIntExtraUniqueName", val);
To check for it use i.hasExtra("MyStringExtraUniqueName") as you did already and to get it use i.getExtra("MyStringExtraUniqueName").
BUT if you only use getExtra you'll be returned data of type object. Remember to cast the returned value to the appropriate type or use one of the specialized getter methods for some predefined data types.
See this for the available getters: http://developer.android.com/reference/android/content/Intent.html
Bundle data = new Bundle();
data.putInt("intKey", 5);
data.putString("stringKey", "stackoverflow");
Intent i = new Intent(MyActivity.this, NewActivity.class);
i.putExtras(data);
//And in the second acitvity fetch this way
Bundle data = getIntent().putExtras(b);
For my class we have to create an application where we catch an SMS message in a broadcast receiver, get the string (assumed to be a URL), add it dynamically to a string-array which is displayed in a fragmentlist. When the list item is clicked we then have to load it into a webview in a fragment.
Everything works until here.
The problem is that the list doesn't update when I try to add the url_act string to it.
Here's my code:
public class UpdateString extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String url_act = "";
Bundle b = getIntent().getExtras();
url_act = b.getString("url");
UrlListFragment uf = (UrlListFragment) getFragmentManager()
.findFragmentById(R.id.listFragment);
String[] urls = getResources().getStringArray(R.array.urls_array);
List<String> list = new ArrayList<String>();
list = Arrays.asList(urls);
ArrayList<String> arrayList = new ArrayList<String>(list);
arrayList.add(url_act);
urls = arrayList.toArray(new String[list.size()]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(UpdateString.this,
android.R.layout.simple_list_item_1, urls);
uf.setListAdapter(adapter);
}
If you need more code for context let me know. Updated
You really should post your logcat output just to be sure, as otherwise we don't know what kind of exception was thrown.
That being said, I bet it is a NullPointerException; findFragmentById() is most likely returning null. This is probably because you never inflate your XML resource to begin with.
I have a list view with couple of items and i set this function get call when a row in the list view is clicked.
I want to open new activity and send him an object from an array of objects.
I have a problem with this line :
Intent i = new Intent(this, Item_Activity.class);
because the this is now no the activity.
this is the code:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Intent i = new Intent(this, Item_Activity.class);
Item item = m_items.get(position);
i.putExtra("object", item);
startActivity(i);
}
});
Problem:
You are passing the wrong context in
Intent i = new Intent(this, Item_Activity.class);
Solution:
Use : YourActivityName.this instead if using simply this
eg. Intent i = new Intent(CurrentActivityName.this, Item_Activity.class);
Add ActivityName.this instead of this only,
Intent i = new Intent(ActivityName.this, Item_Activity.class);
is your Item is parcelable, if not make this object parcelable by following link:
http://prasanta-paul.blogspot.in/2010/06/android-parcelable-example.html
Your object has to be either serializable or parcelable and I don't think you can pass
an array into an intent read this - How to pass an object from one activity to another on Android
more to that
passing an array in intent android