Android, refresh listview after click on list item - android

I have one small problem, after i click on list item, checkbox on item dont change state. Update works perfectly, setChecked maybe, but change will appear after exiting and re-running activity. I read lot of about notifyDataSetChange(), it may work, but not. How can i fix it, like after click on item chechbox value will change.
public class SviatokPridajActivity extends Activity
{
private DatabaseOp mDbHelper;
ListView listview;
String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sviatok_pridaj);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
listview = (ListView) findViewById(R.id.listSviatok);
showUserSettings();
mDbHelper = new DatabaseOp(this);
mDbHelper.open();
Cursor sviatokCursor = mDbHelper.fetchAllSviatokNastav(username, 3);
if (sviatokCursor.getCount()==0)
{
mDbHelper.naplnSviatky(username);
sviatokCursor = mDbHelper.fetchAllSviatokNastav(username, 3);
}
final SviatokCursorAdapter adapter = new SviatokCursorAdapter(this, sviatokCursor);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int stlpec, long arg3)
{
// TODO Auto-generated method stub
Cursor cur = (Cursor) adapter.getItem(stlpec);
String odosli = cur.getString(cur.getColumnIndex("_id"));
String zobraz = cur.getString(cur.getColumnIndex("dlzka"));
CheckBox check = (CheckBox)findViewById(R.id.checkBox);
if (Integer.parseInt(zobraz)==0)
{
mDbHelper.updateSviatok(odosli, username, 1);
} else {
mDbHelper.updateSviatok(odosli, username, 0);
}
check.setChecked(!check.isChecked());
adapter.notifyDataSetChanged();
}
});
}
#Override
public void onPause()
{
super.onPause();
mDbHelper.close();
}
private void showUserSettings()
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
username = sharedPrefs.getString("prefUsername", "NULL");
}
}

you have checked your CheckBox in itemclick but it's not reflected to your itemList so before calling adapter.notifyDataSetChanged(); you should have to refresh listItems with new changes.

I ve answered this question in this : https://stackoverflow.com/a/22954806/1332870
can you check it? if it does not solve your problem please let me know

Reload your Cursor and instead of adapter.notifyDataSetChanged(); use adapter.changeCursor(reloadedCursor);

Not sure if this is a strain on the main thread but you could just set the adapter again in the on click method.

Related

List can't be saved or loaded

I tried making a dynamic list where the user can add elements by writing a text and pushing a button. The user also should be able to delete elements by clicking on them for a longer time.
All of that is working fine, however everytime I close the App the created list is gone. I'm not sure what exactly is failing, either the loading or the saving.
Here is my code:
public class MainActivity extends AppCompatActivity {
private ArrayList<String> ModuleList;
private ArrayAdapter<String> MyAdapter;
private ListView listView;
private Button addButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadData();
addButton=findViewById(R.id.btnPlus);
MyAdapter=new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
listView=findViewById(R.id.listView);
listView.setAdapter(MyAdapter);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addModule(view);
saveData();
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
{
deleteItem(view, position);
saveData();
return true;
}
});
}
private void addModule(View view) {
EditText input =findViewById(R.id.textInput);
String itemText=input.getText().toString();
if(!(itemText.equals("")))
{
ModuleList.add(itemText);
MyAdapter.add(itemText);
MyAdapter.notifyDataSetChanged();
input.setText("");
}
else
{
Toast.makeText(getApplicationContext(),"Please insert Module...",Toast.LENGTH_LONG).show();
}
}
private void deleteItem(View view,int i)
{
Context context = getApplicationContext();
MyAdapter.remove(ModuleList.get(i));
ModuleList.remove(i);
MyAdapter.notifyDataSetChanged();
Toast.makeText(context, "Item Removed", Toast.LENGTH_LONG).show();
}
private void saveData()
{
SharedPreferences sharedPreferences=getSharedPreferences("Shared preferences",MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
Gson gson=new Gson();
String json=gson.toJson(ModuleList);
editor.putString("Task List",json);
editor.apply();
}
private void loadData()
{
SharedPreferences sharedPreferences=getSharedPreferences("Shared preferences",MODE_PRIVATE);
Gson gson=new Gson();
String json=sharedPreferences.getString("Task List",null);
Type type= new TypeToken<ArrayList<String>>() {}.getType();
ModuleList=gson.fromJson(json,type);
if(ModuleList==null){
ModuleList=new ArrayList<>();
}
}
}
I can't see my mistake, but I'm new to all of this. So there might be something obvious missing.
Thank you very much.
i once encountered the same problem and the solution was
instead of
SharedPreferences sharedPreferences=getSharedPreferences("Shared preferences",MODE_PRIVATE);
write (remove the space from the name)
SharedPreferences sharedPreferences=getSharedPreferences("Sharedpreferences",MODE_PRIVATE);
similarly with your variable name
editor.putString("TaskList",json);
String json=sharedPreferences.getString("TaskList",null);
i don't know if this is your case or why this happens since the variable is a string and the space shouldn't matter but for me it never allows me to save anything in sharedPrefs if the name has spaces
then check this line
MyAdapter=new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
update it with this
MyAdapter=new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,ModuleList);
for the issue in saving the item twice the problem is here
if(!(itemText.equals("")))
{
ModuleList.add(itemText);
// MyAdapter.add(itemText); remove this line the itemText is already added to the moduleList
MyAdapter.notifyDataSetChanged();
input.setText("");
}
First: create a static final variable to store "Task List", then add some Log.d("TEST", variable) to show in 'Logcat' the interested variables and then update the question please.

How the spinner items not be kept selected as it is while rerunning the app

Hello I want to Know that how can i keep the spinner items selected throughout the activity so that if i come back form other activity to the activity that is consisting of spinner its still remain selected as it is.
The above statement that i have used that has been solved after this there is an another issue that whenever i restart my app its the selected portion remains as it is i want to know what i can do so that the spinner does not show what i have selected before
I have a code of spinner which i want to keep it selected throughout all the activities ,
daySelection = (Spinner)findViewById(R.id.daypreferance);
//String[] dayName = new String[]{
// "sunday", "monday", "tuesday"
//};
MyClass[] dayName ={
new MyClass("sunday", ""),
new MyClass("monday", "2"),
new MyClass("tuesday", "3")
};
ArrayAdapter<MyClass> adapter = new ArrayAdapter<MyClass>(this , R.layout.spinner_items ,R.id.spinneritem,dayName);
adapter.setDropDownViewResource(R.layout.spinner_items);
hotelSelection.setAdapter(adapter);
daySelection.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
preferDay= parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
public void onPause() {
super.onPause();
daySelection = (Spinner)findViewById(R.id.daypreferance);
SharedPreferences prefs = getSharedPreferences("prefs_name", Context.MODE_PRIVATE);
prefs.edit().putInt("spinner_indx", daySelection.getSelectedItemPosition()).apply();
}
public void onResume() {
super.onResume();
daySelection = (Spinner)findViewById(R.id.daypreferance);
SharedPreferences prefs = getSharedPreferences("prefs_name", Context.MODE_PRIVATE);
int spinnerIndx = prefs.getInt("spinner_indx", 0);
daySelection.setSelection(spinnerIndx);
}
I need to add the code that whenever I restart my app its the selected portion remains as it is I want to know what I can do so that the spinner does not show what I have selected before
try dis and let me know if any error....
daySelection = (Spinner)findViewById(R.id.daypreferance);
//String[] dayName = new String[]{
// "sunday", "monday", "tuesday"
//};
MyClass[] dayName ={
new MyClass("sunday", ""),
new MyClass("monday", "2"),
new MyClass("tuesday", "3")
};
ArrayAdapter<MyClass> adapter = new ArrayAdapter<MyClass>(this , R.layout.spinner_items ,R.id.spinneritem,dayName);
adapter.setDropDownViewResource(R.layout.spinner_items);
hotelSelection.setAdapter(adapter);
daySelection.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//check if preferDay has some valur rhen set on spinner
if(preferDay!=null)
{
daySelection.setSelection(Integer.parseInt(preferDay));
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
you can save state of activity and then set those values after came back
check this stack over flow question and this one
Save the state of the spinner in the onPause() method.
#Override
public void onPause() {
super.onPause();
Spinner spinner = (Spinner)findViewById(R.id.daypreferance);
SharedPreferences prefs = getSharedPreferences("prefs_name", Context.MODE_PRIVATE);
prefs.edit().putInt("spinner_indx", spinner.getSelectedItemPosition()).apply();
}
Restore the state of the spinner in the onResume() method.
#Override
public void onResume() {
super.onResume();
Spinner spinner = (Spinner)findViewById(R.id.daypreferance);
SharedPreferences prefs = getSharedPreferences("prefs_name", Context.MODE_PRIVATE);
int spinnerIndx = prefs.getInt("spinner_indx", 0);
spinner.setSelection(spinnerIndx);
}

encounter null point exception when using Shared Preference

I have an activity which is working without operating the shared preference. After adding it, got null pointer error after clicking the button.
I think the way I am using shared preference is not correct. Anyone can help point out what is the issue? Should I new() it before using?
public class BanknameActivity extends Activity {
String [] bank_name;
String selected_bank_config;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bankname);
// Show the Up button in the action bar.
// setupActionBar();
bank_name = getResources().getStringArray(R.array.bankname);
ListView lv1 = (ListView) findViewById(R.id.bankname_listview);
lv1.setChoiceMode(1); // CHOICE_MODE_SINGLE
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, bank_name);
lv1.setAdapter(adapter);
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
//selected_bank_config = "Citi";
prefs.edit().putString(selected_bank_config, "citi").commit();
return_to_config(view);
}
});
}
Below is part of my code:
public void return_to_config(View view){
Intent intent = new Intent(this, ConfigActivity.class);
startActivity(intent);
this.finish();
}
**you need to initialize your shared Preferences. Without initialization it will always be null.**
yo need to do following stuff:
// mPrefs=getSharedPreferences("Preferences Name",mode);
mPrefs=getSharedPreferences("FBPref",0);
Editor edit=mPrefs.edit();
edit.putString("UserName", "");
edit.putString("UserId","");
edit.putString("EmailId","");
edit.commit();
This code is working fine.
I hope you will appreciate it.

Get value in HashMap Android

I have two activitys...
Activity 1: have a edittext and two button:button1 & button2
Activity 2: have a autocompletetextview and a listview
I want to that when i enter string to edittext and click button1 ,i create a HashMap(static) to save value(set defaul="hello word") and key as string in edittext...
Event when click button1:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
hashMap.put(edittext.getText().toString(),"hello word");//I declared hashMap
}
});
In activity2 :
public class Notification_App extends Activity {
AutoCompleteTextView actv_notification;
ListView lv_notification;
Dictionary1 dictionary1;
ArrayList<String> str_value;
ArrayList<String> array_key;
#Override
public void onCreate(Bundle circle)
{
super.onCreate(circle);
setContentView(R.layout.notification);
actv_notification=(AutoCompleteTextView)findViewById(R.id.actv_notification);
lv_notification=(ListView)findViewById(R.id.listview_notification);
array_key=new ArrayList<String>(dictionary1.hashMap.keySet());
Iterator myVeryOwnIterator = dictionary1.hashMap.keySet().iterator();
while(myVeryOwnIterator.hasNext())
{
String key=(String)myVeryOwnIterator.next();
String value=(String)dictionary1.hashMap.get(key);
str_value.add(value);
}
ArrayAdapter<String> adapter=new ArrayAdapter<String>(Notification_App.this, android.R.layout.simple_dropdown_item_1line,array_key);
ArrayAdapter<String> adapter1=new ArrayAdapter<String>(Notification_App.this, android.R.layout.simple_list_item_1,array_key);
actv_notification.setAdapter(adapter);
lv_notification.setAdapter(adapter1);
lv_notification.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), str_value.get(position), Toast.LENGTH_LONG).show();
}
});
}
but error display: null poiter at line: str_value.add(value);...Can you help me..
I think you just forgot to initialise str_value variable. Put before your while loop:
str_value = new ArrayList<String>();
and it should do the trick.
P.S. I'm not checking the logic of your code, simply pointing out why you get NullPointerException.
Try to add
str_value = new ArrayList<String>();
Before the first
str_value.add(value);
You're getting an exception because str_value is null.
You need to create the actual object:
str_value = new ArrayList<String>();

How to store dropdown item of the spinner to the sqlite database of android

I want to store the dropdown value of the spinner to the database. I am able to get dopdown as per the tutorial in the android developer site but i am not able to store that dropdown value to the database when user click on save button.I don't know it is possible or not if yes please tell me how to do that with some example.
Thanks in advance
This is my code
public class Akshay extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Spinner For Selecting Room
Spinner spinner_room = (Spinner) findViewById(R.id.spinner_for_Room_type_screen_2);
ArrayAdapter adapter_room = ArrayAdapter.createFromResource(this,
R.array.room_array, android.R.layout.simple_spinner_item);
adapter_room.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_room.setAdapter(adapter_room);
spinner_room.setOnItemSelectedListener(new MyOnItemSelectedListener_room());
}
}
// Listener Implementation of Spinner For Selecting Room
public class MyOnItemSelectedListener_room implements OnItemSelectedListener
{
public void onItemSelected(AdapterView parent, View view, int pos, long id)
{
}
public void onNothingSelected(AdapterView parent)
{ // Do nothing.}
};
}
public class Akshay extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.configuration);
// Spinner For Selecting Room
Spinner spinner_room = (Spinner) findViewById(R.id.spinner_for_Room_type_screen_2);
ArrayAdapter<CharSequence> adapter_room = ArrayAdapter.createFromResource(this,
R.array.room_array,android.R.layout.simple_spinner_item);
adapter_room.setDropDownViewResourc(android.R.layout.simple_spinner_dropdown_item);
spinner_room.setAdapter(adapter_room);
spinner_room.setOnItemSelectedListener(new Listener_Of_Selecting_Room_Spinner());
}
// Listener Implementation of Spinner For Selecting Room
public static class Listener_Of_Selecting_Room_Spinner implements OnItemSelectedListener
{
static String RoomType;
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id)
{
// By using this you can get the position of item which you
// have selected from the dropdown
RoomType = (parent.getItemAtPosition(pos)).toString();
}
public void onNothingSelected(AdapterView<?> parent)
{
// Do nothing.
}
};
// Listener Implementation For Saving Number Of Board
private OnClickListener btnListener_Btn_Save_Room_Board = new OnClickListener()
{
public void onClick(View view)
{
DBAdapter dbAdapter1 = new DBAdapter(view.getContext());
String room;
try {
dbAdapter1.createDataBase();
dbAdapter1.openDataBase();
// Here i am using the object RoomType which i have got from
// the Listener of spinner
room = Listener_Of_Selecting_Room_Spinner.RoomType;
ContentValues initialValues1 = new ContentValues();
initialValues1.put("RoomType", room);
//Here i am storing it(RoomType) to the database
dbAdapter1.InsertNumberOfBoardInDB("Configuration", null,initialValues1);
}
catch (Exception e) {
}
finally {
dbAdapter1.close();
}
}
};
}
If you're looking for information on how to use SQLite databases in an Android app, I highly recommend going through the Notepad tutorial.
Or are you stuck at handling the button click?
This doesn't directly answer the question, but design-wise and for simplicity's sake it may make some sense to store UI values as preference.
For example:
public static final String PREFS_NAME = "MyPrefsFile";
public static final String SPINNER_VALUE = "SPINNER VALUE";
SharedPreferences settings = getSharedPreferences(PREFS_NAME , 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(SPINNER_VALUE, <the spinner value>);
editor.commit();
Of course this depends on your requirement, ymmv.

Categories

Resources