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.
Related
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
So, I'm debugging my project in Android Studio, it's just a tutorial I'm doing, and I have a Handler I'm trying to use.
I can step over all the code in the run part. Then when I get out of run it steps into Handler.java and android studio has all these errors marked in in the Handler.java file and the program crashes.
I'm pretty sure Handler is part of the jdk and when added Handler to my activity it imported the file automatically. I've invalidated caches and cleaned the project. I've ran into this problem with a number of tutorials but never found an answer on how to solve.
In the other cases I uninstalled and reinstalled android studio but that didn't help me out.
This is the code that eventually steps into Handler.java but that is not the problem. The problem is that Android Studio says there are errors throughout Handler.java. I'm using Android Studio 2.0 but I've run into this with other versions too with other jdk java files.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Cursor c = sqLite.rawQuery("SELECT CITY_NAME FROM USER_PREF", null);
Log.d("arindam", "c count"+ c.getCount());
if (c.getCount() == 0){
sqLite.execSQL("INSERT INTO USER_PREF (CITY_NAME, VOICE_ON, NOTIF)" +
" VALUES('NONE', 'Y', 'Y')");
}
c.close();
Cursor d = sqLite.rawQuery("SELECT CITY_NAME FROM USER_PREF", null);
Log.d("arindam", "d count" + d.getCount());
if (d.moveToFirst()){
Log.d("arindam", "d NONE" + d.getString(0));
if (d.getString(0).equals("NONE")){
Intent intent = new Intent(StartScreen.this, CityScreen.class);
startActivity(intent);
}
else {
//Intent intent = new Intent(StartScreen.this, HomeScreen.this);
//startActivity(intent);
}
d.close();
finish();
}
}
},1000);
This is the logcat.
11-24 22:05:47.270 1740-1740/com.example.andrewspiteri.basket E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.andrewspiteri.basket, PID: 1740
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.andrewspiteri.basket/com.example.andrewspiteri.basket.CityScreen}: java.lang.RuntimeException: native typeface cannot be made
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.RuntimeException: native typeface cannot be made
at android.graphics.Typeface.<init>(Typeface.java:175)
at android.graphics.Typeface.createFromAsset(Typeface.java:149)
at com.example.andrewspiteri.basket.CityScreen.onCreate(CityScreen.java:26)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
This is CityScreen.java, the program doesn't even get there.
public class CityScreen extends ActionBarActivity {
SQLiteDatabase sqLite;
Spinner city_spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_screen);
Typeface type = Typeface.createFromAsset(getAssets(),"fonts/books.TTF");
//section is to hide the action bar.
ActionBar actionBar = getActionBar();
actionBar.hide();
//Ideally SQL should be handled in a separate helper,
//but for ease of understanding to start
//off, I have kept the code here.
sqLite = this.openOrCreateDatabase("basketbuddy",MODE_PRIVATE, null);
Cursor c = sqLite.rawQuery("SELECT CITY_NAME FROM CITY_LIST",null);
//ideally at least 1 city should be there in city_name
//As I have already synced this with the serve in
//StartScreen.java
if (c.getCount() == 0){
Toast.makeText(getApplicationContext(), "Oh ho..." +
"Some unexpected problem. Please restart the application",
Toast.LENGTH_LONG);
}
TextView city_selection = (TextView) findViewById(R.id.SelectCityText);
city_selection.setTypeface(type);
//Defining the array that will hold the City Names
String[] city_name_db = new String[(c.getCount()+1)];
//By default, the first entry for city list is "Choose City"
//We will understand who this is necessary later.
city_name_db[0] = "Choose City";
//Moving the city names from sqlite to an array city_name_db
if (c.moveToFirst()){
int count = 1;
do {
city_name_db[count] = c.getString(0);
count++;
}
while (c.moveToNext());{
}
//creating an ArrayAdapter for the spinner and then
//associating the ArrayAdapter to the spinner
ArrayAdapter<String> aa = new ArrayAdapter<String>
(getApplicationContext(),R.layout.spinner_item,city_name_db);
city_spinner = (Spinner) findViewById(R.id.spinner1);
city_spinner.setAdapter(aa);
//There is an inherent problem with Spinners. Lets
//assume that there are 3 cities Delhi, Gurgaon, Noida.
//The moment I populate these 3 cities to the spinner,
//by default Delhi will get selected as this is the first
//entry. OnItemSelectedListener will get triggered
//immediately with Delhi as selection and the code will
//proceed. Net net, even the default first value is
//taken as an ItemSelected trigger. The way to bypass
//this is to add a default value 'Choose City' in the
// ArrayAdapter list. Then inside the onItemSelected method,
//ignore if 'Choose City' has been selected.
//SetOnItemSelectedListener listens for any change in item
//if found then it will call onItemSelectedListener listens
//listens for any change in item selected, if found
//then it will call onItemSelected method.
city_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView
parent, View view,
int position, long id) {
if (parent.getItemAtPosition(position).equals("Choose City")){
//do nothing
}
else {
//save selected city as a default city
//for shopping. This city selection is saved in DB
//We may even decide to send to send this data to server,
// however in this example, we are not doing so.
String city_name = city_spinner.getSelectedItem().toString();
Cursor c = sqLite.rawQuery("SELECT CITY_NAME FROM USER_PREF",
null);
if (c.getCount() == 0){sqLite.execSQL("insert into USER_PREF"+"" +
"(CITY_NAME, VOICE_ON) VALUES ('" + city_name +
"', 'Y', 'Y')");
}
if (c.moveToFirst()){
sqLite.execSQL("update USER_PREF set CITY_NAME = '" +
city_name + "'");
}
//Intent intent = new Intent(CityScreen.this, HomeScreen.class);
//startActivity(intent);
sqLite.close();
finish();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}
I'm getting a "Error:(99, 95) error: local variable i is accessed from within inner class; needs to be declared final" for trying to use the "i" variable from a For loop in the OnClick method.
I tried to put this "i" inside a global variable but then I get a "ArrayIndexOutOfBoundsException".
But I can't think in another way to do so.
private void createTextViews(TextView[] textViewArray, LinearLayout linearLayout){
for (int i = 0; i < keys.length; i++) {
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(20, 0, 0, 20);
TextView newView = new TextView(getActivity());
newView.setLayoutParams(layoutParams);
newView.setText("Watch the Trailer " + (i + 1));
newView.setTextSize(22);
newView.setTextColor(getResources().getColor(R.color.words));
newView.setBackgroundColor(getResources().getColor(R.color.button));
newView.setHighlightColor(getResources().getColor(R.color.background));
newView.setPadding(5, 5, 5, 5);
newView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(YOUTUBE_URL+keys[i]));
startActivity(intent);
}
});
linearLayout.addView(newView);
textViewArray[i] = newView;
}
}
How can I do this?
--------------
EDIT
Here's the log for the ArrayIndexOutOfBoundsExeption:
11-03 01:08:13.866 32159-32159/app.com.example.android.popularmovies E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: app.com.example.android.popularmovies, PID: 32159
java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
at app.com.example.android.popularmovies.Detail_ActivityFragment$1.onClick(Detail_ActivityFragment.java:99)
at android.view.View.performClick(View.java:4456)
at android.view.View$PerformClick.run(View.java:18465)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
you must init new final int value
add final int ex = i;
before setOnClickListener
and don't forget to change
Uri.parse(YOUTUBE_URL + keys[i]));
to
Uri.parse(YOUTUBE_URL + keys[ex]));
The reason you are getting the out of bound exception is because in the last loop you are i++ing although it is not entering the loop again but the i that is a class variable is now out of bound. So the whole approach of putting i as a class variable will not work in your case.
A way to achieve this is to actually save i in a tag in the view and then read that tag from the view that is clicked.
newView.setTag(i)
Then in the onClick
v.getTag()
above can be used to get the i
In my app, I need the values to be saved in to Sharedpreferences file RKs_Data without overwriting the existing data. Every time, I click 'Yes' in my app, I require all the values stored in the 'RKs_Data' instead of just having the latest 'name' and 'phoneNo' in to the file.
Is it possible to do so through SharedPreferences ? If yes, how ?
If not, what is next better option for me to implement this ?
For e.g.,
When I first Click one of the contacts like 'Brian', it saves in SharedPreferences both name and phone as
Brian and 99999299999 with the first save on the Shared Preferences file 'RKS_Data'
When I Click on other contact say 'Monet', my RKs_Data should appear like this:
Brian 99999299999
Monet 00010000000
and so on....
I searched for but everywhere it is only mentioned about saving it but nothing about appending or doing some manipulations with the data...
Please guide...
Snippet is like below:
-------
public class RKsContacts_Main extends ListActivity {
// private ListView listView;
private List<ContactBean> list = new ArrayList<ContactBean>();
SharedPreferences sp;
File Fav_Contacts_file;
String contact = null;
List<String> listOfFavoritePhrases = new ArrayList<String>();
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rks_contactslist_main);
ListView listview = getListView();
sp = getSharedPreferences("PACKAGE", Context.MODE_PRIVATE);
-------
--------
#Override
public void onClick(DialogInterface dialog, int which) {
String serialized = sp.getString("phrases", null);
listOfFavoritePhrases = new ArrayList<String>(Arrays.asList(TextUtils.split(serialized, ","))); // Line 141
listOfFavoritePhrases.add(name);
listOfFavoritePhrases.add(phoneNo);
SharedPreferences.Editor editor = sp.edit();
editor.putString("phrases",TextUtils.join(",", listOfFavoritePhrases));
editor.commit();
}
});
alert.show();
}
--------
LogCat below:
07-03 09:00:51.014: E/AndroidRuntime(9574): FATAL EXCEPTION: main
07-03 09:00:51.014: E/AndroidRuntime(9574): Process: com.example.rkscontacts_list, PID: 9574
07-03 09:00:51.014: E/AndroidRuntime(9574): java.lang.NullPointerException
07-03 09:00:51.014: E/AndroidRuntime(9574): at android.text.TextUtils.split(TextUtils.java:332)
07-03 09:00:51.014: E/AndroidRuntime(9574): at com.example.rkscontacts_list.RKsContacts_Main$4.onClick(RKsContacts_Main.java:141)
07-03 09:00:51.014: E/AndroidRuntime(9574): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
07-03 09:00:51.014: E/AndroidRuntime(9574): at android.os.Handler.dispatchMessage(Handler.java:102)
07-03 09:00:51.014: E/AndroidRuntime(9574): at android.os.Looper.loop(Looper.java:136)
07-03 09:00:51.014: E/AndroidRuntime(9574): at android.app.ActivityThread.main(ActivityThread.java:5017)
07-03 09:00:51.014: E/AndroidRuntime(9574): at java.lang.reflect.Method.invokeNative(Native Method)
07-03 09:00:51.014: E/AndroidRuntime(9574): at java.lang.reflect.Method.invoke(Method.java:515)
07-03 09:00:51.014: E/AndroidRuntime(9574): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-03 09:00:51.014: E/AndroidRuntime(9574): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-03 09:00:51.014: E/AndroidRuntime(9574): at dalvik.system.NativeStart.main(Native Method)
Follow these steps:
Extract the value stored in SharedPreferences
String value = prefs.getString(<Key>, <DefaultValue>);
Append to the extracted value
String appendedValue = append(value, newValue);
Write the result back to SharedPreferences
editor.putString(<Key>, appendedValue).commit();
you could CSV format your shared preference data.
For example, Get CSV string from shared preference and add it to a list. Append to your list then put it back into your sharedpreferance. Code example
// init List of strings somewhere before
List<String> listOfFavoritePhrases = new ArrayList<String>();
// append data into list
listOfFavoritePhrases.add("Brian|99999299999");
listOfFavoritePhrases.add("Monet|00010000000");
// Put list of strings after you have made changes back, in CSV format
SharedPreferences prefs = getSharedPreferences("PACKAGE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("phrases",TextUtils.join(",", listOfFavoritePhrases));
editor.commit();
// get data
SharedPreferences prefs = getSharedPreferences("PACKAGE", Context.MODE_PRIVATE);
String serialized = prefs.getString("phrases", "Brian");
listOfFavoritePhrases = new ArrayList<String>(Arrays.asList(TextUtils.split(serialized, ",")));
and then
String CurrentString = listOfFavoritePhrases.get(0); // first element
String[] separated = CurrentString.split("|");
Toast.makeText(this, separated[0], Toast.LENGTH_LONG).show(); // brian
Toast.makeText(this, separated[1], Toast.LENGTH_LONG).show(); // 99999299999
Hope this Helps.
Finally my code looks like this: Sharing the final code as it can be useful to others who are newbies like me :)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rks_contactslist_main);
ListView listview = getListView();
sp = getSharedPreferences("PACKAGE", Context.MODE_PRIVATE);
String str = sp.getString("FAV_CONTACS",
"NO fav contacts are saved as of now");
---------
protected void onListItemClick(ListView listview, View view, int position,
long id) {
// TODO Auto-generated method stub
super.onListItemClick(listview, view, position, id);
ContactBean bean = (ContactBean) listview.getItemAtPosition(position);
showCallDialog(bean.getName(), bean.getPhoneNo());
}
---------
public void onClick(DialogInterface dialog, int which) {
Fav_Contacts_file = getFilesDir();
if (count <5) {
SharedPreferences.Editor editor = sp.edit();
String new_contact = name + " " + phoneNo;
String existing_contact = sp.getString("CONTACTS", "");
/*String existing_phone = sp.getString("phoneNo", "");
String existing_contact = existing_name + " " +existing_phone ;*/
String latestfavContacts = append(existing_contact, new_contact);
editor.putString("CONTACTS", latestfavContacts);
editor.commit();
count++;
Toast.makeText(
getApplicationContext(),
"The data saved successfully to ........ : "
+ Fav_Contacts_file + "/PACKAGE",
Toast.LENGTH_SHORT).show();
Toast.makeText(
getApplicationContext(),
"Name : " + name + " and Phone : "
+ phoneNo, Toast.LENGTH_SHORT)
.show();
}
else {
Toast.makeText(
getApplicationContext(),
"More than 5 Fav Contacts are NOT allowed",
Toast.LENGTH_SHORT).show();
}
}
});
alert.show();
}
protected String append(String existing_contact, String new_contact) {
String latestfavContacts = existing_contact + " | "+ new_contact ;
return latestfavContacts;
}
and the data stored in SharedPreference file 'PACAKAGE' looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
-<map>
<string name="CONTACTS"> | Alen 1 231-231-231 | Alex Zun 1 234-321-231 | Dr. S.K. Taher Ali 040-7265587 | Gazer 1 312-345-452 | Helen (432) 341-1343</string>
</map>
I'm yet to work on the formatting and present it to the UI friendly mode as per my application needs.
i have an arraylist that do this :
ArrayList<Integer> id = new ArrayList<Integer>();
for (int i = 0; i <= 20; i++) {
id.add(getResources().getIdentifier("q"+i, "raw", getPackageName()));}
this method before a little change is working good but now have force close!
and i get this logcat:
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{yaAli.package313.hossein110/yaAli.package313.hossein110.know}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)at android.app.ActivityThread.access$600(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
at android.os.Handler.dispatchMessage(Handler.java)
at android.os.Looper.loop(Looper.java)
at android.app.ActivityThread.main(ActivityThread.java)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at yaAli.package313.hossein110.know.onCreate(know.java:33)
at android.app.Activity.performCreate(Activity.java)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java)
... 12 more
Here is my OnCreate():
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.basetxt);
SharedPreferences settings=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
ln=settings.getString("LASTREADln", null);
if(ln.equals("-1")){ln="0";}
if(ln!=null){
final ScrollView s1=(ScrollView) findViewById(R.id.sV1);
s1.post(new Runnable() {#Override
public void run() {s1.scrollTo(0, Integer.valueOf(ln));} });}
final MediaPlayer mp1=MediaPlayer.create(getBaseContext(), R.raw.arza);
String pos = getIntent().getStringExtra("key");
String arr = getIntent().getStringExtra("list");
TextView tvfa = (TextView)findViewById(R.id.TEXT313);
String fontPath = "fonts/font1.ttf";
String fontPath1 = "fonts/font2.ttf";
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
Typeface tf1 = Typeface.createFromAsset(getAssets(), fontPath1);
SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
tvfa.getRootView().setKeepScreenOn(sharedpreferences.getBoolean("scrnon", false));
String sizefa= sharedpreferences.getString("fontsizefa",null);
String colorfa= sharedpreferences.getString("fontcolorfa",null);
boolean style= sharedpreferences.getBoolean("appfont", false);
boolean music= sharedpreferences.getBoolean("musictype", false);
boolean curr= sharedpreferences.getBoolean("currputfont", false);
String t = read(file(pos,arr,null)); {
if (curr){tvfa.setText(PersianReshape.reshape(t));}else{tvfa.setText(t);} // Txt
tvfa.setTextSize(1, Float.valueOf(sizefa).floatValue()); // Size
tvfa.setTextColor(Color.parseColor(colorfa)); // Color
if (style) { tvfa.setTypeface(tf1); } else {tvfa.setTypeface(tf);} // Type
if (music) { mp1.start(); } else { mp1.stop(); } }} // Play
//----------------------------------------------------------------------------
best practice for java development is to have the literal string do the .equals call. so instead of:
var.equals("string")
you do:
"string".equals(var)
This guarantees you will NEVER have a null pointer exception when doing string comparison.
Also, it looks like you are storing numeric values as strings. Any particular reason you aren't storing them as ints?
Its likely here
ln=settings.getString("LASTREADln", null);
this should be
ln=settings.getString("LASTREADln", "");
since null is set to be your default value if that key does not exist or contain anything, so if it doesn't contain anything you should set it to "", and for your string comparisons you should look for !ln.contentsEquals("") instead of checking it for null
the same goes for all of the strings you get from a preferences file. set the default value to "" instead of null