Data Won't Save To Shared Preferences - java

Layout
Hi! So I've been trying to make a basic note app and I've run into a wall. I've spent hours trying to get my data to save to my sharedPreferences, but no matter what I try it doesn't seem to work. I've added logs to the app so we can examine what is happening.
LOGS:
02-22 18:27:56.767 4929-4929/com.example.jackson.collegeplanner I/TEST: notesSet didn't return null!
(When I click the addnote button)
02-22 18:29:54.500 4929-4929/com.example.jackson.collegeplanner I/TEST: newNote added to notesSet
Code:
public class Schedule extends AppCompatActivity {
ArrayList<String> notes = new ArrayList<>();
// SharedPreferences sharedPreferences = this .getSharedPreferences("com.example.jackson.collegeplanner", Context.MODE_PRIVATE);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, notes);
ListView listView = (ListView) findViewById(R.id.listView);
SharedPreferences myPref = this.getSharedPreferences("com.example.jackson.collegeplanner", Context.MODE_PRIVATE);
Set<String> notesSet = myPref.getStringSet("NN", null);
if(notesSet != null){
notes.addAll(notesSet);
listView.setAdapter(arrayAdapter);
Log.i("TEST", "notesSet didn't return null!");
}
else{
notesSet = new HashSet<String>();
notesSet.add("Ya note's set is empty");
notes.addAll(notesSet);
listView.setAdapter(arrayAdapter);
Log.i("TEST", "noteSet returned null");
}
myPref.edit().putStringSet("NN", notesSet).apply();
}
public void AddNote(View view){
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, notes);
ListView listView = (ListView) findViewById(R.id.listView);
EditText editText = (EditText) findViewById(R.id.editText);
String newNote = editText.getText().toString();
SharedPreferences myPref = this.getSharedPreferences("com.example.jackson.collegeplanner", Context.MODE_PRIVATE);
Set<String> notesSet = myPref.getStringSet("NN", null);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
notesSet.add(newNote);
Log.i("TEST", "newNote added to notesSet");
notes.clear();
notes.addAll(notesSet);
editText.setText("");
myPref.edit().putStringSet("NN", notesSet).apply();
listView.setAdapter(arrayAdapter);
}
}

You can use
if(myPref.edit().putStringSet("notes", set).commit())
Log.d(TAG , "SAVED");
else
Log.d(TAG , "Not Saved");
To check if shared preferences were actually saved.

in your code change
`
if(set == null){
set = new HashSet<String>();
notes.add("Initial Notes");
set.addAll(notes);
}
`
to
`
if(set == null){
set = new HashSet<String>();
notes.add("Initial Notes");
set.addAll(notes);
myPref.edit().putStringSet(set).apply();
}
`

the answer is from a duplicate post I made and it was answered there.
Oh, I just remembered a catch with String Sets in SharedPreferences that you're probably coming up against. (I admit I didn't really test your code very thoroughly when I did it.) You cannot try to modify the Set you get from getStringSet() and then save it back. You need to instantiate a new one, and pass that to putStringSet(). In your code, a simple fix would be: Set<String> notesSet = new HashSet<String>(myPref.getStringSet("NN", null));. – Mike M.

Related

Listview Error on longpress of item for deletion

Visual Reference
EDITED WITH COMMENT FIX
My listView is supposed to, on long tap, delete whatever you tap on. There is data in sharePreferences, so that shouldn't be the problem. So, what I am doing is I am taking data from noteSet, which gets it from myPref. Then, where the listView gets clicked, the notesSet deletes that note. Then, it reuploads the modified notesSet to sharedPreferences and then notesSet is added to notes, which is used by the listview.
I think this is the error code I am getting:
02-23 12:20:12.384 5211-5229/com.example.jackson.collegeplanner E/OpenGLRenderer: GL error: GL_INVALID_OPERATION
02-23 12:20:28.461 550-710/system_process W/InputDispatcher: channel '17b2c24b com.example.jackson.collegeplanner/com.example.jackson.collegeplanner.Schedule (server)' ~ Consumer closed input channel or an error occurred. events=0x9
02-23 12:22:12.723 54-54/? E/EGL_emulation: tid 54: eglCreateSyncKHR(1299): error 0x3004 (EGL_BAD_ATTRIBUTE)
myPref.edit().putStringSet("NN", notesSet).apply();
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
new AlertDialog.Builder(getApplicationContext()).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Pop Up!")
.setMessage("Ready to delete this task?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
SharedPreferences myPref = getApplicationContext().getSharedPreferences("com.example.jackson.collegeplanner", Context.MODE_PRIVATE);
Set<String> notesSet = new HashSet<String>(myPref.getStringSet("NN", null));
ArrayAdapter arrayAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, notes);
ListView listView = (ListView) findViewById(R.id.listView);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
notesSet.remove(i);
notes.clear();
notes.addAll(notesSet);
myPref.edit().putStringSet("NN", notesSet).apply();
listView.setAdapter(arrayAdapter);
Log.i("TEST", "notesSet didn't return null!");
}
})
.setNegativeButton("No", null).show();
return false;
}
});
This is a snippet of code from my program for convienence. The rest of the program works, and app crashes only occur when I introduced this new code. Thanks for your time.
Use Acivity's context instead of getApplicationContext() . Do not use getApplicationContext() anywhere unless it meant to be use . Do it as below .
new AlertDialog.Builder(YourActtivity.this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Pop Up!")
.setMessage("Ready to delete this task?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
SharedPreferences myPref = getSharedPreferences("com.example.jackson.collegeplanner", Context.MODE_PRIVATE);
Set<String> notesSet = new HashSet<String>(myPref.getStringSet("NN", null));
ListView listView = (ListView) findViewById(R.id.listView);
notesSet.remove(i);
notes.clear();
notes.addAll(notesSet);
myPref.edit().putStringSet("NN", notesSet).apply();
ArrayAdapter arrayAdapter = new ArrayAdapter(YourActtivity.this, android.R.layout.simple_list_item_1, notes);
listView.setAdapter(arrayAdapter);
Log.i("TEST", "notesSet didn't return null!");
}
})
.show();
Also Debug your code check and for returned values .

Data not transferring to a new activity

What am I doing wrong? I cannot get my data to transfer from where I click it on the list to the detailed view activity that the click opens.
Here is my code at the button click... and the data is available here due to the fact that the list shows the items.
RecipeRepo repo = new RecipeRepo(this);
final ArrayList<HashMap<String, String>> recipeList = repo.getRecipeList();
if(recipeList.size()!=0) {
ListView lv = (ListView) findViewById(R.id.list);//getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
recipe_Id = (TextView) view.findViewById(R.id.recipe_Id);
String recipeId = recipe_Id.getText().toString();
Intent objIndent = new Intent(getApplicationContext(),RecipeDetail.class);
objIndent.putExtra("recipe_Id", Integer.parseInt( recipeId));
startActivity(objIndent);
}
});
ListAdapter adapter = new SimpleAdapter( SousChef.this,recipeList, R.layout.view_recipe_entry, new String[] { "id","name"}, new int[] {R.id.recipe_Id, R.id.recipe_list_name});
lv.setAdapter(adapter);
}else {
Toast.makeText(this, "No recipe!", Toast.LENGTH_SHORT).show();
}
Like I said, I'm the data is available at this point because the listview shows the ID and the Name of each item.
After I click it using the following code... the activity is blank, and the toast in the item below comes up ID 0
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe_detail);
btnEdit = (Button) findViewById(R.id.detail_edit);
btnClose = (Button) findViewById(R.id.detail_close);
textName = (EditText) findViewById(R.id.detail_recipe_name);
textIngredients = (EditText) findViewById(R.id.detail_recipe_ingredients);
textInstruct = (EditText) findViewById(R.id.detail_recipe_instruct);
textCookTemp = (EditText) findViewById(R.id.detail_cook_temp);
textCookTime = (EditText) findViewById(R.id.detail_recipe_cooktime);
textServes = (EditText) findViewById(R.id.detail_recipe_servings);
btnEdit.setOnClickListener(this);
btnClose.setOnClickListener(this);
_Recipe_Id =0;
Intent intent = getIntent();
_Recipe_Id = intent.getIntExtra("recipe_Id", 0);
RecipeRepo repo = new RecipeRepo(this);
Recipe recipe = new Recipe();
recipe = repo.getRecipeById(_Recipe_Id);
textName.setText(recipe.name);
Toast.makeText(this, "Recipe id is " + recipe.recipe_Id, Toast.LENGTH_SHORT).show();
textIngredients.setText(recipe.ingredients);
textInstruct.setText(recipe.instructions);
textCookTemp.setText(recipe.cooktemp);
textCookTime.setText(recipe.cooktime);
textServes.setText(recipe.serves);
From everything I have read this should be working but I must be leaving something out. Also I am not producing any errors in the logCat or anything.
Word of advise... always make sure you mark the correct columns in your database... A simple mistake can cause you 2 days worth of work to go out the window. In this case I had the getRecipeByID code looking for the column category instead of the column recipe_Id. simple fix but could have been avoided.

Cannot resolve constructor ArrayAdapter when using ListView in Android Studio

I have an activity Mainactivity, in this when a button is pressed then it will show a listview. But in
listAdapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, android.R.id.text1, value);
I am getting "Cannot resolve constructor ArrayAdapter (anonymous android view.View.OnClickListener, int, int, java.lang.String)"
My outer class is "Mainactivity" I tried "Mainactivity.this" instead of "this". But It is showing "cannot resolve constructor" error.
MainActivity class extends Actionbaractivity implements onItemelectedListner
My code is:
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(cnt.getText().toString().length() > 0 &&
number.getText().toString().length() > 0 &&
Integer.parseInt(number.getText().toString()) > 0 &&
Integer.parseInt(cnt.getText().toString()) > 0) {
number.requestFocus();
String[] value = new String{"hello","world"};
try {
temp_count = temp_count + Integer.parseInt(cnt.getText().toString());
count.setText(String.valueOf(temp_count));
temp_amt = temp_amt + (Integer.parseInt(cnt.getText().toString()) * tkt_rate);
amount.setText(String.valueOf(temp_amt));
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, value);
lstView.setAdapter(listAdapter);
lstView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
SparseBooleanArray checked = lstView.getCheckedItemPositions();
int size = checked.size(); // number of name-value pairs in the array
for (int i = 0; i < size; i++) {
int key = checked.keyAt(i);
boolean value = checked.get(key);
if (value) {
row = lstView.getChildAt(i);
row.setBackgroundColor(Color.parseColor("#33B5E5"));
} else {
row = lstView.getChildAt(i);
row.setBackgroundColor(Color.parseColor("#F0F0F0"));
}
}
}
});
Please help...
The error shows that you are putting android view.View.OnClickListener as the first argument.
I know you said you have tried, but you really need to use Mainactivity.this. If it is not working please post the code of the start of your java file.
Also is your activity named as Mainactivity? Remember it is case sensitive, should it be MainActivity? If so, you have to use MainActivity.this
I think it's happening because your class implements onclicklistener. So can you try cast this to Activity? Like the code below:
listAdapter = new ArrayAdapter((Activity)this, android.R.layout.simple_list_item_1, android.R.id.text1, value);
ArrayAdapter needs Context as the first argument. What you can do is to have a field reference to your Context, like the followings.
Added a field to your Activity, private Context mContext;
Inside the onCreate() of your Activity, mContext = this;
Use the mContext to construct ArrayAdapter, listAdapter = new ArrayAdapter(mContext, android.R.layout.simple_list_item_1, android.R.id.text1, value);
Maybe this will help you:
listAdapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_list_item_1,
android.R.id.text1,
Collections.singletonList(value));

Error comming on maketext in toast

public void onClick(View v) {
{
if (db==null) db = new DB(AddStation.this);
if(v.getId()==R.id.ADD ) {
String code = Scode.getText().toString().trim();
String name = SName.getText().toString().trim();
String fac = SFac.getText().toString().trim();
if(name.equals("")){
Scode.setError("Invalid name");
return;
}
if (code.equals("")){ Scode.setError("Invalid email");
return;
}
if (db.addStudent(code, name, fac))
Toast.makeText(AddStation.this, "Student added", Toast.LENGTH_SHORT).show();
else if (v.getId()==R.id.See) {
Toast.makeText(AddStation.this, db.getAllStudents(), Toast.LENGTH_LONG).show();
//Log.v("EditText", db.getAllStudents().toString());
}
}
}
db.close();
Toast.makeText(AddStation.this, db.getAllStudents(), Toast.LENGTH_SHORT).show();
}
}
AddStation is my Fragment name. how to solve this ?
this toast is retriving database and can u guys tell me how to bring data into a dropdown box or gridview instead of a toast. thanks!
Look at the last two lines. First you called db.close();, then called db.getAllStudents(), so ARE YOU KIDDING?
But if not this caused error, then post you logcat trace
PS:check your AddStation, is it extended from Activity or its descendants? If not, extend your AddStation from Activity or its descendants.
You can display this data in List/Spinner, for this you had to add these widgets in your layout. You can populate this data as
1. ListView
ListView listView = (ListView) findViewById(R.id.mylist);
List<String> listRecords = db.getAllStudents();
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item, listRecords);
listView.setAdapter(arrayAdapter);
2. Spinner
Spinner spinner = (Spinner) findViewById(R.id.spinner);
List<String> listRecords = db.getAllStudents();
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, listRecords);
spinner.setAdapter(arrayAdapter);

Android: Checking If Arraylist is Empty JSON

Im using https://github.com/thest1/LazyList as my listview
i wonder how will i check if the listview is Empty or when null?
this is the sample codes from the post Execute
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
// Pass the results into ListViewAdapter.java
adapter = new LvOrderSumAdapter(OrderSum.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
listview.getAdapter().getCount();
String count = ""+listview.getAdapter().getCount();
items.setText(count);
// Close the progressdialog
mProgressDialog.dismiss();
}
Please help !
I tried this code from what i've searched
if(!arraylist.isEmpty()){
listview = (ListView) findViewById(R.id.listOrderSummary);
// Pass the results into ListViewAdapter.java
adapter = new LvOrderSumAdapter(OrderSum.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
listview.getAdapter().getCount();
String count = ""+listview.getAdapter().getCount();
items.setText(count);
//o_total.setText("aaa");
// Close the progressdialog
mProgressDialog.dismiss();
}else{ String msg = "No records found in Database!";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
Intent home_in = new Intent ( OrderSum.this,
Home.class );
startActivity(home_in);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
}
but i still got the error
Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject"
To check if a listView is null:
listView != null;
To check if a listView dont have elements:
listView.getAdapter().getCount()<=0;

Categories

Resources