List View not updating beyond one item - android

I am trying to send one item of a list on being long clicked to another activity's list.But the second activity i.e MySchedule doesnt update beyond one item.
Here's My code
Activity from where i am sending the string
(didnt added the code of string)
public class CloudEvents extends AppCompatActivity {
static int scheduleId = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
new AlertDialog.Builder(CloudEvents.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Save Event")
.setMessage("Do you want to save this event into your schedule?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
scheduleId++;
Toast.makeText(CloudEvents.this,"Saved",Toast.LENGTH_LONG).show();
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.yatin.whatshappeningdtu", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("CloudEvent",listView.getItemAtPosition(position).toString()).apply();
Intent i = new Intent(CloudEvents.this,MySchedule.class);
startActivity(i);
//myArrayAdapter.notifyDataSetChanged();
}
})
.setNegativeButton("No",null)
.show();
return true;
}
});
Activity Receiving the string and making a list
public class MySchedule extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_schedule);
final ArrayList<String> schedule = new ArrayList<>();
final ListView scheduleListView = (ListView)findViewById(R.id.scheduleListView);
String key = "CloudEvent";
String myEvent ="";
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.yatin.whatshappeningdtu", Context.MODE_PRIVATE);
if(sharedPreferences.contains(key))
{
myEvent = sharedPreferences.getString(key,"");
schedule.add(CloudEvents.scheduleId,myEvent);
}
final ArrayAdapter myArrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,schedule);
scheduleListView.setAdapter(myArrayAdapter);
scheduleListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
new AlertDialog.Builder(MySchedule.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure ?")
.setMessage("Do you want to delete this note")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
schedule.remove(position);
myArrayAdapter.notifyDataSetChanged();
CloudEvents.scheduleId--;
}
})
.setNegativeButton("No",null)
.show();
return true;
}
});
}
}
(after adding one item)
Error:Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.add(ArrayList.java:457)
at com.yatin.whatshappeningdtu.MySchedule.onCreate(MySchedule.java:35)
Being racking my brain for hours now.Please Help Thanks !

When you add item first time, your CloudEvents.scheduleId is set to 0 from -1. Suppose your string is "FirstEvent" that you save in CloudEvent key of sharedpreference, and then In MySchedule activity it is added in 0 position of schedule arraylist, and it works fine.
Now when you come back to CloudEvents activity, your CloudEvents.scheduleId is 0 because it's statica variable, and you add another item let's say "SecondEvent", so CloudEvents.scheduleId will change from 0 to 1, and you are saving "SecondEvent" string in CloudEvent key again in sharedpreference, so that previous value "FirstEvent" will override with "SecondEvent" that means in MySchedule activity you will only get "SecondEvent" from sharedpreference, but you are adding this in 1st position of schedule arraylist and 0th position of schedule arraylist will be left null.
Now you are passing this arraylist, with null value in 0th position, in Listview adapter, that's way it is throwing IndexOutOfBoundsException exception.
To solve this issue, you can maintain one ArrayList<String>.In CloudEvents activity make following changes.
private ArrayList<String> eventList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState){
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.yatin.whatshappeningdtu", Context.MODE_PRIVATE);
Collections.addAll(eventList, prefManager.getString("CloudEvent", "").split(","));
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
new AlertDialog.Builder(CloudEvents.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Save Event")
.setMessage("Do you want to save this event into your schedule?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
scheduleId++;
eventList.add(listView.getItemAtPosition(position).toString());
Toast.makeText(CloudEvents.this, "Saved", Toast.LENGTH_LONG).show();
Intent i = new Intent(CloudEvents.this, MySchedule.class);
i.putStringArrayListExtra("EventList", eventList);
startActivity(i);
//myArrayAdapter.notifyDataSetChanged();
}
})
.setNegativeButton("No", null)
.show();
return true;
}
});
}
Now in MySchedule activity make following changes.
public class MySchedule extends AppCompatActivity {
ArrayList<String> schedule = new ArrayList<>();
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_schedule);
sharedPreferences = getApplicationContext().getSharedPreferences("com.yatin.whatshappeningdtu", Context.MODE_PRIVATE);
schedule = getIntent().getStringArrayListExtra("EventList");
ListView scheduleListView = (ListView)findViewById(R.id.scheduleListView);
final ArrayAdapter myArrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,schedule);
scheduleListView.setAdapter(myArrayAdapter);
scheduleListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
new AlertDialog.Builder(MySchedule.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure ?")
.setMessage("Do you want to delete this note")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
schedule.remove(position);
myArrayAdapter.notifyDataSetChanged();
String events = "";
for(int i=0; i<schedule.size(); i++){
events = events + schedule.get(i);
if(i != (schedule.size() - 1)){
events = events + ",";
}
}
sharedPreferences.edit().putString("CloudEvent", events).apply();
}
})
.setNegativeButton("No",null)
.show();
return true;
}
});
}
}

Just try commit() instead of apply()
apply() was added in 2.3, it commits without returning a boolean indicating success or failure.
commit() returns true if the save works, false otherwise.
And also please confirm that the instance of shared preference which is used to read the data is same as the instance to which the data is written.

Related

Add a Multiple-Delete option in ListView Android

In my app, information like file names are stored in the externally storage. They are then implemented into the app with the help of ListView. I can delete files individually with OnItemLongClickListener() but I want to select multiple files in ListView and then click a Delete button. How can I do this? My MainActivity file is below:
public class MainActivity extends AppCompatActivity {
ArrayList<FileName> filenames;
ListViewAdapter adapter;
ListView lv_filenames;
public Handler handler;
private String _path = Environment.getExternalStorageDirectory() + "/sample_directory/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditorManager manager = new EditorManager(getApplicationContext());
manager.CreateNewDirectory();
lv_filenames = (ListView) findViewById(R.id.list);
handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
filenames = manager.GetList();
adapter = new ListViewAdapter(getApplicationContext(), R.layout.listView, filenames);
lv_filenames.setAdapter(adapter);
lv_filenames.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int file_name, long l) {
final File deleteFile = new File(_path + filenames.get(file_name).getName());
final String tempFileName = filenames.get(file_name).getName() + " is deleted";
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Delete File");
builder.setMessage("Do you really want to delete this file?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
boolean deleted = deleteFile.delete();
if (deleted) {
Toast.makeText(getApplicationContext(), tempFileName, Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// Do nothing.
}
});
builder.create();
AlertDialog dialog = builder.create();
dialog.show();
return false;
}
});
}
}
I deleted the extra code. Thanx for helping!
PS -
I heard that in Android 4.4 + files can't be deleted like this. What should I do?
EDIT -
I have seen those answers. But I want to create a button on whose click the check/uncheck buttons would be available. How can I do that? I want the Check/Uncheck buttons to be visible only when I click delete button. Also the other answers are a bit confusing.
I would have a button with a edit or delete icon and have it change the ListView to one with checkboxes in each view. Either make a new ListView with a new Adapter or just tell adapter and set a boolean in it, and then dataSetChange the Adapter.
I fixed my problem. I use a SparseBooleanAdapter to register the delete options.Then I press delete button to delete them.

sharedPreference will not save data while being invoked in onItemSelectedListener

I get a Set from a sharedPreference, I add a value to it, it saves fine. But when I completely close down the app and reopen... that value is gone. THis problem does not happen while I am doing it in an activity, but only in my Spinner listener code.
Here is what I have tried: I passed in the preference and editor object from the activity to the listener class through it's constructor. Therefore, no need to initilize anything. I still get the same error.
Also, I tried to start a instance of the Activity and save do my saving there... but that didnt work either.
I was not able to provide you any code, because it is on a different computer... but the code is not the problem, because that same code works great in an activity
update: code added
public class SpinnerListener1 extends Activity
implements AdapterView.OnItemSelectedListener {
SpinnerAdpter spinnerAdapter1;
Spinner addCtAvail;
String type;
Context c;
SharedPreferences.Editor edit;
SharedPreferences prefs;
// String value;
public SpinnerListener1(SpinnerAdpter vSpinnerAdpter, Spinner vaddCtAvail, String type, Context ctx,SharedPreferences prefs ,SharedPreferences.Editor edit ){
this.spinnerAdapter1 = vSpinnerAdpter;
this.addCtAvail = vaddCtAvail;
this.type = type;
this.c = ctx;
this.prefs = prefs;
this.edit = edit;
}//SpinnerListener1
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String selection = ((TextView) view).getText().toString();
if (selection.equals("new")) {
AlertDialog.Builder builder11 = new AlertDialog.Builder(c);
builder11.setTitle("Add a new value to List");
builder11.setMessage("Please Enter a Value");
builder11.setCancelable(true);
builder11.setIcon(R.drawable.ic_launcher);
final EditText input = new EditText(c);
input.setId(0);
builder11.setView(input);
builder11.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Tabs1 tabInstance = new Tabs1();
String newCTvalue = input.getText().toString();
// have the new entry appear in spinner:
spinnerAdapter1.remove("new");
spinnerAdapter1.add(newCTvalue);
spinnerAdapter1.add("new");
addCtAvail.setAdapter(spinnerAdapter1);
addCtAvail.setSelection(spinnerAdapter1.getCount());
saveNewValue(newCTvalue, type);
}
})
.setNegativeButton("CANCEL",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder11.create().show();
}
}//onItemSelected
public void saveNewValue(String value, String prefname){
Set set = prefs.getStringSet(prefname,null);
set.add(value);
edit.putStringSet(prefname , set);
edit.commit();
}//saveNewValue
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}//SpinnerListener
here is the code for my TabActivity which launches this listner:
public void createSpinner(View view, String type, String texttoShow , Spinner addLoadType){
//prefs = PreferenceManager.getDefaultSharedPreferences(Tabs1.this);
prefs = getApplicationContext().getSharedPreferences("SpinnerPrefs", 0);
edit = prefs.edit();
getSpinnerSharedPref(type);
final SpinnerAdpter spinnerAdapterLoadType = new SpinnerAdpter(this);
spinnerAdapterLoadType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpinnerListener1 spinnerlistenerLoadType = new SpinnerListener1(spinnerAdapterLoadType, addLoadType,type, Tabs1.this, prefs, editor);
addLoadType.setOnItemSelectedListener(spinnerlistenerLoadType);
getSpinnerPrefandPopulate(type,spinnerAdapterLoadType );
spinnerAdapterLoadType.add(texttoShow);
addLoadType.setAdapter(spinnerAdapterLoadType);
addLoadType.setSelection(spinnerAdapterLoadType.getCount()); //display hint

Retaining items in a List View

I'm new to android development having some problems. I created a list view that is based on the user input. User has to enter a category in a dialog box and then it's added into the list. Works like a charm. The question is how do I retain those categories once the user exits from an app and starts it again ? When the user starts the app, the list is blank. Do I have to create a preference screen or something to save what the user types ? Here is my code:
public class MainActivity extends Activity {
final Context context = this;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> listItems = new ArrayList<String>();
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView)findViewById(R.id.listView1);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.menu_add_cat:
LayoutInflater li = LayoutInflater.from(context);
View promptAdd = li.inflate(R.layout.prompt_add, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
//set prompts.xml to alertDialogBuilder
alertDialogBuilder.setView(promptAdd);
final EditText etAddCat = (EditText)promptAdd.findViewById(R.id.etDialogInput);
//set a dialog message
alertDialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/*
* add a cat here
*/
String input = etAddCat.getText().toString();
if(null != input && input.length() > 0){
listItems.add(input);
arrayAdapter.notifyDataSetChanged();
}else{
Toast.makeText(getApplicationContext(), "Please enter a new category", Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
break;
}
//return super.onOptionsItemSelected(item);
return true;
}
}// end of MainActivity
You can save it in SQLite DB, use CursorAdapter for your list view.
If the amount of data you want to save is relatively small you can use SharedPreferences to save the String data in your onClick method.
#Override
public void onClick(DialogInterface dialog, int which) {
String input = etAddCat.getText().toString();
if(null != input && input.length() > 0){
listItems.add(input);
// Add all string data to List<String> listItem
listItem.add(input);
arrayAdapter.notifyDataSetChanged();
}else{
Toast.makeText(getApplicationContext(), "Please enter a new category", Toast.LENGTH_LONG).show();
}
}
When the user leaves your activity, use the onStop() callback method to save your List<Strings> and store it through SharedPreferences.
#Override
private void onStop() {
super.onStop();
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(getResources().getString(R.string.list_of_strings), new HashSet<String>(listItem));
editor.commit;
}
Using the onStart() callback, initialize your List and SharedPreferences. When the user navigates to your activity, your list will be reinitialized when it was saved via onStop().
Finally, iterate through your list, add your items to your ArrayList', create yourArrayAdapter` and set it to your list.
#Override
private onStart(){
super.onStart();
SharedPreferences mSharedPreferences;
mSharedPreferences = this.getApplicationContext().getSharedPreferences("MyPreferences", 0);
List<String> listItems = new ArrayList<String>(mSharedPreferences.getStringSet("ListOfStrings", null));
ListIterator li = listItem.listIterator(0);
while (li.hasNext()) {
newStatusList.add((String)li.next());
}
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
}

Listview + Adapter - delete item and Refresh, not working - Android

this question is is similar to this
* Android - Listview delete item and Refresh
and this (the same , but I added the full code here to check if I have any problems in my code):
please give me code example. . .
can i call an intent to refresh my list ?
I cant refresh my adapter with :
adapter.notifyDataSetChanged();
I tried:
adapter.remove(adapter.getItem(pos));
but without success, just one time (weird...).
there is another answer there:
Call that Activity once again Using Intent
sombody can give me the exact code for this (or for the adapter/cursor) ?
I am trying this for a couple of hours without success.
my full code:
protected void onCreate (Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.personalmessageview);
headtitle= getIntent().getExtras().getString("head");
setTitle(headtitle);
personalresults = getIntent().getExtras().getStringArrayList("personalres");
personalresultswithtime = getIntent().getExtras().getStringArrayList("personalrestime");
// setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,personalresults));
ListView list = (ListView)findViewById(R.id.listview_personal);
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, personalresults);
list.setAdapter(adapter);
registerForContextMenu(list);
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
String time = personalresultswithtime.get(pos).toString();
Show_Alert_box(v.getContext(),"Please select action.",time,pos);
return true;
}
});
public void Show_Alert_box(Context context, String message,String time,int position)
final String timestamp = time;
final int pos = position;
final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(getString(R.string.app_name));
alertDialog.setButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try
{
db = databaseHelper.getWritableDatabase();
db.delete("messages","timestamp" + "=?", new String[] { timestamp });
Log.d("DB"," delete! ");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PersonalMessageView.this, android.R.layout.simple_list_item_1, personalresults);
adapter.remove(adapter.getItem(pos)); //not working t all! why ?
list.notify();
list.invalidate();
personalresults.remove(pos);
personalresultswithtime.remove(pos);
adapter.notifyDataSetChanged();
db.close();
}
catch(Exception e)
{
}
} });
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
} });
alertDialog.setMessage(message);
alertDialog.show();
}
Inside your onClick of Dialog, you are dealing with an entirely new Adapter.There is no accociation of adapter(inside onClick()) to the listView Either you should say list.setAdapter(adapter); inside the onClick() method or make the adapter global.
instead of using
adapter.remove(adapter.getItem(pos));
use
string str=list.getItemAtPosition(index).toString();
personalresults.remove(str);
adapter.notifyDataSetChanged();

Android save state for dialog

How do you save the state of a dialog in android? I have the following dialog with radio buttons but can't figure out how to save the state of the dialog. Thanks for any help
final CharSequence[] items = {"Item 1", "Item 2", "Item 3"};
AlertDialog.Builder builder = new AlertDialog.Builder(Tweaks.this);
builder.setTitle("Pick an item");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
}).show();
You should store the position of the selected item when the user clicks. Then you look for a previously stored index when you display the list. If there is no previously stored value you return -1.
I have an app Preferences helper class ...
public class AppPreferences {
private static final String APP_SHARED_PREFS = "myApp_preferences"; // Name of the file -.xml
private SharedPreferences appSharedPrefs;
private Editor prefsEditor;
public AppPreferences(Context context)
{
this.appSharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
public int getItemIndex() {
return appSharedPrefs.getInt("itemIndex", -1);
}
public void saveItemIndex(int i) {
prefsEditor.putInt("itemIndex", i);
prefsEditor.commit();
}
}
Then, in my code I create a field variable ...
protected AppPreferences appPrefs;
And instantiate an instance of it inside the Activity onCreate() ...
appPrefs = new AppPreferences(getApplicationContext());
Then replace your "-1" with ...
builder.setSingleChoiceItems(items, appPrefs.getItemIndex(), new DialogInterface.OnClickListener() {
And in your onClick() make sure you ...
appPrefs.saveItemIndex(item);
I saved the state in member variables in the DialogFragment. The following code saves the state when the dialog is closed, but not when the app is closed.
public class MyDialogFragment extends DialogFragment {
//this is the default value, set when the dialog is created
private String myValue = "any initial String";
private TextEdit myTextEdit;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//construct the dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
ViewGroup myView = (ViewGroup)inflater.inflate(R.layout.my_view, null);
builder.setView(myView);
//find the view and set the value
myTextEdit = (TextView)myView.findViewById(R.id.my_text_edit);
myTextEdit.setText(myValue);
return builder.create();
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
//when the dialog is dismissed, save the users input and overwrite the initial value
myValue = myTextEdit.getText();
}
}
You can use preference but i would recommand to use the new androidx design pattern. Basically, saving dialog state should not be saved when application is closed. That is we want (so we don't need preferences or something like that).
You can use android view model and saved state to do this work.
Here is a link to show dependencies and versions to use with gradle (https://developer.android.com/jetpack/androidx/releases/lifecycle)
implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-rc01'
You can do like this.
public class HelloAndroidViewModel extends AndroidViewModel{
private SavedStateHandle mState;
public HelloAndroidViewModel(SavedStateHandle savedStateHandle) {
mState = savedStateHandle;
}
public void saveParam(int param){
mState.set("key", param);
}
public int getParam(){
Integer param = mState.get("key");
if(param != null){
return param.intValue();
}
// default value
else {
return -1;
}
}
}
public class HelloAndroid extends Activity {
HelloAndroidViewModel viewModel;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewModel = ViewModelProviders.of(this, new SavedStateViewModelFactory(getApplication(), this).get(AndroidViewModel.class);
}
Then you can use value to retrieve and store with your dialog.
final CharSequence[] items = {"Item 1", "Item 2", "Item 3"};
AlertDialog.Builder builder = new AlertDialog.Builder(Tweaks.this);
builder.setTitle("Pick an item");
builder.setSingleChoiceItems(items, viewModel.getParam(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// save ui state
viewModel.setParam(item);
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
}).show();

Categories

Resources