Getting "0" in logcat for my SharedPreferences? - android

private void aeroMindMaps(List<Details> mList) {
for (Details bean : details) {
final String urlChar = bean.getUrl();
final int idno = bean.getId();
SharedPreferences pref =getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
SharedPreferences.Editor edt = pref.edit();
edt.putString("urlid",urlChar);
edt.putInt("urlidno",idno);
edt.commit();
Log.e("idno for mindmaps01",String.valueOf(idno));
I am getting first log correct and in next log getting 0,I wrote log only one time but getting the values 4 times in logcat
Output of my sharedPreference is:
04-15 13:59:25.480 13612-13612/com.example.****.tabview E/idno for mindmaps01: 68
04-15 13:59:25.547 13612-13612/com.example****.tabview E/idno for mindmaps01: 0
04-15 13:59:25.625 13612-13612/com.example.****.tabview E/idno for mindmaps01: 68
04-15 13:59:25.691 13612-13612/com.example.****.tabview E/idno for mindmaps01: 0

Related

SharedPreferences not saving all the data after restart

I am new to Android App Development and I am supposed to make a TodoList App for a course. But the SharedPreference in my code is not working. I dont know if I'm supposed to use it in a specific way in a specific method like onCreate or onStop.
It is saving the first input the user is entering permanently, but in the same position:
(The "task0" is what I used to track the different variable names I used as argument for "putString" in addStuff method, to avoid replacing values)
It is saving the inputs after that in the same session, but if the user ends that session, all those values after "t" are gone. If the user restarts the app and inputs something else (like "g"), it is saving "g" in that same 3rd position.
I have basic Java knowledge and I tried to understand what is going on using it, but failed. Please let me know where is the mistake and how to use SharedPreferences properly.
public class TodoActivity extends AppCompatActivity {
public ArrayList<String> items;
public ArrayAdapter<String> itemsAdapter;
public ListView list;
public String s;
public EditText taskBox;
public static final String filename = "itemsList";
public TextView text;
public static int counter = 0;//counter starting at 0 no matter what, everytime the app starts
public String newtask= "task";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo);
list = (ListView) findViewById(R.id.list1);text = (TextView) findViewById(R.id.text1);
taskBox = (EditText) findViewById(R.id.box);
s = taskBox.getText().toString();
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
list.setAdapter(itemsAdapter);
//add items to list
items.add("First Item");
items.add("Second Item");
//restore
SharedPreferences sp = this.getSharedPreferences("itemsList", 0);
//checking if it stores the previous values, this gives the last input but not the previous ones after restarting the app
String dummyname = "task";
text.setText(String.valueOf(counter));//since counter is again at
for(int c=0; c<=50; c++){
String num = String.valueOf(c);
dummyname = dummyname + num;
String x = sp.getString(dummyname, "not found");
if (x.equalsIgnoreCase("not found")){
counter=c-1;
break;
} else {
items.add(x);
text.setText(dummyname);
}
}
}
public void addItem(View v){
s = taskBox.getText().toString();
itemsAdapter.add(s);//adding the new task as string
String temp = String.valueOf(counter);
newtask = "task" + temp;
//trying to store the new tasks with different variable names to avoid being replaced
text.setText(newtask);
SharedPreferences sp = this.getSharedPreferences("itemsList", 0);
SharedPreferences.Editor e = sp.edit();
e.putString(newtask,s);
e.apply();
counter++;
}
}
If you have relatively small collection of key-values that you would like to save,
You should use Shared preference API
Read from the shared preference:
Pass the key and value you want to write,create a SharedPreferences.Editor by calling edit() on your SharedPreferences.
Pass key and values you want to save by using this method putInt() ,putString() ,Then call commit() to save the changes. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("KeyName", newHighScore);
editor.commit();
Write from the shared preference:
To retrieve values from a shared preferences file, call methods such as getInt() and getString(),
providing the key for the value you want, and optionally a default value to return if the key isn't present. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt("KeyName", defaultValue);
Two things :
1) To initialize SharedPreferences use :
sharedPreferences = getSharedPreferences("itemsList", Context.MODE_PRIVATE);
2) Where are you calling addItem() method??
The problem is about the Tag you use to save items. See this Line :
dummyname = dummyname + num;
You add item by this format :
task0
task1
task2
but you are getting values in this format
task0
task01
task012
Just change these two line of code :
//dummyname = dummyname + num;
//String x = sp.getString(dummyname, "not found");
String newDummy= dummyname + num;
String x = sp.getString(newDummy, "not found");

put default data to edittext in Android

Get data from edittext e_1, e_2 to sum up those things, but it rarely put those things together. For instance, I wrote 0 in e_1, and 1 in e_2, pref KEY says '1', but when I wrote nothing in e_1, and 1 in e_2, it makes error and down. So although he/she wrote nothing in e_1, it also have to put '0' in a. What I Have TO DO?
a = Integer.parseInt(e_1.getText().toString());
b = Integer.parseInt(e_2.getText().toString());
SharedPreferences.Editor editor = pref_time.edit();
editor.putInt(KEY, a+b));
editor.commit();
Try this out
String editText1=e_1.getText().toString().trim();
String editText2=e_1.getText().toString().trim();
if((editText1!= null || !editText1.equals("")) && (editText2!=null || !editText2.equals("")))
{
a = Integer.parseInt(editTextData1);
b = Integer.parseInt(editTextData2);
SharedPreferences.Editor editor = pref_time.edit();
editor.putInt(KEY, a+b));
editor.commit();
}
If e_2 is empty, in this line:
b = Integer.parseInt(e_2.getText().toString());
you will get an error because e_2.getText().toString() returns empty string, and it can't be parsed to Integer.
You have to check if it is empty first:
String aText = e_1.getText().toString();
String bText = e_2.getText().toString();
a = TextUtils.isEmpty(aText)? 0 : Integer.parseInt(aText);
b = TextUtils.isEmpty(bText)? 0 : Integer.parseInt(bText);
when edittext is empty it return null to e_1.getText().toString() so first check if edittext is empty or not like this :
String editTextData1 = e_1.getText().toString().trim();
String editTextData2 = e_1.getText().toString().trim();
trim(); is to avoid blank spaces and then check like this to avoid any Exception :
if(editTextData1!="" || editTextData2!=""){
a = Integer.parseInt(editTextData1);
b = Integer.parseInt(editTextData2);
SharedPreferences.Editor editor = pref_time.edit();
editor.putInt(KEY, a+b));
editor.commit();
}

Shared Prefereces saved names not showing after restarting the App

I am creating an app that saves that saves user's previous names. I am using Shared Preferences so when the user kills the app and reopens it the names will still show in the saved Activity. The app currently displays the saved names, but once it's closed and the life cycle is killed, and then restarted the names aren't retrieved.
Code to save the names:
protected void addToSaved(String s){
GlobalList.pref = getApplicationContext().getSharedPreferences("MyPref", Context.MODE_PRIVATE); // 0 - for private mode
SharedPreferences.Editor editor = GlobalList.pref.edit();
if(GlobalList.tagsActive.size() < 6){
GlobalList.tagsActive.addFirst(GlobalList.tagsAvail.removeFirst());
editor.putString(GlobalList.tagsActive.getFirst(), s);
}else{
editor.remove(GlobalList.tagsActive.removeLast());
GlobalList.tagsAvail.add(GlobalList.tagsActive.removeLast());
//adding shared pref
GlobalList.tagsActive.addFirst(GlobalList.tagsAvail.removeFirst());
editor.putString(GlobalList.tagsActive.getFirst(), s); // Storing string value
}
//GlobalList.editor.commit(); // commit changes into sharedpreferences file.
editor.commit();
Code to retrieve and display the names:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved_names);
for (int i = 0; i < GlobalList.tagsActive.size(); i++) {
//setting martian name to screen
// getting String
nameTexts[i] = (TextView) findViewById(textId[i]);
//set conditon here so no null pointer
GlobalList.pref = getApplicationContext().getSharedPreferences("MyPref", Context.MODE_PRIVATE); // 0 - for private mode
String s =GlobalList.pref.getString(GlobalList.tagsActive.get(i), "");
nameTexts[i].setText(s);
}
}
}
Code for global list so can be edited across classes:
public class GlobalList {
static LinkedList<String> tagsAvail = new LinkedList<String>();
static LinkedList<String> tagsActive = new LinkedList<String>();
static SharedPreferences pref;
static SharedPreferences.Editor editor;
}
That happens because when the app starts up on onCreate, the length of GlobalList.tagsActive.size() is zero, so the code inside the FOR loop does not execute.
Change your FOR loop for this:
while (true) {
//setting martian name to screen
// getting String
//set conditon here so no null pointer
GlobalList.pref = getApplicationContext().getSharedPreferences("MyPref", Context.MODE_PRIVATE); // 0 - for private mode
String s =GlobalList.pref.getString(GlobalList.tagsActive.get(i), "");
if (s.equals("")){
break; //exits while loop if no more items are found in SharedPref
else{
nameTexts[i] = (TextView) findViewById(textId[i]);
nameTexts[i].setText(s);
}
}

SharedPreferences string Array not working

I got two Activitys where I want to save and to load a two String[] Array (Sizes are same).
Code in Activity 1 looks like this (load)
SharedPreferences data = getSharedPreferences("data",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
for (int i = 0;i<array_question.length;++i)
{
array_question[i] = data.getString("FAE"+i, array_question[i]);
array_answer[i] = data.getString("ATW"+i, array_answer[i]);
}
Activity two (save)
SharedPreferences data = getSharedPreferences("data",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
for (int i = 0;i<Main.array_question.length;++i)
{
editor.putString("FAE"+i,Main.array_question[i]);
editor.putString("ATW"+i,Main.array_answer[i]);
}
editor.commit();
I got no error or crash but also no result.When I want to load them there is nothing... What is my fault ?

Android: Is it possible to have two intents int the same activity?

The following code causes my application to stop working:
// Passing values to the results activity
Intent intent = new Intent(this, TestResults.class);
intent.putExtra("results", results);
intent.putExtra("Questions", question);
intent.putExtra("CorrectAnswer", correctAnswer);
//this.startActivity(intent);
//passing the score value to the splash activity
Intent SplashIntent = new Intent(this, SplashTest.class);
SplashIntent.putExtra("score", score);
this.startActivity(SplashIntent);
Is this becuase I have two intents in the one activity?
Log Cat Crash report:
04-15 16:33:13.894: E/AndroidRuntime(2322): FATAL EXCEPTION: main
04-15 16:33:13.894: E/AndroidRuntime(2322): Process: com.example.multapply, PID: 2322
04-15 16:33:13.894: E/AndroidRuntime(2322): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.multapply/com.example.multapply.SplashTest}: android.content.res.Resources$NotFoundException: String resource ID #0x0
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.os.Handler.dispatchMessage(Handler.java:102)
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.os.Looper.loop(Looper.java:136)
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-15 16:33:13.894: E/AndroidRuntime(2322): at java.lang.reflect.Method.invokeNative(Native Method)
04-15 16:33:13.894: E/AndroidRuntime(2322): at java.lang.reflect.Method.invoke(Method.java:515)
04-15 16:33:13.894: E/AndroidRuntime(2322): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-15 16:33:13.894: E/AndroidRuntime(2322): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-15 16:33:13.894: E/AndroidRuntime(2322): at dalvik.system.NativeStart.main(Native Method)
04-15 16:33:13.894: E/AndroidRuntime(2322): Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.content.res.Resources.getText(Resources.java:244)
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.widget.TextView.setText(TextView.java:3888)
04-15 16:33:13.894: E/AndroidRuntime(2322): at com.example.multapply.SplashTest.onCreate(SplashTest.java:32)
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.app.Activity.performCreate(Activity.java:5231)
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-15 16:33:13.894: E/AndroidRuntime(2322): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-15 16:33:13.894: E/AndroidRuntime(2322): ... 11 more
The crash report is from the section where the app has crashed
Edit: Class that has the two intents:
public class Test extends Activity implements View.OnClickListener{
//declare vars
TextView text;
EditText answer;
Button submit;
int random1;
int random2;
String[] question= new String[10];//change to array?
int correctAnswer[]=new int[10];//change to array?
int[] results=new int[10];
int score=0;
int questionNumber=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
// initialising variables
initialiseVars();
//set up random
setUpRandom();
//Set text view equal to question
text.setText(question[questionNumber-1]);
//set on click listener for submit button
submit.setOnClickListener(this);
//updateQuestion?
updateQuestion();
}
public void initialiseVars() {
text = (TextView) findViewById(R.id.tvTopRandomTest);
answer = (EditText) findViewById(R.id.etEnterAnswerRandomTest);
submit = (Button) findViewById(R.id.btnSubmitRandomTest);
}
public void setUpRandom(){
//setting up randoms
Random random= new Random();
// Generating random number between 1 and 12
random1 = random.nextInt(12) + 1;
// Generating another random number between 1 and 12
random2 = random.nextInt(12) + 1;
question[questionNumber-1]= random1 + " x " + random2 + " = ";
correctAnswer[questionNumber-1]= random1*random2; //note: possibly may not be used
}
public void updateQuestion(){
//updating question after each click
setUpRandom();
text.setText(question[questionNumber-1]);
answer.setText("");
}
public void onClick(View v){
// sets text view equal to whats typed in in editText
final String entry = answer.getText().toString();
// convert from string value to int
int a = Integer.parseInt(entry); // note: maybe change name
//setting the user answer equal to the question
results[questionNumber-1]=a;
if(a==correctAnswer[questionNumber-1]){
score++;
}
if (questionNumber < 10) {
questionNumber++;//updates question
// called after an answer is given
updateQuestion();
} else {
// Passing values to the results activity
Intent intent = new Intent(this, TestResults.class);
intent.putExtra("results", results);
intent.putExtra("Questions", question);
intent.putExtra("CorrectAnswer", correctAnswer);
//this.startActivity(intent);
//passing the score value to the splash activity
Intent SplashIntent = new Intent(this, SplashTest.class);
SplashIntent.putExtra("score", score);
this.startActivity(SplashIntent);
}
}
}
The problem is that after you call startActivity() with the first intent, the code afterward is not executed. This means that whatever data you try to access in SplashTest is not actually present. A workaround to this issue would be to save the data to internal/external storage or SharedPreferences and access it from there.
Since your arrays aren't large, we can definitely use SharePreferences to store the data.
We save each piece of data in SharedPreferences as a String-String key-value pair.
To store the int arrays, we can combine all the elements into a single String and use a comma as a delimiter.
Storing the "question" String array as a String is an interesting problem, since a String can potentially contain any character. This makes it difficult to efficiently choose a delimiter. I wrote a class called EncodeDecode to convert a String array to a String(and back) here: https://gist.github.com/liangricha/10759438. Feel free to read through the code/give feedback. It should be fully functional.
My code snippets below use the functions in my EncodeDecode.
Saving Data
To store the data in SharedPreferences, you can write:
//Grab SharedPreferences of application.
SharedPreferences.Editor editor = getSharedPreferences("Data", MODE_PRIVATE).edit();
//Use StringBuilder to build data string.
StringBuilder strBuild = new StringBuilder();
//Store "results"(int array)
for(int i = 0; i < results.length; i++)
strBuild.append(str.append(correctAnswer[i]).append(","));
editor.putString("results", strBuild.toString());
strBuild.setLength(0);
//Store "question"(String array) ***REFERENCES CLASS IN GIST ABOVE***
String arrStr = EncodeDecode.encode(question)
editor.putString("questions", arrString);
//Store "correctAnswer"(int array)
for(int i = 0; i < correctAnswer.length; i++)
strBuild.append(str.append(correctAnswer[i]).append(","));
editor.putString("correctAnswer", strBuild.toString());
//Store "score"(int)
editor.putString("score", Integer.toString(score));
//Write changes to disk.
editor.commit();
Retrieving Data
First, grab a reference to the SharedPreferences:
SharedPreferences prefs = getSharedPreferences("Data", MODE_PRIVATE);
To get the "results" int array:
String[] resultsStrs = prefs.getString("results", "").split(",");
int arrLength = resultsStrs.length;
int[] results = new int[arrLength];
for(int i = 0; i < resultsStrs.length; i++)
results[i] = Integer.parseInt(resultsStrs[i]);
To get the "question" String array:
String qStr = prefs.getString("question", "");
String[] question = EncodeDecode.decode(qStr);
To get the "correctAnswer" int array:
String[] correctAnsStrs = prefs.getString("correctAnswer", "").split(",");
int arrLength = correctAnsStrs.length;
int[] correctAnswer = new int[arrLength];
for(int i = 0; i < correctAnsStrs.length; i++)
correctAnswer[i] = Integer.parseInt(correctAnsStrs[i]);
To get the "score" int:
String scoreStr = prefs.getString("score", "");
int score = Integer.parseInt(scoreStr);
Problem is not having or not more intents in the same activity: an Intent from a java viewpoint is an object so you can allocate as many intents you'd like.
But when you do startActivity() you are stopping the current activity in order to start a new one so, after that call, any subsequent code is not garantee to be executed as it is contained in an activity which is stopping.
You have to consider the startActivity() as a no return call, like a return statement, and so not put any code after that.
The error in your crash report shows you're trying to call setText(int) (when I'm assuming you're actually trying to set it to a String passed through the Intent, which is actually being parsed as an int).
In your second Activity, you should try to call
setText(String.valueOf(your_int_variable_here));
to make sure it doesn't parse it as a Resource ID (int) instead of an actual String.

Categories

Resources