0

ここでスレッドを呼び出す方法...ここからもエラーだと思います

 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);

        }
4

1 に答える 1

2

あなたの問題はここにあると思います:

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

別のスレッドから IU スレッドを変更しようとしています。UI スレッドで Runnable を呼び出すには、post() メソッドを使用する必要があります。SO で同様の質問がありますが、これは AsyncTask を使用しています: android.view.ViewRoot$CalledFromWrongThreadException: ビュー階層を作成した元のスレッドのみがそのビューにアクセスできます。

post() の使用方法の例もここで見ることができます: http://developer.android.com/resources/articles/painless-threading.html

于 2012-06-04T05:31:15.053 に答える