I am unable to get my ArrayList out when it's on a different page. I would like to get the ArrayList out Android Studio.
This is CartActivity class:
public class CartActivity extends AppCompatActivity {
private ArrayList<CartItem> cartList;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
listView = (ListView) findViewById(R.id.listView);
CartAdapter adapter = null;
cartList = new ArrayList<>();
adapter = new CartAdapter(this, R.layout.adapter_cart_item, cartList);
listView.setAdapter(adapter);
}
}
This is ProductActivity class. It's where the data is being stored into the ArrayList:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product);
myDB = new DatabaseHelper(ProductActivity.this);
textViewPrice = (TextView) findViewById(R.id.textViewPrice);
textViewInfo = (TextView) findViewById(R.id.textViewInfo);
textViewName = (TextView) findViewById(R.id.textViewName);
ivProduct = (ImageView) findViewById(R.id.ivProduct);
btnAddToCart = (Button) findViewById(R.id.btnAddToCart);
spinnerQuantity = (Spinner) findViewById(R.id.spinnerQuantity);
Intent in = getIntent();
Bundle b = in.getExtras();
userID = b.getString("userID");
productID = b.getInt("productID");
Cursor results = myDB.checkProduct();
if (results.getCount() == 0) {
Toast.makeText(getApplicationContext(), "Error: no data found!",
Toast.LENGTH_SHORT).show();
return;
} else {
StringBuffer buffer = new StringBuffer();
while (results.moveToNext()) {
id = results.getInt(0);
name = results.getString(1);
price = results.getString(2);
info = results.getString(4);
quantity = Integer.parseInt(results.getString(5));
image = results.getBlob(6);
if (id == productID) {
textViewName.setText(name);
textViewInfo.setText(info);
textViewPrice.setText("S$" + price);
int[] quantityValues = new int[quantity + 1];
int counter = 0;
for (int i = 0; i < quantityValues.length; i++) {
quantityValues[i] = counter;
counter++;
quantityList.add(Integer.toString(quantityValues[i]));
}
Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
ivProduct.setImageBitmap(bitmap);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, quantityList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerQuantity.setAdapter(adapter);
}
}
}
}
public void addCart(View v) {
cartList.add(new CartItem(name, price,spinnerQuantity.getSelectedItem().toString(), image, id));
Intent productListIntent = new Intent(this, CartActivity.class);
startActivity(productListIntent);
}
You should impliment Serializable in CartItem class and then pass from ProductActivity to CartActivity . Like this :
ProductActivity class.
Intent productListIntent= new Intent(this, CartActivity .class);
productListIntent.putExtra("cartlist", ArrayList<CartItem>mcartItem);
startActivity(productListIntent);
and in CartActivity class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
ArrayList<CartItem> mycart= new ArrayList<CartItem>();
mycart= (ArrayList<CartItem>)getIntent().getSerializableExtra("cartlist");
listView = (ListView) findViewById(R.id.listView);
CartAdapter adapter = null;
adapter = new CartAdapter(this, R.layout.adapter_cart_item, mycart);
listView.setAdapter(adapter);
}
It's not the best practice, but you can make your arrayList
public static ArrayList list;
Then you can access it from ather activity using {class_name}.list
You have to pass your list of your data via intent(as Intent is a message passing Object) From ! activity to another activity. For that you have to make that class Parcable or Serializable . How to make a class Parcable in andriod studio read this answer. Then put thah class into the intent that you are passing to startActivity() method like
intent.putParcelableArrayListExtra("key",your_list);
or
intent.putExtra("key",your_class)// incase of single object
then get it to the onCreate() method of second activity like
getIntent().getParcelableArrayListExtra("your_key")
or
getIntent().getParcelableExtra()// incase of single object
Hope it will help your
Related
Currently i am working with an app that recommends the colleges to the students by taking the input as their aggregate Percentage. In the first activity I have one edit text used for percentage. In second activity I want to recommend the colleges according to input percentage for that i am using explicit intent (to pass the percentage from first activity to second) but i am not familiar with how to use that percentage to recommend the colleges list which suits the entered percentage.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button submitData;
EditText percentage;
public String pData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
setContentView(R.layout.activity_main);
percentage = (EditText)findViewById(R.id.studentpercentage);
submitData = (Button)findViewById(R.id.submitdetails);
submitData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
pData = percentage.getText().toString();
Intent intent = new Intent(getApplicationContext(), DisplayList.class);
intent.putExtra("Percentage", pData);
startActivity(intent);
}
}
);
}
}
DisplayList.java
public class DisplayList extends AppCompatActivity {
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
setContentView(R.layout.activity_display_list);
TextView percentage = (TextView)findViewById(R.id.textView);
Bundle bundle = getIntent().getExtras();
if (bundle.getString("Percentage")!=null) {
String per = (String)bundle.get("Percentage");
}
this.listView = (ListView)findViewById(R.id.listview);
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this);
databaseAccess.open();
List<String> colleges = databaseAccess.getColleges();
databaseAccess.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,colleges);
this.listView.setAdapter(adapter);
}
}
DatabaseAccess.java
/**
* Read all colleges from the database.
*/
public List<String> getColleges() {
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("SELECT * FROM Ahmednagar", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(1));
list.add(cursor.getString(2));
list.add(cursor.getString(3));
list.add(cursor.getString(4));
list.add(cursor.getString(5));
cursor.moveToNext();
}
cursor.close();
return list;
}
Pass the per variable in getColleges() method .
like- getColleges(per);
and change the method and query in db file
like -
public List<String> getColleges(String per) {
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("SELECT * FROM Ahmednagar Where Perentage="+per, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(1));
list.add(cursor.getString(2));
list.add(cursor.getString(3));
list.add(cursor.getString(4));
list.add(cursor.getString(5));
cursor.moveToNext();
}
cursor.close();
return list;
}
I'm trying to figure out how to get the data from a listView, store it in an Array, and be able to access that array of data in another activity. Would I do an Intent for this and pass it as an extra? I've searched around but haven't gotten a clear answer. I want to be able to access that array of data so that I can randomly display it in another activity.
listView.java
public class ListView extends AppCompatActivity {
private static final String TAG = "ListView";
private EditText editText;
private android.widget.ListView listView;
DatabaseHelper mDatabaseHelper;
Button btnAdd;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
mDatabaseHelper = new DatabaseHelper(this);
btnAdd = (Button) findViewById(R.id.btnAdd);
editText = (EditText) findViewById(R.id.editText);
listView = (android.widget.ListView) findViewById(R.id.lv);
ArrayList<String> list = getIntent().getStringArrayListExtra("myList");
android.widget.ListView lv = (android.widget.ListView) findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
//Takes user back to the main activity after clicking on back arrow
ImageView ivBack = (ImageView) findViewById(R.id.ivBackArrow);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: pressed back arrow");
Intent intent = new Intent(ListView.this, MainActivity.class);
startActivity(intent);
}
});
//Adds new hashtag to list and prompts if nothing is entered
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
if (editText.length() != 0) {
addData(newEntry);
editText.setText("");
} else {
toastMessage("you must put something in the text field");
}
}
});
populateListView();
}
/**
* Adds new data into the Database
* #param newEntry
*/
public void addData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Successfully inserted");
recreate();
} else {
toastMessage("Whoops, something went wrong");
}
}
/**
* Default toastMessage
* #param message
*/
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
/**
* Populate listView with data and create listener to navigate to editDeleteList
*/
private void populateListView() {
Log.d(TAG, "populateListView: displaying data in the listview");
//get data and append to list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()) {
//get the value from the database in column 1
//set it to the arraylist
listData.add(data.getString(1));
}
//create arraylist and set it to the adapter
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
listView.setAdapter(adapter);
//set onclick listen to edit activity
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String name = adapterView.getItemAtPosition(position).toString();
Log.d(TAG, "onItemClick: you clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while (data.moveToNext()) {
itemID = data.getInt(0);
}
if (itemID > -1) {
Log.d(TAG, "onItemID: the ID is: " + itemID);
Intent editScreenIntent = new Intent(ListView.this, EditDeleteList.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
} else {
toastMessage("No ID found");
}
}
});
}
/**
* Updates the listView after navigating back from EditDeleteList activity
*/
#Override
protected void onResume() {
super.onResume();
populateListView();
}
}
Get data from listView:
public static String[] getStringArray(ListAdapter adapter){
String[] a = new String[adapter.getCount()];
for (int i = 0; i < a.length; i++)
a[i] = adapter.getItem(i).toString();
return a;}
String[] array = getStringArray(myListView.getAdapter());
Send array from activity to another one:
Intent intent = new Intent(context, Class.class);
intent.putExtra("mylist", array);
Get it back within another activity:
ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("mylist");
You can pass an ArrayList<E> the same way, if the E type is Serializable.
I am assuming 1) You are modifying the ListView, 2) On press of button you want to go to another activity and have the data updated from listview in Activity2. From the ListView's adapter, you can create an interface (UpdateListListener) which will be implemented by the Activity1. Whenever you press button(after editing) you just a)Call notifyDatasetChanged() and on the implemented method listener(onUpdatedList()) you just send the list to the other activity with intent. Since List is an object you need to send the intent as below:
Intent intent = new Intent(this,Activity2.class);
intent.putExtra("myList", ListOfItems);
startActivity(intent);
Where ListOfItems implements Parcelable. You need to study how Parcelable works.
I am trying to bring all the items from the ArrayList getting saved in EditActivity to the MainActivity using SharedPreferences. But only the last entered data gets displayed in the ListView on the first MainActivity. How can I make all the text entered into the EditText get displayed as a different item in the ListView and not replace the earlier item.
Here is my Code:
MainActivity
public class MainActivity extends AppCompatActivity {
private ListView list;
private Button nextButton;
ArrayList<String> arrayList = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
nextButton = (Button) findViewById(R.id.nextButton);
loadData();
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList);
list.setAdapter(adapter);
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
nextActivity();
}
});
}
public void nextActivity(){
Intent intent = new Intent(this, EditActivity.class);
startActivity(intent);
}
public void loadData(){
SharedPreferences sp = getSharedPreferences("Data", Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = sp.getString("list", null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
arrayList = gson.fromJson(json, type);
if(arrayList == null){
arrayList = new ArrayList<String>();
}
}}
EditActivity
public class EditActivity extends AppCompatActivity {
private EditText input;
private Button addButton;
public ArrayList<String> list = new ArrayList<String>();
public ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
input = (EditText) findViewById(R.id.input);
addButton = (Button) findViewById(R.id.addButton);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String getInput = input.getText().toString();
adapter.addAll(getInput);
saveData();
input.setText(""); //clear the value in the edit text
}
});
}
public void saveData(){
SharedPreferences sp = getSharedPreferences("Data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString("list", json);
editor.apply();
}}
I think you forget to add item to list before save and thus the result is you are saving only the last item.
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String getInput = input.getText().toString();
list.add(getInput); //add this line
adapter.addAll(getInput);
saveData();
input.setText(""); //clear the value in the edit text
}
});
I have an app, where a user can enter a number and save to listView. The app is split into 3 activities.
The first activity is the MainActivity, which does something else. The second activity is where I enter a number and save it. The code Is below
public class HomeTeamScored extends Activity {
protected static EditText display;
protected static ArrayAdapter<String> adapter;
Button addButton;
CheckBox checkBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rect_activity_home_goal_player);
display = (EditText) findViewById(R.id.editText);
addButton = (Button) findViewById(R.id.btn);
checkBox = (CheckBox) findViewById(R.id.checkBox);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String task = display.getText().toString();
adapter.add(task);
adapter.notifyDataSetChanged();
SavePreferences();
Intent i = new Intent(HomeTeamScored.this, MainActivity.class);
startActivity(i);
finish();
}
});
}
protected void SavePreferences() {
// TODO Auto-generated method stub
SharedPreferences data = getApplicationContext().getSharedPreferences("saveNumber", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
for (int i = 0; i < adapter.getCount(); ++i){
// This assumes you only have the list items in the SharedPreferences.
editor.putString(String.valueOf(i), adapter.getItem(i));
}
editor.commit();
}
}
In my third activity, I retrieve the saved number.
public class ScoreBoardOverview extends Activity {
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rect_activity_score_board_overview);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
lv = (ListView) findViewById(R.id.listView);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
loadPreferences();
}
protected void loadPreferences(){
SharedPreferences data = getApplicationContext().getSharedPreferences("saveNumber", Context.MODE_PRIVATE);
for (int i = 0;; ++i){
final String str = data.getString(String.valueOf(i), "");
if (!str.equals("")){
adapter.add(str);
} else {
break; // Empty String means the default value was returned.
}
}
}
}
All this is working fine, and it adds a number to listView, but the problem is that it overrides the old value, were instead it should add a second row.
Anyone who can help??
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String task = display.getText().toString();
adapter.add(task);
adapter.notifyDataSetChanged();
SavePreferences();
Intent i = new Intent(HomeTeamScored.this, MainActivity.class);
startActivity(i);
finish();
}
});
}
here your adapter item size will be 0 when you call second activity each time. if you want to add second or third item you should write your
protected void loadPreferences(){
SharedPreferences data = getApplicationContext().getSharedPreferences("saveNumber", Context.MODE_PRIVATE);
for (int i = 0;; ++i){
final String str = data.getString(String.valueOf(i), "");
if (!str.equals("")){
adapter.add(str);
} else {
break; // Empty String means the default value was returned.
}
}
}
method in second activity too. and call loadPreferences() after this line
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
your adapter data size will be changed.
So I'm trying to pass some data from one activity from another and I have some difficulties doing that.
This is the code:
private TextView createNewTextView (String text){
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView newTextView = new TextView(this);
ArrayList<String> players = new ArrayList<String>();
Intent zacniIgro = getIntent();
newTextView.setLayoutParams(lparams);
newTextView.setText(text);
players.add(text);
zacniIgro.putStringArrayListExtra("players", players);
return newTextView;
}
public void zacniIgro (View v){
Intent zacniIgro = new Intent (getApplicationContext(), Igra.class);
startActivity(zacniIgro);
}
How do I now get the data in the new activity? I tried this but it doesn't work
ArrayList<String> players = data.getStringArrayListExtra("players");
Any ideas how else I could do this?
Retrieving list:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_igra);
ArrayList<String> players = data.getStringArrayListExtra("players");
}
It red underlines 'data' so I'm pretty sure there's something wrong with 'data'?
The problem is that you're creating a new intent when you start your new activity. Try this :
ArrayList<String> players = new ArrayList<String>(); //declare it outside of the function
private TextView createNewTextView (String text){
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final TextView newTextView = new TextView(this);
newTextView.setLayoutParams(lparams);
newTextView.setText(text);
players.add(text);
return newTextView;
}
public void zacniIgro (View v){
Intent zacniIgro = new Intent (getApplicationContext(), Igra.class);
zacniIgro.putStringArrayListExtra("players", players);
startActivity(zacniIgro);
}
On the other activity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_igra);
Intent data = getIntent();
ArrayList<String> players = data.getStringArrayListExtra("players");
}