gaurang gaurang - 6 months ago 63
JSON Question

endless recycler view repeating json data

Mainactivity.java :

public class MainActivity extends AppCompatActivity {

private List<Item> colors;
private boolean hasMore;
private AsyncTask asyncTask;
private RecyclerView recyclerView;
private List<TaskRow> mUsers = new ArrayList<>();
String userid="3",Response;
static int pageno=1 ,recordsperpage=5;
private ArrayList<HashMap<String, String>> postList=new ArrayList<HashMap<String, String>>();
static boolean errored = false;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
colors = buildColors();

hasMore = true;

recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setAdapter(new MaterialPaletteAdapter(colors, new RecyclerViewOnItemClickListener() {
@Override
public void onClick(View v, int position) {
if (colors.get(position) instanceof TaskRow) {
Toast toast = Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_SHORT);
toast.show();
}
}
}));
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addItemDecoration(new DividerItemDecoration(this));
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (hasMore && !(hasFooter())) {
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
//position starts at 0
if (layoutManager.findLastCompletelyVisibleItemPosition() == layoutManager.getItemCount() - 2) {

/* asyncTask = new BackgroundTask();
Void[] params = null;
asyncTask.execute(params);*/
new GetPostData().execute();
}
}
}
});

}

@Override
protected void onPause() {
super.onPause();
if (asyncTask != null) {
asyncTask.cancel(false);
}
}

private class GetPostData extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
colors.add(new Footer());
recyclerView.getAdapter().notifyItemInserted(colors.size() - 1);
/*pDialog = new ProgressDialog(getActivity());
pDialog.setIndeterminate(true);
pDialog.setMessage("Please Wait...");*/
//pDialog.show();
}
@Override
protected String doInBackground(String... params) {

try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.e(this.getClass().toString(), e.getMessage());
}
return null;
}
protected void onPostExecute(String result) {
//pDialog.dismiss();
//rprogress.setVisibility(View.GONE);
if(pageno <5)
{
int size = colors.size();
colors.remove(size - 1);//removes footer
colors.addAll(buildColors());
recyclerView.getAdapter().notifyItemRangeChanged(size - 1, colors.size() - size);
Toast.makeText(getApplicationContext(), Integer.toString(pageno), Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "No More Post", Toast.LENGTH_LONG).show();
hasMore = false;
}
errored = false;
}
}

private boolean hasFooter() {
return colors.get(colors.size() - 1) instanceof Footer;
}

private ArrayList<Item> buildColors() {
ArrayList<Item> colors = new ArrayList<Item>(13);

Response = SocialWebService.invokeGetPostWS(userid, pageno, recordsperpage, "selectPostData", MainActivity.this);
try {
//JSONObject jsonRootObject = new JSONObject(MainCategory);

//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = new JSONArray(Response);

//Iterate the jsonArray and print the info of JSONObjects
String CityName, PostID,PostTypeID,PostedByID,PostDate,PostImageID,PostContent,Lang,Lat;
String LocationName,FirstName,LastName;
String Picture,ImageFull,UserID,UserName;
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);

CityName=jsonObject.getString("CityName");
PostID=jsonObject.getString("PostID");
PostTypeID=jsonObject.getString("PostTypeID");
PostedByID=jsonObject.getString("PostedByID");
PostDate=jsonObject.getString("PostDate");
PostImageID=jsonObject.getString("PostImageID");
PostContent=jsonObject.getString("PostContent");
Lang=jsonObject.getString("Lang");
Lat=jsonObject.getString("Lat");
LocationName=jsonObject.getString("LocationName");
FirstName=jsonObject.getString("FirstName");
LastName=jsonObject.getString("LastName");
Picture=jsonObject.getString("Picture");
ImageFull=jsonObject.getString("ImageFull");
UserID=jsonObject.getString("UserID");
UserName=jsonObject.getString("UserName");



HashMap<String, String> data=new HashMap<String,String>();
data.put("CityName",CityName);
data.put("PostID",PostID);
data.put("PostTypeID",PostTypeID);
data.put("PostedByID",PostedByID);
data.put("PostDate",PostDate);
data.put("PostImageID",PostImageID);
data.put("PostContent",PostContent);
data.put("Lang",Lang);
data.put("Lat",Lat);
data.put("LocationName",LocationName);
data.put("FirstName",FirstName);
data.put("LastName",LastName);
data.put("Picture",Picture);
data.put("ImageFull",ImageFull);
data.put("UserID",UserID);
data.put("UserName",UserName);

postList.add(data);
}


for(int i=0;i<postList.size();i++)
{
String cityname = postList.get(i).get("CityName");
String postid=postList.get(i).get("PostID");
String posttypeid = postList.get(i).get("PostTypeID");
String postedbyid=postList.get(i).get("PostedByID");
String postdate=postList.get(i).get("PostDate");
String postimageid=postList.get(i).get("PostImageID");
String postcontent=postList.get(i).get("PostContent");
String lang=postList.get(i).get("Lang");
String lat=postList.get(i).get("Lat");
String locationname=postList.get(i).get("LocationName");
String firstname=postList.get(i).get("FirstName");
String lastname=postList.get(i).get("LastName");
String picture=postList.get(i).get("Picture");
String imagefull=postList.get(i).get("ImageFull");
String userid=postList.get(i).get("UserID");
String username=postList.get(i).get("UserName");



colors.add(new TaskRow(cityname, postid,posttypeid,postedbyid,postdate,postimageid,postcontent,lang,lat,locationname,
firstname,lastname,picture,imagefull,userid,username ));


}
pageno++;
} catch (JSONException e) {e.printStackTrace();}
return colors;
}
}


TaskRow.java :

public class TaskRow extends Item{

String cityname,postid, posttypeid, postedbyid, postdate, postimageid,postcontent,lang,lat,locationname,firstname,lastname,
picture, imagefull, userid, username;


public String getCityname() {
return cityname;
}

public void setCityname(String cityname) {
this.cityname = cityname;
}

public String getPostid() {
return postid;
}

public void setPostid(String postid) {
this.postid = postid;
}

public String getPosttypeid() {
return posttypeid;
}

public void setPosttypeid(String posttypeid) {
this.posttypeid = posttypeid;
}

public String getPostedbyid() {
return postedbyid;
}

public void setPostedbyid(String postedbyid) {
this.postedbyid = postedbyid;
}

public String getPostdate() {
return postdate;
}

public void setPostdate(String postdate) {
this.postdate = postdate;
}

public String getPostimageid() {
return postimageid;
}

public void setPostimageid(String postimageid) {
this.postimageid = postimageid;
}

public String getPostcontent() {
return postcontent;
}

public void setPostcontent(String postcontent) {
this.postcontent = postcontent;
}

public String getLang() {
return lang;
}

public void setLang(String lang) {
this.lang = lang;
}

public String getLat() {
return lat;
}

public void setLat(String lat) {
this.lat = lat;
}

public String getLocationname() {
return locationname;
}

public void setLocationname(String locationname) {
this.locationname = locationname;
}

public String getFirstname() {
return firstname;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}

public String getLastname() {
return lastname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}

public String getPicture() {
return picture;
}

public void setPicture(String picture) {
this.picture = picture;
}

public String getImagefull() {
return imagefull;
}

public void setImagefull(String imagefull) {
this.imagefull = imagefull;
}

public String getUserid() {
return userid;
}

public void setUserid(String userid) {
this.userid = userid;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public TaskRow(String cityname, String postid, String posttypeid, String postedbyid, String postdate, String postimageid,
String postcontent, String lang, String lat, String locationname, String firstname, String lastname,
String picture, String imagefull, String userid, String username) {
this.cityname=cityname;
this.postid=postid;
this.posttypeid=posttypeid;
this.postedbyid=postedbyid;
this.postdate=postdate;
this.postimageid=postimageid;
this.postcontent=postcontent;
this.lang=lang;
this.lat=lat;
this.locationname=locationname;
this.firstname=firstname;
this.lastname=lastname;
this.picture=picture;
this.imagefull=imagefull;
this.userid=userid;
this.username=username;


}
}


My Adapter Class :

public class MaterialPaletteAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Item> data;
private RecyclerViewOnItemClickListener recyclerViewOnItemClickListener;

private static final int TYPE_COLOR = 0;
private static final int TYPE_FOOTER = 1;

public MaterialPaletteAdapter(@NonNull List<Item> data, RecyclerViewOnItemClickListener recyclerViewOnItemClickListener) {
this.data = data;
this.recyclerViewOnItemClickListener = recyclerViewOnItemClickListener;
}

@Override
public int getItemViewType(int position) {
if (data.get(position) instanceof TaskRow) {
return TYPE_COLOR;
} else if (data.get(position) instanceof Footer) {
return TYPE_FOOTER;
} else {
throw new RuntimeException("ItemViewType unknown");
}
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_COLOR) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, parent, false);
PaletteViewHolder pvh = new PaletteViewHolder(row, recyclerViewOnItemClickListener);
return pvh;
} else {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.progress_footer, parent, false);
FooterViewHolder vh = new FooterViewHolder(row);
return vh;
}
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof PaletteViewHolder) {
TaskRow taskRow = (TaskRow) data.get(position);

PaletteViewHolder paletteViewHolder = (PaletteViewHolder) holder;
String myString = taskRow.getPicture();
try {
JSONArray arr = new JSONArray(myString);
byte[] myArray = new byte[myString.length()];
for (int k = 0; k < arr.length(); k++) {
myArray[k] = (byte) arr.getInt(k);
}
Bitmap bmp = BitmapFactory.decodeByteArray(myArray, 0, myArray.length);

paletteViewHolder.profilepic.setImageBitmap(bmp);//small user picture
} catch (JSONException e) {
e.printStackTrace();
}

paletteViewHolder.tvpostby.setText(taskRow.getFirstname() + " " + taskRow.getLastname());

String ackwardRipOff = taskRow.getPostdate().replace("/Date(", "").replace(")/", "");
long time = Long.parseLong(ackwardRipOff);
Date d= new Date(time);
paletteViewHolder.tvdatetime.setText(new SimpleDateFormat("dd-MMM-yyyy h:mm a").format(d));

paletteViewHolder.tvlocation.setText(taskRow.getCityname());

if(taskRow.getPosttypeid().equals("2") || taskRow.getPosttypeid().equals("4"))
{
String myString1 = taskRow.getImagefull();
try {
JSONArray arr = new JSONArray(myString1);
byte[] myArray = new byte[myString1.length()];
for (int k = 0; k < arr.length(); k++) {
myArray[k] = (byte) arr.getInt(k);
}
final Bitmap bmp1 = BitmapFactory.decodeByteArray(myArray, 0, myArray.length);

paletteViewHolder.imgpost.setImageBitmap(bmp1);//post picture
paletteViewHolder.imgpost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp1.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
// Intent i=new Intent(getContext(), ImageFull.class);
// i.putExtra("Image",byteArray);
// getContext().startActivity(i);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
paletteViewHolder.imgpost.setVisibility(View.VISIBLE);
}
paletteViewHolder.tvpost_text.setText(taskRow.getPostcontent());
}

}

@Override
public int getItemCount() {
return data.size();
}


public static class PaletteViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
public ImageView profilepic;
public TextView tvpostby;
public TextView tvdatetime;
public TextView tvlocation;
public TextView tvpost_text;
public ImageView imgpost;
public TextView tvlike;
public TextView tvlikelable;
public TextView tvcommentlable;
public TextView tvsharelable;

private RecyclerViewOnItemClickListener recyclerViewOnItemClickListener;


public PaletteViewHolder(View itemView, RecyclerViewOnItemClickListener recyclerViewOnItemClickListener) {
super(itemView);
profilepic=(ImageView)itemView.findViewById(R.id.profile_pic);
tvpostby=(TextView)itemView.findViewById(R.id.tv_postby);
tvdatetime=(TextView)itemView.findViewById(R.id.tv_date_time);
tvlocation=(TextView)itemView.findViewById(R.id.tv_location);
tvpost_text=(TextView)itemView.findViewById(R.id.tvpost_text);
imgpost=(ImageView)itemView.findViewById(R.id.img_post);
tvlike=(TextView)itemView.findViewById(R.id.tv_like);
tvlikelable=(TextView)itemView.findViewById(R.id.tv_like_lable);
tvcommentlable=(TextView)itemView.findViewById(R.id.tv_comment);
tvsharelable=(TextView)itemView.findViewById(R.id.tv_share);
imgpost.setVisibility(itemView.GONE);
this.recyclerViewOnItemClickListener = recyclerViewOnItemClickListener;
itemView.setOnClickListener(this);
}

@Override
public void onClick(View v) {
recyclerViewOnItemClickListener.onClick(v, getAdapterPosition());
}
}

public static class FooterViewHolder extends RecyclerView.ViewHolder {
public ProgressBar getProgressBar() {
return progressBar;
}

private ProgressBar progressBar;

public FooterViewHolder(View itemView) {
super(itemView);
progressBar = (ProgressBar) itemView.findViewById(R.id.footer);
}
}

}


endless recycler view repeating json data, i have incremented page number but first it will give me 5 records then repeating same records before increasing the page number, after increasing page number it will also repeating the same data from the first page number to the last before increasing the page number, i have tried out https://github.com/danielme-com/Android-Endless-RecyclerView this solution, but i dont know where i am making mistake, can anyone help me out? thanks in andvance.

Answer

Just modify your code with below solution. You should clear your array list before adding new items. hope this will help

 protected void onPostExecute(String result) {
        //pDialog.dismiss();
        //rprogress.setVisibility(View.GONE);
        if(pageno <5)
        {
            int size = colors.size();
            colors.remove(size - 1);//removes footer
            colors.clear(); // just clear your array before adding new items to it
            colors.addAll(buildColors());
            recyclerView.getAdapter().notifyItemRangeChanged(size - 1, colors.size() - size);
            Toast.makeText(getApplicationContext(), Integer.toString(pageno), Toast.LENGTH_LONG).show();
        }
        else
        {
            Toast.makeText(getApplicationContext(), "No More Post", Toast.LENGTH_LONG).show();
            hasMore = false;
        }
        errored = false;
    }