我需要从一个在新线程中完成的网站上获取文本。然后我需要将该文本放在列表视图中。 问题是我无法为列表视图设置数组适配器,直到将文本放入该适配器中使用的列表中。列表填写在用于连接到网站的线程中。
我尝试通过在第一个线程运行的新线程中设置适配器来解决这个问题。程序启动时没有错误,但列表视图中没有显示任何内容。
我正在使用此网站http://www.vogella.com/articles/AndroidListView/article.html
中的列表视图代码我是java和android的新手,所以我希望你明白我想做什么:)
继承代码
package com.example.studentservis;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class MainActivity extends Activity {
String s;
List<String> headersList = new ArrayList<String>();
List<String> contentList = new ArrayList<String>();
ListView listview;
StableArrayAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listView1);
threadStart();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void adapterInit()
{
adapter = new StableArrayAdapter(this, android.R.layout.simple_list_item_1, headersList);
listview.setAdapter(adapter);
}
private class StableArrayAdapter extends ArrayAdapter<String>{
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
@Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
@Override
public boolean hasStableIds() {
return true;
}
}
public void threadStart()
{
//txtView.setText(stringHandler.getString());
new Thread(new Runnable() { // thread
public void run(){
try
{
webRequest();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Runnable()
{
@Override
public void run() {
// TODO Auto-generated method stub
adapterInit();
}
};
}
}).start();
}
public void webRequest() throws Exception{
String servisURL = "http://www.sczg.unizg.hr/student-servis/";
Document doc = Jsoup.connect(servisURL).get();
Elements jobNode = doc.select("div.jobBox");
Elements headersNode = jobNode.select("h1");
Elements contentNode = jobNode.select("content");
for(int i = 0; i < headersNode.size(); i++){
headersList.add(headersNode.get(i).text());
}
for(int i = 0; i < contentNode.size(); i++){
contentList.add(contentNode.get(i).text());
}
}
}
答案 0 :(得分:2)
首先,我建议你阅读this guide,特别是关于使用AsyncTask 而不是原始线程。
第二,据我所知,你想从UI线程调用adapterInit? 所以,你可以试试这个:
runOnUiThread( // <-- method from Activity
new Runnable()
{
@Override
public void run() {
// TODO Auto-generated method stub
adapterInit();
}
}
);
答案 1 :(得分:2)
希望这可能对您有用,我在这里使用异步任务代替线程
public class MainActivity extends Activity {
String s;
List<String> headersList = new ArrayList<String>();
List<String> contentList = new ArrayList<String>();
ListView listview;
StableArrayAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listView1);
// threadStart();
// Here i implemented Asynchronous Task instead of Thread
new SampleAsyncTask().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public class SampleAsyncTask extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(
MainActivity.this);
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(false);
this.dialog.show();
}
@Override
protected Void doInBackground(Void... params) {
try {
webRequest();
adapter = new StableArrayAdapter(MainActivity.this,
android.R.layout.simple_list_item_1, headersList);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
// Here if you wish to do future process for ex. move to another
// activity do here
listview.setAdapter(adapter);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
private class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
@Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
@Override
public boolean hasStableIds() {
return true;
}
}
public void webRequest() throws Exception {
String servisURL = "http://www.sczg.unizg.hr/student-servis/";
Document doc = Jsoup.connect(servisURL).get();
Elements jobNode = doc.select("div.jobBox");
Elements headersNode = jobNode.select("h1");
Elements contentNode = jobNode.select("content");
for (int i = 0; i < headersNode.size(); i++) {
headersList.add(headersNode.get(i).text());
}
for (int i = 0; i < contentNode.size(); i++) {
contentList.add(contentNode.get(i).text());
}
}
}
答案 2 :(得分:1)
也许问题是你没有在适配器上调用方法 notifyDataSetChanged()来强制它更新他的信息,这就像通知适配器底层数据已更新并且需要它刷新相关的列表视图。
您应该在从网站上获取数据后调用它。
答案 3 :(得分:1)
您可以使用处理程序。 在webRequest线程中,当webRequest()完成时,使用Handler通知主线程到adapterInit()。不使用webRequest线程中的另一个线程。 一个简单的例子。
@Override
public void onClick(DialogInterface dialog,
int which) {
setControlsEnable(false);
new Thread() {
public void run() {
WebserviceMethod wb = new WebserviceMethod();
if (wb.DeleteEmployee(
VerificationUtils
.GetInstance()
.CreateToken(),
personId) == 1) {
Message msg = new Message();
msg.obj = SwitchActivityValue.SWITCH_DELETEPERSON_OK;
mHandler.sendMessage(msg);
}
}.start();
}
@Override
public void handleMessage(Message msg){
super.handleMessage(msg);
SwitchActivityValue value = (SwitchActivityValue)msg.obj;
switch (value) {
case SWITCH_DELETEPERSON_OK:
ManageUtils.EmployeeListDataForAdmin.personInfos.clear();
ManageUtils.EmployeeListDataForAdmin.currentPage = 0;
mActivity.switchActivity(mValue);
break;
case SWITCH_DELETEPERSON_FAILED:
break;
default:
break;
}
mActivity.showMessage(value);
}
例如,你可以在Handler中绑定数据。当线程完成时,它使用hanlder发送消息来通知handleMessage处理其他人。