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
Related
I would like to make a game, if i press play button, random level (activity) will open. I got code for this: https://stackoverflow.com/a/29579373/13101103
This is working, but i would like to edit, example, all levels have 2 different answer, answer1 is fail, answer2 is pass the level, if user pass level1, and in level2 fail, than go back to mainactivity, and if start again, then the passed levels will not show again.
Example:
There are 5 levels, user start random level, example level3, it passed, go to next random level, example level2, it pass, go to next... level4, it failed, go back to mainactivity, user start again, but the already passed levels will not show, only unpassed... example start level3... if passed then go to level1....
How can i edit this code for my solution? Can somebody give me some tips? Because in this if i go back to mainactivity and start again, then it start with all levels... I tried to edit, but i'm stucked and not works...
Plus i would like to save progress when user leave the app. In sharedpreferences how can i save the passed levels (arraylist)....?
MainActivity:
enter code here
Button level1Button = findViewById(R.id.level1Button);
level1Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// We are creating a list, which will store the activities that haven't been opened yet
ArrayList<Class> activityList = new ArrayList<>();
activityList.add(Level1Activity.class);
activityList.add(Level2Activity.class);
activityList.add(Level3Activity.class);
activityList.add(Level4Activity.class);
activityList.add(Level5Activity.class);
Random generator = new Random();
int number = generator.nextInt(5) + 1;
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
activity = Level1Activity.class;
// We are adding the number of the activity to the list
activityList.remove(Level1Activity.class);
break;
case 2:
activity = Level2Activity.class;
activityList.remove(Level2Activity.class);
break;
case 3:
activity = Level3Activity.class;
activityList.remove(Level3Activity.class);
break;
case 4:
activity = Level4Activity.class;
activityList.remove(Level4Activity.class);
break;
default:
activity = Level5Activity.class;
activityList.remove(Level5Activity.class);
break;
}
// We use intents to start activities
Intent intent = new Intent(getBaseContext(), activity);
// `intent.putExtra(...)` is used to pass on extra information to the next activity
intent.putExtra("ACTIVITY_LIST", activityList);
startActivity(intent);
}
});
Level1Activity:
enter code here
failbutton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
ArrayList<Class> activityList = new ArrayList<>();
activityList.add(Level1Activity.class);
Bundle extras = getIntent().getExtras();
activityList = (ArrayList<Class>) extras.get("ACTIVITY_LIST");
//Class activity = null;
Intent intent = new Intent(Level1Activity.this, Main2Activity.class);
intent.putExtra("ACTIVITY_LIST", activityList);
startActivity(intent);
}
});
buttonlevel1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Class> activityList = new ArrayList<>();
Bundle extras = getIntent().getExtras();
activityList = (ArrayList<Class>) extras.get("ACTIVITY_LIST");
if(activityList.size() == 0) {
// Do something when after all activities have been opened
//startActivity(new Intent(Level1Activity.this, Main2Activity.class));
//Intent intent = new Intent(Level1Activity.this, Main2Activity.class);
//intent.putExtra("ACTIVITY_LIST", activityList);
//startActivity(intent);
} else {
// Now, the random number is generated between 1 and however many
// activities we have remaining
Random generator = new Random();
int number = generator.nextInt(activityList.size()) + 1;
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
// We will open the first remaining activity of the list
activity = activityList.get(0);
// We will now remove that activity from the list
activityList.remove(0);
break;
case 2:
// We will open the second remaining activity of the list
activity = activityList.get(1);
activityList.remove(1);
break;
case 3:
// We will open the third remaining activity of the list
activity = activityList.get(2);
activityList.remove(2);
break;
case 4:
// We will open the fourth remaining activity of the list
activity = activityList.get(3);
activityList.remove(3);
break;
default:
// We will open the fifth remaining activity of the list
activity = activityList.get(4);
activityList.remove(4);
break;
}
// Note: in the above, we might not have 3 remaining activities, for example,
// but it doesn't matter because that case wouldn't be called anyway,
// as we have already decided that the number would be between 1 and the number of
// activities left.
// Starting the activity, and passing on the remaining number of activities
// to the next one that is opened
Intent intent = new Intent(getBaseContext(), activity);
intent.putExtra("ACTIVITY_LIST", activityList);
startActivity(intent);
}
}
});
level2, level3.... is same just different id-s
I'd suggest using the Singleton pattern to handle passing data between activities.
You can pass the list by intent's putExtra() or by SharedPreferences but with a Singleton class, it looks much better and easier to manipulate your data because they are encapsulated. So much so in your situation where you want to save your levels' states (e.g. when they are already completed).
However, if you really insist on using SharedPreferences to save the list then I suggest converting it to Json by using Gson. (Check below my answer on how to implement this.)
As I said, I'd use the Singleton pattern to avoid creating unnecessary boilerplate code and to encapsulate the levels' states.
LevelManager class (the singleton)
final class LevelManager {
// constants
private static final String LEVELS_SHARED_PREFERENCES_NAME = "app_name.LEVELS";
// variables
private static LevelManager instance;
private List<Class> levels;
private SharedPreferences sharedPreferences;
private LevelManager(Context context) {
sharedPreferences =
context.getSharedPreferences(LEVELS_SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
levels = new ArrayList<>();
initializeList();
}
private void initializeList() {
// Initialize levels, ie. add levels that are not yet completed/passed
// Check in SharedPreferences if level has already been completed
boolean alreadyPassed;
alreadyPassed = sharedPreferences.getBoolean(Level1Activity.class.getSimpleName(), false);
if (!alreadyPassed) levels.add(Level1Activity.class);
alreadyPassed = sharedPreferences.getBoolean(Level2Activity.class.getSimpleName(), false);
if (!alreadyPassed) levels.add(Level2Activity.class);
alreadyPassed = sharedPreferences.getBoolean(Level3Activity.class.getSimpleName(), false);
if (!alreadyPassed) levels.add(Level3Activity.class);
alreadyPassed = sharedPreferences.getBoolean(Level4Activity.class.getSimpleName(), false);
if (!alreadyPassed) levels.add(Level4Activity.class);
alreadyPassed = sharedPreferences.getBoolean(Level5Activity.class.getSimpleName(), false);
if (!alreadyPassed) levels.add(Level5Activity.class);
}
static LevelManager getInstance(Context context) {
if (instance == null) {
instance = new LevelManager(context);
}
return instance;
}
Class getRandomLevel() {
if (levels.isEmpty()) {
return null; // Return null if all levels are already completed
}
Collections.shuffle(levels);
return levels.get(0);
}
void saveLevelState(Class levelClass, boolean passed) {
sharedPreferences.edit().putBoolean(levelClass.getSimpleName(), passed).apply();
if (passed) {
// Remove level from list if user passed it so that it won't
// be included in next levels
levels.remove(levelClass);
}
}
void reset() {
// Clears all entries in SharedPreferences and re-initialize list
sharedPreferences.edit().clear().apply();
initializeList();
}
}
Inside onCreate in MainActivity
// Get LevelManager singleton instance
final LevelManager levelManager = LevelManager.getInstance(this);
Button startButton = findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Get next random level
Class levelToStart = levelManager.getRandomLevel();
// If all levels are already completed
if (levelToStart == null) {
Toast.makeText(MainActivity.this, "All levels are completed!",
Toast.LENGTH_LONG).show();
return;
}
Intent intent = new Intent(MainActivity.this, levelToStart);
startActivity(intent);
}
});
// I added a new button to reset all levels
Button resetButton = findViewById(R.id.resetButton);
resetButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Use the method reset() from LevelManager to restart everything
levelManager.reset();
Toast.makeText(MainActivity.this, "All levels have been reset!",
Toast.LENGTH_LONG).show();
}
});
Inside of onCreate on each Level Activity
// Get LevelManager
final LevelManager levelManager = LevelManager.getInstance(this);
// I created two buttons to simulate pass and fail
Button pass = findViewById(R.id.passButton);
Button fail = findViewById(R.id.failButton);
pass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Save state (Don't forget to change 'N' below)
levelManager.saveLevelState(LevelNActivity.class, true);
// Get next level
Class levelToStart = levelManager.getRandomLevel();
// Check if all are levels already completed
if (levelToStart == null) {
Toast.makeText(LevelNActivity.this, "Completed all levels",
Toast.LENGTH_LONG).show();
finish(); // Must implement to avoid going back to previous level (ie. Activity)
return;
}
Intent intent = new Intent(LevelNActivity.this, levelToStart);
startActivity(intent);
finish();
}
});
fail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
As you can see, you can simply use the finish() method if the user failed the level whereas you use the code below to proceed to the next level:
// Get LevelManager
LevelManager levelManager = LevelManager.getInstance(this);
// Set that the user passed this level (Change 'N' to the current level we are in)
levelManager.saveLevelState(LevelNActivity.class, true);
// Get next level
Class nextLevel = levelManager.getRandomLevel();
// If all levels are completed then 'nextLevel' will be null
if (nextLevel == null) {
// ...
}
// Start next level and finish current
Intent intent = new Intent(this, nextLevel);
startActivity(intent);
finish();
Note: To avoid calling finish() explicitly when starting the next level, you can put android:noHistory="true" in your levels' activity tag inside your manifest file.
How to save list to SharedPreferences by converting it to Json using Gson
To actually use Gson, you'll have to add implementation 'com.google.code.gson:gson:2.8.6' inside your app gradle dependencies.
Also, there's a problem on Gson when parsing Class objects to Json: You need to create your own serializer and deserializer for these objects and register it to your GsonBuilder.
ClassAdapter class (this is where we create our own custom serializer and deserializer for Class objects)
public class ClassAdapter implements JsonSerializer<Class>, JsonDeserializer<Class> {
#Override
public JsonElement serialize(Class src, Type typeOfSrc, JsonSerializationContext context) {
// Get our class 'src' name
return new JsonPrimitive(src.getName());
}
#Override
public Class deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
// Get class
return Class.forName(json.getAsString());
} catch (ClassNotFoundException e) {
// If class could not be found or did not exists, handle error here...
e.printStackTrace();
}
return null;
}
}
Here's a sample usage of saving a list to SharedPreferences by Json using Gson:
// Create new GsonBuilder and register our adapter for Class objects
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Class.class, new ClassAdapter());
// Initialize our list of levels (ie. classes)
List<Class> classes = new ArrayList<>();
classes.add(Level1Activity.class);
classes.add(Level2Activity.class);
classes.add(Level3Activity.class);
classes.add(Level4Activity.class);
classes.add(Level5Activity.class);
// Create Gson from GsonBuilder and convert list to json
Gson gson = gsonBuilder.create();
String json = gson.toJson(classes);
// Save json to SharedPreferences
SharedPreferences sharedPreferences = getSharedPreferences("app_name", MODE_PRIVATE);
sharedPreferences.edit().putString("levels", json).apply();
And to retrieve the list back:
// Retrieve json from SharedPreferences
SharedPreferences sharedPreferences = getSharedPreferences("app_name", MODE_PRIVATE);
String json = sharedPreferences.getString("levels", null);
// Handle here if json doesn't exist yet
if (json == null) {
// ...
}
// Create new GsonBuilder and register our adapter for Class objects
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Class.class, new ClassAdapter());
// Create Gson from GsonBuilder and specify type of list
Gson gson = gsonBuilder.create();
Type type = new TypeToken<ArrayList<Class>>(){}.getType();
// Convert json to list
List<Class> classes = gson.fromJson(json, type);
I hope you gained valuable tips to tackle this problem! And as always, happy coding!
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.
I have two intents.
Main Activity: Containing the Recycler View, showing some default items to make sure it works. An ArrayList is set to the Recycler View, which is the List containing those default items.
Second Activity: A button which will collect the data on the same page and put the data into an object, the object will be added into the Arraylist which set to the Recycler View of the Main Activity.
I made some Toast Message to confirm the object in the 2nd Activity was added to the ArrayList.
//My item
public item(int id, int money, String date, String category, String
description) {
this.id = id;
Money = money;
Date = date;
Category = category;
Description = description;
}
Then I created a class to control my ArrayList
//Building ArrayList
public Util(){
Log.d(TAG, "Util: Start");
if(IncomeItems==null){
IncomeItems = new ArrayList<>();
initIncomeItems();
}
}
private static void initIncomeItems() {
Log.d(TAG, "initIncomeItems: initI");
int Iid = 0
int Money= 0;
String Date = "";
String Category= "";
String Description = "";
Iid++;
IncomeItems.add(new item(Iid, 10000, "8-Jun-2019", "Salary",
"Salary"));
}
//adding item to ArrayList
public boolean addIncomeItem(item Item){
Log.d(TAG, "addIncomeItem: addI");
return IncomeItems.add(Item);
}
//getting ArrayList
public static ArrayList<item> getIncomeItems() {
Log.d(TAG, "getIncomeItems: getI");
return IncomeItems;
}
I set my ArrayList to the RecyclerView in the Main Activity
//Recycler View in Main Activity
RVAdapter IncomeAdapter = new RVAdapter(this);
Util util = new Util();
MainIncomeRV.setAdapter(IncomeAdapter);
MainIncomeRV.setLayoutManager(new GridLayoutManager(this, 1));
IncomeAdapter.notifyDataSetChanged();
IncomeAdapter.setItems(util.getIncomeItems());
In the 2nd Activity, I have a button to create a new item by getting data from the user.(I skipped some Widgets intitiation code here). At last I add the item to the ArrayList which set to the Recycler View in the Main Activity.
//Button in 2nd Activity
SubmitIncomeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Date = date_day.getSelectedItem().toString() +"-" +
date_month.getSelectedItem().toString() + "-" +
date_year.getSelectedItem().toString();
id++;
item IncomeItem = new item(id,
Integer.parseInt(Money.getText().toString()), Date,
IncomeCategories.getSelectedItem().toString(),
Description.getText().toString());
util=new Util();
util.addIncomeItem(IncomeItem);
Toast.makeText(IncomePage.this, IncomeItem.toString(),
Toast.LENGTH_SHORT).show();
Toast.makeText(IncomePage.this,
String.valueOf(util.getIncomeItems().size()), Toast.LENGTH_SHORT).show();
Log.d(TAG, "onClick: addI");
}
});
}
No error occurred, but the item(IncomeItem) created in the 2nd Activity cannot be added to the Main Activity.
I expected the item will show in the Recycler view when I return to the Main Activity. Is it the problem that I use the return button to go back to the Main Activity?
Following two points should work for you:
You should use same util object which is used in MainActivity
instead of creating new in submit button under 2nd Activity, So pass util object to
2nd activity.
Also pass adapter object to 2nd Activity, so that you can call NotifyDatasetChanged()
function after adding item.
This is how it should work. First create an arrayList in your 2ndActivity.
ArrayList<Item> str = new ArrayList<Item>();
In SubmitIncomeBtn,
SubmitIncomeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Date = date_day.getSelectedItem().toString() +"-" + date_month.getSelectedItem().toString() + "-" + date_year.getSelectedItem().toString();
id++;
item IncomeItem = new item(id,Integer.parseInt(Money.getText().toString()), Date, IncomeCategories.getSelectedItem().toString(),Description.getText().toString());
str.add(IncomeItem) // add IncomeItem to arrayList
}
});
In 2ndActivity, you need to have this code to pass arrayList to MainActivity.
#Override
public void onBackPressed() {
Intent intent = new Intent();
intent.putExtra("mylist", str);
setResult(1, intent);
}
Finally in MainActivity, add this code to receive data from 2ndActivity
onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
ArrayList<Item> myList = (ArrayList<Item>) getIntent().getSerializableExtra("mylist");
}
}
}
I am new in Android. I need your help. My Problem is - I have 2 classes Nplist.java and Addcustomer.java. In my AddCustomer class,One TextView and one Button is there to go Nplist class. In my Nplist class there is checklist and this checklist is coming from database and all the checked values are stored in ArrayList<String> and one Button is used to go back to AddCustomer class. I want that ArrayList<String> which is in Nplist to by display in my AddCustomer class Textview . I haved tried these but my Addcustomer class crashed.
1.Nplist.class
add.setOnClickListener(new View.OnClickListener() {<br>
#Override<br>
public void onClick(View view) {<br>
Bundle extra=new Bundle();<br>
extra.putSerializable("objects",checkedList);<br>
Intent intent = new Intent(Nplist.this, AddCustomer.class);<br>
intent.putExtra("extra",extra);<br>
startActivity(intent);<br>
});
2.AddCustomer.class
onCrete()...{
Bundle extra = getIntent().getBundleExtra("extra");<br>
ArrayList<String> object = (ArrayList<String>)extra.getSerializable("objects");<br>
for (String str : object) {<br>
getnp.append(str + "\n");<br>
}
}
What do you expect the result to be?
- What is the actual result you get? (Please include any errors.)
When i go like this Nplist-->AddCustomer its working well but crash on ( AddCustomer-->Nplist-->AddCustomer)
It's because when you are coming back to your AddCustomer Activity the list is null . You can solve this problem by making a global class which will store the list in a Static Field , And You can access that list from any class or Activity you want to. Try out below solution .
Global.java Class is as below :
public class Global {
private static ArrayList<String> object = new ArrayList<>();
public static ArrayList<String> getObject() {
return object;
}
public static void setObject(ArrayList<String> object) {
Global.object = object;
}
}
From NpList.java class set the value of the list as below :
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Global.setObject(checkedList);
Intent intent = new Intent(Nplist.this, AddCustomer.class);
startActivity(intent);
}
});
Now Access in AdCustomer.java as below :
onCreate()...{
Bundle extra = getIntent().getBundleExtra("extra");
ArrayList<String> object = Global.getObject();
for (String str : object) {
getnp.append(str + "\n");
}
}
This maybe helpful for you.
Using putStringArrayListExtra method you can send an array list of strings along with the intent.
Sender side:
Intent intent = ...
intent.putStringArrayListExtra("THE_KEY", theList);
Receiver side:
ArrayList<String> theList = intent.getStringArrayListExtra("THE_KEY");
Passing parameters works with 2 normal activities, but when I try to pass this from the gridview to another activity, the value returns null
First Activity
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//This takes the position id of the image and change
//it to match category id
position = position + 1;
String positionId = String.valueOf(position);
System.out.println(positionId);
Toast.makeText(MenuActivity.this, "position =" + positionId + "\nid =" + id, Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(v.getContext(), MenuItemActivity.class);
myIntent.putExtra("hello", "hello");
startActivityForResult(myIntent, 0);
}
});
My secondary activity (MenuItemActivity.java)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menuitem);
try{
Bundle extras = getIntent().getExtras();
String category = null;
extras.getString("Category "+extras.getString("hello"));
System.out.println("Category = "+category);
} catch(Exception e){
System.out.println("Error "+e.getMessage());
}
from here it looks like a master >> detail page. if so why are you calling
startActivityForResult(myIntent, 0);
instead of a simple
startActivity(myIntent);
can you try this and tell me if this works.
getIntent().getStringExtra("hello");
In your second activity, you need to call setResult to actually pass data back to the first activity.