I have 3 fragment in viewpager (LeftFragment, MidFragment and Right Fragment)
LeftFragment contain a listview, when clicking on listview item, an image will be loaded on MidFragment. I've encountered a bug and spent a lot of time but still unresolved. Here is my code:
LeftFragmnet
public class LeftFragment extends Fragment{
private ListView listView;
private List<ParseObject> ob;
private ProgressDialog mProgressDialog;
private ListViewAdapter adapter;
private List<School> schoollist = null;
private View v;
MainActivity mainActivity = new MainActivity();
MidFragment midFragment = new MidFragment();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.left_fragment, container, false);
initComponent();
new RemoteDataTask().execute();
return v;
}
private void initComponent() {
listView = (ListView)v.findViewById(R.id.lv_left);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mainActivity.viewPager.setCurrentItem(1);
School school = schoollist.get(position);
// midFragment.index = Integer.parseInt(school.getIndex());
midFragment.reloadData(Integer.parseInt(school.getIndex()));
}
});
}
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(getActivity());
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle("Please wait a moment...");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
schoollist = new ArrayList<School>();
try{
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("School");
query.orderByAscending("index");
ob = query.find();
for (ParseObject name : ob){
School map = new School();
map.setIndex(String.valueOf(name.get("index")));
map.setCount(String.valueOf(name.get("count")));
map.setName(String.valueOf(name.get("name")));
schoollist.add(map);
}
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
adapter = new ListViewAdapter(getActivity(), schoollist);
listView.setAdapter(adapter);
mProgressDialog.dismiss();
super.onPreExecute();
}
}
}
MidFragment
public class MidFragment extends Fragment {
// private ProgressDialog mProgressDialog;
private ImageView mImageView;
private VideoView mVideoView;
private DisplayImageOptions options;
private ImageLoader imageLoader = ImageLoader.getInstance();
private Context mContext;
private ImageLoadingListener animateFirstListener;
private ArrayList<ParseObject> objectList = new ArrayList<>();
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// imageLoader.init(ImageLoaderConfiguration.createDefault(mContext));
// mImageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.build();
animateFirstListener = new AnimateFirstDisplayListener();
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.mid_fragment, container, false);
initComponent(view);
mContext = container.getContext();
return view;
}
private void initComponent(View view) {
mImageView = (ImageView) view.findViewById(R.id.image);
mVideoView = (VideoView) view.findViewById(R.id.video);
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mVideoView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// mProgressDialog = new ProgressDialog(getActivity());
// mProgressDialog.setTitle("Please wait a moment...");
// mProgressDialog.setMessage("Loading...");
// mProgressDialog.setIndeterminate(false);
}
public void reloadData(int index){
// mProgressDialog.show();
objectList.clear();
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Data");
query.whereEqualTo("school",(Number)index);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
objectList = (ArrayList<ParseObject>) list;
// mProgressDialog.dismiss();
if (!list.isEmpty())
openFirst();
}
});
}
private void openFirst(){
ParseObject parseObject = objectList.get(0);
ParseFile parseFile = parseObject.getParseFile("file");
if (parseObject.getNumber("type") == (Number)1){
}else{
// mVideoView.setVisibility(View.GONE);
// mImageView.setVisibility(View.VISIBLE);
imageLoader.displayImage(parseFile.getUrl(), mImageView, options, animateFirstListener);
}
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
layout MidFragment
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<VideoView
android:id="#+id/video"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="gone" />
<ImageView
android:id="#+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:contentDescription="#string/app_name" />
</RelativeLayout>
Logcat
05-28 15:41:56.116 19297-19297/animuco.com.ckemi E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: animuco.com.ckemi, PID: 19297
java.lang.IllegalArgumentException: view must not be null
at com.nostra13.universalimageloader.core.imageaware.ViewAware.<init>(ViewAware.java:70)
at com.nostra13.universalimageloader.core.imageaware.ViewAware.<init>(ViewAware.java:50)
at com.nostra13.universalimageloader.core.imageaware.ImageViewAware.<init>(ImageViewAware.java:44)
at com.nostra13.universalimageloader.core.ImageLoader.displayImage(ImageLoader.java:365)
at com.nostra13.universalimageloader.core.ImageLoader.displayImage(ImageLoader.java:340)
at animuco.com.ckemi.Fragment.MidFragment.openFirst(MidFragment.java:119)
at animuco.com.ckemi.Fragment.MidFragment.access$200(MidFragment.java:36)
at animuco.com.ckemi.Fragment.MidFragment$3.done(MidFragment.java:101)
at animuco.com.ckemi.Fragment.MidFragment$3.done(MidFragment.java:95)
at com.parse.Parse$6$1.run(Parse.java:944)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5333)
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:1016)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
I'm not sure but I think the error is due to update the view of viewpager
sorry for my weak english
Thanks for the interest of the people
There are a few issues with the code. IMO.
Your fragment holds a reference to its activity, you already have one call getActivity().
Left fragment holds a reference to Mid fragment - bad practice.
On your RemoteDataTask you call super.onPreExecute() at your
onPostExecute() method, its usually unimplemented but it may cause
you errors in the future.
And to answer your question. You are initilyzing a new instance of MidFragment at your left fragment which isnt attached anywhere therfore MidFragment doesnt start his lifecycle and doesnt call onCreateView(). The Midfragment that LeftFragment is using isnt the same as the one that the ViewPager is using.
Related
In parse i have a class A which has a column (relation) named - view, which relates to class B( contains different images with different object id's).Now what i want to achieve is that : in android i have a activity(A) which has a recycle view which shows all the items of class A. The items are clickable which when clicked brings up the items from class B in parse to activity(B) . Now the issue is we are unable to intent a parse query from activity (A) to activity(B), so that we can display the items of class B in Activity(B).
Is there any different method for this? Any example for this would be of additional help.
EDIT
MainActivity
public class MainActivity extends AppCompatActivity {
ProgressDialog mProgressDialog;
GridAdapter gridAdapter;
RecyclerView recyclerView;
private List<Grid_G_S> grid_list = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from gridview_main.xml
setContentView(R.layout.activity_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(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Parse.com GridView Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
grid_list = new ArrayList<>();
try {
ParseQuery<ParseObject> query = new ParseQuery<>("CardViewClass");
List<ParseObject> object1 = query.find();
for (final ParseObject country : object1) {
// Locate images in flag column
ParseFile image = (ParseFile) country.get("images");
ParseRelation<ParseObject> p = country.getRelation("view");
ParseQuery p2 = p.getQuery();
String f = image.getUrl();
Log.i("yji"," "+p2);
List<ParseObject> oc = p2.find();
for (ParseObject country2:oc){
ParseFile imgs = (ParseFile) country2.get("autoImage");
String fr = imgs.getUrl();
}
Grid_G_S setter = new Grid_G_S();
setter.setX(p2);
setter.setTitles((String) country.get("scrollText1"));
setter.setImages(f);
grid_list.add(setter);
}
}catch (ParseException e){
Log.e("err", e.getMessage());
} catch (com.parse.ParseException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
recyclerView = (RecyclerView) findViewById(R.id.recycler);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getApplicationContext(),3);
gridAdapter = new GridAdapter(MainActivity.this, grid_list);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(gridAdapter);
mProgressDialog.dismiss();
}
GridAdapter
public class GridAdapter extends RecyclerView.Adapter {
Context context;
LayoutInflater inflater;
private List<Grid_G_S> grid_g_sList = null;
private ArrayList<Grid_G_S> arraylist;
public GridAdapter(Context context, List<Grid_G_S> grid_list) {
this.context = context;
this.grid_g_sList = grid_list;
inflater = LayoutInflater.from(context);
this.arraylist = new ArrayList<>();
this.arraylist.addAll(grid_list);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView titles;
ImageView gridImages;
View mview;
MyViewHolder(View v) {
super(v);
mview = v;
titles = (TextView) v.findViewById(R.id.grid_single_text);
gridImages = (ImageView) v.findViewById(R.id.grid_single_image);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.grid_single_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
Grid_G_S item = grid_g_sList.get(position);
holder.titles.setText(item.getTitles());
Picasso.with(context)
.load(grid_g_sList.get(position).getImages())
.into(holder.gridImages);
holder.mview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, Secondactivity.class);
intent.putExtra("image", grid_g_sList.get(position).getImages());
intent.putExtra("query", String.valueOf(grid_g_sList.get(position).getX()));
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return grid_g_sList.size();
}
GridGetterSetter
public class Grid_G_S {
String Images;
String Titles;
ParseQuery x;
public String getImages() {
return Images;
}
public void setImages(String images) {this.Images = images;}
public String getTitles() {
return Titles;
}
public void setTitles(String titles) {this.Titles = titles;}
public ParseQuery getX() {
return x;
}
public void setX(ParseQuery x) {this.x = x;}
SecondActivity
public class Secondactivity extends AppCompatActivity {
String q1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_secondactivity);
new DownloadingTask().execute();
Intent i = getIntent();
String images = i.getStringExtra("image");
q1 = i.getStringExtra("query");
Log.i("this is ", " " + q1);
}
private class DownloadingTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
ParseQuery<ParseObject> query = new ParseQuery<>("CardViewClass");
try {
List<ParseObject> object1 = query.find();
for (final ParseObject country : object1) {
// Locate images in flag column
}
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
I want to send a list of bitmap i retreived from mysql database using asyncTask to the fragment Fragment_ListView.class, in this fragment class i want to set the adapter of the listView with the bitmap token from asyncTask but i don't know how to do that.
Async Task
#Override
protected void onPostExecute(ArrayList<Bitmap> bitmapArrayList) {
super.onPostExecute(bitmapArrayList);
loading.dismiss();
// now after getting images from server , i want to send this bitmapArrayList
// to Fragment_ListView where i set the adapter of the
}
#Override
protected ArrayList<Bitmap> doInBackground(String... params) {
imageList = new ArrayList();
String add1 = "http://192.168.1.11/save/load_image_from_db.php?id=1";
String add2 = "http://192.168.1.11/save/load_image_from_db.php?id=2";
String add3 = "http://192.168.1.11/save/load_image_from_db.php?id=3";
URL url;
Bitmap image = null;
String[] adds = {add1, add2, add3};
for (int i = 0; i < adds.length; i++) {
try {
url = new URL(adds[i]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
image = BitmapFactory.decodeStream(connection.getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imageList.add(image);
image = null;
}
return imageList;
OnCreate of MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listfrg = new Fragment_ListView();
getFragmentManager().beginTransaction().add(R.id.frml, listfrg).commit();
}
Fragment_ListView :
public class Fragment_ListView extends Fragment {
ListView mListView;
static ArrayList<Bitmap> bitmaps;
static MySimpleArrayAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frglist, container, false);
mListView = (ListView) view.findViewById(R.id.listView);
bitmaps = new ArrayList<>();
adapter = new MySimpleArrayAdapter(getActivity(), bitmaps);
mListView.setAdapter(adapter);
return view;
}
Something like this,
Create a new interface file
public interface BitMapArrayCallBack {
abstract void bitmapArray(ArrayList<Bitmap> bitmaps);
}
Then in AsyncTask ... i don't know your class name so i will assume the class ServerRequest
public class ServerRequest {
Context context;
public ServerRequest(Context context) {
this.context = context;
}
public void doAsyncTask(BitMapArrayCallBack bitmapCallback) {
new MyAsyncTask(bitmapCallback).execute();
}
public class MyAsyncTask extends AsyncTask<Void, Void, Void> {
private BitMapArrayCallBack bitmapCallback;
public MyAsyncTask(BitMapArrayCallBack bitmapCallback) {
this.bitmapCallback = bitmapCallback;
}
//call do in background etc..
#Override
protected void onPostExecute(ArrayList<Bitmap> bitmapArrayList) {
super.onPostExecute(bitmapArrayList);
loading.dismiss();
bitmapCallback.bitmapArray(bitmapArrayList);
// This will hold and return your arraylist
}
}
}
Now you must call your asynctask in fragment listview
public class Fragment_ListView extends Fragment {
ListView mListView;
static MySimpleArrayAdapter adapter;
private ServerRequest serverRequest;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frglist, container, false);
mListView = (ListView) view.findViewById(R.id.listView);
serverRequest = new ServerRequest(getActivity);
serverRequest.doAsyncTask(new BitMapArrayCallBack {
#Override
void bitMapArray(ArrayList<Bitmap> bitmaps) {
// in here you have access to the bitmaps array
adapter = new MySimpleArrayAdapter(getActivity(), bitmaps);
mListView.setAdapter(adapter);
}
})
return view;
}
I tried to run it on eclip and it works but on android studio, it fails. I can not find a solution to this problem. I want to load a photo from openFirst(), Error openFirst()
public class MidFragment extends Fragment {
// private ProgressDialog mProgressDialog;
private ImageView mImageView;
private VideoView mVideoView;
private View mView;
private DisplayImageOptions mOptions;
private ImageLoader mImageLoader;
private Context mContext;
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
private ArrayList<ParseObject> objectList = new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.mid_fragment, container, false);
initComponent();
mContext = container.getContext();
return mView;
}
private void initComponent() {
mImageView = (ImageView)mView.findViewById(R.id.image);
mVideoView = (VideoView)mView.findViewById(R.id.video);
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mVideoView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// mProgressDialog = new ProgressDialog(getActivity());
// mProgressDialog.setTitle("Please wait a moment...");
// mProgressDialog.setMessage("Loading...");
// mProgressDialog.setIndeterminate(false);
}
public void reloadData(int index){
// mProgressDialog.show();
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Data");
query.whereEqualTo("school",(Number)index);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
objectList = (ArrayList<ParseObject>) list;
// mProgressDialog.dismiss();
if (!list.isEmpty())
openFirst();
}
});
}
private void openFirst(){
mImageLoader = ImageLoader.getInstance();
mImageLoader.init(ImageLoaderConfiguration.createDefault(mContext));
mOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.build();
ParseObject parseObject = objectList.get(0);
ParseFile parseFile = parseObject.getParseFile("file");
Log.e("****************************",""+parseFile.getUrl());
if (parseObject.getNumber("type") == (Number)1){
// mVideoView.setVisibility(View.VISIBLE);
// mImageView.setVisibility(View.GONE);
// mVideoView.setVideoURI();
}else{
mVideoView.setVisibility(View.GONE);
mImageView.setVisibility(View.VISIBLE);
ImageLoader.getInstance().displayImage(parseFile.getUrl(), mImageView, mOptions, animateFirstListener);
}
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
Logcat
05-18 23:23:02.258 10496-10496/animuco.com.ckemi E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: animuco.com.ckemi, PID: 10496
java.lang.NullPointerException
at com.nostra13.universalimageloader.core.ImageLoaderConfiguration$Builder.<init>(ImageLoaderConfiguration.java:196)
at com.nostra13.universalimageloader.core.ImageLoaderConfiguration.createDefault(ImageLoaderConfiguration.java:127)
at animuco.com.ckemi.Fragment.MidFragment.openFirst(MidFragment.java:99)
at animuco.com.ckemi.Fragment.MidFragment.access$200(MidFragment.java:42)
at animuco.com.ckemi.Fragment.MidFragment$3.done(MidFragment.java:92)
at animuco.com.ckemi.Fragment.MidFragment$3.done(MidFragment.java:86)
at com.parse.Parse$6$1.run(Parse.java:944)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5135)
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:878)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
at dalvik.system.NativeStart.main(Native Method)
thanks for your help
Quite possibly mContext is null. Since this is fragment just remove mContext and use getActivity() instead.
AsyncTask updates the adapter content but does not update the listview. All the code is working fine but when i am updating my adapter, my listview does not reflect any update from adapter. I have also searched over google for this problem but not find any proper solution. it show the exception as below :-
java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification.
Here is my code, please have a look what should i change :-
public class SearchResultScreen extends Fragment {
ListView searchResult;
SearchResultAdapter adapter;
TextView total_jobs,displaying_jobs;
int currentPage=0,threshold=10;
ProgressDialog progress;
JobService jobService;
TextView load_more_jobs;
int flag = 0;
public SearchResultScreen(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.search_result_screen, container, false);
searchResult = (ListView) rootView.findViewById(R.id.search_result);
jobService = new JobService();
jobService.setCurrent_page(currentPage);
load_more_jobs = new TextView(getActivity());
load_more_jobs.setText("Load More Jobs");
load_more_jobs.setGravity(Gravity.CENTER_HORIZONTAL);
load_more_jobs.setPadding(5,5,5,5);
load_more_jobs.setBackgroundColor(Color.GRAY);
Map params = new HashMap();
params.put("skills", getArguments().getString("skills"));
params.put("exp_from", getArguments().getString("exp_from"));
params.put("exp_to", getArguments().getString("exp_to"));
params.put("location", getArguments().getString("location"));
params.put("func_area", getArguments().getString("functional_area"));
params.put("start", jobService.getCurrent_page());
total_jobs = (TextView) rootView.findViewById(R.id.total_jobs_label);
displaying_jobs = (TextView) rootView.findViewById(R.id.displaying_jobs);
progress = new ProgressDialog(getActivity());
progress.setTitle("Please Wait!!");
progress.setMessage("Wait!!");
progress.setCancelable(false);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
new MyAsyncTask(params, progress, searchResult, getActivity(), jobService, total_jobs, displaying_jobs, load_more_jobs, flag, adapter).execute("rest/search_jobs.rest");
currentPage++;
load_more_jobs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(currentPage < jobService.getTotal_page()) {
jobService.setCurrent_page(currentPage);
Map params = new HashMap();
params.put("skills", getArguments().getString("skills"));
params.put("exp_from", getArguments().getString("exp_from"));
params.put("exp_to", getArguments().getString("exp_to"));
params.put("location", getArguments().getString("location"));
params.put("func_area", getArguments().getString("functional_area"));
params.put("start", jobService.getCurrent_page());
flag = 1;
new MyAsyncTask(params, progress, searchResult, getActivity(), jobService, total_jobs, displaying_jobs, load_more_jobs, flag, adapter).execute("rest/search_jobs.rest");
currentPage++;
}
}
});
searchResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
JobSearchModel jobs = (JobSearchModel) adapterView.getItemAtPosition(i);
FragmentManager fragmentManager = getFragmentManager();
Fragment search_result_screen = new SearchResultScreen();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
JobDescription jobDescription = new JobDescription();
Bundle args = new Bundle();
args.putSerializable("jobs", jobs);
jobDescription.setArguments(args);
fragmentTransaction.replace(R.id.content_frame, jobDescription);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
//Toast.makeText(getActivity(), "Id is : " + jobs.getJob_id(), Toast.LENGTH_LONG).show();
}
});
return rootView;
}
static class MyAsyncTask extends AsyncTask<String, Integer, String> {
private Map params;
private ProgressDialog progress;
private ListView list;
private Activity context;
private JobService jobService;
private TextView total_jobs;
private TextView displaying_jobs;
private TextView load_more_jobs;
private int flag;
private SearchResultAdapter adapter;
Object[] object_response;
public MyAsyncTask(Map params, ProgressDialog progress, ListView searchResult, Activity context, JobService jobService, TextView total_jobs, TextView displaying_jobs, TextView load_more_jobs, int flag, SearchResultAdapter adapter) {
this.params = params;
this.progress = progress;
this.list = searchResult;
this.context = context;
this.jobService = jobService;
this.total_jobs = total_jobs;
this.displaying_jobs = displaying_jobs;
this.load_more_jobs = load_more_jobs;
this.flag = flag;
this.adapter = adapter;
}
#Override
public void onPreExecute() {
this.progress.show();
}
public void onProgressUpdate(Integer filesDownloaded) {
}
protected String doInBackground(String... parameters) {
postData(parameters[0]);
return "done";
}
protected void onPostExecute(String result){
context.runOnUiThread(new Runnable() {
#Override
public void run() {
if(flag == 0) {
adapter = new SearchResultAdapter(context, jobService.getModel(object_response));
list.addFooterView(load_more_jobs, null, false);
list.setAdapter(adapter);
} else {
adapter = new SearchResultAdapter(context, jobService.getModel(object_response));
}
total_jobs.setText(""+jobService.getTotal_jobs());
displaying_jobs.setText(""+jobService.displayingJobs());
}
});
adapter.notifyDataSetChanged();
this.progress.dismiss();
}
protected void onProgressUpdate(String progress){
}
public void postData(final String request) {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
object_response = restTemplate.postForObject(UtilClass.baseURL+request, params, JobSearchModel[].class);
}
}
}
You can fixed your error while adding below line
adpater.notifyDataSetChanged();
on whenever the list is changed you must call the above function.
Note: make sure call notifyDataSetChanged() in the UI thread.
Exception is:
java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification.
So you need to notify listview, that adapter data is changed.
Call
listView.invalidateViews();
just after you call
adapter.notifyDataSetChanged();
Hope it helps.
I am using a gridview in fragment. I am loading the gridview in doInBackground.However, I get AsyncTask#1 Fatal Exception. Below is the code that i have tried:
public class Home extends Fragment implements TabHost.OnTabChangeListener,
OnClickListener {
TabHost tabHost;
View vi;
StaggeredAdapter adapter;
TextView tv;
public String urls[] = {
"http://farm9.staticflickr.com/8462/8005636463_0cb4ea6be2.jpg",
"http://farm8.staticflickr.com/7232/6913504132_a0fce67a0e_c.jpg",
"http://farm5.staticflickr.com/4133/5096108108_df62764fcc_b.jpg",
"http://farm5.staticflickr.com/4074/4789681330_2e30dfcacb_b.jpg",
"http://farm9.staticflickr.com/8208/8219397252_a04e2184b2.jpg",
"http://farm9.staticflickr.com/8483/8218023445_02037c8fda.jpg",
"http://farm9.staticflickr.com/8335/8144074340_38a4c622ab.jpg",
"http://farm9.staticflickr.com/8060/8173387478_a117990661.jpg",
"http://farm9.staticflickr.com/8056/8144042175_28c3564cd3.jpg",
"http://farm9.staticflickr.com/8183/8088373701_c9281fc202.jpg",
"http://farm9.staticflickr.com/8185/8081514424_270630b7a5.jpg",
"http://farm9.staticflickr.com/8462/8005636463_0cb4ea6be2.jpg",
"http://farm9.staticflickr.com/8306/7987149886_6535bf7055.jpg",
"http://farm9.staticflickr.com/8444/7947923460_18ffdce3a5.jpg",
"http://farm9.staticflickr.com/8182/7941954368_3c88ba4a28.jpg",
"http://farm9.staticflickr.com/8304/7832284992_244762c43d.jpg",
"http://farm9.staticflickr.com/8163/7709112696_3c7149a90a.jpg",
"http://farm8.staticflickr.com/7127/7675112872_e92b1dbe35.jpg",
"http://farm8.staticflickr.com/7111/7429651528_a23ebb0b8c.jpg",
"http://farm9.staticflickr.com/8288/7525381378_aa2917fa0e.jpg",
"http://farm6.staticflickr.com/5336/7384863678_5ef87814fe.jpg",
"http://farm8.staticflickr.com/7102/7179457127_36e1cbaab7.jpg",
"http://farm8.staticflickr.com/7086/7238812536_1334d78c05.jpg",
"http://farm8.staticflickr.com/7243/7193236466_33a37765a4.jpg",
"http://farm8.staticflickr.com/7251/7059629417_e0e96a4c46.jpg",
"http://farm8.staticflickr.com/7084/6885444694_6272874cfc.jpg" };
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
vi = inflater.inflate(R.layout.home, container, false);
Button iv = (Button) vi.findViewById(R.id.btnMoreDialog);
iv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu homepopup = new PopupMenu(getActivity(), v);
MenuInflater inflater = homepopup.getMenuInflater();
inflater.inflate(R.menu.moredialog, homepopup.getMenu());
homepopup.show();
}
});
new Dialogs().execute(urls);
return vi;
}
private class Dialogs extends AsyncTask<String[] , Void, Void>
{
#Override
protected Void doInBackground(String[]... params) {
StaggeredGridView gridView = (StaggeredGridView) vi
.findViewById(R.id.staggeredGridView1);
int margin = getResources().getDimensionPixelSize(R.dimen.margin);
gridView.setItemMargin(margin);
gridView.setPadding(margin, 0, margin, 0);
// StaggeredAdapter adapter = new StaggeredAdapter(MainActivity.this,
// R.id.photoimageview, urls, R.layout.row_staggered_demo);
StaggeredAdapter adapter = new StaggeredAdapter(vi.getContext(),
R.id.photoimageview, params[0], R.layout.row_staggered_demo);
gridView.setAdapter(adapter);
return null;
}
#Override
protected void onPostExecute(Void result) {
}
#Override
protected void onPreExecute() {
}
}
}
Any ideas pls?
Thanks,
You are attempting to update ui in doInbackground which is not possible.
gridView.setAdapter(adapter);
You need to update ui on the ui thread.
Use runOnUiThread or update ui in onPostExecute
getActivity().runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
}
});