为啥我在 listView 中得到最后一个标题? [关闭]
Posted
技术标签:
【中文标题】为啥我在 listView 中得到最后一个标题? [关闭]【英文标题】:why I am getting the last title in my listView? [closed]为什么我在 listView 中得到最后一个标题? [关闭] 【发布时间】:2020-10-19 13:43:45 【问题描述】:public class MainActivity extends AppCompatActivity
ListView aboutNews;
ArrayList<String> newscontent;
public void DisplayNews(String title)
aboutNews = findViewById(R.id.aboutNews);
newscontent = new ArrayList<String>();
newscontent.add(title);
ArrayAdapter<String> myArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,newscontent);
aboutNews.setAdapter(myArrayAdapter);
public class downloadTask extends AsyncTask<String , Void , String>
@Override
protected String doInBackground(String... urls)
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data!=-1)
char current = (char) data;
result += current;
data = reader.read();
return result;
catch (Exception e)
e.printStackTrace();
return null;
@Override
protected void onPostExecute(String s)
super.onPostExecute(s);
try
JSONObject jsonObject = new JSONObject(s);
String news = jsonObject.getString("articles");
JSONArray arr = new JSONArray(news);
for(int i = 0;i<arr.length();i++)
JSONObject jsonPart = arr.getJSONObject(i);
// Log.i("title",jsonPart.getString("title"));
//Log.i("description",jsonPart.getString("description"));
// Log.i("Image_url",jsonPart.getString("urlToImage"));
// Log.i("published at",jsonPart.getString("publishedAt"));
// Log.i("content",jsonPart.getString("content"));
String title = jsonPart.getString("title");
String description = jsonPart.getString("description");
String urlToImage = jsonPart.getString("urlToImage");
String publish = jsonPart.getString("publishedAt");
String content = jsonPart.getString("content");
Log.i("title",title);
DisplayNews(title);
catch (Exception e)
e.printStackTrace();
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downloadTask task = new downloadTask();
try
task.execute("https://newsapi.org/v2/top-headlines?country=in&apiKey=065e210edf9d43469ed4614ec90c07f7");
catch(Exception e)
e.printStackTrace();
【问题讨论】:
【参考方案1】:因为您每次调用 DisplayNews()
函数时都会重新初始化 ArrayList。
newscontent = new ArrayList<String>();
从 DisplayNews 函数中删除此行并将其添加到 onCreate
方法或其他仅初始化一次的位置。
【讨论】:
非常感谢..它真的帮助了我。以上是关于为啥我在 listView 中得到最后一个标题? [关闭]的主要内容,如果未能解决你的问题,请参考以下文章
ListView 总是从 CustomAdaptor 中删除最后一行
为啥当我在选中 CheckBox 的情况下滚动 ListView 时,它会变为未选中状态?
为啥我在保存 managedObjectContext 时得到 nilError? [复制]