How to fix java.lang.ClassCastException... cannot cast interface - java

In my main activity i have a fragment which displays weather information. I have an interface between the fragment and the main activity that sends data from fragment to activity. The problem is when trying to specifically enter the fragment activity the app crashes and this error is displayed.
Any help or any alternative ways doing it would be appreciated.
private void loadData() {
final List<WeatherForeCast> listWeatherForeCasts = new ArrayList<>();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
"https://www.metaweather.com/api/location/3534/",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("consolidated_weather");
JSONObject jsonObject1 = jsonObject.getJSONObject("parent");
String cityCountry = jsonObject1.getString("title");
cityCountry = cityCountry + " ," + jsonObject.getString("title");
textViewCity.setText(Html.fromHtml(cityCountry ));
for (int x = 0; x < 6; x++) {
JSONObject weatherObject = array.getJSONObject(x);
WeatherForeCast weatherForeCast = new WeatherForeCast(
weatherObject.getInt("air_pressure"),
weatherObject.getInt("wind_speed"),
weatherObject.getInt("the_temp"),
weatherObject.getInt("humidity"),
weatherObject.getString("weather_state_name"),
weatherObject.getString("applicable_date"));
listWeatherForeCasts.add(weatherForeCast);
weatherState = listWeatherForeCasts.get(0).getWeatherState();
if(x == 0) {
sendData();
}
}
;
adapter = new Adapter(listWeatherForeCasts, getActivity());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
public void sendData()
{
Log.i("fault", weatherState);
getFirstWeatherInterface getFirstWeather = (getFirstWeatherInterface) getActivity();
getFirstWeather.getFirst(weatherState);
}
//Interface is implemented in the Activity
#Override
public WeatherForeCast getFirst(String string) {
Log.i("fault2", string);
return null
}
java.lang.ClassCastException: com.fan4.outdoorplus.WeatherFragments.WeatherActivity cannot be cast to com.fan4.outdoorplus.getFirstWeatherInterface
at com.fan4.outdoorplus.WeatherFragments.WeatherFragment.sendData(WeatherFragment.java:143)
at com.fan4.outdoorplus.WeatherFragments.WeatherFragment$1.onResponse(WeatherFragment.java:117)
at com.fan4.outdoorplus.WeatherFragments.WeatherFragment$1.onResponse(WeatherFragment.java:92)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Your problem is in this line. You are trying casting your activity to getFirstWeatherInterface
getFirstWeatherInterface getFirstWeather = (getFirstWeatherInterface) getActivity();

Related

Android - Wait for volley response for continue

I build an app, that it load markers in a map, the markers I get it for volley JSON file, but I need that first to load volley, and after continue executing the code, because the other way show me error with latLng null, this parameter is not loaded fast, and another method execute first and show me null.
My volley code for load markers
public void getMarkers(){
requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray saagTracker = response.getJSONArray("saagMRK");
for (int i = 0; i < saagTracker.length(); i++) {
JSONObject object = saagTracker.getJSONObject(i);
title = object.getString(TITLE);
snnipet = object.getString(SNNIP);
latLng = new LatLng(Double.parseDouble(object.getString(LAT)), Double.parseDouble(object.getString(LNG)));
coor = coor + "|" + object.getString(LAT) + "," + object.getString(LNG); // Menambah data marker untuk di tampilkan ke google map
addMarker(latLng, title, snnipet);
}
} catch (JSONException e) {
e.printStackTrace();
}
//JSONArray array = new JSONArray(response.body().string());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Ocurrio un error", Toast.LENGTH_LONG).show();
}
});
requestQueue.add(jsonObjectRequest);
}
onCreate it need latLng first for it to can load my geofire parameter
geoQuery = geofire.queryAtLocation(new GeoLocation(latLng.latitude, latLng.longitude),0.1f); // latLng it coming null
You would need to implement a call back for the volley response. A very simple way to do this would be the following.
Step 1: Create this interface
public interface VolleyCallBack {
void onSuccess();
}
Step 2: change your getMarkers() method to this:
public void getMarkers(final VolleyCallBack callBack){
requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray saagTracker = response.getJSONArray("saagMRK");
for (int i = 0; i < saagTracker.length(); i++) {
JSONObject object = saagTracker.getJSONObject(i);
title = object.getString(TITLE);
snnipet = object.getString(SNNIP);
latLng = new LatLng(Double.parseDouble(object.getString(LAT)), Double.parseDouble(object.getString(LNG)));
coor = coor + "|" + object.getString(LAT) + "," + object.getString(LNG); // Menambah data marker untuk di tampilkan ke google map
addMarker(latLng, title, snnipet);
callback.onSuccess();
}
} catch (JSONException e) {
e.printStackTrace();
}
//JSONArray array = new JSONArray(response.body().string());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Ocurrio un error", Toast.LENGTH_LONG).show();
}
});
requestQueue.add(jsonObjectRequest);
}
Step 3: Call your getMarkers() method like this:
getMarkers(new VolleyCallBack() {
#Override
public void onSuccess() {
// this is where you will call the geofire, here you have the response from the volley.
geoQuery = geofire.queryAtLocation(new GeoLocation(latLng.latitude, latLng.longitude),0.1f);
});

JSONArray to a ListView array data not shown

i want to when run the app make the jsonRequest without pressing any button and save the data. i just add a method for internet connection check:
if the connection to the internet its true, make the json request pass to the spinner, and save de data.
and when the internet connection its false, just load the data from sharedPreferences to the spinner.
The application runs totally fine with the buttons (with simple onClick methods) and without the verificaConexion method.
But when i remove the buttons, add the verificaConexion method and i have internet connection, just, make the json request, show the data in the spinner and not save the data And when I close the app, remove the wifi, open the app, the spinner shows nothing.
For any reason the methods save and load data doesn't works.
This is my onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnObtener = (Button) findViewById(R.id.btnObtener);
spDelegaciones = (Spinner)findViewById(R.id.spDelegaciones);
btnGuardar = (Button) findViewById(R.id.btnGuardar);
btnCargar = (Button) findViewById(R.id.btnCargar);
txJsonArray = (TextView) findViewById(R.id.txJsonArray);
verificaConexion(this);
}
This is my json Request method, works fine:
public void request() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(json_url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.e("jsonArray", "" + jsonArray);
if (jsonArray == null) {
Toast.makeText(MainActivity.this, "EL JSONArray esta VACIO !!! ", Toast.LENGTH_SHORT).show();
} else {
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
//con el php JsonArrayRequest2.php
// String contact = jsonObject.getString("delegacion");
//con el php JsonArrayVariosCampos.php
String contact = jsonObject.getString("Delegacion");
arrayList.add(contact);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "ERROR...", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(jsonArrayRequest);
}
my guardarDatos method to save the data:
public boolean guardarDatos(){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor mEdit1 = sp.edit();
/* sKey is an array */
mEdit1.putInt("Status_size", arrayList.size());
for(int i=0;i<arrayList.size();i++)
{
mEdit1.remove("Status_" + i);
mEdit1.putString("Status_" + i, arrayList.get(i));
}
Toast.makeText(MainActivity.this, " DATOS GUARDADOS ", Toast.LENGTH_SHORT).show();
return mEdit1.commit();
}
and my cargarDatos method to load the data:
public void cargarDatos(){
SharedPreferences mSharedPreference1 = PreferenceManager.getDefaultSharedPreferences(this);
arrayList.clear();
int size = mSharedPreference1.getInt("Status_size", 0);
for(int i=0;i<size;i++)
{
arrayList.add(mSharedPreference1.getString("Status_" + i, null));
}
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
spDelegaciones.setAdapter(adapter);
Toast.makeText(MainActivity.this, " DATOS CARGADOS ", Toast.LENGTH_SHORT).show();
}
and here is my class to check the internet connection:
public boolean verificaConexion(Context ctx){
boolean bConectado = false;
ConnectivityManager connec = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] redes = connec.getAllNetworkInfo();
for (int i = 0; i < 2; i++) {
if (redes[i].getState() == NetworkInfo.State.CONNECTED) {
bConectado = true;
if(bConectado) {
Toast.makeText(MainActivity.this, " con conexion ", Toast.LENGTH_LONG).show();
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
spDelegaciones.setAdapter(adapter);
request();
guardarDatos();
}else {
cargarDatos();
}
}else{
}
}
return bConectado;
}
Since you are using only one string in contact class. instead of arrayList<Contact> I will use ArrayList<String>
here I have removed singleTone class. and added jsonArrayRequest code inside in same class. and after adding item in arraylist I have called adapter.notifyDataSetChanged();
MainActivity.class
public class MainActivity extends AppCompatActivity {
TextView txdeleg_lista;
Button btnObtener;
ArrayList<String> arrayList = new ArrayList<String>();
ListView listView;
String json_url = "your url";
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnObtener = (Button) findViewById(R.id.btnObtener);
txdeleg_lista = (TextView) findViewById(R.id.txdeleg_lista);
listView = (ListView) findViewById(R.id.lvDelegacion);
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
btnObtener.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//startActivity(new Intent(MainActivity.this, DesplegarLista.class));
listView.setAdapter(adapter);
request();
}
});
}
public void request() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(json_url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.e("jsonArray",""+jsonArray);
if(jsonArray == null){
Toast.makeText(MainActivity.this,"EL JSONArray esta VACIO !!! ", Toast.LENGTH_SHORT).show();
}
else {
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String contact = jsonObject.getString("UFULLNAME");
arrayList.add(contact);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,"ERROR...", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(jsonArrayRequest);
}
}
check and if you have any query comment.

Recursive function using volley out of memory error

I am using Volley library to communicate with my database. I use recursive function to check continuously my database but after a period of time seems like the recursive function stop working and I get the following error:
FATAL EXCEPTION: main
Process: com.example.sakis.loginregister, PID: 22637
java.lang.OutOfMemoryError: pthread_create (stack size 131072 bytes) failed: Try again
at java.lang.VMThread.create(Native Method)
at java.lang.Thread.start(Thread.java:1029)
at com.android.volley.RequestQueue.start(RequestQueue.java:145)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:66)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:78)
at com.example.sakis.loginregister.MultiPlayerActivity.func(MultiPlayerActivity.java:342)
at com.example.sakis.loginregister.MultiPlayerActivity$2.onResponse(MultiPlayerActivity.java:160)
at com.example.sakis.loginregister.MultiPlayerActivity$2.onResponse(MultiPlayerActivity.java:133)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
I think it is a stackoverflow error when i dont get the proper response in time.Here is the recursive function code that i first call in onCreate method:
void func(){
reject=0;
Response.Listener<String> response1Listener = new Response.Listener<String>() {
#Override
public void onResponse(final String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
request = jsonResponse.getInt("request");
requestorigin = jsonResponse.getString("requestorigin");
category = jsonResponse.getInt("category");
dif_level = jsonResponse.getInt("dif_level");
number_of_questions = jsonResponse.getInt("number_of_questions");
time_of_answer = jsonResponse.getInt("time_of_answer");
if(request==0) {
func();
}
if (request == 1) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MultiPlayerActivity.this,R.style.myBackgroundStyle);
alertDialogBuilder.setMessage("Έχεις νέο αίτημα από τον χρήστη " + requestorigin + "\n" + "Κατηγορία Ερωτήσεων: " + array_category[category]
+ "\n" + "Επίπεδο Δυσκολίας: " + array_dif_level[dif_level] + "\n" + "Αριθμός Ερωτήσεων: " + number_of_questions + "\n "
+ "Χρόνος Απάντησης: " + time_of_answer);
alertDialogBuilder.setPositiveButton("Ναι", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Response.Listener<String> response1Listener = new Response.Listener<String>() {
#Override
public void onResponse(final String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
} catch (JSONException e)
{
e.printStackTrace();
}
}
};
SendResponseRequest sendResponseRequest = new SendResponseRequest(username, response1Listener);
RequestQueue queue1 = Volley.newRequestQueue(MultiPlayerActivity.this);
queue1.add(sendResponseRequest);
Response.Listener<String> responseListener=new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success1=jsonResponse.getBoolean("success1");
if(success1) {
Intent intent2 = new Intent(MultiPlayerActivity.this, MultiPlayerGame2Activity.class);
intent2.putExtra("username1",username);
intent2.putExtra("username2",requestorigin);
intent2.putExtra("category", category);
intent2.putExtra("dif_level", dif_level);
intent2.putExtra("number_of_questions", number_of_questions);
intent2.putExtra("time_of_answer", time_of_answer);
intent2.putExtra("level", level);
intent2.putExtra("score", score);
intent2.putExtra("music",music);
intent2.putExtra("sound",sound);
startActivity(intent2);
// android.os.Process.killProcess(android.os.Process.myPid());
finish();
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
};
Back0Request back0Request = new Back0Request(username,responseListener);
RequestQueue queue = Volley.newRequestQueue(MultiPlayerActivity.this);
queue.add(back0Request);
}
});
alertDialogBuilder.setNegativeButton("Όχι", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Response.Listener<String> response1Listener = new Response.Listener<String>() {
#Override
public void onResponse(final String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
reject = jsonResponse.getInt("reject");
if(reject==1) {
func();
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
};
RejectRequestRequest rejectRequestRequest = new RejectRequestRequest(username, response1Listener);
RequestQueue queue1 = Volley.newRequestQueue(MultiPlayerActivity.this);
queue1.add(rejectRequestRequest);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
};
//text2.setText("OK");
CheckRequest checkRequest = new CheckRequest(username, response1Listener);
/***
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
checkRequest.setRetryPolicy(policy);
******/
RequestQueue queue1 = Volley.newRequestQueue(MultiPlayerActivity.this);
queue1.add(checkRequest);
//text3.setText("After ");
}
When the variable requests that I take from the database has a zero value I want to check the database again until it will take a non-zero value. Is there any better way to achieve that so I can avoid recursion because it will cause some overflow errors.
Problem solved when i use Singleton Pattern and re-use the same instance of the queue so i prevent out of memory error:
public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private static Context mContext;
private MySingleton(Context context){
// Specify the application context
mContext = context;
// Get the request queue
mRequestQueue = getRequestQueue();
}
public static synchronized MySingleton getInstance(Context context){
// If Instance is null then initialize new Instance
if(mInstance == null){
mInstance = new MySingleton(context);
}
// Return MySingleton new Instance
return mInstance;
}
public RequestQueue getRequestQueue(){
// If RequestQueue is null the initialize new RequestQueue
if(mRequestQueue == null){
mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
}
// Return RequestQueue
return mRequestQueue;
}
public<T> void addToRequestQueue(Request<T> request){
// Add the specified request to the request queue
getRequestQueue().add(request);
}

public List<Model> loadInBackground() method in android does not get data from jSon Array

I am developing an application using android and i'm trying to get the jSon Array displayed in Listfragment using the loadInBackground() method below in my DataListLoader class:
class DataListLoader extends AsyncTaskLoader<List<Model>> {
List<Model> mModels;
String jsonString;
String name = "Daniel Nyerere", phone = "0652400670";
public DataListLoader(Context context) {
super(context);
loadInBackground();
}
public List<Model> loadInBackground() {
// You should perform the heavy task of getting data from
// Internet or database or other source
// Here, we are generating some Sample data
// Create corresponding array of entries and load with data.
final List<Model> entries = new ArrayList<Model>(50);
StringRequest stringRequest = new StringRequest(
Request.Method.GET, "http://10.0.2.2/webapp/json_get_data.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().contains("server_response")) {
jsonString = response.toString();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while (count < jsonArray.length()) {
JSONObject jo = jsonArray.getJSONObject(count);
name = jo.getString("name");
phone = jo.getString("user_phone");
entries.add(new Model(name, phone));
System.out.println("DATA FROM JSON ARRAY: " + name + " " + phone);
count++;
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue();
requestQueue.add(stringRequest);
entries.add(new Model(name, phone));
return entries;
}
But when i try to run it the data from System.out.println("DATA ENTRIES: "+entries); comes as null list ,so no data get displayed in the fragment activity . Anyone who can help me to fix it so that i get data from json because it consume me a lot of time
//You can call it in UI thread
final List<Model> entries = new ArrayList<Model>(5);
StringRequest stringRequest = new StringRequest(
Request.Method.GET, "http://10.0.2.2/webapp/json_get_data.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//you need to update the `ListView` content here
//If you need you can create new thread here too e.g. using AsyncTask
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue();
requestQueue.add(stringRequest);

Can't populate data from Asynctask?

In my App, I am parsing data from a Json file. It works Fine.Now I changed the code from my main thread to a Asynctask. I am new to Asynctask, so i can't find where i did the mistake. But in the logcat it show the Error is from the DoInBackground.
Thanks in Advance!
OLD CODE
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImageUrl(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
Asynctask Code
public class News extends AsyncTask<JSONObject, Void, FeedListAdapter> {
JSONObject response;
protected FeedListAdapter doInBackground(JSONObject... params) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImageUrl(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(FeedListAdapter result) {
super.onPostExecute(result);
listAdapter.notifyDataSetChanged();
}
}
MY Class
public class FeedListActivity extends BaseActivity {
private static final String TAG = "FeedListActivity";
private ListView NewsView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
News mynews;
private String URL_FEED = "http://www.amsonsindia.net/ins/news.json";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed_list);
setTitle(R.string.feed_list_demo);
mynews=new News();
mynews.execute();
NewsView = (ListView) findViewById(R.id.feed_list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
NewsView.setAdapter(listAdapter);
// making fresh volley request and getting json
GsonRequest<FeedResult> gsonRequest = new GsonRequest<FeedResult>(URL_FEED, FeedResult.class,
new Response.Listener<FeedResult>() {
#Override
public void onResponse(FeedResult response) {
feedItems = response.getFeedItems();
listAdapter.setData(feedItems);
listAdapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addRequest(gsonRequest, TAG);
getimg();
}
LOGCAT
Process: io.bxbxbai.feedlistviewdemo, PID: 2245
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at io.bxbxbai.androiddemos.activity.FeedListActivity$News.doInBackground(FeedListActivity.java:123)
at io.bxbxbai.androiddemos.activity.FeedListActivity$News.doInBackground(FeedListActivity.java:117)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
public class FeedListActivity extends BaseActivity {
private static final String TAG = "FeedListActivity";
private ListView NewsView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
News mynews;
private String URL_FEED = "http://www.amsonsindia.net/ins/news.json";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed_list);
setTitle(R.string.feed_list_demo);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
// i just change feeditem position here
mynews=new News();
mynews.execute();
NewsView = (ListView) findViewById(R.id.feed_list);
NewsView.setAdapter(listAdapter);
// making fresh volley request and getting json
GsonRequest<FeedResult> gsonRequest = new GsonRequest<FeedResult>(URL_FEED, FeedResult.class,
new Response.Listener<FeedResult>() {
#Override
public void onResponse(FeedResult response) {
feedItems = response.getFeedItems();
listAdapter.setData(feedItems);
listAdapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addRequest(gsonRequest, TAG);
getimg();
}
----------
Replace your my class with above and put debug in doinbackgroud
and postexecute
In doInBackground method you cant update UI
change doinbackground code like this--
for (int i = 0; i < feedArray.length(); i++)
{
JSONObject feedObj = (JSONObject) feedArray.get(i);
publishProgress(feedObj.getInt("id"), feedObj.getString("status");
//so on..
}
and within aynctask add
protected void onProgressUpdate(final String... message) {
try {
FeedItem item = new FeedItem();
item.setId(message[0]);
item.setName(message[1);
and so on
feedItems.add(item);
} catch (Exception e) {
if (pd != null) {
pd.dismiss();
}
}
}

Categories