线程和可运行的错误

时间:2012-06-04 04:47:47

标签: android multithreading runnable

这里我如何调用线程...我认为错误也来自这里

 private void retrieveDataFromServer(String term){

    nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("text1",term));
    Thread thread =  new Thread(null, ChkSuggestionListConn);
    thread.start();
}

 //check internet connection

        private boolean chkConnectionStatus(){

        ConnectivityManager connMgr = (ConnectivityManager)
        this.getSystemService(Context.CONNECTIVITY_SERVICE);

        final android.net.NetworkInfo wifi =
        connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        final android.net.NetworkInfo mobile =
        connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if( wifi.isAvailable() ){     
          return true;
         }
         else if( mobile.isAvailable() ){     
              return true;        
         }
         else
         { 
             //Toast.makeText(this, "Kindly check your internet" , Toast.LENGTH_LONG).show();
             startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
             return false;
         }
    }
    private Runnable ChkUserPassConn = new Runnable(){
        @Override
    public void run() {
        //Set flag so we cant load new items 2 at the same time
        //ChkItemsConn = true;
            if(chkConnectionStatus()==true){

                name_str = username_edt.getText().toString();
                pass_str = password_edt.getText().toString();
                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("user",name_str));
                nameValuePairs.add(new BasicNameValuePair("pass",pass_str));
                try{
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http link");
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost); 
                    HttpEntity entity = response.getEntity();
                    InputStream is = entity.getContent();


                    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    is.close();

                    result_str=sb.toString();


                }
                catch(Exception e){
                    Log.e("log_tag", "Error converting result "+e.toString());
                    Toast.makeText(search_name.this, "Error : Internet Problem", Toast.LENGTH_LONG).show();
                }


            }else if(chkConnectionStatus()==false){

            }
        //Done! now continue on the UI thread
        runOnUiThread(returnRes0);
        }
    };  

    private Runnable returnRes0 = new Runnable() {
    @Override
    public void run() {
        if (result_str.equals("")==false){
            //Toast.makeText(ShaketimamaActivity.this,result,Toast.LENGTH_SHORT).show();
            //String userid2 = name;
            ProgressDialog progress = new ProgressDialog(search_name.this);
            progress.setMessage("Loading...please wait..");
            progress.setTitle("SmartShopaholic");
            new MyTask(progress).execute();
            Intent intent2 = new Intent(getApplicationContext(), mainpage.class);
            intent2.putExtra("userid",result_str.trim());
            startActivity(intent2);
        }else{
            Toast.makeText(search_name.this,"Failed login!",Toast.LENGTH_SHORT).show();
        }
        }
    };
    private Runnable ChkFavListConn = new Runnable(){
        @Override
    public void run() {
        //Set flag so we cant load new items 2 at the same time
        //ChkItemsConn = true;
            if(userid.equals("")){
                ProgressDialog progressA = new ProgressDialog(search_name.this);
                progressA.setMessage("Loading...please wait..");
                progressA.setTitle("SmartShopaholic");
                new MyTask(progressA).execute();
                Intent intent = new Intent(getApplicationContext(), register.class);
                startActivity(intent);
            }else{
                ArrayList<NameValuePair> passvalue = new ArrayList<NameValuePair>();
                passvalue.add(new BasicNameValuePair("userid",userid.trim()));
                try{
                    HttpClient client = new DefaultHttpClient();
                    HttpPost post = new HttpPost("http link");
                    post.setEntity(new UrlEncodedFormEntity(passvalue));
                    HttpResponse HRes = client.execute(post); 
                    HttpEntity HEn = HRes.getEntity();
                    InputStream stream = HEn.getContent();

                    BufferedReader BRead = new BufferedReader(new InputStreamReader(stream,"iso-8859-1"),8);
                    StringBuilder SBuilder = new StringBuilder();
                    String getline = null;
                    while ((getline = BRead.readLine()) != null) {
                        SBuilder.append(getline + "\n");
                    }
                    stream.close();
                    System.out.println("dsa");
                    answer2=SBuilder.toString().trim();             
                }
                catch(Exception e){
                    Log.e("log_tag", "Error converting result "+e.toString());
                }

            }
        //Done! now continue on the UI thread
        runOnUiThread(returnRes2);
        }
    };  

    private Runnable returnRes2 = new Runnable() {
        @Override
        public void run() {
            if(answer2.equals("yes")){
                ProgressDialog progressA = new ProgressDialog(search_name.this);
                progressA.setMessage("Loading...please wait..");
                progressA.setTitle("SmartShopaholic");
                new MyTask(progressA).execute();
                Intent intent1 = new Intent(getApplicationContext(), favoritelist.class);
                intent1.putExtra("userid",userid);
                startActivity(intent1); 
            }else{
                ProgressDialog progress = new ProgressDialog(search_name.this);
                progress.setMessage("Loading...please wait..");
                progress.setTitle("SmartShopaholic");
                new MyTask(progress).execute();
                Intent intent = new Intent(getApplicationContext(), noresult.class);                    
                startActivity(intent);
            }
            }
        };
        private Runnable ChkSearchListConn = new Runnable(){
            @Override
        public void run() {
            //Set flag so we cant load new items 2 at the same time
            //ChkItemsConn = true;
                if(chkConnectionStatus()==true){
                    name = getname.getText().toString();

                    if((name.equals(""))){

                        Toast.makeText(search_name.this, "Blank Field..Please Enter", Toast.LENGTH_LONG).show();
                    }else{
                        ArrayList<NameValuePair> passvalue = new ArrayList<NameValuePair>();
                         passvalue.add(new BasicNameValuePair("choose","pName"));
                         passvalue.add(new BasicNameValuePair("text1",name));
                            try{
                                HttpClient client = new DefaultHttpClient();
                                HttpPost post = new HttpPost("http link");
                                post.setEntity(new UrlEncodedFormEntity(passvalue));
                                HttpResponse HRes = client.execute(post); 
                                HttpEntity HEn = HRes.getEntity();
                                InputStream stream = HEn.getContent();


                                BufferedReader BRead = new BufferedReader(new InputStreamReader(stream,"iso-8859-1"),8);
                                StringBuilder SBuilder = new StringBuilder();
                                String getline = null;
                                while ((getline = BRead.readLine()) != null) {
                                    SBuilder.append(getline + "\n");
                                }
                                stream.close();
                                System.out.println("dsa");
                                answer=SBuilder.toString().trim();              
                            }
                            catch(Exception e){
                                Log.e("log_tag", "Error converting result "+e.toString());
                            }

                    }
                }else{

                }
            //Done! now continue on the UI thread
            runOnUiThread(returnRes3);
            }
        };  

        private Runnable returnRes3 = new Runnable() {
            @Override
            public void run() {
                if(answer.equals("yes")){
                    ProgressDialog progress = new ProgressDialog(search_name.this);
                    progress.setMessage("Loading...please wait..");
                    progress.setTitle("SmartShopaholic");
                    new MyTask(progress).execute();
                    Intent intent = new Intent(getApplicationContext(), name_result.class);
                    System.out.println("userid="+userid+",productname="+name);
                    intent.putExtra("productname",name);
                    intent.putExtra("userid", userid);

                    startActivity(intent);
                }else{
                    ProgressDialog progress = new ProgressDialog(search_name.this);
                    progress.setMessage("Loading...please wait..");
                    progress.setTitle("SmartShopaholic");
                    new MyTask(progress).execute();
                    Intent intent = new Intent(getApplicationContext(), noresult.class);                    
                    startActivity(intent);
                }
                }
            };
            private Runnable ChkSuggestionListConn = new Runnable(){
                @Override
            public void run() {
                //Set flag so we cant load new items 2 at the same time
                //ChkItemsConn = true;
                    //System.out.println(number);
                    //http post
                    try{
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost("http link");
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost); 
                        HttpEntity entity = response.getEntity();
                        InputStream is = entity.getContent();

                        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line + "\n");
                        }
                        is.close();
                        result=sb.toString();
                    }
                    catch(Exception e){
                        Log.e("log_tag", "Error converting result "+e.toString());
                       // Toast.makeText(SearchResult.this, "Error : Internet Problem", Toast.LENGTH_LONG).show();
                    }
                    //parse json data
                    try{
                        JSONArray jArray = new JSONArray(result);
                        myBooks = new ArrayList<HashMap<String,Object>>();
                            HashMap<String, Object> hm;
                          //System.out.println(result);  
                            //With the help of HashMap add Key, Values of Book, like name,price and icon path 
                            JSONObject json_data;
                        String[]slist=new String[jArray.length()];    
                        String nameproduct=null;
                        for(int i=0;i<jArray.length();i++){
                            json_data = jArray.getJSONObject(i);
                            nameproduct=json_data.getString("pName");
                            slist[i]=nameproduct;
                        }
                        Set<Object> uniqueSet = new HashSet<Object>(Arrays.asList(slist));
                        Object[] unique = uniqueSet.toArray();
                        for(int i=0;i<unique.length;i++){
                            hm = new HashMap<String, Object>();
                            hm.put(searchTerm, unique[i]);
                            hm.put(picpic, R.drawable.ic_search);
                            myBooks.add(hm);
                            json_data=null;
                        }  
                    }catch(Exception e){
                        listView.setVisibility(View.GONE);       
                    }
                //Done! now continue on the UI thread
                runOnUiThread(returnRes4);
                }
            };  

            private Runnable returnRes4 = new Runnable() {
                @Override
                public void run() {
                    SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(), myBooks, R.layout.autocomplete_listbox, 
                            new String[]{picpic,searchTerm}, new int[]{R.id.image1,R.id.text1});    
                            listView.setAdapter(adapter);
                            listView.setVisibility(View.VISIBLE);
                            listView.setTextFilterEnabled(true);
                    listView.setOnItemClickListener(new OnItemClickListener() {
                        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
                            String selection = listView.getItemAtPosition(position).toString();
                            //Example selection:{ companyName=ckwai1990, pname=dsa, pID=P000000005, price=RM 1230.00 } 
                            int begin=selection.indexOf("searchTerm=");  
                            int end=selection.length()-1;
                            String productID=selection.substring(begin+11,end);
                            getname.setText(productID);
                            listView.setVisibility(View.GONE);
                            }
                        });
                    }
                };

这是我的错误日志

06-04 12:26:51.331: E/AndroidRuntime(12711): FATAL EXCEPTION: Thread-17
06-04 12:26:51.331: E/AndroidRuntime(12711): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.view.ViewRoot.checkThread(ViewRoot.java:3022)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.view.ViewRoot.requestLayout(ViewRoot.java:635)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.view.View.requestLayout(View.java:8320)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.view.View.requestLayout(View.java:8320)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.view.View.requestLayout(View.java:8320)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.view.View.requestLayout(View.java:8320)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:257)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.view.View.requestLayout(View.java:8320)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:257)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.view.View.requestLayout(View.java:8320)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.view.View.requestLayout(View.java:8320)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.view.View.requestLayout(View.java:8320)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.view.View.requestLayout(View.java:8320)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.view.View.requestLayout(View.java:8320)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.view.View.requestLayout(View.java:8320)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.view.View.requestLayout(View.java:8320)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.widget.TableLayout.requestLayout(TableLayout.java:226)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.view.View.requestLayout(View.java:8320)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.view.View.requestLayout(View.java:8320)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.widget.AbsListView.requestLayout(AbsListView.java:1202)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.view.View.setFlags(View.java:4694)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at android.view.View.setVisibility(View.java:3169)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at com.skyhaw.search_name$7.run(search_name.java:789)
06-04 12:26:51.331: E/AndroidRuntime(12711):    at java.lang.Thread.run(Thread.java:1019)

上面给出的错误,因为我在线程方法中使用ListView进行更改,如下所示是致命错误部分:

        private Runnable ChkSuggestionListConn = new Runnable(){
            @Override
        public void run() {
        try{
        ... here is get my http link connection
        }(Exception e){
        Log.e("log_tag", "Error converting result "+e.toString());
        }
        try{
        ... here is get my http result and put it into array
        }(Exception e){
         listView.setVisibility(View.GONE);
         //so the problem at here
        }

这里给出了我通过句柄方法解决的解决方案

        public void handleMessage(Message msg) {
        super.handleMessage(msg);

        if(msg.what == EMPTY_RESULT){
            System.out.println("handleMsg EMPTY_RESULT");
            listView.setVisibility(View.GONE);
            }
          }
        };

        //note that handle method is do at the above OnCreate

        private Runnable ChkSuggestionListConn = new Runnable(){
            @Override
        public void run() {
        try{
        ... here is get my http link connection
        }(Exception e){
        Log.e("log_tag", "Error converting result "+e.toString());
        }
        try{
        ... here is get my http result and put it into array
        }(Exception e){
         messageHandler.sendEmptyMessage(EMPTY_RESULT);

        }

1 个答案:

答案 0 :(得分:1)

我认为你的问题在这里:

getname.setText(productID);
listView.setVisibility(View.GONE);

您正在尝试从另一个线程修改IU线程。您应该使用post()方法在UI线程中调用Runnable。这是SO中的类似问题,尽管这个问题使用了AsyncTask:android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

您还可以在此处查看如何使用post()的示例: http://developer.android.com/resources/articles/painless-threading.html