Java 如何从后台类在列表视图中添加数据

Java 如何从后台类在列表视图中添加数据,java,android,Java,Android,我得到了这个例外 android.view.ViewRootImpl$CalledFromErrorThreadException:只有创建视图层次结构的原始线程才能接触其视图 代码如下: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_page2);

我得到了这个例外

android.view.ViewRootImpl$CalledFromErrorThreadException:只有创建视图层次结构的原始线程才能接触其视图

代码如下:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_page2);



        lv = (ListView) findViewById(R.id.list_view);



        btnNew = (Button)findViewById(R.id.btnAddNew);
        btnNew.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent moveToNewUser = new Intent(getApplication(),ExecutiveInfo2.class);
                moveToNewUser.putExtra("ClickType","1");
                startActivity(moveToNewUser);
            }
        });

        new Connection2().execute();

        // Listview Data
       }

    private class Connection2 extends AsyncTask {

        @Override
        protected Object doInBackground(Object... arg0) {
            test2();
            return null;
        }

        @Override
        protected void onPostExecute(Object s) {
        super.onPostExecute(s);
      }

    }

    public void test2() {
        HttpURLConnection connection = null;
        try {
            sharedpreferences = getSharedPreferences("MyPrefs", this.MODE_PRIVATE);

             String storedUUID = sharedpreferences.getString("UUID", "");

            String url2= "http://crm.xqicai.com/sales/getExecutiveInfo?UUID="+storedUUID;
            //String url = "http://crm.xqicai.com/sales/login";
            URL postUrl = new URL(url2);

            connection = (HttpURLConnection) postUrl.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);

            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 设置编�,�则中文乱�

            while (true) {
                String str = reader.readLine();
                if (str == null) {
                    break;
                }
                System.out.println(str);

                JSONObject mainObject = new JSONObject(str);
                Status = mainObject.getString("status");
                int j=0;
                if(Status.equals("0"))
                {
                    JSONObject uniObject = mainObject.getJSONObject("data");
                    JSONArray a = uniObject.getJSONArray("data");
                    for (int i = 0; i < a.length(); i++) {

                        JSONObject json_obj = a.getJSONObject(i);


                        String demo = json_obj.getString("realName");
                        fetchedNames[j]= demo;
                        j++;

                    }

                    // Adding items to listview

                    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fetchedNames);

                    lv.setAdapter(adapter);
                    }
                else
                {
                    JSONObject mainObject2 = new JSONObject(str);
                    errorMsg = mainObject2.getString("msg");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
        }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
 }
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u main\u page2);
lv=(ListView)findViewById(R.id.list\u视图);
btnNew=(按钮)findViewById(R.id.btnAddNew);
btnNew.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
Intent moveToNewUser=newintent(getApplication(),executiveInfo.class);
moveToNewUser.putExtra(“点击类型”,“1”);
startActivity(moveToNewUser);
}
});
新连接2().execute();
//列表视图数据
}
私有类连接2扩展了异步任务{
@凌驾
受保护对象doInBackground(对象…arg0){
test2();
返回null;
}
@凌驾
受保护的void onPostExecute(对象s){
super.onPostExecute(s);
}
}
公共无效测试2(){
HttpURLConnection=null;
试一试{
SharedReferences=GetSharedReferences(“MyPrefs”,this.MODE\u PRIVATE);
String storedUUID=SharedReferences.getString(“UUID”,“UUID”);
字符串url2=”http://crm.xqicai.com/sales/getExecutiveInfo?UUID=“+storedUUID;
//字符串url=”http://crm.xqicai.com/sales/login";
URL postrl=新URL(url2);
connection=(HttpURLConnection)postrl.openConnection();
connection.setDoOutput(真);
connection.setDoInput(true);
connection.setRequestMethod(“GET”);
connection.setUseCaches(false);
connection.setInstanceFlowRedirects(true);
setRequestProperty(“内容类型”、“应用程序/json”);
connection.connect();
BufferedReader=新的BufferedReader(新的InputStreamReader(connection.getInputStream(),“utf-8”);//ê¾ç½ç¼–ç�,å�¦åˆ™ä¸­æ–‡ä¹±ç �
while(true){
String str=reader.readLine();
如果(str==null){
打破
}
系统输出打印项次(str);
JSONObject mainObject=新的JSONObject(str);
Status=mainObject.getString(“Status”);
int j=0;
如果(状态等于(“0”))
{
JSONObject uniObject=mainObject.getJSONObject(“数据”);
JSONArray a=uniObject.getJSONArray(“数据”);
对于(int i=0;i

我只是一个初学者,所以请原谅我问了一个可能很愚蠢的问题。

哪一行给出了错误?问题在于,您更新了在主线程中创建的视图,即AsyncTask(另一个线程)中的视图。您应该在AsyncTask的onPostExecute中更新此视图(这是在主线程中完成的)。我看不到您立即更新视图的位置

编辑: 如果你把这两条线放在一起,你的问题就应该解决了

adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fetchedNames);
lv.setAdapter(adapter);
或在:

protected void onPostExecute(Object s)
测试:

    ListView lv...
    lv.post(new Runnable() {
        @Override
        public void run() {
            //Update UI;
            lv.setAdapter(...);
        }
    })

您可以尝试在asynctask内使用带有sendEmptyMessage()的处理程序通过异常传递

Handler mHandler=新处理程序(Looper.getMainLooper()){
@凌驾
公共无效handleMessage(消息输入消息){
//向listview添加项目
adapter=new ArrayAdapter(这是android.R.layout.simple\u list\u item\u 1,fetchedNames);
低压设置适配器(适配器);
}
});
以下代码的注释:

//在asynctask中调用mHandler.sendEmpyMessage():

if(Status.equals("0"))
                {
                    JSONObject uniObject = mainObject.getJSONObject("data");
                    JSONArray a = uniObject.getJSONArray("data");
                    for (int i = 0; i < a.length(); i++) {

                        JSONObject json_obj = a.getJSONObject(i);


                        String demo = json_obj.getString("realName");
                        fetchedNames[j]= demo;
                        j++;

                    }

                    // Adding items to listview
                    mHandler.sendEmpyMessage(0); //0 or any number is identify code from you want use to check with every action
if(Status.equals(“0”))
{
JSONObject uniObject=mainObject.getJSONObject(“数据”);
JSONArray a=uniObject.getJSONArray(“数据”);
对于(int i=0;i
您需要调用runOnUIThread()方法来从后台线程更新listview中的数据。您也尝试过,但无法处理.adapter的可能副本=新的ArrayAdapter(这个,android.R.layout.simple_列表_项_1,fetchedNames);lv.setAdapter(适配器);因此,您创建了'lv=(listview
Handler mHandler = new Handler(Looper.getMainLooper()) {
                @Override
                public void handleMessage(Message inputMessage) {

                    // Adding items to listview

                    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fetchedNames);

                    lv.setAdapter(adapter);   
                }
});
if(Status.equals("0"))
                {
                    JSONObject uniObject = mainObject.getJSONObject("data");
                    JSONArray a = uniObject.getJSONArray("data");
                    for (int i = 0; i < a.length(); i++) {

                        JSONObject json_obj = a.getJSONObject(i);


                        String demo = json_obj.getString("realName");
                        fetchedNames[j]= demo;
                        j++;

                    }

                    // Adding items to listview
                    mHandler.sendEmpyMessage(0); //0 or any number is identify code from you want use to check with every action