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
Related
This question already has answers here:
Proper way to avoid parseInt throwing a NumberFormatException for input string: ""
(7 answers)
Closed 6 years ago.
I've tried lot of things found here, but it keeps crashing. I wanna know what do i need to add in order to show a Toast message when button is clicked and EditText is empty.
INFO: The app is supposed to send the two values in the EditText's to another activity, showing Toast's in the following exceptions:the first value higher than 6; the second value higher than (firstvalue*14); and if the fields are empty (which is my problem)
Here's my code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView saludo_bienvenida;
EditText et1_creditos;
EditText et2_faltas;
Button boton_ingresar;
Button boton_info;
String numero_creditos;
String numero_faltas_actuales;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
saludo_bienvenida = (TextView) findViewById(R.id.saludo_bienvenida);
et1_creditos = (EditText) findViewById(R.id.edittext1_numero_creditos);
et2_faltas = (EditText) findViewById(R.id.edittext2_numero_faltas);
boton_ingresar = (Button) findViewById(R.id.boton_ingresar);
boton_info = (Button) findViewById(R.id.boton_info);
if (boton_ingresar != null) {
boton_ingresar.setOnClickListener(this);
}
if (boton_info != null) {
boton_info.setOnClickListener(this);
}
et1_creditos.setInputType(InputType.TYPE_CLASS_NUMBER);
et2_faltas.setInputType(InputType.TYPE_CLASS_NUMBER);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.boton_ingresar:
numero_creditos = et1_creditos.getText().toString();
numero_faltas_actuales = et2_faltas.getText().toString();
int numero_creditos1 = Integer.parseInt(numero_creditos);
int numero_faltas_actuales1 = Integer.parseInt(numero_faltas_actuales);
int o = numero_creditos1 * 14;
if (numero_creditos1>6) {
Toast.makeText(getApplicationContext(), "Ingrese un número válido de créditos", Toast.LENGTH_LONG).show();
}else if (numero_faltas_actuales1 > o){
Toast.makeText(getApplicationContext(), "El número de faltas ingresadas es mayor que el número de horas del curso", Toast.LENGTH_LONG).show();
}else{
Intent intent = new Intent(MainActivity.this,Resultados.class);
intent.putExtra("numero_creditos",numero_creditos);
intent.putExtra("numero_faltas_actuales",numero_faltas_actuales);
startActivity(intent);
}
break;
case R.id.boton_info:
Intent informacion = new Intent(MainActivity.this,Informacion.class);
startActivity(informacion);
break;
}
}
}
This is the log:
06-17 01:36:17.419 2738-2738/absence_counter.app.jorgepasco.com.absencecounter E/AndroidRuntime: FATAL EXCEPTION: main
Process: absence_counter.app.jorgepasco.com.absencecounter, PID: 2738
java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at absence_counter.app.jorgepasco.com.absencecounter.MainActivity.onClick(MainActivity.java:60)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
So thanks you for your log !
You can see on your log that you have a problem when you parseInt. You try to parseInt an empty String.
So when the user do not write anything, you have to set a default value yourself.
You can do something like that before your parse:
if(numero_creditos.equals(""))
numero_creditos = "0";
But if I were you, I would force the user to right directly an integer
Please, show us your log box.
Perhaps the app crash because you don't have any default case in your switch case. So if v.getId() is not what you think, it will crash.
Simply, add that at the end of your switch case:
switch(v.getId()){
case: ...
case: ...
default: Toast.makeText(getApplicationContext(),"v.getId = " + v.getId());
}
But I would be easier for me to solve your problem with your log box !
et1_creditos.getText() can maybe send a null value. Then null.toString() has no sense because null does not have toString().
try:
String creditos = et1_creditos.getText()
if(creditos != null){
//stuff here
}
It is failing on this line.
int numero_creditos1 = Integer.parseInt(numero_creditos);
If your numeor_creditos is empty it won't be integer.
Try
int numero_creditos1;
if(TextUtils.isEmpty(numero_creditos){
numero_creditos1 = 0;
} else {
numero_creditos1 = Integer.parseInt(numero_creditos);
}
I am having error in this for past couple of days, have tried using breakpoints to figure why is it giving null pointer exception, but i am not able to understand which value is getting stuck. How can i make db be not null, so as to run this code.
I have an abstract class that calls this method on certain conditional statement. It has to return a long value. Which is to be used for some other method.
This method long save is implemented in another class which returns a value after calling db.insert, but i am getting Null Pointer Exception
java.lang.NullPointerException: Attempt to invoke virtual method 'long android.database.sqlite.SQLiteDatabase.insert(java.lang.String, java.lang.String, android.content.ContentValues)' on a null object reference
I have following doubts :
Why is this giving error when i am using it in Fragment, but when i am using with Activity it's working fine. What can be the reason.
Also How is getWritableDatabase gets called when i pass db as an argument.
long save(SQLiteDatabase db) {
ContentValues cv = new ContentValues();
long now = System.currentTimeMillis();
cv.put(COL_CREATEDTIME, now);
cv.put(COL_MODIFIEDTIME, now);
//cv.putNull(COL_MODIFIEDTIME);
cv.put(COL_NAME, name==null ? "" : name);
//if (fromDate != null)
cv.put(COL_FROMDATE, fromDate==null ? "" :fromDate);
//if (toDate != null)
cv.put(COL_TODATE, toDate==null ? "" :toDate);
//if (rule != null)
cv.put(COL_RULE, rule==null ? "" :rule);
//if (interval != null)
cv.put(COL_INTERVAL, interval==null ? "" :interval);
cv.put(COL_SOUND, sound ? 1 : 0);
//if (sound != null)
//Log.e(TAG, "Error inserting " + now);
return db.insert(TABLE_NAME,null, cv);}
public class DosageDB extends Application {
public static DBHelper dbHelper;
public static SQLiteDatabase db;
public static final String TIME_OPTION = "time_option";
public static final String DATE_RANGE = "date_range";
public static final String DATE_FORMAT = "date_format";
public static final String TIME_FORMAT = "time_format";
public static final String VIBRATE_PREF = "vibrate_pref";
public static final String RINGTONE_PREF = "ringtone_pref";
public static final String DEFAULT_DATE_FORMAT = "yyyy-M-d";
#Override
public void onCreate() {
super.onCreate();
PreferenceManager.setDefaultValues(this,R.xml.settings, false);
sp = PreferenceManager.getDefaultSharedPreferences(this);
dbHelper = new DBHelper(this);
db = dbHelper.getWritableDatabase();
}
}
Stacktrace :
09-10 15:05:39.582 2423-2423/healerkart.com.dosage E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: healerkart.com.dosage, PID: 2423
java.lang.NullPointerException: Attempt to invoke virtual method 'long android.database.sqlite.SQLiteDatabase.insert(java.lang.String, java.lang.String, android.content.ContentValues)' on a null object reference
at healerkart.com.dosage.Delta.Alarm.save(Alarm.java:65)
at healerkart.com.dosage.Delta.AbstractModel.persist(AbstractModel.java:54)
at healerkart.com.dosage.Delta.Alarm.persist(Alarm.java:10)
at healerkart.com.dosage.Alpha.dosageFrag$2.onClick(dosageFrag.java:134)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Since DosageDB was extending Application, i forgot to mention the Application name attribute in the AndroidManifest.xml
Thanks anyways.
I built an android app that casts a spinner to a switch, to enable the user to select an operator for a calculation and see the result.
It is from the Android Boot Camp lessons. I was unhappy to find my app had no compile errors but crashed on start-up. I was watching the logcat as I ran the application and found the nullpointer exception to be on line 40. Where I pull the spinner's selection to a string variable.
//spinner
op3 = operation.getSelectedItem().toString();
I dumped the contents of my logcat to a text file. Here is what I think is relevant.
09-30 22:26:58.401: E/AndroidRuntime(1565): FATAL EXCEPTION: main
09-30 22:26:58.401: E/AndroidRuntime(1565): Process: com.schmop.flashmath, PID: 1565
09-30 22:26:58.401: E/AndroidRuntime(1565): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.schmop.flashmath/com.schmop.flashmath.MainActivity}: java.lang.NullPointerException
and
**09-30 22:26:58.401: E/AndroidRuntime(1565): Caused by: java.lang.NullPointerException
09-30 22:26:58.401: E/AndroidRuntime(1565): at** com.schmop.flashmath.MainActivity.onCreate(MainActivity.java:40)
09-30 22:26:58.401: E/AndroidRuntime(1565): at android.app.Activity.performCreate(Activity.java:5231)
09-30 22:26:58.401: E/AndroidRuntime(1565): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-30 22:26:58.401: E/AndroidRuntime(1565): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
09-30 22:26:58.401: E/AndroidRuntime(1565): ... 11 more
Here is the contents of my mainActivity in
MainActivity.java
public class MainActivity extends ActionBarActivity {
int number1;
int number2;
int result;
int op1;
int op2;
String op3 = null;
int calculator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText first = (EditText)findViewById(R.id.num);
final EditText second = (EditText)findViewById(R.id.num2);
final Spinner operation = (Spinner)findViewById(R.id.operator);
final Button equals = (Button)findViewById(R.id.button1);
final TextView t = (TextView)findViewById(R.id.result);
operation.setSelection(0);
//spinner
op3 = operation.getSelectedItem().toString();
//start logic
//onclick listener
equals.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//gettext
number1 = Integer.parseInt(first.getText().toString());
number2 = Integer.parseInt(second.getText().toString());
if(number1 < 21 && number1 > 0 && number2 < 21 && number2 > 0) {
//switch
switch(calculator) {
case 1: op3 = "+";
calculator = number1 + number2;
break;
case 2: op3 = "-";
calculator = number1 - number2;
break;
case 3: op3 = "x";
calculator = number1 * number2;
break;
}
} else {
t.setText("Error: One of your Numbers is out of Range");
}
t.setText(number1 + op3 + number2 + "=" + calculator);
}
});
//end logic
}
Since it was calling a null variable, I tried adding junk data into the declaration of op3 as an attempt to fix my problem. This proved unsuccessful. I've seen some examples being solved by adding a check for null in an if statement, however I dont think it would apply here.
Documentation for getSelectedItem():
Returns The data corresponding to the currently selected item, or null if there is nothing selected.
When the app is starting up, nothing is yet selected. Move the
op3 = operation.getSelectedItem()
inside the onClick() and check for != null before trying to call toString() on the result.
You haven't set any contents for the spinner, so operation.getSelectedItem() is returning null. The NPE is from trying to then call toString(). Populate your spinner first before trying to access items, or at least put a null check when you try to retrieve an item.
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.
EDIT:A Pastebin consisting of the relevant parts of my project:
Here is the updated code
Also ColouredItem is a wrapper for:
public class ColouredItem
{//Only a wrapper class,no behaviour has been defined here
String name,colour;
}
I get a NumberFormatException when trying to parse a colour from a String using the following code:
row.setBackgroundColor(Color.parseColor(item.colour));
I use the following to create a list of items from a resource:
for(int i=0;i<list.length;i++)
{
item=new ColouredMenuItem();
String[] cmenu =list[i].split("#");
item.name=cmenu[0];
item.colour="#"+cmenu[1];
Log.d(TAG, item.colour);
menuList.add(item);
}
This is the exception that I get...I have found that view.setBackgroundColor only takes an integer value:
#ffffff
#ffffBB
#fff45f
#ffff00
Shutting down VM
threadid=1: thread exiting with uncaught exception (group=0x4001d800)
FATAL EXCEPTION: main
java.lang.NumberFormatException: ffffff
at java.lang.Long.parse(Long.java:364)
at java.lang.Long.parseLong(Long.java:354)
at android.graphics.Color.parseColor(Color.java:207)
at com.example.samplelistproject.MadAdapter.getView(MadAdapter.java:60)
at android.widget.AbsListView.obtainView(AbsListView.java:1315)
at android.widget.ListView.makeAndAddView(ListView.java:1727)
at android.widget.ListView.fillDown(ListView.java:652)
at android.widget.ListView.fillFromTop(ListView.java:709)
at android.widget.ListView.layoutChildren(ListView.java:1580)
at android.widget.AbsListView.onLayout(AbsListView.java:1147)
at android.view.View.layout(View.java:7035)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:7035)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
at android.view.View.layout(View.java:7035)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:7035)
at android.view.ViewRoot.performTraversals(ViewRoot.java:1045)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Adding the # as some of the answers suggest did not solve the issue:
java.lang.NumberFormatException: Invalid long: "#ffffff"
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
No difference with this implementation either:
String cmenu=list[i];
item.name=cmenu.substring(0, cmenu.indexOf("#"));
item.colour=cmenu.substring(cmenu.indexOf("#"));
Use this code
row.setBackgroundColor(Color.parseColor("#424242"));
it helped me too,dont remove "#".
i used this code
private List<String> item;
item = new ArrayList<String>();
item.add("#424242");
row.setBackgroundColor(Color.parseColor(item.get(0)));
and its working gud for me,may be your split thing is not working good
or for your code
Button btn;
ColouredMenuItem item;
ArrayList<ColouredMenuItem> menuList = new ArrayList<ColouredMenuItem>();
String[] list = new String[] { "Page1 #ffffff", "Page2 #ffffBB" };
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sample);
try {
btn = (Button) findViewById(R.id.button1);
for (int i = 0; i < list.length; i++) {
item = new ColouredMenuItem();
String[] cmenu = list[i].split("#");
item.name = cmenu[0];
item.color = "#" + cmenu[1];
Log.d("colored", item.color);
menuList.add(item);
}
btn.setBackgroundColor(Color.parseColor(menuList.get(1).color));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this is working good at my side
this is new code
Make your colored item as a bean class with getter and setter like this
public class ColouredMenuItem {// Only a wrapper class,no behaviour has been defined
// here
String name, colour;
List<ColouredMenuItem> list=new ArrayList<ColouredMenuItem>();
public List<ColouredMenuItem> getList() {
return list;
}
public void setList(List<ColouredMenuItem> menuList) {
this.list = menuList;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
}
Then in your adapter use this code
try {
Log.d(TAG, menuList.get(position).colour);
textView.setText(menuList.get(position).getName());
{
row.setBackgroundColor(Color.parseColor(menuList.get(position).getColour()));
}
} catch (Exception ex) {
Log.e(TAG, "Still does not work");
}
Just give it a try,it works here at my side
Also your array is like this only na
<string-array name="menu_array">
<item>Page1 #ff7788</item>
<item>Page1 #ff6688</item>
<item>Page1 #424242</item>
</string-array>
Try Color.parseColor("#ffffff"); instead of Color.parseColor("ffffff");
look at the Stack trace it will tell you:
java.lang.NumberFormatException: ffffff
at java.lang.Long.parse(Long.java:364)
at java.lang.Long.parseLong(Long.java:354)
at android.graphics.Color.parseColor(Color.java:207)
at com.example.samplelistproject.MadAdapter.getView(MadAdapter.java:60)
Line by Line:
you are trying to format Hexadecimal (base 16) value "0xffffff" to a decimal (base 10) value
you're trying to parse hexadecimal string "ffffff" to type Long
same as above.
error is thrown when calling `Color.parseColor()`
error is thrown from your MadAdapter.java Class on line 60.
so, you need to find a way to parse it from Hexadecimal instead of decimal value. Hexadecimal values are usually preceeded by 0x[value] OR #[value]
Assuming: while parsing the color from string object "item" is not taken from array of list, rather its taking instance variable of ColoureMenuItem.
ColouredMenuItem item;
ArrayList<ColouredMenuItem> menuList = new ArrayList<ColouredMenuItem>();
String[] list = new String[]{"#ffffff","#00ffff"};
// parsing your string here, no change in this
for(int i=0;i<list.length;i++)
{
item=new ColouredMenuItem();
String[] cmenu =list[i].split("#");
item.name=cmenu[0];
item.color="#"+cmenu[1];
Log.d("colored", item.color);
menuList.add(item);
}
// confirming whether value are parsing or not.
for(int i=0;i<menuList.size();i++)
{
int color = Color.parseColor(menuList.get(i).color);
Log.d("color",""+menuList.get(i).color);
}
and your ColouredMenuItem class.
public class ColouredMenuItem {
public String color;
public String name;
}