adapter does not update listview after update - android

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.

Related

How do i populate a listview with json inside a fragment with tablayout and viewpager

how do i populate my listview with JSON inside a fragment. The app runs with no error, but the listview is empty. I am not getting any data inside my fragment. But when i make it as an activity and not as a fragment the listview is populated with JSON data.
Here is my fragment code with listview and json parsing
public class News extends Fragment {
private ListView lv;
private String JSON_STRING;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(news, container, false);
lv = (ListView) rootView.findViewById(R.id.listView3);
getJSON();
return rootView;
}
private void showResult(){
JSONObject jsonObject;
ArrayList<HashMap<String,String>> list = new ArrayList<>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY1);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String title = jo.getString(Config.TAG_title);
HashMap<String,String> match = new HashMap<>();
match.put(Config.TAG_title,title);
list.add(match);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
getActivity(), list, R.layout.newsadapterlayout,
new String[]{Config.TAG_title,Config.TAG_content, Config.TAG_n_date, Config.TAG_NID},
new int[]{ R.id.title});
lv.setAdapter(adapter);
}
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
JSON_STRING = s;
showResult();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(Config.URL_NEWS);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
Solved it, I forgot to add permissions in manifest lol
Here is my logcat
/* setup these below variables */
private int currentScrollState, currentFirstVisibleItem, currentVisibleItemCount, currentTotalItemCount;
if (lv.size() > 0) {
ListAdapter adapter = new SimpleAdapter(
getActivity(), list, R.layout.newsadapterlayout,
new String[]{Config.TAG_title,Config.TAG_content, Config.TAG_n_date, Config.TAG_NID},
new int[]{ R.id.title});
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
lv.setSelectionFromTop(currentFirstVisibleItem, 0); /* you missed here*/
}
Implement other ListView callbacks something like below:
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.currentTotalItemCount = totalItemCount;
}
private void isScrollCompleted() {
if (currentFirstVisibleItem + currentVisibleItemCount >= currentTotalItemCount) {
if (this.currentVisibleItemCount > 0 && this.currentScrollState == OnScrollListener.SCROLL_STATE_IDLE) {
}
}
}

Updating/Creating Custom Listview on PostExecute inside a Fragment

So I have a Sections Pager Application in Android. On my fourth fragment, I run an asynctask that connects to a device via bluetooth and updates a custom list that I created (supposedly) However, the list either updates late or doesn't update at all. I'm not exactly sure what to do on the postexecute to allow update so I updated it outside of the asynctask.
Code is below:
public class FourthFragment extends Fragment {
private WeakReference<getBeacons> getBeaconTaskWeakRef;
ArrayList<ArtInfo> ArtList = new ArrayList<>();
;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
startNewBeaconsAsyncTask();
}
ArrayList<String> titles = new ArrayList<>();
ArrayList<String> artists = new ArrayList<>();
ArrayList<String> years = new ArrayList<>();
ArrayList<Integer> images = new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
for (int i = 0; i < ArtList.size(); i++) {
titles.add(ArtList.get(i).getArtTitle());
artists.add(ArtList.get(i).getArtistName());
years.add(ArtList.get(i).getYear());
int resID = getResources().getIdentifier(ArtList.get(i).getImageFilename(), "drawable", "com.acuart.acumen.acuart");
images.add(resID);
}
View v = inflater.inflate(R.layout.frag_list, container, false);
ListView byTitleList = (ListView) v.findViewById(R.id.byTitleList);
byTitleList.setAdapter(new titleList(getActivity(), R.layout.custom_list, titles));
return v;
}
private void startNewBeaconsAsyncTask() {
getBeacons newbeacons = new getBeacons(this);
this.getBeaconTaskWeakRef = new WeakReference<getBeacons>(newbeacons);
newbeacons.execute();
}
class titleList extends ArrayAdapter<String> {
public titleList(Context context, int resource, ArrayList<String> objects) {
super(context, resource, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = ((Activity) getContext()).getLayoutInflater().inflate(R.layout.custom_list, null);
TextView title = (TextView) v.findViewById(R.id.row_title);
TextView artist = (TextView) v.findViewById(R.id.row_artist);
TextView year = (TextView) v.findViewById(R.id.row_year);
ImageView image = (ImageView) v.findViewById(R.id.row_image);
title.setText(titles.get(position));
artist.setText(artists.get(position));
year.setText(years.get(position));
image.setBackgroundResource(images.get(position));
return v;
}
}
private class getBeacons extends AsyncTask<Void, Void, Void> {
private WeakReference<FourthFragment> fragmentWeakReference;
private getBeacons(FourthFragment fragment) {
this.fragmentWeakReference = new WeakReference<FourthFragment>(fragment);
}
ProgressDialog dialog = new ProgressDialog(getActivity());
Context context = getApplicationContext();
int artCount = 0;
SQLHelper markerDBHelper = new SQLHelper(context);
#Override
protected void onPreExecute() {
dialog.setMessage("Loading, please wait...");
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
checkBluetooth();
}
#Override
protected void onPostExecute(Void v) {
dialog.dismiss();
}
} //processing bluetooth data and creating a query for database return.
}
Any help/comments/ideas are appreciated.
Code in onPostExecute() runs on the UI thread, so you should be able to update your list adapter there.
I'm a bit confused by your question, are you saying that it takes a long time for onPostExecute() to run? Did you have your code in there to update the list, and then moved it out because onPostExecute() took too long to be called?
Do you have a bunch of other async tasks running?
I didn't have time to test compile/test this, so there could very well be some syntax mistakes, but this is just to give you an idea
In titleList add a method to update the data backing the adapter list so:
public void updateAdapterData(ArrayList<String> newData) {
clear();
addAll(newData);
notifyDataSetChanged();
}
And the async task could do something like this
private titleList mTitleList; //Set this in your onCreateView
private class getBeacons extends AsyncTask<Void, Void, ArrayList<String>> {
#Override
protected void onPreExecute() {
dialog.setMessage("Loading, please wait...");
dialog.show();
}
#Override
protected ArrayList<Object> doInBackground(Void... params) {
//If checkbluetooth returns a list..
return checkBluetooth();
}
#Override
protected void onPostExecute(ArrayList<String> newList) {
mTitleList.updateAdapterData(newList)
dialog.dismiss();
}
}
At First set the ListView adapter as follows:
titleList adapter=new titleList(getActivity(), R.layout.custom_list, titles));
byTitleList.setAdapter(adapter);
After doing the background task if you get an List of "titles", then in "onPostExecute" method you can do the following:-
private class getBeacons extends AsyncTask<Void, Void, ArrayList<String> > {
ArrayList<String> titles = new ArrayList<String>();
private getBeacons() {
}
#Override
protected void onPreExecute() {
}
#Override
protected ArrayList<String> doInBackground(Void... params) {
//call a method for assigning values to titles
return titles;
}
#Override
protected void onPostExecute(ArrayList<String> titles) {
//Now assign this arraylist referrence to your actual titles arraylist
adapter.notifyDataSetChanged();
}
}
You just need to update the ArrayList in your titleList adapter and call notifyDataSetChanged() on the adapter. I suggest doing this with a setList() method in the titleList class. You also need to keep a reference of the adapter where it is accessible by your AsyncTask.

Listview items reloaded on fragment

In my app there is a fragment class (TabFragmentComerTiposRestaurante). It has also two tab fragments in it (Case 0: PrimaryFragmentComerTiposRestaurante, Case 1: SocialFragmentComerTiposRestaurante).
On both fragment classes there is a listview. When clicking on an item from this list, another fragment class is shown (PrimaryFragmentComer.
Shorty this the schema:
TabFragmentComerTiposRestaurante(#F1)
-[PrimaryFragmenComerTiposRestaurante](#F11)--[PrimaryFragmentComer](#F111)
-[SocialFragmentComerTiposRestaurante](#F12)--[SocialFragmentComer](#F121)
The issue I need to solve is the following:
If at (#F111) or at (#F121) the users click on the back button, then the listview items from #F11 and #F12 are loaded again. That means, if on the first #F11 call there is an item called "Cocina americana", then going back from #F111 to #F11 or going back from #F121 to #F12, there are now two equal items: First row=Cocina americana, Second row=Cocina americana. And that happens every time the user goes from #F11 or #F12 to #F111 or #F112.
Here you can find the code for
F1:
public class TabFragmentComerTiposRestaurante extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2 ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.tab_layout_tipo_rte,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new PrimaryFragmentComerTiposRestaurante();
case 1 : return new SocialFragmentComerTiposRestaurante();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "CIUDAD JUAREZ";
case 1 :
return "EL PASO";
}
return null;
}
}
}
Code for #F11
public class PrimaryFragmentComerTiposRestaurante extends Fragment implements AdapterView.OnItemClickListener {
private OnFragmentInteractionListener mListener;
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "..hiddene here";
private ProgressDialog pDialog;
private List<TipoRestaurante> tipoRestauranteList = new ArrayList<TipoRestaurante>();
private ListView listView;
private CustomListAdapterTipoRte adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.primary_layout_tiporte, null);
}
#Override
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
listView = (ListView) getView().findViewById(R.id.list);
adapter = new CustomListAdapterTipoRte (getActivity(), tipoRestauranteList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Procesando tipos..");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
Log.d("estoy aqui","estoy");
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
TipoRestaurante restaurante = new TipoRestaurante();
restaurante.setId_tipo(obj.getInt("id_tipo"));
restaurante.setNombre_tipo(obj.getString("nombre_tipo"));
restaurante.setFoto_tipo(obj.getString("foto_tipo"));
Log.d(TAG, response.toString());
// adding movie to movies array
tipoRestauranteList.add(restaurante);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage(obj.optString("id_tipo"));
// pDialog.show();
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TipoRestaurante rteActual = (TipoRestaurante) adapter.getItem(position);
String msg = "Has elegido el tipo " + rteActual.getNombre_tipo();
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
Fragment newFragment = new PrimaryFragmentComer();
Bundle args = new Bundle();
args.putInt("myIntLabel", 2);
args.putString("myStringLabel", rteActual.getNombre_tipo());
//and you can add all you want to that bundle like this
newFragment.setArguments(args);
if (mListener != null) {
mListener.onFragmentInteraction(newFragment);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Fragment fragment);
}
}
And now code for #F111:
public class PrimaryFragmentComer extends Fragment implements AdapterView.OnItemClickListener {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "...hidden here";
private ProgressDialog pDialog;
private List<Restaurante> restauranteList = new ArrayList<Restaurante>();
private ListView listView;
private CustomListAdapterRte adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.primary_layout_comer, null);
}
#Override
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
Bundle args = getArguments();
String hola = args.getString("myStringLabel");
Log.d("TIPO RTE", hola);
listView = (ListView) getView().findViewById(R.id.list);
adapter = new CustomListAdapterRte (getActivity(), restauranteList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Procesando restaurantes...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url+hola,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Restaurante restaurante = new Restaurante();
restaurante.setId_rte(obj.getInt("id_rte"));
restaurante.setNombre(obj.getString("nombre_rte"));
restaurante.setDescripcion(obj.getString("descripcion_rte"));
restaurante.setLatitud(obj.getDouble("latitud_rte"));
restaurante.setLongitud(obj.getDouble("longitud_rte"));
restaurante.setDireccion(obj.getString("direccion_rte"));
restaurante.setWeb(obj.getString("web_rte"));
restaurante.setTel_rte(obj.getString("tel_rte"));
restaurante.setTel_reservas(obj.getString("tel_reservas"));
restaurante.setFoto(obj.getString("foto_rte"));
restaurante.setCalificacion(obj.getDouble("calificacion_rte"));
restaurante.setTipo_rte(obj.getString("tipo_rte"));
restaurante.setFacebook(obj.getString("facebook_rte"));
restaurante.setTwitter(obj.getString("google_rte"));
restaurante.setZona(obj.getString("zona_rte"));
restaurante.setCiudad(obj.getInt("ciudad"));
restaurante.setPoi(obj.getInt("poi"));
// adding movie to movies array
restauranteList.add(restaurante);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage(obj.optString("id_rte"));
// pDialog.show();
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Restaurante rteActual = (Restaurante) adapter.getItem(position);
String msg = "Elegiste el restaurante " + rteActual.getNombre();
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
Intent intent = new Intent(getActivity(), Detalle_Restaurante.class);
intent.putExtra("id_rte", rteActual.getId_rte());
intent.putExtra("nombre_rte", rteActual.getNombre());
intent.putExtra("descripcion_rte", rteActual.getDescripcion());
intent.putExtra("latitud_rte", rteActual.getLatitud());
intent.putExtra("longitud_rte", rteActual.getLongitud());
intent.putExtra("direccion_rte", rteActual.getDireccion());
intent.putExtra("web_rte", rteActual.getWeb());
intent.putExtra("tel_rte", rteActual.getTel_rte());
intent.putExtra("tel_reservas", rteActual.getTel_reservas());
intent.putExtra("foto_rte", rteActual.getFoto());
intent.putExtra("calificacion_rte", rteActual.getCalificacion());
intent.putExtra("tipo_rte", rteActual.getTipo_rte());
intent.putExtra("facebook_rte", rteActual.getFacebook());
intent.putExtra("google_rte", rteActual.getTwitter());
intent.putExtra("zona_rte", rteActual.getZona());
intent.putExtra("ciudad_rte", rteActual.getCiudad());
intent.putExtra("poi_rte", rteActual.getPoi());
startActivity(intent);
}
}
As mentioned in the comment,
Data is being readded to tipoRestauranteList in your onResponse() method so to avoid that write tipoRestauranteList.clear() after hidePDialog().
Same will be happening in your #F12. Doing this you can rectify the same. :)

Load Image in Viewpager

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.

How can i convert this activity to a fragment? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to parse an rss feed and since i'm a beginner in android i cannot find a way to do this through a fragment..
This is the activity i want to convert into a fragment
public class Clients extends Activity {
private Clients local;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
local = this;
GetRSSDataTask task = new GetRSSDataTask();
task.execute("http://www.itcuties.com/feed/");
Log.d("ITCRssReader", Thread.currentThread().getName());
}
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
#Override
protected List<RssItem> doInBackground(String... urls) {
Log.d("ITCRssReader", Thread.currentThread().getName());
try {
RssReader rssReader = new RssReader(urls[0]);
return rssReader.getItems();
} catch (Exception e) {
Log.e("ITCRssReader", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(List<RssItem> result) {
ListView itcItems = (ListView) findViewById(R.id.listView);
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(local,android.R.layout.simple_list_item_1,result);
itcItems.setAdapter(adapter);
itcItems.setOnItemClickListener(new ListListener(result, local));
}
}
}
I already have tried to convert it but the onItemClick is getting some errors.
public void onItemClick(AdapterView parent, View view, int pos, long id) {
Intent intent = new Intent(activity, Clients.class);
intent.putExtra("description", listItems.get(pos).getLink());
activity.startActivity(intent);
}
Can someone please help me???
You should call the fragment without ui. It is needed to add ui, but not to make it visible.
public class MyFragmet extends Fragment {
public static final String TAG = "MyFragmet";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.MY_FRAGMENT_NULL_VIEW,
container, false);
local = this;
GetRSSDataTask task = new GetRSSDataTask();
task.execute("http://www.itcuties.com/feed/");
Log.d("ITCRssReader", Thread.currentThread().getName());
return view;
}
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
#Override
protected List<RssItem> doInBackground(String... urls) {
Log.d("ITCRssReader", Thread.currentThread().getName());
try {
RssReader rssReader = new RssReader(urls[0]);
return rssReader.getItems();
} catch (Exception e) {
Log.e("ITCRssReader", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(List<RssItem> result) {
Intent intent = new Intent();
intent.setAction(TAG ); // also here you can add other information
sendBroadcast(intent);
}
}
}
and add this to activity
private BroadcastReceiver receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ListView itcItems = (ListView) findViewById(R.id.listView);
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(local,android.R.layout.simple_list_item_1,result);
itcItems.setAdapter(adapter);
itcItems.setOnItemClickListener(new ListListener(result, local));
}
};
registerReceiver(receiver, new IntentFilter(MyFragmet.TAG));
FragmentManager fm = getFragmentManager();
Fragment fragment = fm.findFragmentByTag(MyFragmet.TAG);
if (fragment == null) {
getFragmentManager()
.beginTransaction()
.add(R.id.fragment, new MyFragmet(),MyFragmet.TAG)
.commit();
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
Ok, here's my attempt:
I've replaced your ArrayAdapter with a baseadapter (finer tuned control over what happens with your items) - define a layout similiar to the list item you have in your ArrayAdapter, point the BaseAdapter at it, and set up the views within the onCreateView block.
Other than that, I think it should drop in pretty well.
public class Clients extends Fragment implents ListView.OnItemClickListener {
private Clients local;
private ListView itcItems;
private RssItemBaseAdapter adapter;
private ArrayList<Rssitem> itemList = new ArrayList<RssItem>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
local = this;
GetRSSDataTask task = new GetRSSDataTask();
task.execute("http://www.itcuties.com/feed/");
Log.d("ITCRssReader", Thread.currentThread().getName());
}
#Override
public void onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
view rootView = infalter.inflate(R.layout.activity_my,container,false);
itcItems = (ListView)findViewById(R.id.listView);
itcItems.setOnItemClickListener(this);
adapter = new RssItemBaseAdapter(getActivity(),itemList);
itcItems.setAdapter(adapter);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i , long l){
RssItem item = adapter.getItem(i);
<Handle your Intent code here>
}
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
#Override
protected List<RssItem> doInBackground(String... urls) {
Log.d("ITCRssReader", Thread.currentThread().getName());
try {
RssReader rssReader = new RssReader(urls[0]);
return rssReader.getItems();
} catch (Exception e) {
Log.e("ITCRssReader", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(List<RssItem> result) {
itemList = result;
adapter.swapList(itemList);
adapter.notifyDataSetChanged();
}
}
private class RssItemBaseAdapter extends BaseAdapter(){
private Context mContext;
private ArrayList<RssItem> mRssList;
public RssItemBaseAdapter(Context context, ArrayList<RssItem> obj){
mContext = context;
mRssList = obj;
}
#Override
public int getCount() {return mRssList.size(); }
#Override
public RssItem getItem(int i) {return mRssList.get(i); }
#Override
public long getItemId(int i) { return i }
#Override
public view getView(int i, View convertView, ViewGroup parent){
View rootView = convertView;
if (rootView == null){
View rootView = Inflater.from(mContext).inflate(R.layout.YOUR_SIMPLE_LAYOUT_HERE,parent,false);
}
<do your view setting here>
return rootView;
}
public ArrayList<RssItem> swapList (ArrayList<RssItem> newList){
ArrayList<RssItem> oldList = mRssList;
mRssList = newList;
return oldList;
}
}
}

Categories

Resources