将数据添加到从服务器获取的 Recycleview 时出错
Posted
技术标签:
【中文标题】将数据添加到从服务器获取的 Recycleview 时出错【英文标题】:Error in Adding data into Recycleview which are fetched from server 【发布时间】:2018-07-14 12:19:37 【问题描述】:我正在尝试从服务器获取字符串(用户名),想将其放入 Recycle。为此,我使用 JSON 获取数据并使用 Asynctask 生成新线程。我成功从服务器获取用户名但未能将它们放入在回收审查中。
这是我的 Mainactivity.java
public class MainActivity extends AppCompatActivity
BufferedReader reader;
private String content;
RecyclerView recyclerView;
Adapter madapter;
List<String> data = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ApiAsyncTask().execute();
private class ApiAsyncTask extends AsyncTask<Void, Void, Void>
@Override
protected Void doInBackground(Void... voids)
getData();
return null;
@Override
protected void onPostExecute(Void aVoid)
super.onPostExecute(aVoid);
recyclerView=(RecyclerView)findViewById(R.id.rv123);
recyclerView.setLayoutManager(new LinearLayoutManager());
data.add("name");
Dataadapter madapter = new Dataadapter(data);
recyclerView.setAdapter(madapter);
private void getData()
try
URL url = new URL("https://jsonplaceholder.typicode.com/comments");
URLConnection conn = url.openConnection();
conn.setDoOutput(false);
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
// Append server response in string
sb.append(line + " ");
// Append Server Response To Content String
content = sb.toString();
Log.e("TAG", "Response is -> " + content);
JSONArray jsonArray = new JSONArray(content);
for(int i=0;i<=4;i++)
JSONObject jsonObject=jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
Log.e("TAG", "Username is -> " + name);
catch (MalformedURLException e)
e.printStackTrace();
catch (IOException e)
e.printStackTrace();
catch (JSONException e)
e.printStackTrace();
这是我的适配器
public class Dataadapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
public TextView textView;
private List<String> data;
public Dataadapter(List<String> data)
this.data = data;
public class MyViewHolder extends RecyclerView.ViewHolder
public MyViewHolder(View itemView)
super(itemView);
textView = itemView.findViewById(R.id.tv);
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View dataView = layoutInflater.inflate(R.layout.container, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(dataView);
return myViewHolder;
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position)
textView.setText(data.get(position));
@Override
public int getItemCount()
return data.size();
使用 2 个 XML 文件。一个是 Mainactivity.xml,另一个是 Container.xml。请帮助我了解如何将用户名(我从服务器获取)显示到 recycleview。现在,当我运行应用程序时,它只是仅显示布局。在该布局中没有获得任何用户名。但在我的日志中,我可以看到用户名。谢谢
【问题讨论】:
在 getDate() 方法中,您只打印要记录的名称,而不是将它们添加到您的列表中 请发送正确的代码先生。另外,想知道我应该在 recyclerView.setLayoutManager(new LinearLayoutManager());谢谢你 【参考方案1】:只需将对象添加到您的列表中
for(int i=0;i<=4;i++)
JSONObject jsonObject=jsonArray.getJSONObject(i);
data.add(jsonObject.getString("name"));
LinearLayoutManager 构造函数采用一个参数,一个 Context。
在您的 onPostExecute 中,执行此操作 -
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
【讨论】:
【参考方案2】:试试这段代码,我测试过了,它可以工作了。
这里是 MainActivity.java
public class MainActivity extends AppCompatActivity
private static final String TAG = MainActivity.class.getSimpleName();
BufferedReader reader;
RecyclerView recyclerView;
Dataadapter madapter;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rv123);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
madapter = new Dataadapter();
recyclerView.setAdapter(madapter);
new ApiAsyncTask().execute();
private class ApiAsyncTask extends AsyncTask<Void, Void, List<String>>
@Override
protected List<String> doInBackground(Void... voids)
return getData();
@Override
protected void onPostExecute(List<String> names)
madapter.updateData(names);
private List<String> getData()
List<String> data = new ArrayList<>();
try
URL url = new URL("https://jsonplaceholder.typicode.com/comments");
URLConnection conn = url.openConnection();
conn.setDoOutput(false);
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
// Append server response in string
sb.append(line);
// Append Server Response To Content String
String content = sb.toString();
Log.e("TAG", "Response is -> " + content);
JSONArray jsonArray = new JSONArray(content);
for (int i = 0; i < 50; i++)
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
Log.e("TAG", "Username is -> " + name);
data.add(name);
catch (MalformedURLException e)
e.printStackTrace();
catch (IOException e)
e.printStackTrace();
catch (JSONException e)
e.printStackTrace();
Log.d(TAG, "getData: " + data.size());
return data;
这里是 Dataadapter.java
public class Dataadapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
public TextView textView;
private List<String> data;
public Dataadapter()
data = new ArrayList<>();
public class MyViewHolder extends RecyclerView.ViewHolder
public MyViewHolder(View itemView)
super(itemView);
textView = itemView.findViewById(R.id.tv);
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View dataView = layoutInflater.inflate(R.layout.container, parent, false);
return new MyViewHolder(dataView);
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position)
textView.setText(data.get(position));
@Override
public int getItemCount()
return data.size();
public void updateData(List<String> data)
this.data = data;
notifyDataSetChanged();
从 API 端点返回的数据包含 500 项,我使用 50 代替以加快加载速度。
【讨论】:
【参考方案3】:您不应该将 holder 的 textView 作为适配器的局部变量并在 holder 的构造函数上赋值。由于ViewHolder
可能会被重用并解析为Adapter.onBindViewHolder()
,然后onBindViewHolder()
方法中使用的textView 不是holder 中的textView(未调用ViewHolder
构造函数)。您可以将 textView 作为MyViewHolder
的变量并使用holder.getTextView().setText(item)
设置文本。
【讨论】:
以上是关于将数据添加到从服务器获取的 Recycleview 时出错的主要内容,如果未能解决你的问题,请参考以下文章
我的 Apache 反向代理将代码添加到从 head 标记获取的 HTML 文件的正文中