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);
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()))
Below is my MainActivity.java (I have removed some of unnecessary code. My main activity was a Navigation Viewer activity)
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<MainStoryTile> list = new ArrayList<MainStoryTile>();
int[] image_id = { R.drawable.sample, R.drawable.sample, R.drawable.sample};
String[] name, email, mobile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = getResources().getStringArray(R.array.person_name);
email = getResources().getStringArray(R.array.person_email);
mobile = getResources().getStringArray(R.array.person_mobile);
int count = 0;
for(String NAME: name){
MainStoryTile contact = new MainStoryTile(image_id[count], NAME, email[count], mobile[count]);
count++;
list.add(contact);
}
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new MainStoryAdapter(list);
recyclerView.setAdapter(adapter);
}
#Override
public void onBackPressed() {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
return true;
}
}
Below is my Adapter class. (Note : there is an inner class)
public class MainStoryAdapter extends RecyclerView.Adapter<MainStoryAdapter.StoryViewHolder>{
ArrayList<MainStoryTile> contacts = new ArrayList<MainStoryTile>();
public MainStoryAdapter(ArrayList<MainStoryTile> contacts){
this.contacts = contacts;
}
#Override
public StoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_main,parent,false );
StoryViewHolder storyViewHolder = new StoryViewHolder(view);
return storyViewHolder;
}
#Override
public void onBindViewHolder(StoryViewHolder holder, int position) {
MainStoryTile CON = contacts.get(position);
holder.person_img.setImageResource(CON.getImage_id());
holder.person_name.setText(CON.getName());
holder.person_email.setText(CON.getEmail());
holder.person_mobile.setText(CON.getMobile());
}
#Override
public int getItemCount() {
return contacts.size();
}
public static class StoryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView person_img;
TextView person_name, person_email, person_mobile;
public StoryViewHolder(View view){
super(view);
person_img = (ImageView) view.findViewById(R.id.person_image);
person_name = (TextView) view.findViewById(R.id.person_name);
person_email = (TextView) view.findViewById(R.id.person_email);
person_mobile = (TextView) view.findViewById(R.id.person_mobile);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Log.d("MY LOG", "sdurfhiusrhdidysdysdysdysdys r");
}
}
}
When I click on a item, my app crashes. below is error log :
03-17 15:20:38.638 28744-28744/com.storyteller.pro.storyteller E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.storyteller.pro.storyteller, PID: 28744
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4286)
at android.view.View.performClick(View.java:5242)
at android.view.View$PerformClick.run(View.java:21196)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6938)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4281)
at android.view.View.performClick(View.java:5242)
at android.view.View$PerformClick.run(View.java:21196)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6938)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:4277)
at android.view.ViewGroup.addView(ViewGroup.java:4127)
at android.view.ViewGroup.addView(ViewGroup.java:4068)
at android.view.ViewGroup.addView(ViewGroup.java:4041)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:247)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:114)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4281)
at android.view.View.performClick(View.java:5242)
at android.view.View$PerformClick.run(View.java:21196)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6938)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
03-17 15:20:43.048 28744-28744/com.storyteller.pro.storyteller I/Process: Sending signal. PID: 28744 SIG: 9
Update: Even after I commented the following line in the view.setOnClickListener(this); in the MainStoryAdapter, my app still crashing when I click on an item.
Below is the project for those who like to see more > project zip version
I checked your project and you, why ever, define android:onClick="setContentView" in your content_main.xml layout for the CardView.
Remove that attribute and it works.
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.
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'm trying to retrieve data from a json with multiple values and cast it into a listview but im gettting the error java.util.hashmap cannot be cast to java.util.list.
I'm using volley.
The FeedListActivity Class:
public void updateList() {
feedListView= (ListView) findViewById(R.id.custom_list);
feedListView.setVisibility(View.VISIBLE);
progressbar.setVisibility(View.GONE);
feedListView.setAdapter(new CustomListAdapter(this, feedList));
feedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = feedListView.getItemAtPosition(position);
ClientesContatosModel newsData = (ClientesContatosModel) o;
Intent intent = new Intent(FeedListActivity.this, FeedDetailsActivity.class);
intent.putExtra("nome", newsData);
startActivity(intent);
}
});
}
JSONArray dados = json.getJSONArray("dados");
// parsing json object
for (int i = 0; i < dados.length(); i++) {
JSONObject item = dados.getJSONObject(i);
feedList = new ArrayList<ClientesModel>();
ClientesModel mClientesModel = new ClientesModel();
ClientesContatosModel mClientesContatoModel = new ClientesContatosModel();
/* cadastra os dados necessários no objeto no modelo */
mClientesModel.setId(item.optInt("id"));
mClientesModel.setNome(item.optString("nome"));
mClientesModel.setTipo_pessoa(item.optString("tipo_pessoa"));
mClientesModel.setInformacoes_adicionais(item.optString("informacoes_adicionais"));
mClientesModel.setCpf(item.optString("cpf"));
mClientesModel.setCnpj(item.optString("cnpj"));
JSONArray contatos = item.getJSONArray("contatos");
for (int j = 0; j < contatos.length(); j++) {
JSONObject data = contatos.getJSONObject(j);
mClientesContatoModel.setNome(data.optString("nome"));
mClientesContatoModel.setCargo(data.optString("cargo"));
FeedDetailsActivity class:
public class FeedDetailsActivity extends Activity {
private ClientesContatosModel feed;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed_details);
feed = (ClientesContatosModel) this.getIntent().getSerializableExtra("nome");
if (null != feed) {
TextView title = (TextView) findViewById(R.id.title);
title.setText(feed.getNome());
}
}
Here is the Log:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.javatechig.feedreader/com.javatechig.feedreader.FeedDetailsActivity}: java.lang.ClassCastException: java.util.HashMap cannot be cast to com.javatechig.feedreader.model.ClientesContatosModel
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.util.HashMap cannot be cast to com.javatechig.feedreader.model.ClientesContatosModel
at com.javatechig.feedreader.FeedDetailsActivity.onCreate(FeedDetailsActivity.java:26)
at android.app.Activity.performCreate(Activity.java:5248)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
Because HashMap#values() return a java.util.Collection and you cant cast Collection into ArrayList, thus you get ClassCastException.
where as in case of ArrayList(HashMap.values()) ArrayList constructor takes Collection as an argument. Thus you wont get ClassCastException when you pass HashMap.values() as an argument to ArrayList.
HashMap#values(): check the return type in the source, as ask yourself, can a java.util.Collection be casted into java.util.ArrayList ?? No
public Collection<V> values() {
921 Collection<V> vs = values;
922 return (vs != null ? vs : (values = new Values()));
923 }
ArrayList(Collection): check the argument type in the source. can a method whose argument is a super type accepts sub type ? Yes
public ArrayList(Collection<? extends E> c) {
151 elementData = c.toArray();
152 size = elementData.length;
153 // c.toArray might (incorrectly) not return Object[] (see 6260652)
154 if (elementData.getClass() != Object[].class)
155 elementData = Arrays.copyOf(elementData, size, Object[].class);
156 }