I'm new in recycle view. Tthis is sample code for my RecycerView. I'm getting data from internet and in onPostExecute() I set the adapter.
RecyclerView recycle;
MyAdapter adapters;
private static String url;
private static final String TAG_CONTACTS = "contacts";
JSONArray contacts = null;
ProgressDialog pDialog;
private int preLast;
int page = 0, in, to;
Boolean loadmore = true;
HashMap<String, String> item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = "http://192.168.1.20/adres/getAds.php";
recycle = (RecyclerView) findViewById(R.id.recycle);
recycle.setItemAnimator(new DefaultItemAnimator());
new GetContacts().execute();
final GestureDetector mGestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
private class GetContacts extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
Boolean goterr = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {
String jsonStr = Fun.getHtml(url);
Log.v("this", jsonStr);
ArrayList<HashMap<String, String>> dataC = new ArrayList<HashMap<String, String>>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
if (contacts.length() < 20)
loadmore = false;
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
HashMap<String, String> contact = new HashMap<String, String>();
contact.put("id", new String(c.getString("id").getBytes("ISO-8859-1"), "UTF-8"));
contact.put("name", new String(c.getString("name").getBytes("ISO-8859-1"), "UTF-8"));
dataC.add(contact);
dataC.add(contact);
}
} catch (JSONException e) {
Log.v("this", e.getMessage());
goterr = true;
} catch (UnsupportedEncodingException e) {
Log.v("this", e.getMessage());
goterr = true;
}
} else {
goterr = true;
}
return dataC;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
if (pDialog.isShowing() && pDialog != null)
pDialog.dismiss();
if (!isCancelled() && goterr == false && result != null) {
if (adapters == null) {
adapters = new MyAdapter(MainActivity.this, result);
recycle.setAdapter(adapters);
recycle.setLayoutManager(new LinearLayoutManager(MainActivity.this));
} else {
adapters.addAll(result);
}
} else {
//MyToast.makeText(MainActivity.this, DariGlyphUtils.reshapeText(MainActivity.this.getResources().getString(R.string.problemload)));
}
}
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private LayoutInflater inflater;
public ArrayList<HashMap<String, String>> list;
public MyAdapter(Context context, ArrayList<HashMap<String, String>> list) {
inflater = LayoutInflater.from(context);
this.list = list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parrent, int i) {
View view = inflater.inflate(R.layout.customrow, parrent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
public void addAll(ArrayList<HashMap<String, String>> result) {
if (this.list == null) {
this.list = result;
} else {
this.list.addAll(result);
}
notifyDataSetChanged();
}
public HashMap<String, String> geting(int position) {
return list.get(position);
}
#Override
public void onBindViewHolder(MyViewHolder viewHolder, int position) {
item = list.get(position);
viewHolder.txt.setText(item.get("onvan"));
}
#Override
public int getItemCount() {
return list.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView txt;
ImageView img;
public MyViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
txt = (TextView) itemView.findViewById(R.id.txt);
img = (ImageView) itemView.findViewById(R.id.img);
}
#Override
public void onClick(View v) {
item = adapters.geting(getPosition());
Log.v("this", "id " + item.get("id"));
/*Intent in=new Intent (FistActiivty.this,AdDetails.class);
in.putExtra("ad_id",item.get("id"));
startActivity(in)*/
;
}
}
}
after I run it , I get this error :
RecyclerView﹕ No adapter attached; skipping layout
what is wrong with this code ?
The problem is that during the first layout pass, while your AsyncTask is still fetching data from the network, your RecyclerView has not adapter.
You can instead attach the (empty) adapter in onCreate() and update the adapter's data in your onPostExecute(). Just make sure that your adapter properly handles having an empty data set.
Related
this is my adapter class where i am having a add to cart button
public class ServiceSelectionOptionsListAdapter extends ArrayAdapter<ServiceSelectionOptionsDataModel> {
private Context context;
private int layoutResourceId;
ListView list;
static final String TAG = "LISTT";
HashMap<Integer, Integer> hashMap;
String response;
ProgressDialog pdilog;
SharedPreferences prefs;
String serverresponse1;
private List<ServiceSelectionOptionsDataModel> data;
String custid;
JSONArray _jsonarray;
JSONObject jsonObject;
String subsrvceopid;
String quantity = "1";
String cartcounter;
TextView counter;
public ServiceSelectionOptionsListAdapter(Context context, int layoutResourceId,
List<ServiceSelectionOptionsDataModel> data) {
super(context, R.layout.serviceselectionoptionslist, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
hashMap = new HashMap<Integer, Integer>();
prefs = context.getSharedPreferences(AppConstants.VERIFICATION,
Context.MODE_PRIVATE);
custid = prefs.getString(AppConstants.CUSTOMERID, "");
cartcounter = prefs.getString(AppConstants.CARTITEMCOUNTER, "");
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
View row = convertView;
final ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.optionname = (TextView) row.findViewById(R.id.tvsubserviceoptionname);
holder.addtocart = (Button) row.findViewById(R.id.btnaddtocart);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final ServiceSelectionOptionsDataModel item = data.get(position);
holder.optionname.setText(item.getOptionname());
holder.addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer index = (Integer) view.getTag();
subsrvceopid = data.get(position).getId();
new addtocart().execute(custid, subsrvceopid, quantity);
new cartitemsdetails().execute(custid);
SharedPreferences.Editor editor = context.getSharedPreferences(AppConstants.VERIFICATION, context.MODE_PRIVATE).edit();
editor.putString(AppConstants.SUBSERVIEOPTIONID, subsrvceopid);
editor.commit();
notifyDataSetChanged();
}
});
return row;
}
static class ViewHolder {
TextView optionname;
// TextView charges;
Button addtocart;
TextView counter;
}
and this is my activity class where i m getting the size of the cart items list
class cartitemsdetails extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
pdilog = new ProgressDialog(ServiceSelectionOptionsListActivity.this);
pdilog.setMessage("Please Wait....");
pdilog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
String response = JSONFunctions.getJSONfromURL("http://cpanel.smartindiaservice.com/api/cartdetails?customerid=" + params[0]);
try {
jsonarray = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
size = jsonarray.length();
counter.setText(String.valueOf(size));
if (size == 0 )
{
viewcart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ServiceSelectionOptionsListActivity.this, NoItemsInTheCart.class);
startActivity(intent);
}
});
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ServiceSelectionOptionsListActivity.this, NoItemsInTheCart.class);
startActivity(intent);
}
});
}
if(size>0) {
viewcart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ServiceSelectionOptionsListActivity.this, MyCart.class);
startActivity(intent);
}
});
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ServiceSelectionOptionsListActivity.this, MyCart.class);
startActivity(intent);
}
});
}
pdilog.dismiss();
super.onPostExecute(aVoid);
}
}
class OptionsSelection extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
response = JSONFunctions.getJSONfromURL("http://cpanel.smartindiaservice.com/api/subserviceoptions?subserviceid=" + params[0]);
try {
_jsonarray = new JSONArray(response);
for (int i = 0; i < _jsonarray.length(); i++) {
ServiceSelectionOptionsDataModel datamodel = new ServiceSelectionOptionsDataModel();
jsonObject = _jsonarray.getJSONObject(i);
optionname = jsonObject.getString("OptionName");
datamodel.setOptionname(optionname);
charge = jsonObject.getString("Charges");
datamodel.setCharge(charge);
subserviceoptionid = jsonObject.getString("SubServiceOptionID");
datamodel.setId(subserviceoptionid);
lstDataModel.add(datamodel);
}
} catch (Exception e) {
System.out.println(e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ServiceSelectionOptionsListAdapter adapter = new ServiceSelectionOptionsListAdapter(ServiceSelectionOptionsListActivity.this, R.layout.serviceselectionoptionslist, lstDataModel);
options.setAdapter(adapter);
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
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.
I am using listview to populate data coming from the server. This listview will show that data in a fragmentTab. Now the data is parsing fine and logcat is also showing the data. But the data is not being populated by listview. I tried to see the error through debugging but there is no problem. Even the Holder in adapter catches the data but it's not displayed. I don't know what the problem is. I tried the following questions but didn't got the answer.
Android - ListView in Fragment does not showing up
Android - ListView in Fragment does not show
ListView in Fragment Not Displayed
Below is my fragment and the adapter.
Tastemaker Fragment:
public class TasteMakersFragment extends Fragment
{
CommonClass commonTasteMakers;
String tasteMaker_url = CommonClass.url+ URLConstants.Host.URL_ALL_SUGGESTED_TASTEMAKERS;
String user_token = "8aa0dcd5aaf54c8a5aaef1aa242f342f";
ListView suggested_list;
List<SuggestedUserModel> suggestedUsers_list = new ArrayList<>();
SuggestedUsersAdapter mAdapter;
int selectedPosition = 0;
public TasteMakersFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.from(getActivity()).inflate(R.layout.suggested_users_tastemakers, null);
commonTasteMakers = new CommonClass(getActivity().getApplicationContext());
suggested_list = (ListView)v.findViewById(R.id.lst_suggestedUsers);
new GetSuggestedUsers().execute(tasteMaker_url);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
private class GetSuggestedUsers extends AsyncTask< String, Void, Void>
{
private ProgressDialog Dialog = new ProgressDialog(getActivity());
protected void onPreExecute() {
if (suggestedUsers_list.isEmpty())
{
Dialog = ProgressDialog.show(getActivity(),"Please be patient!","Fetching for first time...");
}
}
#Override
protected Void doInBackground(String... params)
{
if (suggestedUsers_list.isEmpty())
{
getSuggestedUsers();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
else{
Log.d("---- Already Fetched --", "---- Already Fetched ----");
return null;
}
}
protected void onPostExecute(Void unused)
{
Dialog.dismiss();
mAdapter = new SuggestedUsersAdapter(getActivity(), suggestedUsers_list);
suggested_list.setAdapter(mAdapter);
suggested_list.setSelection(selectedPosition);
mAdapter.notifyDataSetChanged();
//startMainActivity();
}
}
private List<SuggestedUserModel> getSuggestedUsers()
{
StringRequest postRequest = new StringRequest(Request.Method.POST, tasteMaker_url, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try {
//JSONObject jsonResponse = new JSONObject(response).getJSONObject("form");
JSONObject jsonResponse = new JSONObject(response);
if (jsonResponse.has("data"))
{
JSONObject data = jsonResponse.getJSONObject("data");
String code = jsonResponse.getString("code");
if(code.equals("200"))
{
if(data.has("tasteMakers"))
{
JSONArray tastemakers = data.getJSONArray("tasteMakers");
for (int i =0; i<tastemakers.length(); i++)
{
JSONObject jsnObj = tastemakers.getJSONObject(i);
String id = jsnObj.getString("userId");
String name = jsnObj.getString("name");
String profilePic = jsnObj.getString("imgUrl");
Boolean isFollowed = jsnObj.getBoolean("isFollowed");
suggestedUsers_list.add(new SuggestedUserModel(id,
name,
profilePic,
isFollowed));
Log.d("Names are ----", "size is=" + name +" and their id are: "+id);
}
// Log.d("Adapter list ----", "size is=" + suggestedUsers_list.size());
}
}
else {
Log.d("Error0 Error Error", "response------:" + jsonResponse);
}
}
// Log.d("response222---------","response22222------:"+jsonResponse);
} catch (JSONException e) {
Log.d("-----Stop------", "!!!");
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("sessionToken", user_token);
return params;
} };
postRequest.setRetryPolicy(new DefaultRetryPolicy(20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(getActivity().getApplicationContext()).add(postRequest);
return suggestedUsers_list;
}
}
Adapter Class:
public class SuggestedUsersAdapter extends BaseAdapter {
Context context;
int count = 1;
private List<SuggestedUserModel> allUsers;
public SuggestedUsersAdapter(FragmentActivity activity, List<SuggestedUserModel> suggestUserModel)
{
Log.d("Custom Adapter called", "" + suggestUserModel.size());
context = activity;
allUsers = suggestUserModel;
//FragmentActivity mActivity = activity;
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return allUsers.size();
// return imageId.length;
}
#Override
public Object getItem(int position) {
return allUsers.get(position);
// return position;
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint({"ViewHolder", "InflateParams", "CutPasteId"})
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final mHolder holder;
// int type = getItemViewType(position);
LayoutInflater layoutInflater;
getItemViewType(position);
if (convertView == null)
{
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.suggested_users_tastemaker_cell, null);
holder = new mHolder();
// convertView.setTag(mFeedsListItemViewHolder);
holder.txt_suggestUserName = (TextView) convertView.findViewById(R.id.tv_tasteMakerName);
holder.imgV_userProfile = (ImageView) convertView.findViewById(R.id.imgBtn_tasteMaker_pic);
holder.btnFollow = (Button) convertView.findViewById(R.id.btnFollow_tasteMaker);
holder.btnFollowing = (Button) convertView.findViewById(R.id.btnFollowing);
convertView.setTag(holder);
} else {
holder = (mHolder) convertView.getTag();
}
final SuggestedUserModel suggestUser = allUsers.get(position);
holder.txt_suggestUserName.setText(allUsers.get(position).getSuggested_UserName());
/*if(suggestUser.getSuggested_UserImage().equals(""))
{
Picasso
.with(context)
.load(R.mipmap.ic_launcher)
.transform(new CropSquareTransformationHomePage())
.into(holder.imgV_userProfile);
}
else {
Picasso
.with(context)
.load(suggestUser.getSuggested_UserImage())
.transform(new CropSquareTransformationHomePage())
.into(holder.imgV_userProfile);
}*/
holder.pos = position;
//mFeedsListItemViewHolder.setData(allPersons.get(position));
return convertView;
}
private class mHolder {
TextView txt_suggestUserName;
ImageView imgV_userProfile;
Button btnFollow;
Button btnFollowing;
int pos;
}
}
Note: I already tried declaring listview and assigning adapter in onActivityCreated() method of fragment but no effect.
Any Help will be appreciated.
I have a gridview on my activity ,I get data via json and add them to my adapter .
this is the code:
gridView = (GridView) findViewById(R.id.gridView);
contactList = new ArrayList<HashMap<String, String>>();
new GetContacts().execute();
private class GetContacts extends AsyncTask<Void, Void,ArrayList<HashMap<String, String>>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {
Spots_tab1_json sh = new Spots_tab1_json();
String jsonStr = sh.makeServiceCall(url+page, Spots_tab1_json.GET);
ArrayList<HashMap<String, String>> dataC = new ArrayList<HashMap<String, String>>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
if(contacts.length()<20)
loadmore=false;
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
HashMap<String, String> contact = new HashMap<String, String>();
contact.put("id", new String(c.getString("id").getBytes("ISO-8859-1"), "UTF-8"));
contact.put("url", new String(c.getString("url").getBytes("ISO-8859-1"), "UTF-8"));
contact.put("text", new String(c.getString("text").getBytes("ISO-8859-1"), "UTF-8"));
dataC.add(contact);
}
} catch (JSONException e) {
goterr=true;
} catch (UnsupportedEncodingException e) {
goterr=true;
}
} else {
Log.v("this","mi;;");
goterr=true;
}
return dataC;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
if(!isCancelled() && goterr==false){
if(ladap==null){
ladap=new ListAdapter(FistActiivty.this,result);
gridView.setAdapter(ladap);
}else{
ladap.addAll(result);
}
}else{
MyToast.makeText(FistActiivty.this, DariGlyphUtils.reshapeText(getResources().getString(R.string.problemload)));
}
}
}
public class ListAdapter extends BaseAdapter {
Activity activity;
public ArrayList<HashMap<String,String>> list;
public ListAdapter(Activity activity, ArrayList<HashMap<String, String>>list ) {
super();
this.activity=FistActiivty.this;
this.list=list;
}
public HashMap<String, String> geting(int position) {
return list.get(position);
}
public void addAll(ArrayList<HashMap<String, String>> result) {
if(this.list==null){
//this.list = new ArrayList<HashMap<String, String>>();
this.list =result;
}else{
this.list.addAll(result);
}
//list.addAll(result);
notifyDataSetChanged();
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return list.get(position);
}
public long getItemId(int arg0) {
return 0;
}
private class ViewHolder {
TextView Message;
ImageView img ;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.row_grid, null);
holder = new ViewHolder();
holder.Message = (TextView) convertView.findViewById(R.id.text);
holder.Message.setTypeface(typeface);
holder.img=(ImageView)convertView.findViewById(R.id.image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
item = list.get(position);
String text = item.get("text");
Log.v("this","11"+ text);
holder.Message.setText(text);
String imgurl = item.get("url");
if(imgurl.length()>5)
imageLoader.displayImage(imgurl, holder.img,options, imageListener);
else
holder.img.setImageDrawable(getResources().getDrawable(R.drawable.noimage));
return convertView;
}
ok , at this step, I get data from internet via json , post it to ListAdapter and add them to my gridview and no problem .
in listview ,we can add ask for more data when we reach at the bottom of listview , But how can I call function to add more items whwen I reach at the end of gridview ?
The best way to implement this is via using PullToRefreshLibrary here. Import that library to your workspace and implement setOnRefreshListener with onPullUpToRefresh. This will indicate the end of the list. You can set a request to the server to get more data to view when the end of the list is reached.
On the server, you can implement pagination to load the next set of data every time you reach the end of the list.
I hope this will help you.
i've a listview on my activity , when I reach the end of listview , it calls async and it getting new data using json .
this is the async and baseAdaper codes :
ListAdapter ladap;
private class GetContacts AsyncTask<Void, Void,ArrayList<HashMap<String, String>>> {
#Override
protected Void doInBackground(Void... arg0) {
Spots_tab1_json sh = new Spots_tab1_json();
String jsonStr = sh.makeServiceCall(url + page, Spots_tab1_json.GET);
ArrayList<HashMap<String, String>> dataC = new ArrayList<HashMap<String, String>>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = new String(c.getString("id").getBytes("ISO-8859-1"), "UTF-8");
String dates = new String(c.getString("dates").getBytes("ISO-8859-1"), "UTF-8");
String price = new String(c.getString("gheymat").getBytes("ISO-8859-1"), "UTF-8");
HashMap<String, String> contact = new HashMap<String, String>();
contact.put("id", id);
contact.put("dates", dates);
contact.put("price", price);
dataC.add(contact);
}
}
} catch (JSONException e) {
goterr = true;
} catch (UnsupportedEncodingException e) {
goterr = true;
}
} else {
goterr = true;
}
return dataC;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
if (!isCancelled() && goterr == false) {
if(ladap==null){
ladap=new ListAdapter(MainActivity.this,result);
lv.setAdapter(ladap);
}else{
ladap.addAll(result);
ladap.notifyDataSetChanged();
}
}
}
public class ListAdapter extends BaseAdapter {
Activity activity;
public ArrayList<HashMap<String, String>> list;
public ListAdapter(Activity activity,ArrayList<HashMap<String, String>> list) {
super();
this.activity = (Activity) activity;
this.list = list;
}
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
this.list = result;
notifyDataSetChanged();
}
public int getCount() {
return contactList.size();
}
public Object getItem(int position) {
return contactList.get(position);
}
public long getItemId(int arg0) {
return 0;
}
private class ViewHolder {
TextView title,price;
ImageView img ;
//RelativeLayout rl;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.item, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.price = (TextView) convertView.findViewById(R.id.price);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
item = contactList.get(position);
holder.price.setText(item.get("price"));
return convertView;
}
}
I logged here , when I reach the end of listView , it calls addAll and it returns new 30 items buy it doesn't added to listview , I don't know why .
First of all you have already notify your list view when you call addAll() so this code no longer required please remove from your code :
ladap.notifyDataSetChanged();
Add new data to list view data holder instead of assign new data to list view data holder :
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
this.list = result;
notifyDataSetChanged();
}
Replace with :
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
if(list==null){
list = new ArrayList<HashMap<String, String>>();
}
list.addAll(result)
notifyDataSetChanged();
}
Try to change this :
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
this.list = result;
notifyDataSetChanged();
}
To :
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
for(int i = 0;i < result.size(); i++)
list.add(result.get(i));
//notifyDataSetChanged(); //no need to call again here
}
The point is, i think this.list = result; will delete the old items before adding a new item.