I am new to Android and Java programming and for some reason (I cant point out) my app wont even open.It says "Unfortunately 'app name' has crashed". It has no compile-time errors in it?
Here is the Logcat:
08-19 04:54:07.024 24170-24170/com.elie.billsplitter E/AndroidRuntime﹕FATAL EXCEPTION: main
Process: com.elie.billsplitter, PID: 24170
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.elie.billsplitter/com.elie.billsplitter.MainActivity}: java.lang.NumberFormatException: Invalid int: ""
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: 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 com.elie.billsplitter.MainActivity.<init>(MainActivity.java:11)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
08-19 04:54:09.781 24170-24177/com.elie.billsplitter W/art﹕ Suspending all threads took: 793.743ms
08-19 04:54:36.935 24170-24170/com.elie.billsplitter I/Process﹕ Sending signal. PID: 24170 SIG: 9
Here is the Java file:
public class MainActivity extends Activity {
public int x = Integer.parseInt("");
public int y = Integer.parseInt("");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Button
Button btn = (Button) findViewById(R.id.button);
//EditText
EditText nop = (EditText) findViewById(R.id.editText);
EditText cob = (EditText) findViewById(R.id.editText2);
x = Integer.parseInt(nop.getText().toString());
y = Integer.parseInt(cob.getText().toString());
final TextView tv = (TextView) findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int z = x / y;
tv.setText(z);
}
});
}
}
Most probably you are parsing an empty string into the integer.
x = Integer.parseInt(nop.getText().toString());
y = Integer.parseInt(cob.getText().toString());
before getting the text from the Edittext check that whether it is empty or not. You are parsing an empty string probably.
you can make a check like this:
if(!(nop.toString().trim().equalsIgnoreCase("") && cob.toString().trim().equalsIgnoreCase(""))){
x = Integer.parseInt(nop.getText().toString());
y = Integer.parseInt(cob.getText().toString());
}
and also your are making the initilization the integers in an incorrect way:
May be these are the lines where you are getting exceptions. You cannot parse blank strings to integer.
instead of this:
public int x = Integer.parseInt("");
public int y = Integer.parseInt("");
write this:
public int x = 0;
public int y = 0;
or
public int x = Integer.parseInt("0");
public int y = Integer.parseInt("0");
Before converting to a number you can check if it is a numeric string. For some ideas read this thread on stackoverflow: How to check if a String is numeric in Java
Somewhere in your code you are converting a invalid string or a empty string into a number, which is causing the NumberFormatException.
String x = "abc";
int num = Integer.parseInt(x);
How do I solve it?
try
{
String x = "abc";
int num = Integer.parseInt(x);
}
catch(NumberFormatException ne)
{
System.out.println("Invalid Number!");
}
In your code, replace:
public int x = Integer.parseInt("");
public int y = Integer.parseInt("");
with
public int x;
public int y;
The default values of x and y will be 0. You don't have to add that.
Reason of Error: Integer.parseInt() converts the string inside it to an integer. You have tried to convert "" to an integer, which is not even a number... So NumberFormatException occurred.
Related
This question already has answers here:
android.content.res.Resurces$NotFoundException : String resource ID #0x0 [duplicate]
(2 answers)
Closed 3 years ago.
I am converting JSON data from a server to String and storing in an ArrayList so that I can display the data on a separate activity page. With my string values, this is working perfectly fine. However, when I try with my integer values, my app crashes with a fatal error.
This is my loop to convert the JSON data to strings and add to Array.
for (int i=0; i < jsonArray.length(); i++) {
String make = jsonArray.getJSONObject(i).get("make").toString();
String model = jsonArray.getJSONObject(i).get("model").toString();
String reg = jsonArray.getJSONObject(i).get("license_number").toString();
int year = Integer.parseInt(jsonArray.getJSONObject(i).get("year").toString());
int price = Integer.parseInt(jsonArray.getJSONObject(i).get("price").toString());
String colour = jsonArray.getJSONObject(i).get("colour").toString();
int number_doors = Integer.parseInt(jsonArray.getJSONObject(i).get("number_doors").toString());
String transmission = jsonArray.getJSONObject(i).get("transmission").toString();
int mileage = Integer.parseInt(jsonArray.getJSONObject(i).get("mileage").toString());
String fuel_type = jsonArray.getJSONObject(i).get("fuel_type").toString();
int engine_size = Integer.parseInt(jsonArray.getJSONObject(i).get("engine_size").toString());
String body_style = jsonArray.getJSONObject(i).get("body_style").toString();
String condition = jsonArray.getJSONObject(i).get("condition").toString();
String notes = jsonArray.getJSONObject(i).get("notes").toString();
Vehicle V = new Vehicle(make,model, year, price, reg, colour, number_doors, transmission, mileage, fuel_type,engine_size, body_style, condition, notes);
vehicleArrayList.add(V);
}
I then have an on click listener so when an object is selected it will take you to another activity with fully populated details on each vehicle.
vehicleList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), DetailsActivity.class);
intent.putExtra("license_number", vehicleArrayList.get(position));
startActivity(intent);
}
});
And this is the code in my DetailsActivity.class that clicking on an object should take you to.
Bundle extras = getIntent().getExtras();
Vehicle vehicle = (Vehicle) extras.get("license_number");
System.out.println("received from the intent: " + vehicle.getLicense_number());
TextView reg = findViewById(R.id.vecReg);
TextView make = findViewById(R.id.make);
TextView model = findViewById(R.id.model);
// TextView year = findViewById(R.id.year);
// TextView price = findViewById(R.id.price2);
TextView colour = findViewById(R.id.colour2);
TextView transmission = findViewById(R.id.transmission2);
// TextView mileage = findViewById(R.id.mileage2);
TextView fuel = findViewById(R.id.fuel2);
// TextView engine = findViewById(R.id.engine2);
// TextView doors = findViewById(R.id.doors2);
TextView body = findViewById(R.id.body2);
TextView condition = findViewById(R.id.condition2);
TextView notes = findViewById(R.id.notes2);
reg.setText(vehicle.getLicense_number());
make.setText(vehicle.getMake());
model.setText(vehicle.getModel());
// year.setText(vehicle.getYear());
// price.setText(vehicle.getPrice());
colour.setText(vehicle.getColour());
transmission.setText(vehicle.getTransmission());
// mileage.setText(vehicle.getMileage());
fuel.setText(vehicle.getFuel_type());
// engine.setText(vehicle.getEngine_size());
// doors.setText(vehicle.getNumber_doors());
body.setText(vehicle.getBody_style());
condition.setText(vehicle.getCondition());
notes.setText(vehicle.getNotes());
As you can see, I have commented out the integer values as whenever I have not commented them out, I receive the fatal error. This is from my logcat.
03-28 12:40:56.959 16172-16172/com.example.vehicledatabaseapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.vehicledatabaseapp, PID: 16172
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.vehicledatabaseapp/com.example.vehicledatabaseapp.DetailsActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x7df
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x7df
at android.content.res.Resources.getText(Resources.java:299)
at android.widget.TextView.setText(TextView.java:4132)
at com.example.vehicledatabaseapp.DetailsActivity.onCreate(DetailsActivity.java:42)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
03-28 12:40:59.856 16172-16172/com.example.vehicledatabaseapp I/Process: Sending signal. PID: 16172 SIG: 9
The line "com.example.vehicledatabaseapp.DetailsActivity.onCreate(DetailsActivity.java:42)" is referring to the line "year.setText(vehicle.getYear());"
you have to convert your int value to String before set it to TextView.
year.setText(String.valueOf(vehicle.getYear()))
This question already has answers here:
How exactly does the android:onClick XML attribute differ from setOnClickListener?
(17 answers)
Closed 6 years ago.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.juliandrach.eatfit, PID: 2223
java.lang.IllegalStateException: Could not find method aldirindersalami(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
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:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Basically the error occurs when I am updating a variable by pressing a button and then trying to display the value of the variable with a toast in the same task.
public class Mahlzeiten extends AppCompatActivity {
public static int proteine = 0;
public static int carbs = 0;
public static int fette = 0;
public static int kcal = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mahlzeiten);
String text = "Hallo" + proteine + "danke";
Toast.makeText(Mahlzeiten.this, text, Toast.LENGTH_SHORT).show();
}
public void aldirindersalami (int proteine){
proteine++;
// String text1 = "Hallo" + proteine + "danke";
// Toast.makeText(Mahlzeiten.this, text1, Toast.LENGTH_SHORT).show();
}
}
You have an onClick listener set in the xml but you didn't implement the onClick method in the code. You need the following method
public void aldirindersalami(View v) {}
to handle the click on the button.
this is my first activity, i want to pass the value to second activity to do calculation and show the result in the textview.But I dont know why when i key in all the detail at activity 1, and click the custom button it jump out from the app
public void onClick(View v){
switch (v.getId())
{
case R.id.customMarco:
if(gender.getText().toString().equals("") || age.getText().toString().equals("")||
height.getText().toString().equals("")||weight.getText().toString().equals("")||
activity.getText().toString().equals("")||goal.getText().toString().equals(""))
{
Toast.makeText(getApplicationContext(), "Please key in all your detail above !", Toast.LENGTH_LONG).show();
}
else {
String cal = finalCal_result.getText().toString();
String carb = carb_result.getText().toString();
String protein = protein_result.getText().toString();
String fat = fat_result.getText().toString();
Intent intent = new Intent(this, CustomMarco.class);
intent.putExtra("Cal", cal);
intent.putExtra("Carb", carb);
intent.putExtra("Protein", protein);
intent.putExtra("Fat", fat);
startActivity(intent);
}
break;
}
This is my second activity, to get the valur from activity 1 and do calculation and show the result in textview cp. But I dont know why when i key in all the detail at activity 1, and click the custom button it jump out from the app
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom__marco);
cal = (EditText) findViewById(R.id.field_cal);
String calNum =getIntent().getStringExtra("Cal");
cal.setText ( calNum );
cal.setOnClickListener(this);
carb = (EditText) findViewById(R.id.field_carb);
String carbNum =getIntent().getStringExtra("Carb");
carb.setText ( carbNum );
carb.setOnClickListener(this);
Button setButton = (Button) findViewById(R.id.setButton);
setButton.setOnClickListener(this);
TextView cp = (TextView) findViewById(R.id.cp);
float cal_n = Float.parseFloat(calNum);
float carb_n = Float.parseFloat(carbNum);
int carbPValue = calculateCP(cal_n,carb_n);
cp.setText(String.valueOf(carbPValue) + " %");
}
private int calculateCP(float cal_n, float carb_n){
return (int) ((carb_n/cal_n)*4*100);
}
here the log cat error
12-03 21:25:39.284
28640-28640/com.example.sam.iifym E/AndroidRuntime:
FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sam.iifym/com.example.sam.iifym.CustomMarco}: java.lang.NumberFormatException: Invalid int: "3809 cal"
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2383)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2435)
at android.app.ActivityThread.access$600(ActivityThread.java:168)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1379)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5434)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:852)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:619)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NumberFormatException: Invalid int: "3809 cal"
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parse(Integer.java:375)
at java.lang.Integer.parseInt(Integer.java:366)
at java.lang.Integer.parseInt(Integer.java:332)
at com.example.sam.iifym.CustomMarco.onCreate(CustomMarco.java:59)
at android.app.Activity.performCreate(Activity.java:5224)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1151)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2347)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2435)
at android.app.ActivityThread.access$600(ActivityThread.java:168)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1379)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5434)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:852)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:619)
at dalvik.system.NativeStart.main(Native Method)
Bundle extras = getIntent().getExtras();
String carb = extras.getString("Carb");
for more info just check this answer:
https://stackoverflow.com/a/5265952/2074990
There is problem in your string.
LogCat says Invalid int: "3809 cal"
You pass Invalid data in that string.
You can just pass only Integer for convert String to Float
Example :
Valid String is "3809".
Instead of "3809 cal".
Caused by: java.lang.NumberFormatException: Invalid int: "3809 cal"
You're trying to convert the String "3809 cal" to int/float, while "3809 cal" is not a valid format of int/float.
Check your cal String in the first activity, it must be "3809" instead of "3809 cal".
I'm looking to create a running total on my MainActivity.java, this will be done through adding integers calculated in ActivityAdd.java then sending them across onClick save to a TextView in the MainActivity.java.
It's currently not opening the app due to the stack flow error stating invalid int "". Any advise on this?
AddActivity.Java
OnClickListener button02OnClickListener =
new OnClickListener(){
#Override
public void onClick(View v) {
String theText = result.getText().toString();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.putExtra("calorie", theText);
startActivity(intent);
}};
MainActivity.Java
String calorie = getIntent().getStringExtra("calorie");
TextView textView1 = (TextView)findViewById(R.id.textView1);
Integer oldValue = Integer.parseInt(textView1.getText().toString());
Integer newValue = Integer.parseInt(calorie);
textView1.setText((oldValue + newValue));
StackFlow error
02-24 09:42:39.873 2535-2535/com.example.student.neillapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.student.neillapp, PID: 2535
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.student.neillapp/com.example.student.neillapp.MainActivity}: java.lang.NumberFormatException: Invalid int: ""
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: 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 com.example.student.neillapp.MainActivity.onCreate(MainActivity.java:30)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
The Error occurs due to Empty String "" in textView1.
You are not checking if the String is Blank or not.
So, I added extra 2 lines.
String calorie = getIntent().getStringExtra("calorie");
TextView textView1 = (TextView)findViewById(R.id.textView1);
String strOldValue = textView1.getText().toString();
//Integer oldValue = StringUtils.isNotBlank(myString) ? Integer.parseInt(myString) : 0;
//UPDATE: Replace above with
//Integer oldValue = (myString != null && !myString.isEmpty()) ? Integer.parseInt(myString) : 0;
//UPDATE:
Integer oldValue = 0;
try {
oldValue = Integer.parseInt(myString);
} catch(Exception e) {
//oldValue = 0;
}
Integer newValue = Integer.parseInt(calorie);
textView1.setText((oldValue + newValue));
I think this might help you.
If i understood , what you are looking for is starting an activity for result...
So to do that in your main activity you have to start the ActivityAdd for result like so..
Intent intent = new Intent(getActivity(), ActivityAdd.class);
startActivityForResult(intent,1);
Also in the main activity then you override method onActivityResult like so :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == getActivity().RESULT_OK){
//UPDATE TEXTVIEWS HERE
//DATA IS THE INTENT
}
}
Now in our add activity we must return result once we have it..
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.putExtra("calorie", theText);
setResult(RESULT_OK, intent);
finish();
In you MainActivity.java
String calorie = getIntent().getStringExtra("calorie");
TextView textView1 = (TextView)findViewById(R.id.TextView1);
Integer oldValue = Integer.parseInt(textView1.getText().toString());
Integer newValue = Integer.parseInt(calorie);
//setText() needs a String to set so you can do anyone of the following
textView1.setText(""+(oldValue + newValue));
or
Integer total = oldValue + newValue;
textView1.setText(total.toString());
I created a new activity which is supposed to read elements in a text file then display them as a ListView, but when I try to start the activity by clicking on its icon in the emulator I get this error message :
Unfortunately, app has stopped working
I don't understand why because the project seems to have been compiled correctly ?
PS : The activity I try to open is SortedLocationsListActivity.
Logcat error message :
02-04 13:51:32.340 2900-2900/fr.isima.android.tp1.tp1 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: fr.isima.android.tp1.tp1, PID: 2900
java.lang.RuntimeException: Unable to start activity ComponentInfo{fr.isima.android.tp1.tp1/fr.isima.android.tp1.tp2.SortedLocationsListActivity}: java.lang.NumberFormatException: Invalid long: "1400390852000A"
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NumberFormatException: Invalid long: "1400390852000A"
at java.lang.Long.invalidLong(Long.java:124)
at java.lang.Long.parse(Long.java:366)
at java.lang.Long.parseLong(Long.java:353)
at fr.isima.android.tp1.tp2.SortedLocationsListActivity.onCreate(SortedLocationsListActivity.java:37)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Here is a part of my SortedLocationsListActivity (I modified the onCreate method) :
public class SortedLocationsListActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_sorted_locations_list);
InputStream is = getResources().openRawResource(R.raw.locations);
BufferedReader in = new BufferedReader(new InputStreamReader(is));
List<String> maListe = new ArrayList<String>();
String myligne;
LocationAdapter adapter = new LocationAdapter(this, R.layout.row_location);
try {
while((myligne = in.readLine()) != null)
{
String a[] = myligne.split(";");
Long _date=Long.parseLong(a[2], 36);
System.out.println(a[0]+" "+a[1]+" "+a[2]);
adapter.addLocation(a[0],a[1],_date);
}
setListAdapter(adapter);
}
catch(IOException e)
{
System.out.println("Error");
}
}
Ok, so the code that causes the problem is :
Long _date=Long.parseLong(a[2], 36);
Basically want I'm trying to do is to convert a String which can be "1400390852000A" for example to the Long type, how can I do it correctly ?
Ok, I corrected the error and I have managed to start the activity but it only displays a blank screen instead of the list I want, Here is the adapter that i coded :
public class LocationAdapter extends BaseAdapter {
private List<Location> Locations;
int monLayout;
LayoutInflater inflater;
public LocationAdapter(Context context, int layout){
monLayout=layout;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Locations = new ArrayList<Location>();
}
private class Location{
public String name;
public String address;
public Long date;
public Location(String _name,String _address , Long _date){
name=_name;
address=_address;
date=_date;
}
}
private class ViewHolder{
TextView name_view;
TextView address_view;
TextView date_view;
public ViewHolder(View rowLayout){
name_view = (TextView)rowLayout.findViewById(R.id.name);
date_view = (TextView)rowLayout.findViewById(R.id.date);
address_view = (TextView)rowLayout.findViewById(R.id.address);
}
}
public void addLocation(String _name,String _address,Long _date){
//Création d'une nouvelle location avec les données en paramètres
Location new_loc = new Location(_name, _address,_date);
//Ajout de la location à la liste des locations
Locations.add(new_loc);
}
/*Méthodes de la classe mère*/
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
if (view == null)
view = inflater.inflate(monLayout, parent, false);
ViewHolder holder = (ViewHolder)view.getTag();
if (holder == null)
{
holder = new ViewHolder(view);
view.setTag(holder);
}
Location location = (Location)getItem(position);
holder.name_view.setText(location.name);
holder.address_view.setText(location.address);
holder.date_view.setText("Test");
return view;
}
}
Can someone tell me where the problem may come from ?
Reason is this >> java.lang.NumberFormatException: Invalid long: "1400390852000A"
You are trying to convert String type to Long by Long.parseLong in your activity. Correct this and it will work.
String value >> 1400390852000A, can not be converted to Long.
check your SortedLocationsListActivity line number 37. Bug is there, go kill it :)
take a look at SortedLocationsListActivity line 37.
it's look's like an NumberFormatException: Invalid long: "1400390852000A".
check the parameters here:
Long _date=Long.parseLong(a[2], 36);
Go to line 37 of SortedLocationsListActivity class and check for a Long parsing method. Make sure that the parameter in this is always a number.
Long _date=Long.parseLong(a[2], 36);
Make sure that String myligne, after the ;, has only numbers.
Basically want I'm trying to do is to convert a String wich can be "1400390852000A" for example to the Long type, how can I do it correctly ?
It depends on the format of your Strings. If it's always the case that the letter is at the end then you can get the number by adding this in your code, just before the parsing:
String a[] = myligne.split(";");
String myFinalString = a[2].substring(0, a[2].length()-1);
Long _date=Long.parseLong(myFinalString, 36);