Listview is not updating after SwipeRefreshLayout - android

I have code to show listview from my server, but when I update the data from server and refresh it in my app, the listview still getting the old data, and after several minutes when I open the app again, it updated the new data that I updated before.
My Main Fragment
public class DosenFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
ListView list;
SwipeRefreshLayout swipe;
List<Dosen> itemList = new ArrayList<>();
AdapterDosen adapter;
private static final String TAG = DosenFragment.class.getSimpleName();
private static String url_select = Server.URL + "select.php";
public static final String TAG_ID_DOSEN = "id_dosen";
public static final String TAG_NAME = "name";
public static final String TAG_STATUS = "status";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.matkul_list, container, false);
swipe = (SwipeRefreshLayout) v.findViewById(R.id.swipe_refresh_layout);
list = (ListView) v.findViewById(R.id.list);
adapter = new AdapterDosen(getActivity(), itemList);
list.setAdapter(adapter);
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
itemList.clear();
adapter.notifyDataSetChanged();
callVolley();
}
});
return v;
}
#Override
public void onRefresh() {
itemList.clear();
adapter.notifyDataSetChanged();
callVolley();
}
private void callVolley() {
swipe.setRefreshing(true);
JsonArrayRequest jArr = new JsonArrayRequest(url_select, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Dosen item = new Dosen();
item.setId_dosen(obj.getString(TAG_ID_DOSEN));
item.setName(obj.getString(TAG_NAME));
item.setAlamat(obj.getString(TAG_STATUS));
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
AppController.getInstance().addToRequestQueue(jArr);
}
}
I have tried to do something with itemList.clear(); and adapter.notifyDataSetChanged(); but nothing change.
My Main Adapter
public class AdapterDosen extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Dosen> items;
public AdapterDosen(Activity activity, List<Dosen> items) {
this.activity = activity;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int location) {
return items.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
Dosen data = items.get(position);
TextView id = (TextView) convertView.findViewById(R.id.id);
TextView name = (TextView) convertView.findViewById(R.id.nama);
TextView alamat = (TextView) convertView.findViewById(R.id.alamat);
id.setText(data.getId_dosen());
name.setText(data.getName());
alamat.setText(data.getAlamat());
return convertView;
}
}
I'm sorry for my bad english.
Please help.

try this , add this method in your adatper
public void updateList(List<Dosen> newlist) {
items.clear();
items.addAll(newlist);
this.notifyDataSetChanged();
}
and in callVolley() method , replace this
adapter.notifyDataSetChanged();
with
adapter.updateList();
Hope this helps

Use the below Code...
/* Within the RecyclerView.Adapter class */
// Clean all elements of the recycler
public void clear() {
items.clear();
notifyDataSetChanged();
}
// Add a list of items -- change to type used
public void addAll(List<Dosen> newlist) {
items.addAll(newlist);
notifyDataSetChanged();
}
callvolly() method inside.
adapter.clear();
adapter.addAll(item);
public void onRefresh() {
callVolley();
}

please try this code i have changed something it will work fine
public class AdapterDosen extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Dosen> items;
public AdapterDosen(Activity activity, List<Dosen> items) {
this.activity = activity;
this.items = items;
}
public void setData(List<Dosen> items){
this.items = items
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int location) {
return items.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
Dosen data = items.get(position);
TextView id = (TextView) convertView.findViewById(R.id.id);
TextView name = (TextView) convertView.findViewById(R.id.nama);
TextView alamat = (TextView) convertView.findViewById(R.id.alamat);
id.setText(data.getId_dosen());
name.setText(data.getName());
alamat.setText(data.getAlamat());
return convertView;
}
}
public class DosenFragment extends Fragment implements
SwipeRefreshLayout.OnRefreshListener {
ListView list;
SwipeRefreshLayout swipe;
List<Dosen> itemList = new ArrayList<>();
AdapterDosen adapter;
private static final String TAG = DosenFragment.class.getSimpleName();
private static String url_select = Server.URL + "select.php";
public static final String TAG_ID_DOSEN = "id_dosen";
public static final String TAG_NAME = "name";
public static final String TAG_STATUS = "status";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.matkul_list, container, false);
swipe = (SwipeRefreshLayout)
v.findViewById(R.id.swipe_refresh_layout);
list = (ListView) v.findViewById(R.id.list);
adapter = new AdapterDosen(getActivity(), itemList);
list.setAdapter(adapter);
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
itemList.clear();
adapter.notifyDataSetChanged();
callVolley();
}
});
return v;
}
#Override
public void onRefresh() {
//itemList.clear();
//adapter.notifyDataSetChanged();
callVolley();
}
private void callVolley() {
swipe.setRefreshing(true);
JsonArrayRequest jArr = new JsonArrayRequest(url_select, new
Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
itemList .clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj =
response.getJSONObject(i);
Dosen item = new Dosen();
item.setId_dosen(obj.getString(TAG_ID_DOSEN));
item.setName(obj.getString(TAG_NAME));
item.setAlamat(obj.getString(TAG_STATUS));
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.setData(itemList );
adapter.notifyDataSetChanged();
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
AppController.getInstance().addToRequestQueue(jArr);
}

Related

ListView JSON Array doesn't work

The array "ary" receives the data from the server and the Adapter, but doesn't show the data in the ListView. Is there a problem with receiving the data after the onCreate() method?
Does anyone have an idea/solution?
public class ScheduleActivity extends AppCompatActivity {
public ListView list;
public ScheduleViewAdapter mSVAdapter;
public JSONArray ary;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
list = (ListView) findViewById(R.id.lstSchedule);
ary = new JSONArray();
mSVAdapter = new ScheduleViewAdapter(this, ary);
list.setAdapter(mSVAdapter);
buildList();
}
public void setListView(JSONArray ary) {
this.ary = ary;
mSVAdapter.notifyDataSetChanged();
}
private void buildList() {
final RequestQueue requestQueue = Volley.newRequestQueue(this);
// String URL1 = "http://10.0.2.2:3000/users/:userId/offers/";
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// vorläufiger hardcode
String userID = "5b2f9f3cd56ff67974d2f58e";
/* userID = settings.getString("userID", "");*/
String URL1 = "http://10.0.2.2:3000/orders/?buyerID=".concat(userID).concat("/userorder");
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL1, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("ConsoleText", response);
try {
JSONArray ary2 = new JSONArray(response);
setListView(ary2);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ConsoleText", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
requestQueue.add(stringRequest);
}
}
Okay, so this is an edit.
That's the adapter. maybe you can find the error here. Thanks:
public class ScheduleViewAdapter extends BaseAdapter{
private Context mContext;
private JSONArray orders;
public ScheduleViewAdapter() {
}
public ScheduleViewAdapter(Context mContext, JSONArray orders) {
this.mContext = mContext;
this.orders = orders;
}
#Override
public int getCount() {
if(orders == null){
return 0;
}else{
return orders.length();
}
}
#Override
public JSONObject getItem(int position) {
if(orders == null){
return null;
}else{
return orders.optJSONObject(position);
}
}
#Override
public long getItemId(int position) {
JSONObject object = getItem(position);
return object.optLong("id");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
//Only creates new view when recycling isn't possible
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.activity_schedule, parent, false);
}
TextView tvItem =(TextView)convertView.findViewById(R.id.tvItem);
// TextView tvUserName =(TextView)convertView.findViewById(R.id.tvUserName);
// TextView tvAddress =(TextView)convertView.findViewById(R.id.tvAddress);
JSONObject json_data = getItem(position);
if(json_data != null){
try {
String type = json_data.getString("title");
// tvItem.append("" + json_data.getString("title"));
} catch (JSONException e) {
e.printStackTrace();
}
}
return convertView;
}
}
Change your method to this,
public void setListView(JSONArray ary) {
this.ary = ary;
mSVAdapter = new ScheduleViewAdapter(this, ary);
list.setAdapter(mSVAdapter);
}
and onCreate to this,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
list = (ListView) findViewById(R.id.lstSchedule);
ary = new JSONArray();
buildList();
}

Json volley listview error incompatible types Adapter

I have been following some tutorials to retrieve json data and add it to a listview using volley. I have been stuck in this error trying to solve it for some time, so i had to seek out some help. I tried many examples, this one seems the most intuitive to learn, but i just cant get passed this error, thank you
i cant solve this error
this is my model class
public class Trilhos {
private int id;
private String titulo;
private int id_user;
private String dificuldade;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public int getId_user() {
return id_user;
}
public void setId_user(int id_user) {
this.id_user = id_user;
}
public String getDificuldade() {
return dificuldade;
}
public void setDificuldade(String dificuldade) {
this.dificuldade = dificuldade;
}
}
my adapter
public class AdapterTrilhos extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Trilhos> triList;
public AdapterTrilhos(List<Trilhos> triList, Activity activity) {
this.activity = activity;
this.triList = triList;
}
#Override
public int getCount() {
return this.triList.size();
}
#Override
public Object getItem(int position) {
return this.triList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.dadoslista, null);
TextView idtxt = (TextView)
convertView.findViewById(R.id.txtid);
TextView tittxt = (TextView)
convertView.findViewById(R.id.txttit);
TextView usertxt = convertView.findViewById(R.id.txtuser);
TextView diftxt = (TextView)
convertView.findViewById(R.id.txtdif);
Trilhos t = triList.get(position);
idtxt.setText(t.getId());
tittxt.setText(t.getTitulo());
usertxt.setText(t.getId_user());
diftxt.setText(t.getDificuldade());
return convertView;
}
}
my main_activity (listarTrilhos)
public class ListarTrilhos extends Activity {
private static final String
urlget="http://192.168.1.68/loginsignup/getTrilhos.php";
private ListView listView;
private AdapterTrilhos adapter;
private List<Trilhos> TrilhosList = new ArrayList<Trilhos>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listatrilhos);
listView=findViewById(R.id.listv);
adapter=new AdapterTrilhos(this,TrilhosList);
listView.setAdapter(adapter);
criarLista();
}
public void criarLista(){
RequestQueue mRequestQueue =
Volley.newRequestQueue(getApplicationContext());
JsonArrayRequest request = new JsonArrayRequest(
urlget,
new Response.Listener<JSONArray>(){
#Override
public void onResponse(JSONArray response) {
int count = response.length();
for(int i = 0; i < count; i++){
try {
JSONObject jo = response.getJSONObject(i);
Trilhos tri=new Trilhos();
tri.setId(jo.getInt("id"));
tri.setTitulo(jo.getString("titulo"));
tri.setId_user(jo.getInt("id_user"));
tri.setDificuldade(jo.getString("dificuldade"));
TrilhosList.add(tri);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(), response.toString(),
Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "onErrorResponse",
Toast.LENGTH_LONG).show();
}
}
);
Object TAG_REQUEST_QUEUE = new Object();
request.setTag(TAG_REQUEST_QUEUE);
mRequestQueue.add(request);
mRequestQueue.start();
}
}
I didn't read all of your code but noticed that you have constructor
public AdapterTrilhos(List<Trilhos> triList, Activity activity) {
this.activity = activity;
this.triList = triList;}
change adapter=new AdapterTrilhos(this, TrilhosList); to
adapter=new AdapterTrilhos(TrilhosList, this);

The content of the adapter has changed but ListView did not receive a notification. How can i notify the list?

This is my fragment where I create the listview. When the data changed the listview is not notify. How can I do this? I make the request in viewModel using volley. I receive the next error: java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. Make sure your adapter calls notifyDataSetChanged() when its content changes. [in ListView(2131558620, class android.widget.ListView) with Adapter(class pharma.com.pharmaapp.Common.EventsArrayAdapter)]
at android.widget.ListView.layoutChildren(ListView.java:1582)
public class EventesFragment extends Fragment {
private final String TAG = EventesFragment.class.getSimpleName();
private ArrayList<EvenimentType> events = new ArrayList<>();
private ListView eventsListView;
private SwipeRefreshLayout swipeContainer;
public EventsArrayAdapter eventsArrayAdapter;
private EventsFragmentViewModel eventsFragmentViewModel = new EventsFragmentViewModel();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_events, container, false);
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), SearchActivity.class);
startActivity(intent);
}
});
if(events.size() != 0) {
events.clear();
}
eventsListView = (ListView) view.findViewById(R.id.listView_events);
swipeContainer = (SwipeRefreshLayout) view.findViewById(R.id.swipeContainer);
eventsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = ((EvenimentType) eventsListView.getAdapter().getItem(position)).getName();
Log.d(TAG, "Click " + name);
Intent intent = new Intent(getActivity(), SelectedEventActivity.class);
intent.putExtra("Parceable", events.get(position));
startActivity(intent);
}
});
eventsListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
String name = ((EvenimentType) eventsListView.getAdapter().getItem(position)).getName();
return false;
}
});
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
events.clear();
eventsFragmentViewModel.loadEvents(getActivity());
eventsFragmentViewModel.setInterface(new EventsFragmentViewModel.EventsFragmentInterface() {
#Override
public void takeData(ArrayList<EvenimentType> list) {
if(eventsArrayAdapter == null) {
eventsArrayAdapter = new EventsArrayAdapter(getActivity(), list);
eventsListView.setAdapter(eventsArrayAdapter);
swipeContainer.setRefreshing(false);
} else {
events = list;
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
eventsArrayAdapter.notifyDataSetChanged();
}
});
swipeContainer.setRefreshing(false);
}
}
});
}
});
loadEvents();
return view;
}
public void loadElementsToArrayAdapter() {
eventsArrayAdapter = new EventsArrayAdapter(getContext(), events);
// eventsArrayAdapter.notifyDataSetChanged();
swipeContainer.setRefreshing(false);
eventsListView.setAdapter(eventsArrayAdapter);
eventsFragmentViewModel.saveEvents(events, getActivity());
}
public void loadEvents() {
eventsFragmentViewModel.loadEvents(getActivity());
eventsFragmentViewModel.setInterface(new EventsFragmentViewModel.EventsFragmentInterface() {
#Override
public void takeData(ArrayList<EvenimentType> list) {
events = list;
loadElementsToArrayAdapter();
}
});
}
#Override
public void onResume() {
super.onResume();
// eventsFragmentViewModel.getUserEventsId(getActivity());
}
}
This is the Base Adapter class:
public class EventsArrayAdapter extends BaseAdapter {
private static final String TAG = EventsArrayAdapter.class.getSimpleName();
private Context context;
private List<EvenimentType> list = null;
public EventsArrayAdapter(Context context, List<EvenimentType> objects) {
this.context = context;
this.list = objects;
}
public void addAll(List<EvenimentType> objects) {
if(list == null) {
list = new ArrayList<>();
}
list.addAll(objects);
notifyDataSetChanged();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null) {
convertView = inflater.inflate(R.layout.item_array_adapter, null);
}
TextView title = (TextView) convertView.findViewById(R.id.text_simposion_title);
TextView date = (TextView) convertView.findViewById(R.id.text_simposion_date);
TextView location = (TextView) convertView.findViewById(R.id.text_simposion_location);
TextView price = (TextView) convertView.findViewById(R.id.text_simposion_price);
ImageView image = (ImageView) convertView.findViewById(R.id.image_event);
Log.d(TAG, "Checking: " + checkEvent(list.get(position)));
if (checkSelection(list.get(position)) == true) {
title.setText(list.get(position).getName());
date.setText(list.get(position).getDate());
location.setText(list.get(position).getLocation());
price.setText(list.get(position).getPaid());
image.setImageResource(R.drawable.ic_simposions);
} else {
title.setText(list.get(position).getName());
date.setText(list.get(position).getDate());
location.setText(list.get(position).getLocation());
price.setText(list.get(position).getPaid());
}
Log.d(TAG, "getView");
return convertView;
}
This is the viewModel where I make the request
public class EventsFragmentViewModel extends LoginViewModel {
private static final String TAG = EventsFragmentViewModel.class.getSimpleName();
private ArrayList<EvenimentType> events = new ArrayList<>();
EventsFragmentInterface listener = null;
public void loadEvents(final Context context) {
DataServices dataServices = new DataServices(context);
dataServices.getEvents();
dataServices.setCommunicationInterface(new RequestToServer.CommunicationInterface() {
#Override
public void takeResponse(JSONObject response) {
try {
Log.d(TAG, response.toString());
EvenimentType evenimentType = new EvenimentType();
JSONArray obj = response.getJSONArray("entry");
Log.d(TAG, obj.length() + "");
for (int i = 0; i < obj.length(); i++) {
events.add(evenimentType.createEvent(obj.getJSONObject(i)));
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(TAG, "EVENTS: " + events.size());
if(listener!= null) {
listener.takeData(events);
}
}
});
}
public void saveEvents(ArrayList<EvenimentType> list, Context context) {
Preferences preferences = new Preferences(context);
preferences.saveToSharedPreferencesEvents(list);
preferences.getFromSharedPreferencesEvents();
}
public void setInterface(EventsFragmentInterface listener) {
this.listener = listener;
}
public interface EventsFragmentInterface {
public void takeData(ArrayList<EvenimentType> list);
}
}

GridView in a tab fragment is displayed only after scrolling to that tab second time

I have a fragment for a tab which displays JSON parsed results in GridView. The results are not displayed when scrolled to that tab for first time. But after switching tabs, results are displayed in second visit.
public class StoresFragment extends Fragment {
private ProgressBar loading;
private ArrayList<String> storenamefinal = new ArrayList<String>();
private ArrayList<Integer> imagelinksfinal = new ArrayList<Integer>();
private GridView gridview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.stores_layout,null);
}
#Override
public void onViewCreated(final View view, final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
gridview = (GridView) getActivity().findViewById(R.id.grid_stores);
loading = (ProgressBar) getActivity().findViewById(R.id.proStores);
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
new getData(getActivity()).execute();
}
}
private class getData extends AsyncTask<Void, Void, Void> {
private Context context;
public getData(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
String url = Config1.DATA_URL;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
return null;
}
private void showJSON(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray("result");
int i = result.length();
Log.i("Result", result.toString());
for (int j = 0; j < i; j++) {
storenamefinal.add(null);
imagelinksfinal.add(null);
}
String temp;
for (int j = 0; j < i; j++) {
JSONObject Data = result.getJSONObject(j);
Log.i("Data", Data.toString());
temp = (Data.getString("mainpriority"));
Log.i("temp", temp.toString());
storenamefinal.set(Integer.parseInt(temp) - 1, Data.getString("storename"));
Log.i("Result Length", storenamefinal.toString());
imagelinksfinal.add(R.drawable.sg1);
}
Log.i("Result Length", storenamefinal.toString());
Toast.makeText(getActivity(), storenamefinal.get(0), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(Void result)
{
loading.setVisibility(View.GONE);
gridview.setVisibility(View.VISIBLE);
if (storenamefinal != null) {
final GridAdapterStores gridadapter = new GridAdapterStores(getActivity(), storenamefinal, imagelinksfinal);
gridview.setAdapter(gridadapter);
}
}
}
}
Adapter.
public class GridAdapterStores extends BaseAdapter {
private Context context;
private ArrayList<String> storename = new ArrayList<String>();
private ArrayList<Integer> imagelinks = new ArrayList<Integer>();
public GridAdapterStores(Context c, ArrayList<String> storename, ArrayList<Integer> imagelinks) {
context = c;
this.imagelinks = imagelinks;
this.storename = storename;
}
#Override
public int getCount() {
return storename.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View grid;
if (convertView == null) {
grid = new View(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
grid = inflater.inflate(R.layout.grid_stores, parent, false);
} else {
grid = (View) convertView;
}
TextView textViewStoreName = (TextView) grid.findViewById(R.id.store_name);
// ImageView imageViewStoreImage = (ImageView) grid.findViewById(R.id.store_image);
textViewStoreName.setText(storename.get(position));
// Integer x=imagelinks.get(position);
// imageViewStoreImage.setImageResource(x);
return grid;
}
}
And also, everytime tab is switched, gridview gets added, but data is displayed in only one gridview.

(Android) ListView: Load 5 items at a time, when scroll down

So I made an sliding tabs app that loads json into a listview. My question is how would I implement something that would only load 5 listview items in the beginning and would load another 5 when you scroll down? (Instead of loading all of the listview items in the beginning)
I have search the web and I can't really understand how to do this. Any suggestions or ideas will be appreciated.
This is some of my code. These classes is where I think the code would go: I used SlidingTabLayout & strip from the android developer site.
CustomListAdapter code:
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Tanga> tangasItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Tanga> movieItems) {
this.activity = activity;
this.tangasItems = movieItems;
}
#Override
public int getCount() {
return tangasItems.size();
}
#Override
public Object getItem(int location) {
return tangasItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
TextView name = (TextView) convertView.findViewById(R.id.name);
// getting movie data for the row
Tanga m = tangasItems.get(position);
// title
name.setText(m.getName());
return convertView;
}
}
Fragment:
public class Tab1 extends Fragment {
private static final String url = "website.json";
private List<Tanga> tangaList = new ArrayList<Tanga>();
private ListView listView;
private CustomListAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onActivityCreated (Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
listView = (ListView) getView().findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), tangaList);
listView.setAdapter(adapter);
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Tanga movie = new Tanga();
//name
String name = obj.getString("name");
movie.setName(name);
// adding movie to movies array
tangaList.add(movie);
} 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("Error: ");
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tabs, container, false);
return v;
}
}
Tanga Code: (model)
public class Tanga {
private String name;
public Tanga() {
}
public Tanga(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
There are multiple ways you could handle this, the simplest way would be to create another ArrayList of type Tanga, let's suppose it's name is tangaList2. What you have to do is in your for loop write this code.
public void onResponse(JSONArray response) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Tanga movie = new Tanga();
//name
String name = obj.getString("name");
movie.setName(name);
// adding movie to movies array
if(i < 5) {
tangaList.add(movie);
}
else {
tangaList2.add(movie);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
Now after this you should also implement the onScrollListener in your Fragment:
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if ((++firstVisibleItem) + visibleItemCount > totalItemCount) {
for(int i = 0; i < 5 && tangaList2.size() > 0; i++){
tangaList.add(tangaList2.get(0));
tangaList2.remove(0);
}
}
}
});

Categories

Resources