2015-10-26 40 views
-1

我正在做一個應用程序,需要從android發送數據到數據庫。我正在使用JSONParser。但是當我啓動應用程序時,我遇到了問題,它不會將數據發送到服務器。我得到了「String name = inputName.getText()。toString();」的錯誤。這是它:方法getText必須從UI線程調用

protected String doInBackground(String... args) { 
      String name = inputName.getText().toString(); 
      String date = inputDate.getText().toString(); 
      String time = inputTime.getText().toString(); 
      String latitude = inputLatitude.getText().toString(); 
      String longitude = inputLongitude.getText().toString(); 
      String contacts = inputContacts.getText().toString(); 

      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 
      params.add(new BasicNameValuePair("name", name)); 
      params.add(new BasicNameValuePair("date", date)); 
      params.add(new BasicNameValuePair("time", time)); 
      params.add(new BasicNameValuePair("latitude", latitude)); 
      params.add(new BasicNameValuePair("longitude", longitude)); 
      params.add(new BasicNameValuePair("contacts", contacts)); 

      // getting JSON Object 
      // Note that create product url accepts POST method 
      JSONObject json = jsonParser.makeHttpRequest(url_create_product, 
        "POST", params); 

      // check log cat fro response 
      Log.d("Create Response", json.toString()); 

      // check for success tag 
      try { 
       int success = json.getInt(TAG_SUCCESS); 

       if (success == 1) { 
        // successfully created product 
        Intent i = new Intent(getApplicationContext(), MainActivity.class); 
        startActivity(i); 

        // closing this screen 
        finish(); 
       } else { 
        // failed to create product 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

      return null; 
     } 

     /** 
     * After completing background task Dismiss the progress dialog 
     * **/ 
     protected void onPostExecute(String file_url) { 
      // dismiss the dialog once done 
      pDialog.dismiss(); 
     } 

    } 

回答

0

由於錯誤告訴你,你不能在背景線程上調用getText()。相反,將您的六個getText()調用放入您的AsyncTask的構造函數中,或者可能調用onPreExecute()回調函數,因此getText()調用是在主應用程序線程上進行的。

+0

或者使用在主線程上創建的'Handler',並從後臺線程調用處理程序的'sendMessage'方法。 – t0mm13b

+0

@ t0mm13b:不在'AsyncTask'的'doInBackground()'內。 doInBackground()的其餘部分在繼續之前需要數據。 – CommonsWare

+0

我已找到解決問題的解決方案。這是鏈接[lhttp://stackoverflow.com/questions/32011996 ....](http://stackoverflow.com/questions/32011996/method-gettext-must-be-called-from-the-ui-線程Android的工作室?RQ = 1)。但它仍然不會將數據發送到服務器。錯誤是否與服務器有關或者存在一些不匹配問題? –

相關問題