Passing Arraylist<CustomObject> using Parcelable, passing null - java

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

Related

Android checkbox checked one variable

I have a many checkbox and I saved in a String if it's checked like this:
String juice = "";
if (apple.isChecked()) {
juice = apple.getText().toString().trim() + " " + etiquetas;
}
if (orange.isChecked()) {
juice = orange.getText().toString().trim() + " " + etiquetas;
}
But when I need in another Activity put the checkbox checked, idk how to checked because I saved in one. I really need to be like this in one variable, because they're instructions for the exam. And thas's my code for the other Activity;
Intent intent = getIntent();
if(intent != null){
String juice_2 = (String) getIntent().getStringExtra("EXTRA_JUICE");
//apple.setChecked();
}
In the current activity, you can use a single String that has multiple juice words separated by a SPACE character.
And at the destination activity, split the string into an array of strings based on the SPACE character, and then set the checkBox value if this array contains your specific juice.
at Activity A:
String juice = "";
if (apple.isChecked()) {
juice = apple.getText().toString().trim() + " ";
}
if (orange.isChecked()) {
juice = orange.getText().toString().trim() + " ";
}
// Going to Activity B
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("JUICE", juice);
startActivity(intent);
at Activity B:
if (getIntent() != null) {
String juice = getIntent().getStringExtra("JUICE");
if (juice != null) {
String[] splittedJuice = juice.split(" ");
ArrayList list = new ArrayList();
// Convert array into a List
Collections.addAll(list, oldLines);
// Check if the list contains "orange"
if (list1.contains("orange")) {
orange.setChecked(true);
}
if (list1.contains("apple")) {
apple.setChecked(true);
}
}
}
To pass data from one activity to another you can use Intent.putExtra().
The line will look something like this:
intent.putExtra(LABEL, juice);
where: LABEL is a String which allows second activity to find your variable,
juice is your variable.
To resolve the problem you can use something like this:
public class First extends AppCompatActivity {
private final static String LABEL = "juices";
String juice;
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
final CheckBox apple = (CheckBox) findViewById(R.id.apple);
Button nextIntent = (Button) findViewById(R.id.next);
nextIntent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (apple.isChecked()) {
juice = apple.getText().toString();
}
Intent intent = new Intent(getApplicationContext(), Second.class);
intent.putExtra(LABEL, juice);
startActivity(intent);
}
});
}
}
Second Activity:
public class Second extends AppCompatActivity {
private final static String LABEL = "juices";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
Intent intent = getIntent();
String dataReceived = intent.getStringExtra(LABEL);
System.out.println("Your string: " + dataReceived);
}
}
Anyway, I would recommend that you pass Boolean values to the next activity without converting them to a String if it's only to check/uncheck Checkboxes in the second layout.
If you have a lot of variables in the first activity you can pass them to the array, send it to the another activity (by the similar way) and iterate to check/uncheck boxes.

How to Add new data to a array list via intents

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'

Add values to ArrayList from different activity

I'm trying to create an app like shopping cart
Using this to access my database http://www.tutecentral.com/restful-api-for-android-part-2/
And i'm stuck at adding products to cart, so far I understand that the selected products go to arraylist in a few tutorials. In the code below I have two Activities, the MaterialView (this shows the details of the materials and has the option to add to cart), and the MaterialCart (shows the list of selected products.)
this is the block of code in MaterialView to send the values to MaterialCart
ButtonAdd.setOnClickListener(new View.OnClickListener(){
public void onClick (View view){
Intent i=new Intent(MaterialView.this, MaterialCart.class);
i.putExtra("mID", mid);
i.putExtra("name", Name.getText().toString());
i.putExtra("qty", Qty.getText().toString());
i.putExtra("price", Price.getText().toString());
i.putExtra("stock", Stock.getText().toString());
i.putExtra("rqQty", RqQty.getText().toString());
startActivity(i);
Toast.makeText(MaterialView.this, "Added Succesfully.", Toast.LENGTH_LONG).show();
}
} );
I have used Intent to pass the values (I'm pretty sure this method is wrong, I also tried calling the MaterialCart class itself to access the arrayList so I can add values and it didn't work)
This is the block of codes in my MaterialCart to receive the values
public class MaterialCart extends Activity {
final ArrayList<PropertyCartTable> materialProperties = new ArrayList<>();
#SuppressLint("LongLogTag")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_material_cart);
Intent i = new Intent();
Bundle extras = getIntent().getExtras();
try{
String Name = extras.getString("name");
String Qty = extras.getString("qty");
String Price = extras.getString("price");
String Stock = extras.getString("stock");
String RqQty = extras.getString("rqQty");
String ID = extras.getString("mID");
Log.d("EXTRAS:", Name + " " + Qty + " " + ID);
materialProperties.add(new PropertyCartTable( ID,Name,Qty,Price,Stock,RqQty));
getIntent().removeExtra("Name");
getIntent().removeExtra("Qty");
getIntent().removeExtra("Price");
getIntent().removeExtra("Stock");
getIntent().removeExtra("RqQty");
getIntent().removeExtra("MID");
}
catch (Exception h){
Log.d("Exception!",h.toString());
}
// materialProperties.add(array);
Log.d("MaterialView.Cart isEmpty", String.valueOf(materialProperties.isEmpty()));
if(materialProperties.isEmpty()) {
Toast.makeText(this, "You have no materials to request.", Toast.LENGTH_LONG).show();
i = new Intent(MaterialCart.this, ProductDetails.class);
startActivity(i);
}else{
ArrayAdapter<PropertyCartTable> adapter = new propertyArrayAdapter(this, 0, materialProperties);
ListView listView = (ListView) findViewById(R.id.lv_materialcart);
listView.setAdapter(adapter);
}
}
The codes work for receiving the values, but when I go back to the materialView (or choose another product) the ArrayList doesn't append the values.
What I'm trying to achieve here is to add the values from the MaterialView (even if the user adds many prodducts) to MaterialCart's ArrayList.
You can let your Application contain the data:
public class MyApp extends Application {
private static List<String> data = new ArrayList<>();
public static void addItem(String item) {
data.add(item);
}
public static List<String> getData() {
return data;
}
}
And when button is clicked:
ButtonAdd.setOnClickListener(new View.OnClickListener(){
public void onClick (View view){
MyApp.addItem(your item);
Intent i=new Intent(MaterialView.this, MaterialCart.class);
startActivity(i);
}
} );
And in MaterialCart.class:
List<String> data = MyApp.getData();
But remember:data will be clear when app is closed.And if you want save it locally,you need to use SharedPreferences

String is null while obtaining from another class using getIntent

Right now I am have a activity screen with edittext lines that I am obtaining user input from. When I hit the create event button on the button, the event text should populate into a news feed that I have on another activity.
Here is the portion CreateEvent activity/screen code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_event);
CreateEvent_Button = (Button)findViewById(R.id.create_event_button);
WhatEvent_Text = (EditText)findViewById(R.id.what_event);
WhenEventTime_Text = (EditText)findViewById(R.id.time_event);
WhenEventDate_Text = (EditText)findViewById(R.id.date_event);
WhereEvent_Text = (EditText)findViewById(R.id.where_event);
CreateEvent_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WhatEvent_String = WhatEvent_Text.getText().toString();
WhenEventTime_String = WhenEventTime_Text.getText().toString();
WhenEventDate_String = WhenEventDate_Text.getText().toString();
WhereEvent_String = WhereEvent_Text.getText().toString();
Log.e("What: ", WhatEvent_String);
Log.e("When_Time: ", WhenEventTime_String);
Log.e("When_Date: ", WhenEventDate_String);
Log.e("Where_Event: ", WhereEvent_String);
Intent intent = new Intent(CreateEvent.this,MainActivity.class);
intent.putExtra("WhatEvent_String", WhatEvent_String);
intent.putExtra("WhenEventTime_String", WhenEventTime_String);
intent.putExtra("WhenEventDate_String", WhenEventDate_String);
intent.putExtra("WhereEvent_String", WhereEvent_String);
startActivity(intent);
MainActivity main= new MainActivity();
//make sure you call method from other class correctly
main.addEvent();
}
});
}
When the create event button is pressed, it creates an event into the MainActivity screen/activity; however, the user input is null. I am not sure why this is happening because I believe I am using the intent methods correctly.
Here is my MainActivity screen.
Here is the getIntent method in my onCreate method in my MainActivity
Intent intent = getIntent();
if (null != intent) {
test = intent.getStringExtra("WhatEvent_String");
}
However, when I call my addEvent method:
protected void addEvent() {
// Instantiate a new "row" view.
// final ViewGroup newView = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.list_row, mContainerView, false);
// Set the text in the new row to a random country.
// Because mContainerView has android:animateLayoutChanges set to true,
// adding this view is automatically animated.
//mContainerView.addView(newView, 0);
HitupEvent hitupEvent = new HitupEvent();
hitupEvent.setTitle("Rohit "+ "wants to "+test );
hitupEvent.setThumbnailUrl(roro_photo);
//hitupEvent.setRating(30);
//hitupEvent.setYear(1995);
//hitupEvent.setThumbnailUrl(null);
ArrayList<String> singleAddress = new ArrayList<String>();
singleAddress.add("17 Fake Street");
singleAddress.add("Phoney town");
singleAddress.add("Makebelieveland");
hitupEvent.setGenre(singleAddress);
hitupEventList.add(hitupEvent);
adapter.notifyDataSetChanged();
}
The event input text is null. I am not sure why this is happening.
I tried to resolve it but no luck,
How to send string from one activity to another?
Pass a String from one Activity to another Activity in Android
Any idea as for how to resolve this?!
Thanks!
Don't use Intent to get the String you put through putExtra()
Intent intent = getIntent(); // don't use this
if (null != intent) {
test = intent.getStringExtra("WhatEvent_String");
}
Instead Use Bundle, an example snippet
Bundle extra = getIntent().getExtras();
if(extra!=null){
test= extra.getString("WhatEvent_String");
}
EDIT
I noticed just now that you're calling the method main.addEvent() from the wrong place ! Call it in the MainActivity in the onCreate() method.
Remove these lines
MainActivity main= new MainActivity();
//make sure you call method from other class correctly
main.addEvent();
and in your MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourLayout);
Bundle extra = getIntent().getExtras();
if(extra!=null){
test= extra.getString("WhatEvent_String");
}
addEvent(); // call your addEvent() method here
}

Is it possible to pass a int and a string both from one activty to another , if yes then how to achive it?

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);

Categories

Resources