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
Related
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));
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'm new at android programming, I want to fetch Parse in ListView arrangement and i found the perfect guide, but i cant really implement it on my code.
I have browse a lot for 2 days and i give up.
Here's the error
E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.osbert.buttons, PID: 2732
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:818)
Caused by: java.lang.RuntimeException: You must call Parse.initialize(context, oauthKey, oauthSecret) before using the Parse library.
at com.parse.ParseUser.checkApplicationContext(ParseUser.java:1426)
at com.parse.ParseUser.getCurrentUserAsync(ParseUser.java:1048)
at com.parse.ParseUser.access$900(ParseUser.java:27)
at com.parse.ParseUser$9.then(ParseUser.java:1041)
at com.parse.ParseUser$9.then(ParseUser.java:1038)
at com.parse.TaskQueue.enqueue(TaskQueue.java:61)
at com.parse.ParseUser.getCurrentUserAsync(ParseUser.java:1038)
at com.parse.ParseUser.getCurrentUserAsync(ParseUser.java:1001)
at com.parse.ParseQuery.getUserAsync(ParseQuery.java:352)
at com.parse.ParseQuery.access$1600(ParseQuery.java:78)
at com.parse.ParseQuery$15.call(ParseQuery.java:1000)
at com.parse.ParseQuery$15.call(ParseQuery.java:997)
at com.parse.ParseQuery.doWithRunningCheck(ParseQuery.java:936)
at com.parse.ParseQuery.findInBackground(ParseQuery.java:997)
at com.parse.ParseQuery.find(ParseQuery.java:588)
at com.example.osbert.buttons.RestaurantList$RemoteDataTask.doInBackground(RestaurantList.java:60)
at com.example.osbert.buttons.RestaurantList$RemoteDataTask.doInBackground(RestaurantList.java:34)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.osbert.buttons.RestaurantList has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{27bb5583 V.E..... R......D 0,0-729,322} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:298)
at com.example.osbert.buttons.RestaurantList$RemoteDataTask.onPreExecute(RestaurantList.java:46)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.osbert.buttons.RestaurantList.onCreate(RestaurantList.java:30)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
And here's my code
package com.example.osbert.buttons;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;
public class RestaurantList extends Activity {
// Declare Variables
ListView listview;
List<ParseObject> ob;
ProgressDialog mProgressDialog;
ListViewAdapter adapter;
private List<WorldPopulation> worldpopulationlist = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute RemoteDataTask AsyncTask
new RemoteDataTask().execute();
}
// RemoteDataTask AsyncTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(RestaurantList.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
worldpopulationlist = new ArrayList<WorldPopulation>();
try {
// Locate the class table named "Country" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"Country");
// Locate the column named "ranknum" in Parse.com and order list
// by ascending
query.orderByAscending("ranknum");
ob = query.find();
for (ParseObject country : ob) {
// Locate images in flag column
ParseFile image = (ParseFile) country.get("flag");
WorldPopulation map = new WorldPopulation();
map.setRank((String) country.get("rank"));
map.setCountry((String) country.get("country"));
map.setPopulation((String) country.get("population"));
map.setFlag(image.getUrl());
worldpopulationlist.add(map);
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(RestaurantList.this,
worldpopulationlist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
finish();
}
}
}
Pls help :((
Thanks in advance
Have you even tried resolving this?
Caused by: java.lang.RuntimeException: You must call Parse.initialize(context, oauthKey, oauthSecret) before using the Parse library?
Its the cause of the crash.
Also why are you calling finish() i onPostExecute?! It will close your activity...and i suppose you would like to see the results in your list view?
U error Logs says the solution.....
Caused by: java.lang.RuntimeException: You must call Parse.initialize(context, oauthKey, oauthSecret) before using the Parse library.
at com.parse.ParseUser.checkApplicationContext(ParseUser.java:1426)
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 ;)
I did the getting values from internet and putting data from the GRID_DATA array to a grid view both worked separately and both worked fine. I combined both together where the data from the JSONObject will add values to the JSON Array so from that the GRID_DATA will get the strings needed for the GRID View. But I get some errors in it.
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
public class QGFragment extends Fragment {
GridView grdView;
// This Data show in grid ( Used by adapter )
String strurl;
//URL to get JSON Array
private static String url = "http://localhost/app/data.php";
//JSON Node Names
private static final String TAG_QP = "qp";
private static final String TAG_NAME = "name";
//private static final String TAG_VAL = "val";
//private static final String TAG_NPICS = "nPics";
JSONArray qp = null;
static String[] GRID_DATA;
public QGFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_qg, container, false);
grdView = (GridView)rootView.findViewById(R.id.gridview);
new JSONParse().execute();
// Instance of ImageAdapter Class
grdView.setAdapter( new GridAdapter( getActivity(), GRID_DATA ) );
return rootView;
}
class GridAdapter extends BaseAdapter {
private Context context;
private final String[] gridValues;
//Constructor to initialise values
public GridAdapter(Context context, String[ ] gridValues) {
this.context = context;
this.gridValues = gridValues;
}
#Override
public int getCount() {
// Number of times getView method call depends upon gridValues.length
return gridValues.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
// Number of times getView method call depends upon gridValues.length
public View getView(int position, View convertView, ViewGroup parent) {
// LayoutInflator to call external grid_item.xml file
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
// get layout from grid_item.xml ( Defined Below )
gridView = inflater.inflate( R.layout.grid_list , null);
// set value into textview
TextView textView = (TextView) gridView
.findViewById(R.id.icon_text);
textView.setText(gridValues[position]);
// set image based on selected text
ImageView imageView = (ImageView) gridView
.findViewById(R.id.icon_image);
imageView.setImageResource(R.drawable.ic_launcher);
} else {
gridView = (View) convertView;
}
return gridView;
}
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
qp = json.getJSONArray(TAG_QP);
for(int i = 0 ; i < qp.length(); i++){
JSONObject c = qp.getJSONObject(i);
// Storing JSON item in a Variable
String name = c.getString(TAG_NAME);
//String val = c.getString(TAG_VAL);
//String npics = c.getString(TAG_NPICS);
GRID_DATA[i] = name;
//Set JSON Data in TextView
};
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
The Log Cat is:
12-24 20:53:06.702: W/dalvikvm(4304): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
12-24 20:53:06.743: E/AndroidRuntime(4304): FATAL EXCEPTION: main
12-24 20:53:06.743: E/AndroidRuntime(4304): java.lang.NullPointerException
12-24 20:53:06.743: E/AndroidRuntime(4304): at com.qrodsintegrated.QGFragment$GridAdapter.getCount(QGFragment.java:74)
12-24 20:53:06.743: E/AndroidRuntime(4304): at android.widget.GridView.setAdapter(GridView.java:180)
12-24 20:53:06.743: E/AndroidRuntime(4304): at com.qrodsintegrated.QGFragment.onCreateView(QGFragment.java:51)
12-24 20:53:06.743: E/AndroidRuntime(4304): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:795)
12-24 20:53:06.743: E/AndroidRuntime(4304): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:998)
12-24 20:53:06.743: E/AndroidRuntime(4304): at android.app.BackStackRecord.run(BackStackRecord.java:622)
12-24 20:53:06.743: E/AndroidRuntime(4304): at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1330)
12-24 20:53:06.743: E/AndroidRuntime(4304): at android.app.FragmentManagerImpl$1.run(FragmentManager.java:417)
12-24 20:53:06.743: E/AndroidRuntime(4304): at android.os.Handler.handleCallback(Handler.java:605)
12-24 20:53:06.743: E/AndroidRuntime(4304): at android.os.Handler.dispatchMessage(Handler.java:92)
12-24 20:53:06.743: E/AndroidRuntime(4304): at android.os.Looper.loop(Looper.java:137)
12-24 20:53:06.743: E/AndroidRuntime(4304): at android.app.ActivityThread.main(ActivityThread.java:4340)
12-24 20:53:06.743: E/AndroidRuntime(4304): at java.lang.reflect.Method.invokeNative(Native Method)
12-24 20:53:06.743: E/AndroidRuntime(4304): at java.lang.reflect.Method.invoke(Method.java:511)
12-24 20:53:06.743: E/AndroidRuntime(4304): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-24 20:53:06.743: E/AndroidRuntime(4304): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-24 20:53:06.743: E/AndroidRuntime(4304): at dalvik.system.NativeStart.main(Native Method)
12-24 20:53:08.722: I/Process(4304): Sending signal. PID: 4304 SIG: 9
It looks like GRID_DATA is never given a value, hence the NullPointerException when you try to access it's member (gridValues.length) at QGFragment.java:74.
You are setting an item in the array at GRID_DATA[i] = name; but never actually creating the array with something like GRID_DATA = new String[];
Array Initiliazation
An array is just a list of objects (in this case Strings). Each object has an address that can be accessed with [location] in that list. But if you never create that list in the first place then accessing [location] of that list that doesn't exist isn't going to work.