New arraylist item overwrites previous listview item - android

Currently I'm trying to send intent data from user input to display onto my custom adapter. The intent data from user input from the detailspage.java class will be sent to the listview page with custom Arrayadapter. However each time i add a new item it overwrites my previous entries. Hope some kind souls can help someone new to android.
Below are snippets of my code.
// Set a click listener on that button
btnAddData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveExercise(exerciseName);
}
});
}
private void saveExercise(String name) {
// Read from input fields
// Use trim to eliminate leading or trailing white space
String setString = mSetEditText.getText().toString().trim();
String repString = mRepEditText.getText().toString().trim();
String nameString = name;
Intent intent = new Intent(ExerciseDetailActivity.this, WorkoutSetActivity.class);
intent.putExtra("name", nameString);
intent.putExtra("set", setString);
intent.putExtra("rep", repString);
startActivity(intent);
}
The intent data will be sent to the activity page to initiate the custom ArrayAdapter.
public class WorkoutSetActivity extends AppCompatActivity {
ArrayList<WorkoutSet> workout = new ArrayList<WorkoutSet>();
/** Adapter for the ListView */
WorkoutSetAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.exercise_list);
adapter = new WorkoutSetAdapter(this, workout);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
Intent intent = this.getIntent();
String name = intent.getExtras().getString("name");
String set = intent.getExtras().getString("set");
String rep = intent.getExtras().getString("rep");
adapter.add(new WorkoutSet(name,set,rep));
Toast.makeText(WorkoutSetActivity.this, "Workout added.", Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
}
}
Lastly the custom ArrayAdapter code. This is where I set the custom listview.
public class WorkoutSetAdapter extends ArrayAdapter<WorkoutSet> {
public WorkoutSetAdapter(Activity context, ArrayList<WorkoutSet> workout) {
super(context, 0, workout);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.activity_workout_set, parent, false);
}
WorkoutSet currentWorkout = getItem(position);
// Find individual views that we want to modify in the list item layout
TextView nameTextView = (TextView) listItemView.findViewById(R.id.workout_name);
TextView setTextView = (TextView) listItemView.findViewById(R.id.workout_set);
TextView repTextView = (TextView) listItemView.findViewById(R.id.workout_rep);
nameTextView.setText(currentWorkout.getName());
setTextView.setText("Sets: "+ currentWorkout.getSet());
repTextView.setText("Reps: "+ currentWorkout.getRep());
return listItemView;
}
}

each time i add a new item it overwrites my previous entries
There are no "previous entries". startActivity loads an empty adapter each time and you only add one element.
What you want is a SQLite database (or any persistent storage layer, but SQLite is provided without more libraries).
On the plus side, your Intent and Adapter code look fine.

Every time,you call startActivity (), you open a new WorkoutSetActivity, it's a new WorkoutSetActivity object instance, so the arrayAdapter is also new one, it will only display the data you send this time.
If you want to display all the data, you must save the previous data to database or file. At WorkoutSetActivity onCreate (), you should get the previous data, put them and current data to the adapter.

Related

How to Highlight the Item (Listview) of Next Activity After Clicking the Item(Listview) of Previous Activity?

I have two Fragments. One Fragment Consist of Questions While OtherFragment consist of Answers. For Example If one person click on Question(8) It means u can say that Item No 8, then it should go to next activity and highlight the Answer (8) of that Question. I am stuck. I shall be thank full to you.
Here is Some Code Which are sending Question No or list Item no to next Activity and next Activity code receiving this Question no and i saved it into Interger "a". Now what type of IF condition can work in the Next Activity?
First Activity
lst.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int index = position + 1;
Intent it = new Intent(this.getActivity(), NextActivity.class);
it.putExtra("Qlist", index);
startActivity(it);
}
Next Activity
Intent it = getActivity().getIntent();
int a = it.getIntExtra("Qlist", 0);
String result=String.valueOf(a);
Toast.makeText(getActivity(), ""+a, Toast.LENGTH_LONG).show();
ListView Adapter code of First Activity (using SQlite)
DatabaseAccess db=DatabaseAccess.getInstance(getActivity().getApplicationContext());
List<String> lst;
db.open();
lst=db.getexamq();
db.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ExamQ.this.getActivity(), android.R.layout.simple_list_item_1, lst);
lv.setAdapter(adapter);
ListView Adapter code of Next Activity (using SQlite)
DatabaseAccess db=DatabaseAccess.getInstance(getActivity().getApplicationContext());
List<String> lst;
db.open();
lst=db.getexamq();
db.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ExamA.this.getActivity(), android.R.layout.simple_list_item_1, lst);
lv.setAdapter(adapter);
Use the intent Bundle to move the questionId or question No to the next activity
In the adapter of the Questions ListView, set a different background color for the question with a similar questionId. You can even set the background to have a fade animation or change to normal after a certain number of milliseconds or seconds.
ALL THE CODE REQUIRED IS A LOT Write something(some code), and we can help on the ListViewAdapter in case it doesn't work
EDIT: SAMPLE FAST CUSTOM ADAPTER CODE
lv.setAdapter(new ArrayAdapter(ExamQ.this.getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, lst){
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
final String examQ = lst[position];
if (v == null) {
LayoutInflater vi = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(android.R.layout.simple_list_item_1, null);
}
TextView tv = (TextView) v.findViewById(android.R.id.text1);
tv.setText(examQ);
if( examQ.equals(result)) { // Unique identifier here
v.setBackground(Color.RED); //Some other fancy color here
}
return v;
}
});
However, I just discovered you do not have a unique identifier for each question. So for the time being just use the question string and pass it to the next activity
Suppose You have a textview for each answer in the listview of second fragment. Then you can compare the question id in the getView() of adapter of listview in second fragment. Now when you find your answer just call textview.setBackgroundColor().
Edit:
After lv.setAdapter (adapter); add
View v = lv.getViewAt(a);
if(v!=null)
v.setBackgroundColor (Color.RED);

ListView item gets destroyed while moving to other activity

My first activity contains a listview with textviews in each cell and uses a custom adapter. So if you click on any of the items, it will open up a form activity containing textfields. The user can fill up the details and once they press the save form button the details appear on the listview. Now I am trying to add items to the list dynamically. I have created a button which when clicked adds a new instance item so that more users can register the same way. I have been able to implement these functions. However, my problem now is when i click on the newly added item and go to the form activity and click save, i am not able to see the newly added entry after i come back to the listview activity.All I see is the first entry alone. So i am guessing it gets destroyed as soon as i leave the activity. How to ensure all newly added items are not destroyed when i keep moving between these two activities.
Here is my code of the ListView Activity:
public class FormTableActivity extends Activity {
private PassengerListAdapter adapter;
Button add_passenger;
String mrzdata,ic_data,name_data;
SharedPreferences nPref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.final_display_listview);
nPref = PreferenceManager.getDefaultSharedPreferences(this);
mrzdata = nPref.getString("MRZ", "");
name_data = nPref.getString("resultData", "");
ic_data = nPref.getString("icdata", "");
final ListView lv1 = (ListView) findViewById(R.id.custom_list);
adapter = new PassengerListAdapter(this);
adapter.add(new CustomerDetails(ic_data, name_data, mrzdata));
add_passenger = (Button) findViewById(R.id.add_user);
add_passenger.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// mrzdata = "";
// name_data = "";
// ic_data = "";
adapter.add(new CustomerDetails(ic_data, name_data, mrzdata));
}
});
lv1.setAdapter(adapter);
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Intent intent = new Intent(v.getContext(), FirstActivity.class);
startActivity(intent);
}
});
}
The easiest way to pass data between Intent is
Intent intent = new Intent(getBaseContext(), your_list_view_activity.class);
intent.putExtra("String_Key", data1);
//data1 could be an array of string where you have hold the values previously
startActivity(intent);
now on your list_view_activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
String [] value = extras.getString("String_Key");
}
This way you won't get any exception but you get to populate your listView if there is data.
Another way to get data is via SharedPreference but I won't recommend it as it increases the size of the app.
You have to save these newly added items somewhere , e.g. to a SQLite database and retrieve them on create to populate the listview
You can see here if You want, the code is commented ,
here I have a listview with custom adapter with two items
the feed's name and it's url
i add URL and name using a text input dialog (with two edit text), save to DB, and retrieve them on create to populate the listview
https://github.com/enricocid/iven-feed-reader/blob/master-as/project/app/src/main/java/com/iven/lfflfeedreader/mainact/ListActivity.java

Transfer two listview data on click of one listview

In my activity I have two listviews with some data. On first listview selected row will be highlighted on click and on click on 2nd listview new activity starts.
I want to send the highlighted row data of first listview and clicked row of 2nd listview data on next activity. How can Iachieve that?
supposing your lists are named list1 & list2, add to your list2 onItemClickListener that should looks something like this :
public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) {
String highlightedItem = (String)list1.getSelectedItem();
String clickedItem = (String)list2.getItemAtPosition(position);
Intent intent = new Intent(FirstAcivity.this, SecondActivity.class);
intent.putExtra("highlightedItem", highlightedItem);
intent.putExtra("clickedItem", clickedItem);
startActivity(intent);
}
and then in your Second Activity you can receive the items like this :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent intent = getIntent();
if (intent != null){
String highlightedItem = intent.getStringExtra("highlightedItem");
String clickedItem = intent.getStringExtra("clickedItem");
}
}
I have assumed your list items are of type String but you can apply the same logic for any other type.
In case your want to send object not just primitives you need to make your objects implements Serializable or Parcelable interface.

Android programming: I cant get data to reload into arrayadapter

I am still stuck with this issue, can anyone help. It seems that my problem is that I cant update the data list. I have tried every solution that I've searched for on google etc.. but half the time i'm not even sure that I'm doing the correct thing.
I've used the onResume() to call notifyDataSetChanged, it didn't work. I've tried putting a refresh method into the adapter which i then called in OnResume(). Again it didn't work. Some people suggest clearing the adpater (adapter.clear();) in onResume and then using the addAll() function to relist the data but nothing works.
There has to be a simple solution to this. I have literally been stuck on this for 2 days now. very frustrated.
Here's my Fragment code again...
enter code here
public class SavedAppFragment extends ListFragment {
private static final String TAG = "AppClicked"; //DEBUGGER
private ArrayList<App> mSavedApps;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Populate the ArrayList
mSavedApps = SavedAppData.get(getActivity()).getApps();
AppAdapter adapter = new AppAdapter(mSavedApps);
setListAdapter(adapter);
}
//LIST ITEM CLICKED: /*Control what happens when list item is clicked: I.E. Load up a quiz while putting an EXTRA key containg the package name of the App to be launhced should the user get the question correct */ #Override public void onListItemClick(ListView l, View v, int position,long id) { //Return the crime for the list item that was clicked App c = ((AppAdapter) getListAdapter()).getItem(position); Log.d(TAG, "was clicked");
//Start the Activity that will list the detail of the app
Intent i = new Intent(getActivity(), Quiz_Activity.class);
String name = c.getPackage();
i.putExtra("packagename", name);
startActivity(i);
}
private class AppAdapter extends ArrayAdapter {
private ArrayList<App> mSavedApps;
public AppAdapter(ArrayList<App> apps) {
super(getActivity(), 0, apps);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//If we weren't given a view, inflate one
if (null == convertView) {
convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_app, null);
//((AppAdapter) getListAdapter()).notifyDataSetChanged();
}
((AppAdapter) getListAdapter()).notifyDataSetChanged();
//Configure the view for this crime
App c = getItem(position);
TextView nameTextView = (TextView) convertView.findViewById(R.id.app_name);
nameTextView.setText(c.getName());
// nameTextView.setText(applicationInfo.loadLabel(packageManager));
TextView packageTextView = (TextView) convertView.findViewById(R.id.app_package);
packageTextView.setText(c.getPackage());
CheckBox appCheckBox = (CheckBox) convertView.findViewById(R.id.app_checked);
appCheckBox.setChecked(c.isChecked());
//Return the view object to the ListView
return convertView;
}
}
}
THANKS!!!
When you return to Activity B, the previous Activity B hasn't been destroyed. Thus, it skips the onCreate. Move all of the stuff you want to make sure happens every time into the onResume. I think you want to make your Adapter a class variable (I'll call it mAdapter) in onCreate, and add code that will get data from the list directly. If you need to do something, put a "refresh" function in the adapter. I'm assuming you have a custom Adapter, because I've never heard of AppAdapter. If you don't, then extend AppAdapter and add that functionality. Thus, your onCreate should look like this:
mAdapter = new AppAdapter(mSavedApps);
setListAdapter(mAdapter);
Your onRefresh could update the data contained in the adapter by some new update function, like so:
mAdapter.update(SavedAppData.get(getActivity()).getApps());

Android app - how to display a list of items and make them clickable

I need to display a list of text items to the screen and make them clickable. So it would be something like a list of links on a web application.
How can I do that in an Android Activity screen?
It would be some random number of items that I have to pull from a db and display all as links.
Any idea how that can be done?
You should read the doc about ListActivity, ListView and follow the Hello ListView tutorial.
Yes you can do it. Create a DataExchange class to fetch it from Db..
Store the Strings in an Array.
Create a ArrayAdapter to display the array of Strings you got from the database.
for Example
public class AndroidListViewActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
String[] numbers = {"one","two","three","four"}
// here you store the array of string you got from the database
// Binding Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, numbers));
// refer the ArrayAdapter Document in developer.android.com
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String num = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("number", num);
startActivity(i);
}
});
}
}
The secondActivity to display the Particular item you have clicked should be
public class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_item_view);
TextView txtProduct = (TextView) findViewById(R.id.product_label);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("number");
// displaying selected product name
txtProduct.setText(product);
}
}
you have to create various layout files accordingly..
Hope this helps you :)
You should use a ListView. It's very simple, just create a ListActivity, put your items inside an Adapter and then set it as the Adapter of your ListActivity.
You can read more about ListViews here
There is also a new paradigm called ListFragment.
I have used ListViews before but prefer the fragments approach now - it's just very straight forward and quite flexible esp on tablets since the interation with another area on the screen when selecting an item is quite flexible and only requires very little code.
Just one example:
public class Select_FoodCategories_Fragment extends android.app.ListFragment {
private static final boolean DEBUG = true;
#Override
public void onCreate(Bundle savedInstanceState) {
if (DEBUG)
Log.i(this.getClass().getSimpleName(), " ->"
+ Thread.currentThread().getStackTrace()[2].getMethodName());
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (DEBUG)
Log.i(this.getClass().getSimpleName(), " ->"
+ Thread.currentThread().getStackTrace()[2].getMethodName());
HoldingActivity a = (HoldingActivity) getActivity();
//accessing a variable of the activity is easy
a.visibleListViewInFragment = getListView();
List<XYZ> listTodisplay = a.getListToDisplay();
MyAdapter adapter = new MyAdapter(
getActivity(), 0, listTodisplay);
setListAdapter(adapter);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
if (DEBUG)
Log.i(this.getClass().getSimpleName(), " ->"
+ Thread.currentThread().getStackTrace()[2].getMethodName());
XYZ item = (XYZ) getListAdapter()
.getItem(position);
}
}
More info here: http://developer.android.com/reference/android/app/ListFragment.html
By the way, I find it really worth it to get familiar with the new fragments concept - it just makes live much easier - esp on tablets!
ps I left the debug statements in on purpose - since it helps alto to understand the whole concept much faster in my experience

Categories

Resources