Retrieving integer data from JSON and displaying on separate activity [duplicate] - java

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()))

Related

I'm trying to create a dynamic table but when i lunch the app it just crash

the table code
public class Main5Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
{
TableLayout markstable = (TableLayout) findViewById(R.id.datatable);
TableRow tableRow = new TableRow(this);
TextView tv0 = new TextView(this);
tv0.setText(" Student ");
tv0.setTextColor(Color.WHITE);
tableRow.addView(tv0);
TextView tv1 = new TextView(this);
tv1.setText(" Oral Mark ");
tv1.setTextColor(Color.WHITE);
tableRow.addView(tv1);
TextView tv2 = new TextView(this);
tv2.setText(" Home Work ");
tv2.setTextColor(Color.WHITE);
tableRow.addView(tv2);
TextView tv3 = new TextView(this);
tv3.setText(" Test ");
tv3.setTextColor(Color.WHITE);
tableRow.addView(tv3);
markstable.addView(tableRow);
for (int i = 0; i < 50; i++) {
TableRow tableRow1 = new TableRow(this);
TextView t1v = new TextView(this);
t1v.setText( + i);
t1v.setTextColor(Color.WHITE);
t1v.setGravity(Gravity.CENTER);
tableRow1.addView(t1v);
TextView t2v = new TextView(this);
t2v.setText("Student " + i);
t2v.setTextColor(Color.WHITE);
t2v.setGravity(Gravity.CENTER);
tableRow1.addView(t2v);
TextView t3v = new TextView(this);
t3v.setText("Student" + i);
t3v.setTextColor(Color.WHITE);
t3v.setGravity(Gravity.CENTER);
tableRow1.addView(t3v);
TextView t4v = new TextView(this);
t4v.setText( + i * 15 / 32 * 10);
t4v.setTextColor(Color.WHITE);
t4v.setGravity(Gravity.CENTER);
tableRow1.addView(t4v);
markstable.addView(tableRow1);
}
}
}
}
here, i try to make a table for a teacher to save the students names and marks in it and save it to edit it, delete it or replace it
the table just crashes,
by the way i;m trying to make them a text field to enter data but it also crashes
this is my error:
Process: com.mohnad.theeducationnewera.marksbook, PID: 4321
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mohnad.theeducationnewera.marksbook/com.mohnad.theeducationnewera.marksbook.Main5Activity}: android.content.res.Resources$NotFoundException: String resource ID #0x0
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: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:274)
at android.widget.TextView.setText(TextView.java:4122)
at com.mohnad.theeducationnewera.marksbook.Main5Activity.onCreate(Main5Activity.java:45)
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) 
It looks like it telling you that it doesn't know what the variable resource ID is:
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
Just a guess after looking at what you posted

Pass the value from activity 1 to activity 2 to do calculation and show the result

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".

My app keeps crashing but has no errors in it

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.

saving multiple values from one changing TextView using shared preferences?

I have one textView value that the can be changed using a plus and minus button. (like androids number picker object but custom.)
I need to be able to extract each value and save if depending on a spinner value that is set by the user.
For each value that is saved for each spinner position, when the user returns to the same position on the spinner, the previous value entered will appear indicating a value has already been entered.
For Instance:(If spinner is the day of the week)(value is the TextView/custom Spinner) "If the user selects Wednesday, and picks a value of 7, then goes to Monday and picks 8, if the user returns to Wednesday the value entered before (7) will show, if the user returns to Monday the value 8 will show.
Spinner code
final Spinner spinner1 = (Spinner) findViewById(R.id.sp_dotw);
final ArrayAdapter<CharSequence> adapter =
ArrayAdapter.createFromResource(this, R.array.dotw_array, R.layout.custom_spinner);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
spinner1position = position;
spinnerPos();
showToast("spinnerdotw: position= " + position + "id=" + id);
}
public void onNothingSelected(AdapterView<?> adapterView) {
showToast("No Dotw selected");
}
});
Number picker code
#Override
public void onClick(View v) {
String getString = String.valueOf(tvSony.getText());
int current1 = Integer.parseInt(getString);
if (v == btnUp1) {
if (current1 < nEnd) {
current1++;
tvSony.setText(String.valueOf(current1));
}
}
if (v == btnDown1) {
if (current1 > nStart) {
current1--;
tvSony.setText(String.valueOf(current1));
}
}
sonyRs = current1;
}
Any Suggestions on how to do this would be highly appreciated ?
My Attempt So far:
SharedPreferences sp = getSharedPreferences("sun32save", MODE_PRIVATE);
SharedPreferences.Editor spedit = sp.edit();
if (spinner1position == 0 & spinner2position == 0) {
spedit.putString("sun32Son", String.valueOf(sonyRs));
String savedValue1 = sp.getString("sun32Son", "");
spedit.commit();
tvSony.setText(savedValue1);
}
//if a value is found, display value
if (spinner1position == 0 & spinner2position == 1) {
spedit.putString("sun35Son", String.valueOf(sonyRs));
String savedValue2 = sp.getString("sun35Son", "");
spedit.commit();
tvSony.setText(savedValue2);
This returns the default value 0 if i go back to the same spinner position.
Screenshot
Edit Error
06-01 18:37:51.503 18264-18264/com.example.liam.quickreport20 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.liam.quickreport20, PID: 18264
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.liam.quickreport20/com.example.liam.quickreport20.UnitsForm}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object com.example.liam.quickreport20.UnitsForm$Cache.get(java.lang.Object)' on a null object reference
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.NullPointerException: Attempt to invoke virtual method 'java.lang.Object com.example.liam.quickreport20.UnitsForm$Cache.get(java.lang.Object)' on a null object reference
at com.example.liam.quickreport20.UnitsForm.loadTextFields(UnitsForm.java:220)
at com.example.liam.quickreport20.UnitsForm.onCreate(UnitsForm.java:152)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            

Activity doesn't start

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);

Categories