This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I just parse the json data using Gson.but it gives a NullPointerException
this is my json file here JSON File
This is my CustomAdapter which handles the operation and add the data to listview
MyCustomAdapter
package com.vap.gsonexample;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
* Created by Virat Puar on 14-11-2015.
*/
public class CustomAdapter extends BaseAdapter {
private List<Response.DataEntity> weatheritem;
private Context mcontext;
private LayoutInflater inflater;
public CustomAdapter(Context mcontext, List<Response.DataEntity> weatheritem) {
this.mcontext = mcontext;
this.weatheritem = weatheritem;
}
#Override
public int getCount() {
return weatheritem.size();
}
#Override
public Object getItem(int position) {
return weatheritem.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater)mcontext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view =inflater.inflate(R.layout.each_item,parent,false);
Response.DataEntity dataEntity = (Response.DataEntity) getItem(position);
ImageView thumbnial = (ImageView) view.findViewById(R.id.thumbnial);
TextView date = (TextView) view.findViewById(R.id.date);
TextView weathercode = (TextView) view.findViewById(R.id.weathercode);
String imageUrl = dataEntity.getWeather().get(position).getWeatherIconUrl().get(position).getValue();
date.setText(dataEntity.getWeather().get(position).getDate());
weathercode.setText(dataEntity.getWeather().get(position).getWeatherCode());
Picasso.with(mcontext).load(imageUrl).into(thumbnial);
return view;
}
}
This is my Main Activity code where error occurs MainActivity
package com.vap.gsonexample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import java.lang.reflect.Type;
import java.util.List;
import cz.msebera.android.httpclient.Header;
public class MainActivity extends AppCompatActivity {
Response response;
CustomAdapter customAdapter;
String url ="http://api.worldweatheronline.com/free/v1/weather.ashx?" +
"q=Rajkot&format=json&num_of_days=5&key=xz9js2zhayhj4bcxuf7br2bg";
Gson gson;
AsyncHttpClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = (ListView) findViewById(R.id.listView);
client = new AsyncHttpClient();
client.get(MainActivity.this,url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
String responsestr = new String(responseBody);
Type listtype = new TypeToken<Response>(){}.getType();
Response response = gson.fromJson(responsestr, listtype);
customAdapter = new CustomAdapter(MainActivity.this, (List<Response.DataEntity>) response.getData());
listView.setAdapter(customAdapter);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Toast.makeText(getApplication(),"Fail"+statusCode+error,Toast.LENGTH_LONG).show();
}
});
}
}
And Finally this is my log file
E/AndroidRuntime: FATAL EXCEPTION: main
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: java.lang.RuntimeException: java.lang.ClassCastException: com.vap.gsonexample.Response$DataEntity cannot be cast to java.util.List
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at com.loopj.android.http.AsyncHttpResponseHandler.onUserException(AsyncHttpResponseHandler.java:304)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:395)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at com.loopj.android.http.AsyncHttpResponseHandler$ResponderHandler.handleMessage(AsyncHttpResponseHandler.java:510)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:4745)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: Caused by: java.lang.ClassCastException: com.vap.gsonexample.Response$DataEntity cannot be cast to java.util.List
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at com.vap.gsonexample.MainActivity$1.onSuccess(MainActivity.java:40)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:351)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at com.loopj.android.http.AsyncHttpResponseHandler$ResponderHandler.handleMessage(AsyncHttpResponseHandler.java:510)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:4745)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-14 07:25:32.366 1412-1412/? E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
11-14 07:25:32.394 119-173/? E/SocketStream: readFully was waiting for 403440 bytes, got 16192
11-14 07:25:32.394 119-173/? E/SocketStream: readFully was waiting for 387248 bytes, got 16192
11-14 07:25:32.394 119-173/? E/SocketStream: readFully was waiting for 371056 bytes, got 16192
11-14 07:25:32.398 119-173/? E/SocketStream: readFully was waiting for 354864 bytes, got 15664
11-14 07:25:32.398 119-173/? E/SocketStream: readFully was waiting for 339200 bytes, got 16192
11-14 07:25:32.398 119-173/? E/SocketStream: readFully was waiting for 323008 bytes, got 16192
11-14 07:25:32.398 119-173/? E/SocketStream: readFully was waiting for 306816 bytes, got 16192
11-14 07:25:32.398 119-173/? E/SocketStream: readFully was waiting for 290624 bytes, got 16192
11-14 07:25:32.398 119-173/? E/SocketStream: readFully was waiting for 274432 bytes, got 8232
11-14 07:25:32.402 119-173/? E/SocketStream: readFully was waiting for 266200 bytes, got 16192
11-14 07:25:32.402 119-173/? E/SocketStream: readFully was waiting for 250008 bytes, got 16192
11-14 07:25:32.402 119-173/? E/SocketStream: readFully was waiting for 233816 bytes, got 16192
11-14 07:25:32.402 119-173/? E/SocketStream: readFully was waiting for 217624 bytes, got 16192
11-14 07:25:32.402 119-173/? E/SocketStream: readFully was waiting for 201432 bytes, got 8232
11-14 07:25:32.402 119-173/? E/SocketStream: readFully was waiting for 193200 bytes, got 16192
11-14 07:25:32.406 119-173/? E/SocketStream: readFully was waiting for 177008 bytes, got 16192
11-14 07:25:32.406 119-173/? E/SocketStream: readFully was waiting for 160816 bytes, got 16192
11-14 07:25:32.406 119-173/? E/SocketStream: readFully was waiting for 144624 bytes, got 15664
11-14 07:25:32.406 119-173/? E/SocketStream: readFully was waiting for 128960 bytes, got 16192
11-14 07:25:32.406 119-173/? E/SocketStream: readFully was waiting for 112768 bytes, got 16192
11-14 07:25:32.406 119-173/? E/SocketStream: readFully was waiting for 96576 bytes, got 16192
11-14 07:25:32.406 119-173/? E/SocketStream: readFully was waiting for 80384 bytes, got 15664
11-14 07:25:32.406 119-173/? E/SocketStream: readFully was waiting for 64720 bytes, got 16192
11-14 07:25:32.410 119-173/? E/SocketStream: readFully was waiting for 48528 bytes, got 16192
11-14 07:25:32.410 119-173/? E/SocketStream: readFully was waiting for 32336 bytes, got 16192
11-14 07:33:23.734 119-173/? E/SocketStream: readFully was waiting for 403440 bytes, got 16192
11-14 07:33:23.734 119-173/? E/SocketStream: readFully was waiting for 387248 bytes, got 16192
11-14 07:33:23.738 119-173/? E/SocketStream: readFully was waiting for 371056 bytes, got 16192
11-14 07:33:23.738 119-173/? E/SocketStream: readFully was waiting for 354864 bytes, got 15664
11-14 07:33:23.738 119-173/? E/SocketStream: readFully was waiting for 339200 bytes, got 16192
11-14 07:33:23.738 119-173/? E/SocketStream: readFully was waiting for 323008 bytes, got 16192
11-14 07:33:23.738 119-173/? E/SocketStream: readFully was waiting for 306816 bytes, got 16192
11-14 07:33:23.738 119-173/? E/SocketStream: readFully was waiting for 290624 bytes, got 16192
11-14 07:33:23.738 119-173/? E/SocketStream: readFully was waiting for 274432 bytes, got 8232
11-14 07:33:23.742 119-173/? E/SocketStream: readFully was waiting for 266200 bytes, got 16192
11-14 07:33:23.746 119-173/? E/SocketStream: readFully was waiting for 250008 bytes, got 16192
11-14 07:33:23.746 119-173/? E/SocketStream: readFully was waiting for 233816 bytes, got 16192
11-14 07:33:23.746 119-173/? E/SocketStream: readFully was waiting for 217624 bytes, got 16192
11-14 07:33:23.746 119-173/? E/SocketStream: readFully was waiting for 201432 bytes, got 8232
11-14 07:33:23.746 119-173/? E/SocketStream: readFully was waiting for 193200 bytes, got 16192
11-14 07:33:23.746 119-173/? E/SocketStream: readFully was waiting for 177008 bytes, got 16192
11-14 07:33:23.746 119-173/? E/SocketStream: readFully was waiting for 160816 bytes, got 16192
11-14 07:33:23.746 119-173/? E/SocketStream: readFully was waiting for 144624 bytes, got 16192
11-14 07:33:23.750 119-173/? E/SocketStream: readFully was waiting for 128432 bytes, got 8232
11-14 07:33:23.750 119-173/? E/SocketStream: readFully was waiting for 120200 bytes, got 16192
11-14 07:33:23.754 119-173/? E/SocketStream: readFully was waiting for 104008 bytes, got 16192
11-14 07:33:23.754 119-173/? E/SocketStream: readFully was waiting for 87816 bytes, got 16192
11-14 07:33:23.754 119-173/? E/SocketStream: readFully was waiting for 71624 bytes, got 16192
11-14 07:33:23.754 119-173/? E/SocketStream: readFully was waiting for 55432 bytes, got 8232
11-14 07:33:23.754 119-173/? E/SocketStream: readFully was waiting for 47200 bytes, got 16192
11-14 07:33:23.754 119-173/? E/SocketStream: readFully was waiting for 31008 bytes, got 16192
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: User-space exception detected!
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: java.lang.NullPointerException
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at com.vap.gsonexample.MainActivity$1.onSuccess(MainActivity.java:36)
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:351)
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at com.loopj.android.http.AsyncHttpResponseHandler$ResponderHandler.handleMessage(AsyncHttpResponseHandler.java:510)
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at android.os.Handler.dispatchMessage(Handler.java:99)
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at android.os.Looper.loop(Looper.java:137)
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at android.app.ActivityThread.main(ActivityThread.java:4745)
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at java.lang.reflect.Method.invokeNative(Native Method)
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at java.lang.reflect.Method.invoke(Method.java:511)
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-14 07:33:26.842 1489-1489/? E/AsyncHttpRH: at dalvik.system.NativeStart.main(Native Method)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: FATAL EXCEPTION: main
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: java.lang.RuntimeException: java.lang.NullPointerException
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at com.loopj.android.http.AsyncHttpResponseHandler.onUserException(AsyncHttpResponseHandler.java:304)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:395)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at com.loopj.android.http.AsyncHttpResponseHandler$ResponderHandler.handleMessage(AsyncHttpResponseHandler.java:510)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:4745)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: Caused by: java.lang.NullPointerException
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at com.vap.gsonexample.MainActivity$1.onSuccess(MainActivity.java:36)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:351)
11-14 07:33:26.846 1489-1489/? E/AndroidRuntime: at com.loopj.android.http.AsyncHttpResponseHandler$ResponderHandler.handleMessage(AsyncHttpResponseHandler.java:510)
Please help someone to find this error.
This is my Response model
package com.vap.gsonexample;
import java.util.List;
/**
* Created by Virat Puar on 14-11-2015.
*/
public class Response {
private DataEntity data;
public void setData(DataEntity data) {
this.data = data;
}
public DataEntity getData() {
return data;
}
public class DataEntity {
private List<RequestEntity> request;
private List<Current_conditionEntity> current_condition;
private List<WeatherEntity> weather;
public void setRequest(List<RequestEntity> request) {
this.request = request;
}
public void setCurrent_condition(List<Current_conditionEntity> current_condition) {
this.current_condition = current_condition;
}
public void setWeather(List<WeatherEntity> weather) {
this.weather = weather;
}
public List<RequestEntity> getRequest() {
return request;
}
public List<Current_conditionEntity> getCurrent_condition() {
return current_condition;
}
public List<WeatherEntity> getWeather() {
return weather;
}
public class RequestEntity {
/**
* query : Rajkot, India
* type : City
*/
private String query;
private String type;
public void setQuery(String query) {
this.query = query;
}
public void setType(String type) {
this.type = type;
}
public String getQuery() {
return query;
}
public String getType() {
return type;
}
}
public class Current_conditionEntity {
private String precipMM;
private String observation_time;
private List<WeatherDescEntity> weatherDesc;
private String visibility;
private String weatherCode;
private String pressure;
private String temp_C;
private String cloudcover;
private String temp_F;
private String winddirDegree;
private String windspeedMiles;
private String windspeedKmph;
private String humidity;
private String winddir16Point;
private List<WeatherIconUrlEntity> weatherIconUrl;
public void setPrecipMM(String precipMM) {
this.precipMM = precipMM;
}
public void setObservation_time(String observation_time) {
this.observation_time = observation_time;
}
public void setWeatherDesc(List<WeatherDescEntity> weatherDesc) {
this.weatherDesc = weatherDesc;
}
public void setVisibility(String visibility) {
this.visibility = visibility;
}
public void setWeatherCode(String weatherCode) {
this.weatherCode = weatherCode;
}
public void setPressure(String pressure) {
this.pressure = pressure;
}
public void setTemp_C(String temp_C) {
this.temp_C = temp_C;
}
public void setCloudcover(String cloudcover) {
this.cloudcover = cloudcover;
}
public void setTemp_F(String temp_F) {
this.temp_F = temp_F;
}
public void setWinddirDegree(String winddirDegree) {
this.winddirDegree = winddirDegree;
}
public void setWindspeedMiles(String windspeedMiles) {
this.windspeedMiles = windspeedMiles;
}
public void setWindspeedKmph(String windspeedKmph) {
this.windspeedKmph = windspeedKmph;
}
public void setHumidity(String humidity) {
this.humidity = humidity;
}
public void setWinddir16Point(String winddir16Point) {
this.winddir16Point = winddir16Point;
}
public void setWeatherIconUrl(List<WeatherIconUrlEntity> weatherIconUrl) {
this.weatherIconUrl = weatherIconUrl;
}
public String getPrecipMM() {
return precipMM;
}
public String getObservation_time() {
return observation_time;
}
public List<WeatherDescEntity> getWeatherDesc() {
return weatherDesc;
}
public String getVisibility() {
return visibility;
}
public String getWeatherCode() {
return weatherCode;
}
public String getPressure() {
return pressure;
}
public String getTemp_C() {
return temp_C;
}
public String getCloudcover() {
return cloudcover;
}
public String getTemp_F() {
return temp_F;
}
public String getWinddirDegree() {
return winddirDegree;
}
public String getWindspeedMiles() {
return windspeedMiles;
}
public String getWindspeedKmph() {
return windspeedKmph;
}
public String getHumidity() {
return humidity;
}
public String getWinddir16Point() {
return winddir16Point;
}
public List<WeatherIconUrlEntity> getWeatherIconUrl() {
return weatherIconUrl;
}
public class WeatherDescEntity {
/**
* value : Sunny
*/
private String value;
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
public class WeatherIconUrlEntity {
/**
* value : http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0001_sunny.png
*/
private String value;
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
}
public class WeatherEntity {
private String date;
private String precipMM;
private List<WeatherDescEntity> weatherDesc;
private String tempMinF;
private String weatherCode;
private String tempMinC;
private String winddirection;
private String winddirDegree;
private String windspeedMiles;
private String windspeedKmph;
private String tempMaxF;
private String winddir16Point;
private List<WeatherIconUrlEntity> weatherIconUrl;
private String tempMaxC;
public void setDate(String date) {
this.date = date;
}
public void setPrecipMM(String precipMM) {
this.precipMM = precipMM;
}
public void setWeatherDesc(List<WeatherDescEntity> weatherDesc) {
this.weatherDesc = weatherDesc;
}
public void setTempMinF(String tempMinF) {
this.tempMinF = tempMinF;
}
public void setWeatherCode(String weatherCode) {
this.weatherCode = weatherCode;
}
public void setTempMinC(String tempMinC) {
this.tempMinC = tempMinC;
}
public void setWinddirection(String winddirection) {
this.winddirection = winddirection;
}
public void setWinddirDegree(String winddirDegree) {
this.winddirDegree = winddirDegree;
}
public void setWindspeedMiles(String windspeedMiles) {
this.windspeedMiles = windspeedMiles;
}
public void setWindspeedKmph(String windspeedKmph) {
this.windspeedKmph = windspeedKmph;
}
public void setTempMaxF(String tempMaxF) {
this.tempMaxF = tempMaxF;
}
public void setWinddir16Point(String winddir16Point) {
this.winddir16Point = winddir16Point;
}
public void setWeatherIconUrl(List<WeatherIconUrlEntity> weatherIconUrl) {
this.weatherIconUrl = weatherIconUrl;
}
public void setTempMaxC(String tempMaxC) {
this.tempMaxC = tempMaxC;
}
public String getDate() {
return date;
}
public String getPrecipMM() {
return precipMM;
}
public List<WeatherDescEntity> getWeatherDesc() {
return weatherDesc;
}
public String getTempMinF() {
return tempMinF;
}
public String getWeatherCode() {
return weatherCode;
}
public String getTempMinC() {
return tempMinC;
}
public String getWinddirection() {
return winddirection;
}
public String getWinddirDegree() {
return winddirDegree;
}
public String getWindspeedMiles() {
return windspeedMiles;
}
public String getWindspeedKmph() {
return windspeedKmph;
}
public String getTempMaxF() {
return tempMaxF;
}
public String getWinddir16Point() {
return winddir16Point;
}
public List<WeatherIconUrlEntity> getWeatherIconUrl() {
return weatherIconUrl;
}
public String getTempMaxC() {
return tempMaxC;
}
public class WeatherDescEntity {
/**
* value : Sunny
*/
private String value;
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
public class WeatherIconUrlEntity {
/**
* value : http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0001_sunny.png
*/
private String value;
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
}
}
}
Response.getData() is DataEntity .You cast it to List<DataEntity>
Related
every time I try to open my fragment in my MainActivity.class my app crashs.
MainActivity.class
/* Menu */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_server:
Intent intent = new Intent(getApplicationContext(), AddServerFragment.class);
startActivity(intent);
return true;
case R.id.menu_refresh:
myWebView.reload();
return true;
default:
return true;
}
...
public class AddServerFragment extends Fragment {
public AddServerFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.add_ip, container, false);
Button btn_back, btn_add;
final EditText server_ip, server_name;
server_ip = (EditText) findViewById(R.id.edit_server_address);
server_name = (EditText) findViewById(R.id.edit_server_name);
/* Back Button */
btn_back = (Button) findViewById(R.id.btn_back);
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
/* Add IP Button */
btn_add = (Button) findViewById(R.id.btn_add);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String new_server_ip = null, new_server_name = null;
ArrayList<String> server_name_list = new ArrayList<String>();
ArrayList<String> server_ip_list = new ArrayList<String>();
new_server_ip = server_ip.getText().toString();
server_ip_list.add(new_server_ip);
new_server_name = server_name.getText().toString();
server_name_list.add(new_server_name);
}
});
return rootView;
}
}
My errorlog only say, I have to add the Fragment in my Manifest.xml as activity. But I know, I don't have to add it there.
Errorlog
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: FATAL EXCEPTION: main
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: Process: de.kwietzorek.fulcrumwebview, PID: 18345
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: android.content.ActivityNotFoundException: Unable to find explicit activity class {de.kwietzorek.fulcrumwebview/de.kwietzorek.fulcrumwebview.MainActivity$AddServerFragment}; have you declared this activity in your AndroidManifest.xml?
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1794)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Instrumentation.execStartActivity(Instrumentation.java:1512)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Activity.startActivityForResult(Activity.java:3917)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Activity.startActivityForResult(Activity.java:3877)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:784)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Activity.startActivity(Activity.java:4200)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Activity.startActivity(Activity.java:4168)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at de.kwietzorek.fulcrumwebview.MainActivity.onOptionsItemSelected(MainActivity.java:90)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.Activity.onMenuItemSelected(Activity.java:2908)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:361)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:147)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.internal.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.app.AppCompatDelegateImplV7.onMenuItemSelected(AppCompatDelegateImplV7.java:621)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:153)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:948)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.support.v7.internal.view.menu.MenuPopupHelper.onItemClick(MenuPopupHelper.java:191)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.widget.AdapterView.performItemClick(AdapterView.java:310)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.widget.AbsListView.performItemClick(AbsListView.java:1145)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.widget.AbsListView$PerformClick.run(AbsListView.java:3042)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.widget.AbsListView$3.run(AbsListView.java:3879)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
11-14 15:22:05.935 18345-18345/de.kwietzorek.fulcrumwebview E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Edit
My Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Wrong with the above code:
ERROR Intent intent = new Intent(getApplicationContext(), AddServerFragment.class);
startActivity(intent);
Use the correct method for using fragment, you have used method for starting activity.
AddServerFragment is Fragment not activity.
For fragment to add in activity, you have to use the following approach:
In your activity,
XML code part in activity_main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Java Code Part in MainActivity.class:
if (findViewById(R.id.fragment_container) != null) {
if (savedInstanceState != null) {
return;
}
// Create an instance of AddServerFragment
AddServerFragment firstFragment = new AddServerFragment();
// if there are any extras
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
You need to add the activity declaration to your manifest file:
<activity android:name=".MainActivity" >
</activity>
You cant use intent when you want open fragment.
You can try FragmentManager.
Example:
public void getFragment(Fragment fragment) {
FragmentManager fm = getSupportFragmentManager();
Fragment mFragment = fm.findFragmentById(R.id.fragment_container);
if (mFragment == null) {
mFragment = fragment;
fm.beginTransaction()
.add(R.id.fragment_container, mFragment)
.commit();
}
if (mFragment != null) {
mFragment = fragment;
fm.beginTransaction().addToBackStack(null)
.replace(R.id.fragment_container, mFragment)
.commit();
}
}
I have popupMenu and CheckBox. I need make write status CheckBox to boolean.
This code not working:
MenuItem fast_result;
boolean fast=false;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.FastResult:
fast_result = item.getSubMenu().getItem(R.id.FastResult);//This is 182 line
fast_result.setChecked(!fast_result.isChecked());
fast=fast_result.isChecked();
return true;
}
}
It is errors:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.alexvsalex.HelpforMath.RootsActivity.onOptionsItemSelected(RootsActivity.java:182)
at android.app.Activity.onMenuItemSelected(Activity.java:2502)
at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:950)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
at com.android.internal.view.menu.ListMenuPresenter.onItemClick(ListMenuPresenter.java:163)
at android.widget.AdapterView.performItemClick(AdapterView.java:292)
at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
at android.widget.AbsListView$1.run(AbsListView.java:3168)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
What to do?
The problem is solved:
case R.id.FastResult:
fast_result = item; //There was an error
fast_result.setChecked(!fast_result.isChecked());
fast=fast_result.isChecked();
return true;
im making a simple calories calculator and it gives me that error, i already reviewed the code and searched here for the solution but im not able to see why is not running.
I thought it was because i had not initialized the variable, so i did it and still got the same error, maybe is something with the spinners, im new on using spinners
here is the code:
public class CaloriesCalculator extends ActionBarActivity {
EditText etAge, etWeight, etHeight;
Button btnCalculate;
TextView tvResult;
Spinner spinnerGender, spinnerActivity;
String itemGender, itemActivity;
int Height=0;
int Weight=0;
int Age=0;;
double bmr=0.0;
double tdee=0.0;
String result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.caloriescalculator);
spinnerGender=(Spinner)findViewById(R.id.spinnerGender);
spinnerActivity=(Spinner)findViewById(R.id.spinnerActivity);
etAge=(EditText)findViewById(R.id.etAge);
etWeight=(EditText)findViewById(R.id.etWeight);
etHeight=(EditText)findViewById(R.id.etHeight);
tvResult=(TextView)findViewById(R.id.tvResult);
List<String> list = new ArrayList<String>();
list.add("Male");
list.add("Female");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, list );
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGender.setAdapter(dataAdapter);
List<String> list2 = new ArrayList<String>();
list.add("Sedentary");
list.add("Lightly Active");
list.add("Moderalety Active");
list.add("Very Active");
list.add("Extremely Active");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, list2 );
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerActivity.setAdapter(dataAdapter2);
btnCalculate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
spinnerGender.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
spinnerActivity.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
itemGender=String.valueOf(spinnerGender.getSelectedItem());
itemActivity=String.valueOf(spinnerActivity.getSelectedItem());
if(itemGender=="Male"){
Weight=Integer.parseInt(etWeight.getText().toString());
Height=Integer.parseInt(etHeight.getText().toString());
Age=Integer.parseInt(etAge.getText().toString());
if(itemActivity=="Sedentary"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.2;
}
else if(itemActivity=="Lightly Active"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.375;
}
else if(itemActivity=="Moderalety Active"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.55;
}
else if(itemActivity=="Very Active"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.725;
}
else if(itemActivity=="Extremely Active"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.9;
}
}
else if(itemGender=="Female") {
Weight=Integer.parseInt(etWeight.getText().toString());
Height=Integer.parseInt(etHeight.getText().toString());
Age=Integer.parseInt(etAge.getText().toString());
if(itemActivity=="Sedentary"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.2;
}
else if(itemActivity=="Lightly Active"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.375;
}
else if(itemActivity=="Moderalety Active"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.55;
}
else if(itemActivity=="Very Active"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.725;
}
else if(itemActivity=="Extremely Active"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.9;
}
}
result=Double.toString(tdee);
tvResult.setText(result);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
logcat:
11-28 17:20:05.501: E/AndroidRuntime(1455): FATAL EXCEPTION: main
11-28 17:20:05.501: E/AndroidRuntime(1455): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.calculadoracalorias/com.app.calculadoracalorias.CaloriesCalculator}: java.lang.NullPointerException
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.os.Handler.dispatchMessage(Handler.java:99)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.os.Looper.loop(Looper.java:137)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-28 17:20:05.501: E/AndroidRuntime(1455): at java.lang.reflect.Method.invokeNative(Native Method)
11-28 17:20:05.501: E/AndroidRuntime(1455): at java.lang.reflect.Method.invoke(Method.java:525)
11-28 17:20:05.501: E/AndroidRuntime(1455): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-28 17:20:05.501: E/AndroidRuntime(1455): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-28 17:20:05.501: E/AndroidRuntime(1455): at dalvik.system.NativeStart.main(Native Method)
11-28 17:20:05.501: E/AndroidRuntime(1455): Caused by: java.lang.NullPointerException
11-28 17:20:05.501: E/AndroidRuntime(1455): at com.app.calculadoracalorias.CaloriesCalculator.onCreate(CaloriesCalculator.java:67)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.Activity.performCreate(Activity.java:5133)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-28 17:20:05.501: E/AndroidRuntime(1455): ... 11 more
11-28 17:24:42.341: D/AndroidRuntime(1507): Shutting down VM
11-28 17:24:42.341: W/dalvikvm(1507): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-28 17:24:42.371: E/AndroidRuntime(1507): FATAL EXCEPTION: main
11-28 17:24:42.371: E/AndroidRuntime(1507): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.calculadoracalorias/com.app.calculadoracalorias.CaloriesCalculator}: java.lang.NullPointerException
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.os.Handler.dispatchMessage(Handler.java:99)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.os.Looper.loop(Looper.java:137)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-28 17:24:42.371: E/AndroidRuntime(1507): at java.lang.reflect.Method.invokeNative(Native Method)
11-28 17:24:42.371: E/AndroidRuntime(1507): at java.lang.reflect.Method.invoke(Method.java:525)
11-28 17:24:42.371: E/AndroidRuntime(1507): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-28 17:24:42.371: E/AndroidRuntime(1507): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-28 17:24:42.371: E/AndroidRuntime(1507): at dalvik.system.NativeStart.main(Native Method)
11-28 17:24:42.371: E/AndroidRuntime(1507): Caused by: java.lang.NullPointerException
11-28 17:24:42.371: E/AndroidRuntime(1507): at com.app.calculadoracalorias.CaloriesCalculator.onCreate(CaloriesCalculator.java:70)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.Activity.performCreate(Activity.java:5133)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-28 17:24:42.371: E/AndroidRuntime(1507): ... 11 more
Yout btnCalculate is null, you should initialize before doing the onclickListener:
btnCalculate = (Button)findViewById(R.id.btnCalculate); //your id
Also note that you are initializing the dataAdapter2 but actually you are using dataAdapert, and list2 dont have any elements, because you declare it but u are filling always list1
I want this fragment to write to a csv file when a button is clicked but I keep getting java.io.IOException: open failed:ENOENT (No such file or directory). Any help would be greatly appreciated.
public class AddFragment extends Fragment {
static EditText spent,saved,coupons;
Button writeExcelButton;
String data;
Spinner spinner;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.add_layout, container, false);
setSpinnerContent(view);
spent = (EditText) view.findViewById(R.id.spent1);
saved = (EditText) view.findViewById(R.id.saved1);
coupons = (EditText) view.findViewById(R.id.coupons1);
writeExcelButton = (Button) view.findViewById(R.id.button_addGroc);
writeExcelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateSheet();
}
});
return view;
}
private void setSpinnerContent (View view) {
spinner = (Spinner) view.findViewById(R.id.groc_store);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.store1, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
public void updateSheet() {
try {
// This is the string that should be written to file
String mySpin =spinner.getSelectedItem().toString();
data = mySpin + "," + spent.getText().toString() + "," + saved.getText().toString() + "," + coupons.getText().toString() + "/n";
// This is the file that should be written to
String sdCard = Environment.getExternalStorageDirectory().toString();
File dir = new File(sdCard + "/dir");
if (!dir.exists()) {
dir.mkdir();
}
File myFile = new File(dir.getAbsolutePath(), "savings.csv");
// if file doesn't exists, then create it
if (!myFile.exists()) {
myFile.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is what my LogCat looks like
11-14 13:29:23.681: W/System.err(14386): java.io.IOException: open failed: ENOENT (No such file or directory)
11-14 13:29:23.681: W/System.err(14386): at java.io.File.createNewFile(File.java:948)
11-14 13:29:23.691: W/System.err(14386): at com.example.myfirstapp.AddFragment.updateSheet(AddFragment.java:101)
11-14 13:29:23.691: W/System.err(14386): at com.example.myfirstapp.AddFragment$1.onClick(AddFragment.java:59)
11-14 13:29:23.691: W/System.err(14386): at android.view.View.performClick(View.java:4240)
11-14 13:29:23.691: W/System.err(14386): at android.view.View$PerformClick.run(View.java:17721)
11-14 13:29:23.691: W/System.err(14386): at android.os.Handler.handleCallback(Handler.java:730)
11-14 13:29:23.691: W/System.err(14386): at android.os.Handler.dispatchMessage(Handler.java:92)
11-14 13:29:23.691: W/System.err(14386): at android.os.Looper.loop(Looper.java:137)
11-14 13:29:23.691: W/System.err(14386): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-14 13:29:23.691: W/System.err(14386): at java.lang.reflect.Method.invokeNative(Native Method)
11-14 13:29:23.691: W/System.err(14386): at java.lang.reflect.Method.invoke(Method.java:525)
11-14 13:29:23.701: W/System.err(14386): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-14 13:29:23.711: W/System.err(14386): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-14 13:29:23.711: W/System.err(14386): at dalvik.system.NativeStart.main(Native Method)
11-14 13:29:23.711: W/System.err(14386): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
11-14 13:29:23.711: W/System.err(14386): at libcore.io.Posix.open(Native Method)
11-14 13:29:23.711: W/System.err(14386): at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
11-14 13:29:23.711: W/System.err(14386): at java.io.File.createNewFile(File.java:941)
Try changing
dir.mkdir();
to
dir.mkdirs();
Also try just passing dir instead of dir.getAbsolutePath()
Edit
Also you don't want to concatanate file paths like that. Try:
File myFile = new File(Environment.getExternalStorageDirectory(), "dir/savings.csv");
if (!myFile.exists()) {
myFile.mkdirs();
myFile.createNewFile();
}
Add this permissions in manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I am developing app with Jsoup. The problem is it is not working when I am calling it from other class with the help of Getters. But it is running when I call it within Single Activity. I am not able to find why exactly it is not working, as it should.
Here are the logCat files with all the activities.
LogCat
11-14 20:16:52.063: E/AndroidRuntime(1871): FATAL EXCEPTION: AsyncTask #1
11-14 20:16:52.063: E/AndroidRuntime(1871): java.lang.RuntimeException: An error occured while executing doInBackground()
11-14 20:16:52.063: E/AndroidRuntime(1871): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-14 20:16:52.063: E/AndroidRuntime(1871): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.lang.Thread.run(Thread.java:856)
11-14 20:16:52.063: E/AndroidRuntime(1871): Caused by: java.lang.IllegalArgumentException: Must supply a valid URL
11-14 20:16:52.063: E/AndroidRuntime(1871): at org.jsoup.helper.Validate.notEmpty(Validate.java:102)
11-14 20:16:52.063: E/AndroidRuntime(1871): at org.jsoup.helper.HttpConnection.url(HttpConnection.java:57)
11-14 20:16:52.063: E/AndroidRuntime(1871): at org.jsoup.helper.HttpConnection.connect(HttpConnection.java:27)
11-14 20:16:52.063: E/AndroidRuntime(1871): at org.jsoup.Jsoup.connect(Jsoup.java:73)
11-14 20:16:52.063: E/AndroidRuntime(1871): at com.example.frgbdf.jsoupAct$Parsee.doInBackground(jsoupAct.java:30)
11-14 20:16:52.063: E/AndroidRuntime(1871): at com.example.frgbdf.jsoupAct$Parsee.doInBackground(jsoupAct.java:1)
11-14 20:16:52.063: E/AndroidRuntime(1871): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-14 20:16:52.063: E/AndroidRuntime(1871): ... 4 more
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(getApplicationContext(), LineGraph.class);
startActivity(i);
}
}
LineGraph
public class LineGraph extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
jsoupAct mJsoupAct = new jsoupAct();
String parseStrings;
parseStrings = mJsoupAct.getOutput();
Log.d("xstring", parseStrings + "");
}
}
jsoupAct
public class jsoupAct extends Activity {
String output = "00";
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
url = "www.google.com";
}
public void mExecute() {
new Parsee().execute();
}
public class Parsee extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
try {
Document doc = Jsoup.connect(url).get();
String body = doc.body().text();
output = body.toString();
} catch (IOException e) {
e.printStackTrace();
}
return output;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(output);
}
}
public String getOutput() {
mExecute();
return output;
}
public void setOutput(String output) {
this.output = output;
}
}
You are specifying the URL in a string local to the jsoupAct activity. The string will be null if you try to access from other Activities. To solve it move the string inside the AsyncTask class and it will work
Or add empty constructor to the jsonAct activity and assign the value of url in it. onCreate() is called only when to start an activity using the startActivity()
You have already answered your own question:
Caused by: java.lang.IllegalArgumentException: Must supply a valid URL
at org.jsoup.helper.Validate.notEmpty(Validate.java:102)
at org.jsoup.helper.HttpConnection.url(HttpConnection.java:57)
at org.jsoup.helper.HttpConnection.connect(HttpConnection.java:27)
at org.jsoup.Jsoup.connect(Jsoup.java:73)
at com.example.frgbdf.jsoupAct$Parsee.doInBackground(jsoupAct.java:30)
at com.example.frgbdf.jsoupAct$Parsee.doInBackground(jsoupAct.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
... 4 more