I'm trying to implement a listview and what I want exactly is:
The app launches, 1 item from ListView is being chosen and starts a webview. This step is done
But what I want is that 2. time when I launch the app, it will start from that item and not show the list again. So it will continue always to start on that item I pressed first time.
I hope someone can show me a tutorial I can follow or some keyword I will try to see if I can do it.
*UPDATE --> Code
public class AndroidListViewActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, adobe_products));
ListView lv = getListView();
SharedPreferences prefs = getSharedPreferences("PREFERENCE", MODE_PRIVATE);
boolean firstrun = prefs.getBoolean("firstrun", true);
if (firstrun) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstrun", false);
editor.apply();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(getApplicationContext(), EnkeltView.class);
// sending data to new activity
i.putExtra("url", "https://google.dk");
startActivity(i);
}
});
}
// Save the state
getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.edit()
.putBoolean("firstrun", false)
.commit();
}
}
Use SharedPreference works like a DB but in a small scale:SharedPreference
Android documentation: This data will persist across user sessions (even if your application is killed).
So SharedPreferences shouldn't be getting wiped when a device reboots or force closes.
you can store item in shared preferences in 1st time and during second time you can check if your shared Preference is not null then It launch the application with item stored in it.
Related
I have a weird bug which I'm not sure why it's happening,
I have 2 activities: activity A and activity B.
When the app starts, it initializes a spinner once. I go to the second activity and then go back <-
onRestart() of the Activity A will be called. My problem is that even though I clear my spinner and reinitialize it in onRestart() it keeps reading the values.
For example, if spinner has 1/2 when you go to activity B then back to activity A, spinner has = 1/2/1/2.
I find this weird because when I just set the spinner adapter to null and comment out my initialize of spinner when I go back to activity A from activity B, my spinner is empty.
here is my code:
#Override public void onRestart() {
super.onRestart();
Spinner location = findViewById(R.id.spinnerLocation);
location.setAdapter(null);
initSpinner();// if this is commented out spinner is cleared, if not commented the same valus are added again
}
here is code for initSpinner(reads from shared prefs) this is not the problem
public void initSpinner(){
Spinner location = findViewById(R.id.spinnerLocation);
location.setAdapter(null);
SharedPreferences prefs = this.getSharedPreferences("Locations", Context.MODE_PRIVATE); //preffilename
SharedPreferences.Editor editor = prefs.edit();
editor.putString("1","St. Catharines");
editor.putString("2","Toronto");
editor.putString("3","Niagara Falls");
editor.commit();
int s = prefs.getAll().size();
for(int f=0;f<25;f++) {
if (prefs.getString(String.valueOf(f + 1), null) != null) {
DefaultLocations.add(prefs.getString(String.valueOf(f + 1), null));
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, DefaultLocations);
//set the spinners adapter to the previously created one.
location.setAdapter(adapter);
}
do
DefaultLocations.clear() before for loop inside initSpinner() method it may not clear when u adding new values
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
This is my method to change a color of a single ListView item. But I want to remember the color of the last selected item and, if the Activity is created (in onCreate() method), show it.
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
l.getChildAt(position).setBackgroundColor(Color.GREEN);
if (save != -1 && save != position){
l.getChildAt(save).setBackgroundColor(Color.WHITE);
}
save = position;
}
EDIT:
This is onCreate method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_go_to_alarams);
preferences = this.getSharedPreferences("com.example.projektzaliczeniowy", Context.MODE_PRIVATE);
lv = (ListView) findViewById(android.R.id.list);
setListAdapter(adapter);
int save = preferences.getInt("positionNr", -1);
if (save != -1){
lv.getChildAt(save).setBackgroundColor(Color.GREEN); // **HERE IS AN ERROR**
}
}
This is fragment of my xml:
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.39"
android:clickable="true" >
</ListView>
Sorry for my English :) Can you help me?
Change the code of your if to this:
SharedPreferences prefs = this.getSharedPreferences(getPackageName(),MODE_PRIVATE);
int save = prefs.getInt("selected", -1);
if (save != -1 && save != position){
l.getChildAt(save).setBackgroundColor(Color.WHITE);
}
prefs.edit().putInt("selected",position).apply();
And on your onCreate
SharedPreferences prefs = this.getSharedPreferences(getPackageName(),MODE_PRIVATE);
int save = prefs.getInt("selected", -1);
if(save!=-1)
listview.getChildAt(save).setBackgroundColor(Color.WHITE);
Use shared preferences
To store the int color value
SharedPreferences pref = getActivity().getSharedPreferences("preferences_app", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("color", Color.GREEN);
editor.commit();
//To retrieve and use the int color value
SharedPreferences pref = getActivity().getSharedPreferences("preferences_app", 0);
SharedPreferences.Editor editor = pref.edit();
Integer color = pref.getInt("color", null);
if(color != null) yourView.setBackgroundColor(color);
You can store the color and the position of the selected item in the SharedPreferences
EDIT: Since the SharedPreference is already given as an answer by #Pedro Oliveira, I will give you some other options.
Global variables for the class:
int position;
int color;
ListView lView;
You can store the position in a Bundle i.e. savedInstanceState:
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// This bundle will be passed to onCreate if the process is
// killed or reset.
savedInstanceState.putInt("Position", position);
savedInstanceState.putInt("Color", color);
}
And then in your onCreate():
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// here you can initialize your ListView
lView = (ListView) findViewById(YOUR_ID);
// get the position and color from the instance
// state we saved in onSaveInstanceState
if(savedInstanceState != null) {
position = savedInstanceState.getInt("Position");
color = savedInstanceState.getInt("Color");
}
// Create OnListItemClickListener and color the item at position
}
The Bundle will get passed to onRestoreInstanceState() so you can use that as well:
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// This bundle has also been passed to onCreate.
position = savedInstanceState.getInt("Position");
color = savedInstanceState.getInt("Color");
}
To remember a list item, you can also give each list item an id:
dynamically by calling the setId(__ID__) method
statically in your XML file where the ListView is defined by adding id="__ID__" property
Then you can store this Id String either in SharedPreferences or in a Bundle savedInstanceState and use this Id to get the item in your onCreate().
The simplest way to save temporary state of an activity is to override onSaveInstanceState(). This method receives a Bundle parameter. You can add data to this Bundle which will later be passed to your onCreate() method when the activity restarts.
Note that this process only occurs when the activity is destroyed and restarted. If the user returns to the activity by clicking the back button, the activity may not have been destroyed. However, this isn't a problem because all of the activity's settings have been preserved in memory and will be used when the activity is displayed again.
I know it is an old question but this problem also happened to me.
I wanted to highlight the item selected and remember that selection even if the app was closed and started again.
Here my solution.
*All the code below was implemented on the onCreate
private ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, users){
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = super.getView(position, convertView, parent); //store the view on a variable, so you can use it later
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); //initialize sharedPreferences
int id = sharedPreferences.getInt("CURRENT_ID", -1);
if (position == id) {
int colorId = sharedPreferences.getInt("CURRENT_COLOR", -1);
view.setBackgroundColor(colorId);//Here we can get access to the specific item, and set the color
} else {view.setBackgroundColor(1);}
return view;
}
};
listView.setAdapter(adapter);
In summary, From the onCreate method you do not have access to an specific adapter item, you need to implement the getView and use:
view.setBackgroundColor(colorId);
Unlike the listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
you can easily get access via parent.getChildAt(someIdPosition)
I hope this can be helpful for someone in the future.
I am to android coding and have what I hope will be a simple question. I have an app that has a demographics page, with various spinners (although I will only use 1 for this example). The spinners are already populated, but the user can save them once they have made their choice so every time they open this app the previous choices are there.
My code to load the values into the spinner is
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_demographics);
// Show the Up button in the action bar.
setupActionBar();
SharedPreferences prefs = getSharedPreferences("data_file", MODE_PRIVATE);
int ageValue = prefs.getInt("Age", 0);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
//set the default according to value
spinner.setSelection(ageValue);
}
and then my code to save the data is
public void submitDemo(View view) {
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
int ageValue = spinner.getSelectedItemPosition();
//save the current data from the spinner
SharedPreferences prefs = getSharedPreferences("data_file", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("Age", ageValue);
editor.commit();
finish();
}
I'm not bothered about capturing the value when they change the spinner, just simply at the end. I know it's probably something simple that I'm missing, but if anyone can help I would greatly appreciate it
First, set an adapter:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(),
android.R.layout.simple_spinner_item,
getResources().getStringArray(R.array.your_string_array));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
If setSelection(value) doesn't work try with
spinner.setSelection(ageValue, true);
This will "animate" the selection, i.e. scroll it to the selected position.
I have included my ListAdapter in my EMPLOYEE class.And list1 contains the values of Empname,
Eno,Salary fetched from webservices.Now after displaying the 5 records in the employee
screen...when I click on Depatrment Activity and come back to Employee ... the initial
5 records are appended to the list and now 10 records are present and so on .... the process is going on like this...
Please help me so as no duplicates are appended and it has to refresh the list.
Note : clear() or notifydatasetchanged(), invalidate() are not working.
ListAdapter adapter = new SimpleAdapter(this, list1,
R.layout.employee, new String[] { "EmpName","Eno", "Salary" }, new int[]
{R.id.ename, R.id.eno,R.id.sal});
setListAdapter(adapter);
Listview lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
pos = position;
registerForContextMenu(getListView());
}
});
TextView tvdept = (TextView) findViewById(R.id.Department);
tvdept.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Employee.this, Department.class));
}
});
Without seeing more code, it's difficult to be sure, but I'll hazard a guess...
When you leave an activity and come back, the framework tries to restore you to where you were using the savedInstanceState bundle. It uses this to re-create where you last were in that activity. It sounds like you have set up the list in the onCreate method and haven't checked for a savedInstanceState bundle, so when you come back to the activity the framework is restoring your list and then proceeds into your code and re-creates the list (in this case adding the same data again).
Try wrapping your list creation code in an if that checks for the existence of the savedInstanceState bundle.
Like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// do your list setup here
}
}
Using that, if you come back to the activity and the framework saved your state, it will simply restore it and not run through your list creation code.
I know this doesn't answer the actual question, but it should solve the root issue (duplicating list data on return to activity).