列表中的最后一个项目<对象>在RecyclerView项目的特定文本视图中重复 [英] Last Item in List<Object> is repeated in a specific textview of RecyclerView item

查看:252
本文介绍了列表中的最后一个项目<对象>在RecyclerView项目的特定文本视图中重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Object类( public static List< Restaurant> res; )来设置我从服务器获取json数据的数据。应用程序的流程如下。



步骤1:(MainActivity.class)



从服务器获取数据



步骤2:



Json数据转换为 List< Object> 类。并在MainActivity

中声明为 List< Object> 作为 public static



步骤3:



这里我需要将 List< Object> 类值填入Recyclerview。由于声明为公共静态,所以我直接调用这个方法,在适配器中设置一个MainActivity作为父级的片段。

  adapter = new CardAdapter(MainActivity.res,context); 
recyclelerView.setAdapter(adapter);
adapter.notifyDataSetChanged();

但问题是在填充RecyclerView时,我只得到最后一个项目被重复直到 列表<餐厅> 大小



MainActivity(AsyncTask方法):

  private class TabNameSync extends AsyncTask< Void,Void,String> {
String BASE_URL = Config.DATA_URL;
ProgressDialog nDialog;
HashMap< String,String> hashMapPost = new HashMap<>();

@Override
protected void onPreExecute(){
nDialog = new ProgressDialog(MainActivity.this);
nDialog.setMessage(Loading ...);
nDialog.setIndeterminate(true);
nDialog.setCancelable(true);
nDialog.show();
}

@Override

protected String doInBackground(Void ... params){

HttpURLConnection con = null;
InputStream is = null;

StringBuffer buffer;
String bufferVariable = null;

hashMapPost.put(tag,onload);
hashMapPost.put(lat,18.71851808);
hashMapPost.put(log,97.74131474);

try {
con =(HttpURLConnection)(new URL(BASE_URL))。openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestMethod(POST);
con.connect();
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os,UTF-8));
writer.write(commonUtil.getPostDataString(hashMapPost));

writer.flush();
writer.close();
os.close();

buffer = new StringBuffer();
int responseCode = con.getResponseCode();
if(responseCode == HttpsURLConnection.HTTP_OK){
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
字符串;
while((line = br.readLine())!= null)
buffer.append(line).append(\r\\\
);
is.close();
}
con.disconnect();
bufferVariable = buffer.toString();
return buffer.toString();
} catch(Throwable t){
t.printStackTrace();
} finally {
try {
if(is!= null){
is.close();
}
} catch(Throwable t){
}
try {
if(con!= null){
con.disconnect();
}
} catch(Throwable t){
}
if(!bufferVariable.equalsIgnoreCase()){
try {

JSONArray jArray = new JSONArray(bufferVariable);
int jsonLength = jArray.length(); (int j = 0; j< jArray.length(); j ++){

Restaurant_Beam item;


JSONObject jsonObj = jArray.getJSONObject(j);
item = new Restaurant_Beam();
item.setIG_LIKECOUNT(jsonObj.getInt(Config.LIKE));
item.setIG_DELIVERY(jsonObj.getInt(Config.DELIVERYTIME));
item.setIG_PRODUCTID(jsonObj.getString(Config.PRODUCTID));
item.setIG_SALES_PRICE(jsonObj.getString(Config.SALESPRICE));
item.setIG_VOUCHER_ID(jsonObj.getString(Config.VOUCHERID));
item.setIG_VOUCHEROFFER(jsonObj.getString(Config.VOUCHEROFFER));
item.setIG_CATEGORY_ID(jsonObj.getString(Config.CATEID));
item.setIG_IMAGEURL(jsonObj.getString(Config.IMGID));
item.setIG_PRODUCTNAME(jsonObj.getString(Config.PRODUCTNAME));
item.setIG_CATEGORYNAME(jsonObj.getString(Config.CATENAME));

Restaurant.add(item);

listSuperHeroes =餐厅;

strTabName = jsonObj.getString(Cate Name);
String strProductID = jsonObj.getString(Pro_Id);
String strProductName = jsonObj.getString(Product_Name);
String strSalesPrice = jsonObj.getString(Sales Price);
String strVoucherId = jsonObj.getString(Voucher Id);
String strVoucherOffer = jsonObj.getString(voucher Offer);
String strCatId = jsonObj.getString(Cat Id);
String strImage = jsonObj.getString(Image);
String strLikes = jsonObj.getString(likes);
String strDeliveryTime = jsonObj.getString(deliverytime);
strDbName = jsonObj.getString(dbname)


tabName.add(strTabName);

DbName.add(strDbName);

if(jsonLength == jArray.length()){
JSONObject jsonObj2 = jArray.getJSONObject(jsonLength - 1);
Config.IMAGE_URL = jsonObj2.getString(url);
}
}


} catch(JSONException e){
e.printStackTrace();
}
}
}
返回null;
}

@Override
protected void onPostExecute(String result){
super.onPostExecute(result);

final TabLayout tabLayout =(TabLayout)findViewById(R.id.tabs);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

values = new ArrayList< String>();
values = tabName;
HashSet< String> hashSet = new HashSet< String>();
hashSet.addAll(values);
values.clear();
values.addAll(hashSet);

nDialog.dismiss();

// setTime_ToSlide();
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
tabLayout.post(new Runnable(){
@Override
public void run(){
tabLayout.setupWithViewPager(viewPager);
}
} );
SharedPreferences.Editor editor = pref.edit();
editor.putString(FIRST_TAB,values.get(1));
editor.putString(SECOND_TAB,values.get(0));
editor.putString(THIRD_TAB,values.get(2));
editor.commit();

}
}



这里只重复RED舍入的数据,其他数据与正确的数据相关。 / strong>



我也发贴了我的代码。请检查。

解决方案

自己修复错误。我已经改变的是我将每个变量( Product Name,CategoryName )设置为 List< Object> class中的public static String。 p>

删除静态后,我得到了确切的结果。我的 RecyclerView 被改编为完美的。

而不是

  public static String ProductName; 

使用此

 code> public String ProductName; 


I am using Object class( public static List<Restaurant> res;) to set data that I am getting json data from server. The flow of the app is as follow.

Step 1: (MainActivity.class)

Getting data from server

Step 2:

Set all the Json data into List<Object> class. And declared List<Object> as a public static in MainActivity

Step 3:

Here I need to populate List<Object> class values into the Recyclerview.Due to declared as public static, I called this directly while setting in adapter in a fragment which has a MainActivity as a parent.

  adapter = new CardAdapter(MainActivity.res, context);
  recyclerView.setAdapter(adapter);
  adapter.notifyDataSetChanged();

But the issue is that while populating RecyclerView,I am getting only the last Item is repeated upto the List<Restaurant> size.

MainActivity (AsyncTask Method):

 private class TabNameSync extends AsyncTask<Void, Void, String> {
        String BASE_URL = Config.DATA_URL;
        ProgressDialog nDialog;
        HashMap<String, String> hashMapPost = new HashMap<>();

        @Override
        protected void onPreExecute() {
            nDialog = new ProgressDialog(MainActivity.this);
            nDialog.setMessage("Loading...");
            nDialog.setIndeterminate(true);
            nDialog.setCancelable(true);
            nDialog.show();
        }

        @Override

        protected String doInBackground(Void... params) {

            HttpURLConnection con = null;
            InputStream is = null;

            StringBuffer buffer;
            String bufferVariable = null;

            hashMapPost.put("tag", "onload");
            hashMapPost.put("lat", "18.71851808");
            hashMapPost.put("log", "97.74131474");

            try {
                con = (HttpURLConnection) (new URL(BASE_URL)).openConnection();
                con.setDoInput(true);
                con.setDoOutput(true);
                con.setRequestMethod("POST");
                con.connect();
                OutputStream os = con.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(commonUtil.getPostDataString(hashMapPost));

                writer.flush();
                writer.close();
                os.close();

                buffer = new StringBuffer();
                int responseCode = con.getResponseCode();
                if (responseCode == HttpsURLConnection.HTTP_OK) {
                    is = con.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String line;
                    while ((line = br.readLine()) != null)
                        buffer.append(line).append("\r\n");
                    is.close();
                }
                con.disconnect();
                bufferVariable = buffer.toString();
                return buffer.toString();
            } catch (Throwable t) {
                t.printStackTrace();
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (Throwable t) {
                }
                try {
                    if (con != null) {
                        con.disconnect();
                    }
                } catch (Throwable t) {
                }
                if (!bufferVariable.equalsIgnoreCase(" ")) {
                    try {

                        JSONArray jArray = new JSONArray(bufferVariable);
                        int jsonLength = jArray.length();

                        for (int j = 0; j < jArray.length(); j++) {

                            Restaurant_Beam item;
                            JSONObject jsonObj = jArray.getJSONObject(j);
                            item = new Restaurant_Beam();
                            item.setIG_LIKECOUNT(jsonObj.getInt(Config.LIKE));
                            item.setIG_DELIVERY(jsonObj.getInt(Config.DELIVERYTIME));
                            item.setIG_PRODUCTID(jsonObj.getString(Config.PRODUCTID));
                            item.setIG_SALES_PRICE(jsonObj.getString(Config.SALESPRICE));
                            item.setIG_VOUCHER_ID(jsonObj.getString(Config.VOUCHERID));
                            item.setIG_VOUCHEROFFER(jsonObj.getString(Config.VOUCHEROFFER));
                            item.setIG_CATEGORY_ID(jsonObj.getString(Config.CATEID));
                            item.setIG_IMAGEURL(jsonObj.getString(Config.IMGID));
                            item.setIG_PRODUCTNAME(jsonObj.getString(Config.PRODUCTNAME));
                            item.setIG_CATEGORYNAME(jsonObj.getString(Config.CATENAME));

                            Restaurant.add(item);

                            listSuperHeroes = Restaurant;

                            strTabName = jsonObj.getString("Cate Name");
                            String strProductID = jsonObj.getString("Pro_Id");
                            String strProductName = jsonObj.getString("Product_Name");
                            String strSalesPrice = jsonObj.getString("Sales Price");
                            String strVoucherId = jsonObj.getString("Voucher Id");
                            String strVoucherOffer = jsonObj.getString("voucher Offer");
                            String strCatId = jsonObj.getString("Cat Id");
                            String strImage = jsonObj.getString("Image");
                            String strLikes = jsonObj.getString("likes");
                            String strDeliveryTime = jsonObj.getString("deliverytime");
                            strDbName = jsonObj.getString("dbname");


                            tabName.add(strTabName);

                            DbName.add(strDbName);

                            if (jsonLength == jArray.length()) {
                                JSONObject jsonObj2 = jArray.getJSONObject(jsonLength - 1);
                                Config.IMAGE_URL = jsonObj2.getString("url");
                            }
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
            tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

            values = new ArrayList<String>();
            values = tabName;
            HashSet<String> hashSet = new HashSet<String>();
            hashSet.addAll(values);
            values.clear();
            values.addAll(hashSet);

            nDialog.dismiss();

            //    setTime_ToSlide();
            viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
            tabLayout.post(new Runnable() {
                @Override
                public void run() {
                    tabLayout.setupWithViewPager(viewPager);
                }
            });
            SharedPreferences.Editor editor = pref.edit();
            editor.putString("FIRST_TAB", values.get(1));
            editor.putString("SECOND_TAB", values.get(0));
            editor.putString("THIRD_TAB", values.get(2));
            editor.commit();

        }
    }

Here only the RED rounderd data is repeated and the other data are relevant to the correct data.

I have posted my code too.Please check it.

解决方案

Fixed bug by myself. What I have changed is that I had set every variable(Product Name,CategoryName) as public static String in List<Object> class.

After removing static I got the exact result.My RecyclerView is adapted as perfect.Like the following

Instead of

public static String ProductName;

use this

public String ProductName;

这篇关于列表中的最后一个项目&lt;对象&gt;在RecyclerView项目的特定文本视图中重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆