List can't be saved or loaded - android

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.

Related

Call and set Global variable

I'm trying to create a global variable that I can referece anywhere. I need to be able to set the variable depending on the selection the user makes from the ListAdapter onclick. I just can't figure out how to code this. I also need to use that variable for if statements. Sorry I am new to this :)
Here is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_flavor);
String[] select_flavor_list = {"Kansas City", "Memphis", "Texas", "North Carolina", "South Carolina","Alabama"};
ListAdapter FlavorListAdapter = new ArrayAdapter<String>(this, R.layout.row_layout_flavor, R.id.flavor_text_view,
select_flavor_list);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(FlavorListAdapter);
//For list view selection, begin here...
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int position, long id) {
GlobalClass flavorPref = ((GlobalClass)getApplicationContext());
flavorPref.setFlavorPreference(String a) = String.valueOf(adapterView.getItemAtPosition(position));
if (flavorPref.equals("Kansas City")) {
Intent intent = new Intent(FlavorListView.this, KansasCity.class);
startActivity(intent);
setContentView(R.layout.kansas_city);
Toast.makeText(FlavorListView.this, "test " + flavorPref,
Toast.LENGTH_LONG).show();
}
else if (flavorPicked.equals("Memphis")) {
Intent intent = new Intent(FlavorListView.this, KansasCity.class);
startActivity(intent);
setContentView(R.layout.kansas_city);
Toast.makeText(FlavorListView.this, "test " + flavorPref,
Toast.LENGTH_LONG).show();
}
}
});
}
This is the Global class I created:
public class GlobalClass extends Application {
public String flavorPreference;
public String getFlavorPreference(){
return flavorPreference;
}
public void setFlavorPreference(String a){
flavorPreference = a;
}
}
You can use android shared preference to this kind of usage
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Editor editor = pref.edit();
Insert or Update Value
editor.putString("key_name", "string value");
Get Value
pref.getString("key_name", null);

Android, refresh listview after click on list item

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.

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.

How to access values defined in AsyncTask from an activity

I have code like this
#Override
public void onCreate(Bundle savedInstanceState) {
addItemsOnSpinnerOrgaLevel();
btn_getReport.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//How can i access map and list defined in orgaLevelTask(AsyncTask)???
Like
String option = parent.getItemAtPosition(pos).toString();
int orgaCode = orgaLevelMap.get(option);
// Both are defined in AsyncTask ??
}); //end of anonymous class
} //end of onCreate()
public void addItemsOnSpinnerOrgaLevel() {
orgaLevelTask = new OrgaLevelTask(AccountReportActivity.this, spinner_orgaLevel, spinner_branch, txt_extra, txt_extra1);
orgaLevelTask.execute();
} //end of addItemsOnSpinnerOrgaLevel()
In AsyncTask onPostExecute() Method i have
#Override
protected void onPostExecute(ArrayList<OrgaLevel> result) {
super.onPostExecute(result);
if (result != null) {
addItemsOnSpinnerOrgaLevel(result);
}
dialog.dismiss();
} //end of onPostExecute()
public void addItemsOnSpinnerOrgaLevel(ArrayList<OrgaLevel> result) {
orgaLevelElementslist = new ArrayList<String>();
orgaLevelElementslist.add("All");
orgaLevelMap = new HashMap<String, Integer>();
orgaLevelMap.put("All", 0);
for (int i=0; i<result.size(); i++) {
OrgaLevel orgaLevelRecord = (OrgaLevel) result.get(i);
String key = orgaLevelRecord.getOrgaName();
String value = orgaLevelRecord.getOrgaCode();
orgaLevelMap.put(key, Integer.parseInt(value));
orgaLevelElementslist.add(key);
} //end of for()
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(accountReportActivity, android.R.layout.simple_spinner_item, orgaLevelElementslist);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_orgaLevel.setAdapter(dataAdapter);
setSpinnerOrgaLevelListener();
} //end of addItemsOnSpinnerOrgaLevel()
private void setSpinnerOrgaLevelListener() {
spinner_orgaLevel.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
String option = parent.getItemAtPosition(pos).toString();
int orgaCode = orgaLevelMap.get(option);
subOrgaLevelTask = new SubOrgaLevelTask(accountReportActivity, spinner_branch, orgaCode);
subOrgaLevelTask.execute();
} //end of onItemSelected()
}); //end of anonymous class
} //end of setSpinnerOrgaLevelListener()
In the subOrgaLevelTask i also have the same hash map as in this class. You can see that what i am trying to do is, put a key value in spinner. So when my btn_getReport button get click then i get the value of the selected item. Like if All is slected then i get 0 and so on. This key value thing is working. The problem is when btn_getReport get click then how can i get the value of the selected item. Because i am filling items in a background thread(In OrgaLevelTask and SubOrgaLevelTask) and my button is in Activity. So how can i do that when button get click, then i get the values from the map defined in OrgaLevelTask and SubOrgaLevelTask ?
Thanks
well, make them public in orgaLevelTask, and simply access them. orgaLevelTask should be a variable in you activity class. Have you tried it? any errors?
You must make sure orgaLevelTask members will be accessed in thread safe manner

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