why my images not load with Picasso library in view pager? - java

Hi developers i'm trying to load images in view pager using Picasso library but everything it's return me empty view pager don't what happens to my code
This is my Fragment code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_details, container, false);
Bundle bundle = this.getArguments();
String id = bundle.getString("id");
dish_images_array = new ArrayList<>();
new get_dishes_details_data().execute(getString(R.string.dish_details)+id);
pager = (ViewPager)v.findViewById(R.id.img_slider);
pager.setAdapter(new slider_images(getActivity(), dish_images_array));
return v;
}
this is my slider_images.java adapter code
package com.example.yasee.bitescene.adapter;
import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.example.yasee.bitescene.R;
import com.squareup.picasso.Picasso;
import java.util.List;
public class slider_images extends PagerAdapter {
Context c;
private List<String> _imagePaths;
private LayoutInflater inflater;
ImageView imgDisplay;
public slider_images(Activity c, List<String> imagePaths) {
this._imagePaths = imagePaths;
this.c = c;
}
#Override
public int getCount() {
return this._imagePaths.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == (object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.slider, container, false);
imgDisplay = (ImageView) viewLayout.findViewById(R.id.slider_image);
Picasso.with(c).load(_imagePaths.get(position)).into(imgDisplay);
(container).addView(viewLayout);
return viewLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
(container).removeView((RelativeLayout) object);
}
}
this is my error
06-20 05:12:05.095 3280-3280/com.example.yasee.bitescene E/InputEventReceiver: Exception dispatching input event.
06-20 05:12:05.095 3280-3280/com.example.yasee.bitescene E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
06-20 05:12:05.115 3280-3280/com.example.yasee.bitescene E/MessageQueue-JNI: java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 0, found: 3 Pager id: com.example.yasee.bitescene:id/img_slider Pager class: class android.support.v4.view.ViewPager Problematic adapter: class com.example.yasee.bitescene.adapter.slider_images
at android.support.v4.view.ViewPager.populate(ViewPager.java:1071)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
at android.support.v4.view.ViewPager.onTouchEvent(ViewPager.java:2114)
at android.view.View.dispatchTouchEvent(View.java:7706)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2210)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1945)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2068)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1515)
at android.app.Activity.dispatchTouchEvent(Activity.java:2458)
at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:60)
at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:60)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2016)
at android.view.View.dispatchPointerEvent(View.java:7886)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:3954)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3833)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3399)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3449)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3418)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3525)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3426)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3582)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3399)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3449)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3418)
at android.view.ViewRootImpl$InputStage.apply(View
06-20 05:12:05.125 3280-3280/com.example.yasee.bitescene E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.yasee.bitescene, PID: 3280
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 0, found: 3 Pager id: com.example.yasee.bitescene:id/img_slider Pager class: class android.support.v4.view.ViewPager Problematic adapter: class com.example.yasee.bitescene.adapter.slider_images
The above error in android monitor when i try to slide images..
and this is my result.
this is my AsyncTask task code
private class get_dishes_details_data extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Loading... please wait");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("dish_details");
for (int i = 0; i < jarray.length(); i++) {
JSONObject jsonrealobject = jarray.getJSONObject(i);
dishname = jsonrealobject.getString("dish_name");
restaurantname = jsonrealobject.getString("name");
businesses_id = jsonrealobject.getString("businesses_id");
}
JSONArray imagesarry = jsono.getJSONArray("dish_images");
for (int i = 0; i < imagesarry.length(); i++){
JSONObject jobject = imagesarry.getJSONObject(i);
String image = jobject.getString("dish_image");
dish_images_array.add(image);
}
return true;
}
} catch (ParseException | IOException | JSONException e1) {
e1.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
textView_dish_name = (TextView)getActivity().findViewById(R.id.textView_dish_name);
textView_dish_name.setText(dishname);
textView_dish_name.setTypeface(custom_font);
restaurent_name = (TextView)getActivity().findViewById(R.id.restaurent_name);
restaurent_name.setText(restaurantname);
restaurent_name.setTypeface(custom_font);
yelp_id = (TextView)getActivity().findViewById(R.id.yelp_id);
yelp_id.setText("Link To The Restaurant: https://www.yelp.com/biz/"+businesses_id);
yelp_id.setTypeface(custom_font);
if(result == false){
Toast.makeText(getActivity(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}

Expected adapter item count: 0, found: 3 means you've set the adapter too earlier than the items of page and it's clearly saying that you didn't call pageAdapter.notifyDataSetChanged().
I suggest having a look at this format of PagerAdapter and make yours as similar. See where notifyDataSetChanged() has been called there.

The problem is nothing to do with Picasso. As per your logs I think you are updating the arryalist but not calling notifyDataSetChanged().
PagerAdapter#notifyDataSetChanged! Expected adapter item count: 0, found: 3
Now as per your code, my suggestion is to change few lines -
slider_images sliderImagesAdapter; // At class level
pager = (ViewPager)v.findViewById(R.id.img_slider);
sliderImagesAdapter = new slider_images(getActivity(), dish_images_array)
pager.setAdapter(sliderImagesAdapter);
Here make an class level variable for slider_images. and in onPostExecute,
do this,
if(result)
sliderImagesAdapter.notifyDataSetChanged();
Call notifyDataSetChanged() every-time you making any change(add/remove) in list provided to any adapter.
Hope it will help you :)

if your notifyDataSetChanged() is not working you can re-initialize the adapter
pager.setAdapter(new slider_images(getActivity(), dish_images_array));

Related

Android - How to pass another activity application context from java class extends fragments to asynctask?

Hi I am trying to make application that has view pager and tablayout. So when I choose 'friends' tab layout it will call java class named FragFriends.java,
In this class I want to inflate layout where recycler view adapter is filled with data from database that I retrieve using asynctask method in class PHPuserlist.java
However my application suddenly stopped
Here is the the FragFriends.java
public class FragmentFriends extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.activity_user_view,container,false);// The activity that contains recyclerview
View dview = inflater.inflate(R.layout.activity_profile,container,false); //This is the activity that contains tablayout
PHPUserList phpUserList = new PHPUserList(dview.getContext());
phpUserList.execute();
return rootview;
}
}
I have implement this recycler view with intent and it work just fine. But I need to use this with fragment
Pleas help me
This is the logcat
05-27 16:55:12.198 14031-14031/com.rumahdosen.www.rumahdosen E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.rumahdosen.www.rumahdosen, PID: 14031
java.lang.NullPointerException
at com.rumahdosen.www.rumahdosen.PHPUserList.onPreExecute(PHPUserList.java:82)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.rumahdosen.www.rumahdosen.FragmentFriends.onCreateView(FragmentFriends.java:20)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1545)
at android.view.View.measure(View.java:16834)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:824)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:500)
at android.view.View.measure(View.java:16834)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:16834)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:391)
at android.view.View.measure(View.java:16834)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
at android.view.View.measure(View.java:16834)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
at android.view.View.measure(View.java:16834)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2332)
at android.view.View.measure(View.java:16834)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2252)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1315)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1513)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1192)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6231)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
at android.view.Choreographer.doCallbacks(Choreographer.java:591)
at android.view.Choreographer.doFrame(Choreographer.java:560)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774)
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)
Below is the PHPUserList.java
public class PHPUserList extends AsyncTask<Void,UserList,Void> {
private Context context;
Activity activity;
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<UserList> arrayList = new ArrayList<>();
PHPUserList(Context ctx){
this.context = ctx;
activity = (Activity)ctx;
}
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("http://njtwicomp.pe.hu/listuser.php");
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine())!=null)
{
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
String json_string = stringBuilder.toString().trim();
JSONObject jsonObject = new JSONObject(json_string);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
count++;
UserList userList = new UserList(JO.getString("Name"),JO.getString("Username"));
publishProgress(userList);
}
Log.d("JSON STRING", json_string);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
recyclerView = (RecyclerView) activity.findViewById(R.id.RVUserList);
layoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
}
#Override
protected void onProgressUpdate(UserList... values) {
arrayList.add(values[0]);
adapter.notifyDataSetChanged();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
I try to find the recyclerview by id in another activity while I set the activity as the activity of the passed context. But I don't know how to fix that
So how do I get the activity which is not the context that I passed in asynctask?
Change this:
PHPUserList phpUserList = new PHPUserList(dview.getContext());
phpUserList.execute();
to :
new PHPUserList(getActivity()).execute();
In your fragment class just put getActivity(), where Context is needed it will do the job!
just use getContext();
This does the work.
In case you need to use the Activity Context then Have static context of ClassName.this

I keep getting a nullpointer exception with my JSON Object Calls

For some reason I keep getting a nullpointer exception with my double parsing. AFter further inquiry there seems to be some issue with my JSON Objects but I have no clue what the issue is.I am pulling JSON data form openweathermap api. I scuessfully pulled and printed the data into the log.i, however when I try to access with the JSONObject I am getting an error. Please help.
Code:
package com.anuraagy.myweather;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.content.*;
import android.os.Build;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
public class MyActivity extends Activity {
private String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
private JSONObject myObject,mainObject,nameObject;
private ImageView myImage;
private TextView titleText;
private String hello,weatherName,max_temp,min_temp;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
RequestTask task = new RequestTask();
task.execute(new String[]{"http://api.openweathermap.org/data/2.5/weather?q=Ashburn&APPID=970bf0e4978dae293b065f8f2830ba58"});
return rootView;
}
public class RequestTask extends AsyncTask<String, String, String> {
private TextView myView;
private String s;
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
Log.i("", responseString);
return responseString;
}
#Override
protected void onPostExecute(String result){
Log.i("","hello");
super.onPostExecute(result);
try {
myObject = new JSONObject(result);
nameObject = myObject.getJSONObject("weather");
weatherName = nameObject.getString("main");
mainObject = myObject.getJSONObject("main");
Log.i("Wather Name",weatherName);
Log.i("mainObject",mainObject.toString());
hello = mainObject.getString("temp");
max_temp = mainObject.getString("temp_max");
min_temp = mainObject.getString("temp_min");
} catch(JSONException jsonException){
}
double f = Double.parseDouble(hello);
double max = Double.parseDouble(max_temp);
double min = Double.parseDouble(min_temp);
double realMax = (max - 273)* 1.8 + 32;
double realMin = (min - 273)* 1.8 + 32;
double realTemp = (max - 273)* 1.8 + 32;
int myMax = (int)realMax;
int myMin = (int)realMin;
int myWeather = (int)realTemp;
titleText = (TextView)getActivity().findViewById(R.id.textView3);
String fe = titleText.getText().toString();
fe.replace("definetly",weatherName);
myView = (TextView)getActivity().findViewById(R.id.textView);
// if()
// {
//
// }
// else
// {
//
// }
myImage = (ImageView)getActivity().findViewById(R.id.imageView);
myImage.setImageResource(R.drawable.clearnight);
String weather = myWeather + "";
myView.setText(weather + (char) 0x00B0 +"F");
// //Do anything with response..
}
}
}
}
Error:
10-16 10:01:26.398 664-664/com.anuraagy.myweather E/Trace﹕ error opening trace file: No such file or directory (2)
10-16 10:01:35.058 664-668/com.anuraagy.myweather D/dalvikvm﹕ GC_CONCURRENT freed 75K, 2% free 11112K/11335K, paused 17ms+3ms, total 312ms
10-16 10:01:35.058 664-664/com.anuraagy.myweather D/dalvikvm﹕ WAIT_FOR_CONCURRENT_GC blocked 282ms
10-16 10:01:35.498 664-664/com.anuraagy.myweather D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
10-16 10:01:38.388 664-680/com.anuraagy.myweather I/﹕ {"coord":{"lon":-77.49,"lat":39.04},"sys":{"type":1,"id":2856,"message":0.0194,"country":"US","sunrise":1413458470,"sunset":1413498574},"weather":[{"id":701,"main":"Mist","description":"mist","icon":"50d"},{"id":721,"main":"Haze","description":"haze","icon":"50d"},{"id":741,"main":"Fog","description":"fog","icon":"50d"}],"base":"cmc stations","main":{"temp":288.03,"pressure":1008,"humidity":100,"temp_min":286.15,"temp_max":290.15},"wind":{"speed":2.86,"deg":261.502},"clouds":{"all":90},"dt":1413468071,"id":4744870,"name":"Ashburn","cod":200}
10-16 10:01:38.398 664-664/com.anuraagy.myweather I/﹕ hello
10-16 10:01:38.438 664-664/com.anuraagy.myweather D/AndroidRuntime﹕ Shutting down VM
10-16 10:01:38.438 664-664/com.anuraagy.myweather W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40a13300)
10-16 10:01:38.448 664-664/com.anuraagy.myweather E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at java.lang.StringToReal.parseDouble(StringToReal.java:244)
at java.lang.Double.parseDouble(Double.java:295)
at com.anuraagy.myweather.MyActivity$PlaceholderFragment$RequestTask.onPostExecute(MyActivity.java:141)
at com.anuraagy.myweather.MyActivity$PlaceholderFragment$RequestTask.onPostExecute(MyActivity.java:91)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Be careful - "weather" is a JSONArray, not a JSONObject. The NullPointerException is likely due to that.
Try instead using myObject.getJSONArray("weather"), and from there iterate through the JSONObjects inside.
See here for more information on that last part: Accessing members of items in a JSONArray with Java
It looks like myObject doesn't have item named "temp", so:
- on line 133 you set hello to null
- on line 141 you pass that null to Double.parseDouble()
- get your exception because class Double can't digest null
That's it!
Check it in the debugger, but I'm almost sure - according to your stack trace

NullPointerException on onPostExecute method

I’m having a navigation drawer for my app that contains a menu with which I can navigate between the fragments. The first fragment that i get after the app lunch is the Home which contains a listView and a footer attached in the bottom (is just for the test). The problem is when I lunch the Home fragment for the first time nothing happen and its work very well, but when I change the fragments from the navigation drawer and trying to get back the home fragment the app crash. The error log show me a null pointer Exception. Thes is my code detail
onCreateView method
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (v != null) {
ViewGroup parent = (ViewGroup) v.getParent();
if (parent != null)
parent.removeView(v);
}
try {
v = inflater.inflate(R.layout.fragment_homes, container, false);
listView = (ListView) v.findViewById(R.id.homeList);
l = new HomeListAdapter(this, homeList);
if(l == null)
Log.i("tag","null");
listView.setAdapter(l);
} catch (InflateException e) {
}
return v;
}
onPostExecute method
#Override
protected void onPostExecute(final String res) {
/*try {
jObj = new JSONArray(res);
} catch (JSONException e) {
e.printStackTrace();
}*/
/* JSONArray j = null;
try {
j = new JSONArray(res);
} catch (JSONException e) {
e.printStackTrace();
}*/
// Parsing json
for (int i = 0; i < 5; i++) {
//JSONObject obj = j.getJSONObject(i);
Home home = new Home();
//String photoNews = java.net.URLDecoder.decode(obj.getString("photonews"), "UTF-8");
home.setNomC("Karim Ennassiri");
home.setPhotoP("http://i1239.photobucket.com/albums/ff509/FestusMANAFEST/iker-casillas20Wallpaper__yvt2.jpg");
home.setPhotoAr("http://voyage-essaouira-maroc.com/upload/apostrophe_image_(13).jpg");
home.setText("Chlada V2.0 Edition");
home.setNbrSick("5");
home.setNbrComm("8");
home.setNbrShare("0");
homeList.add(home);
}
l.notifyDataSetChanged();
//pDialog.hide();
}
The error log
10-10 09:31:30.884 2447-2447/com.example.user.unchained E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.user.unchained, PID: 2447
java.lang.NullPointerException
at com.example.user.unchained.HomesActivity$PlaceholderFragment$FeedsTask.onPostExecute(HomesActivity.java:375)
at com.example.user.unchained.HomesActivity$PlaceholderFragment$FeedsTask.onPostExecute(HomesActivity.java:277)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
And this is exactly the line that cause the error : l.notifyDataSetChanged();. I notice that the error is just in the case when i'm trying to display the fragment for the secode time.
So any help please ? Thanks !
You need to use this in doInBackground.
#Override
protected Void doInBackground(void... ) {
try {
for (int i = 0; i < 5; i++) {
//JSONObject obj = j.getJSONObject(i);
Home home = new Home();
//String photoNews = java.net.URLDecoder.decode(obj.getString("photonews"), "UTF-8");
home.setNomC("Karim Ennassiri");
home.setPhotoP("http://i1239.photobucket.com/albums/ff509/FestusMANAFEST/iker-casillas20Wallpaper__yvt2.jpg");
home.setPhotoAr("http://voyage-essaouira-maroc.com/upload/apostrophe_image_(13).jpg");
home.setText("Chlada V2.0 Edition"); //give some other name in getter setter for setText in Home.java. It makes not to understand whether you are using setText for textview assigning.
home.setNbrSick("5");
home.setNbrComm("8");
home.setNbrShare("0");
homeList.add(home);
}
postExecute is used to display UI. don't perform heavy operation like parsing in PostExecute.

Updating Listview ( SharedPreferences -> ArrayList) from separate Class

I would like to update my Listview in a fragmen in a onPostExecute() separate class.
The first initialization of the the Listview doas work, but wehe I call createList() again, the App crashes (NullPointerException)
Any Idea?
Main_Fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View fragmentView = inflater.inflate(R.layout.main_fragment, container, false);
StartSocketService = (Button) fragmentView.findViewById(R.id.start_socketservice);
StartSocketService.setOnClickListener(this);
StopSocketService = (Button) fragmentView.findViewById(R.id.stop_socketservice);
StopSocketService.setOnClickListener(this);
listview = (ListView) fragmentView.findViewById(R.id.listView1);
createList();
return fragmentView;
}
public void createList(){
//Reading Server IPs from SharedPreferences and put them to ListView
SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
for (int i = 0; i < 255; i++) {
if ((settings.getString("Server"+i,null)) != null) {
serverList.add(settings.getString("Server"+i, null));
Log.v("Reading IP: " +settings.getString("Server"+i, null), " from SraredPreferrences at pos.: "+i );
}
}
//Initializing listView
final StableArrayAdapter adapter = new StableArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, serverList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
view.animate().setDuration(2000).alpha(0).withEndAction(new Runnable() {
#Override
public void run() {
serverList.remove(item);
adapter.notifyDataSetChanged();
view.setAlpha(1);
}
});
}
});
}
Some class:
async_cient = new AsyncTask<Void, Void, Void>() {
...
protected void onPostExecute(Void result) {
Toast.makeText(mContext, "Scan Finished", Toast.LENGTH_SHORT).show();
Main_Fragment cList = new Main_Fragment();
cList.createList();
super.onPostExecute(result);
}
};
Log:
07-29 14:42:46.428 3382-3382/de.liquidbeam.LED.control D/AndroidRuntime﹕ Shutting down VM
07-29 14:42:46.428 3382-3382/de.liquidbeam.LED.control W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41549ba8)
07-29 14:42:46.438 3382-3382/de.liquidbeam.LED.control E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.liquidbeam.LED.control, PID: 3382
java.lang.NullPointerException
at de.liquidbeam.LED.control.fragments.Main_Fragment.createList(Main_Fragment.java:56)
at de.liquidbeam.LED.control.background.UDP_Discover$1.onPostExecute(UDP_Discover.java:94)
at de.liquidbeam.LED.control.background.UDP_Discover$1.onPostExecute(UDP_Discover.java:57)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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)
07-29 14:47:46.591 3382-3382/de.liquidbeam.LED.control I/Process﹕ Sending signal. PID: 3382 SIG: 9
Lines:
56 : SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
94 : cList.createList();
57: async_cient = new AsyncTask<Void, Void, Void>() {
You creating a new instance of your fragment with no context (activity) to run in. So
the line
SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
Tries to get his activity but there is no activity where the fragment lives in ;)

How to avoid app crash when using Async-task in Fragments?

I am trying to show images in grid-view using tab-swipe. But when include async-task to fetch images from json URL the app does not even starting. It just crashes and closed. Here is my code.
import android.support.v4.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class GamesFragment extends Fragment {
public GamesFragment(){}
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
GridView gridview;
GridViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
ArrayList<HashMap<String, String>> items;
private Button button;
static String CATEGORY = "category";
int setlimit = 6;
int tolimit = 5;
static String IMAGE = "image";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.gridview_main, container, false);
new DownloadJSON().execute();
return rootView;
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle("Student Government App");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL
("http://jsonurl.com");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("wallpaper");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("category", jsonobject.getString("category"));
map.put("image", jsonobject.getString("image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
gridview = (GridView) getView().findViewById(R.id.gridViewCustom);
// Pass the results into ListViewAdapter.java
adapter = new GridViewAdapter(getActivity(), arraylist);
gridview.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
}
How can i prevent it from app crash? Any help would be be great.
Logcat:
07-03 15:22:36.692 838-838/info.androidhive.tabsswipe D/ActivityThread﹕ ACT- AM_ON_PAUSE_CALLED ActivityRecord{41353570 token=android.os.BinderProxy#41352cb0 {info.androidhive.tabsswipe/info.androidhive.tabsswipe.MainActivity}}
07-03 15:22:36.707 838-838/info.androidhive.tabsswipe D/ActivityThread﹕ ACT-PAUSE_ACTIVITY_FINISHING handled : 0 / android.os.BinderProxy#41352cb0
07-03 15:22:36.904 838-838/info.androidhive.tabsswipe D/OpenGLRenderer﹕ Flushing caches (mode 0)
07-03 15:22:36.944 838-838/info.androidhive.tabsswipe D/OpenGLRenderer﹕ Flushing caches (mode 0)
07-03 15:22:36.989 838-838/info.androidhive.tabsswipe D/OpenGLRenderer﹕ Flushing caches (mode 0)
07-03 15:22:37.003 838-838/info.androidhive.tabsswipe E/WindowManager﹕ Activity info.androidhive.tabsswipe.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4136f300 that was originally added here
android.view.WindowLeaked: Activity info.androidhive.tabsswipe.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4136f300 that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:418)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:294)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:226)
at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:151)
at android.view.Window$LocalWindowManager.addView(Window.java:547)
at android.app.Dialog.show(Dialog.java:277)
at info.androidhive.tabsswipe.GamesFragment$DownloadJSON.onPreExecute(GamesFragment.java:65)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at info.androidhive.tabsswipe.GamesFragment.onCreateView(GamesFragment.java:48)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:938)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:478)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
at android.view.View.measure(View.java:15264)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4918)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15264)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:833)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
at android.view.View.measure(View.java:15264)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4918)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2161)
at android.view.View.measure(View.java:15264)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2131)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1242)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1435)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1127)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4609)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:747)
at android.view.Choreographer.doCallbacks(Choreographer.java:567)
at android.view.Choreographer.doFrame(Choreographer.java:536)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:733)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:4987)
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:821)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
at dalvik.system.NativeStart.main(Native Method)
07-03 15:22:37.004 838-838/info.androidhive.tabsswipe D/OpenGLRenderer﹕ Flushing caches (mode 0)
07-03 15:22:37.004 838-838/info.androidhive.tabsswipe D/ActivityThread﹕ ACT-DESTROY_ACTIVITY handled : 1 / android.os.BinderProxy#41352cb0
07-03 15:22:37.004 838-838/info.androidhive.tabsswipe D/OpenGLRenderer﹕ Flushing caches (mode 1)
You should move gridview initialized in your onCreateView(...) before new DownloadJSON().execute();
gridview = (GridView) rootview.findViewById(R.id.gridViewCustom);
Change you oncreateview like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.gridview_main, container, false);
gridview = (GridView) rootView.findViewById(R.id.gridViewCustom);
new DownloadJSON().execute();
return rootView;
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog = null;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading , Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
super.onPreExecute();
}
change your onPostExecute this way
#Override
protected void onPostExecute(Void args) {
mProgressDialog.dismiss();
gridview = (GridView) getView().findViewById(R.id.gridViewCustom);
// Pass the results into ListViewAdapter.java
adapter = new GridViewAdapter(getActivity(), arraylist);
gridview.setAdapter(adapter);
super.onPostExecute(arg);
}
}
You open That app in Debugging mode
and see the error in console (choose warning) and find the error and clear it

Categories