2016-04-15 83 views
1

我需要帮助。我得到“getText()。toString()”的错误,它说:“getTEXT方法应该从UI线程调用......”这是什么意思呢?当提交数据时,数据不会保存在数据库中。有人可以帮我请我的时间不多了已经?:'(如果有需要什么,让我知道getText()。toString()常量和资源类型不匹配

这里是我的代码:。

SecondScreen.java

import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.Menu; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 
import android.widget.Button; 
import android.view.View.OnClickListener; 
import android.widget.CheckBox; 
import android.widget.EditText; 
import android.widget.Spinner; 
import android.widget.Toast; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.util.ArrayList; 
import java.util.List; 

public class SecondScreen extends Activity { 

    // Progress Dialog 
    private ProgressDialog pDialog; 

    JSONParser jsonParser = new JSONParser(); 
    EditText name_eT; 
    EditText age_eT; 
    EditText email_eT; 
    EditText phone_eT; 
    EditText descr_eT; 

    private static String url_submit_data = "http://khaty-ismail0.rhcloud.com/phptutorial/submit.php"; 

    // JSON Node names 
    private static final String TAG_SUCCESS = "success"; 

    private Button submitButton; 

    String Name="1"; 
    String Age="1"; 
    String Gender ="1"; 
    String Email ="1"; 
    String Phone ="1"; 
    String IncidentType ="1"; 
    String Description ="1";  

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.second_layout); 

     // Edit Text 
     inputName = (EditText) findViewById(R.id.name_eT); 
     age_eT = (EditText) findViewById(R.id.age_eT); 
     email_eT = (EditText) findViewById(R.id.email_eT); 
     phone_eT = (EditText) findViewById(R.id.phone_eT); 
     descr_eT = (EditText) findViewById(R.id.descr_eT); 

     CheckBox cBoxMale = (CheckBox) findViewById(R.id.checkBoxMale); 
     CheckBox cBoxFemale = (CheckBox) findViewById(R.id.checkBoxFemale); 

     Spinner list = (Spinner) findViewById(R.id.spinner); 

     // Create button 
     Button submitButton = (Button) findViewById(R.id.subm_btn); 

     // button click event 
     submitButton.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View view) { 
       // creating new product in background thread 
       /*String Name = name_eT.getText().toString(); 
       String Age = age_eT.getText().toString(); 
       String Email = email_eT.getText().toString(); 
       String Phone = phone_eT.getText().toString(); 
       String Description = descr_eT.getText().toString();*/ 


       /*Intent i = new Intent(getApplicationContext(),SubmitData.class); 
       startActivity(i);*/ 

       new SubmitData().execute(Name, Age, Gender, Email, Phone, IncidentType, Description); 
      } 
     }); 
    } 

    public void onCheckboxClicked(View V) { 
     boolean checked = ((CheckBox) V).isChecked(); 

     switch (V.getId()) { 
      case R.id.checkBoxMale: 
       if (checked); 
        //Male 
       else 
        //No gender 
        break; 

      case R.id.checkBoxFemale: 
       if (checked); 
        //Female 
       else 
        //No gender 
        break; 

     } 
    } 

    /** 
    * Background Async Task to Create new product 
    * */ 
    class SubmitData extends AsyncTask<String, String, String> { 

     /** 
     * Before starting background thread Show Progress Dialog 
     * */ 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(SecondScreen.this); 
      pDialog.setMessage("Submitting your data..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
     } 

     /** 
     * Creating product 
     * */ 


     protected String doInBackground(String... args) { 
      //noinspection ResourceType 
      String Name = name_eT.getText().toString(); 
      //noinspection ResourceType 
      String Age = age_eT.getText().toString(); 
      String Email = email_eT.getText().toString(); 
      String Phone = phone_eT.getText().toString(); 
      String Description = descr_eT.getText().toString(); 

      String Name = args[0]; 
      String Age = args[1]; 
      String Gender = args [2]; 
      String Email = args[3]; 
      String Phone = args[4]; 
      String IncidentType = args[5]; 
      String Description = args[6]; 

      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 
      params.add(new BasicNameValuePair("Name", Name)); 
      params.add(new BasicNameValuePair("Age", Age)); 
      params.add(new BasicNameValuePair("Gender", Gender)); 
      params.add(new BasicNameValuePair("Email", Email)); 
      params.add(new BasicNameValuePair("Phone", Phone)); 
      params.add(new BasicNameValuePair("Incident Type", IncidentType)); 
      params.add(new BasicNameValuePair("Description", Description)); 

      // getting JSON Object 
      // Note that create product url accepts POST method 

      ServiceHandler serviceClient = new ServiceHandler(); 
      String json = serviceClient.makeServiceCall(url_submit_data, ServiceHandler.POST, params); 

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

      // check for success tag 
      if (json != null) { 
       try { 
        JSONObject jsonObj = new JSONObject(json); 
        boolean error = jsonObj.getBoolean("error"); 
        // checking for error node in json 
        if (!error) { 
         // new category created successfully 
         Log.e("Prediction added successfully ", "> " + jsonObj.getString("message")); 
        } else { 
         Log.e("Add Prediction Error: ", 
           "> " + jsonObj.getString("message")); 
        } 

       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 

      } else { 
       Log.e("JSON Data", "JSON data error!"); 
      } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      super.onPostExecute(result); 
     } 
    } 
} 

这里是我的ServiceHandler.java

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.util.List; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.utils.URLEncodedUtils; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.util.EntityUtils; 

import android.util.Log; 

public class ServiceHandler { 

    static String response = null; 
    static InputStream is = null; 
    public final static int GET = 1; 
    public final static int POST = 2; 

    public ServiceHandler() { 

    } 

    /* 
    * Making service call 
    * @url - url to make request 
    * @method - http request method 
    * */ 
    public String makeServiceCall(String url, int method) { 
     return this.makeServiceCall(url, method, null); 
    } 

    /* 
    * Making service call 
    * @url - url to make request 
    * @method - http request method 
    * @params - http request params 
    * */ 
    public String makeServiceCall(String url, int method,List<NameValuePair> params) { 
     try { 
      // http client 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpEntity httpEntity = null; 
      HttpResponse httpResponse = null; 

      // Checking http request method type 
      if (method == POST) { 
       HttpPost httpPost = new HttpPost(url); 
       // adding post params 
       if (params != null) { 
        httpPost.setEntity(new UrlEncodedFormEntity(params)); 
       } 

       httpResponse = httpClient.execute(httpPost); 

      } else if (method == GET) { 
       // appending params to url 
       if (params != null) { 
        String paramString = URLEncodedUtils 
          .format(params, "utf-8"); 
        url += "?" + paramString; 
       } 
       HttpGet httpGet = new HttpGet(url); 
       Log.d("url", url); 

       httpResponse = httpClient.execute(httpGet); 

      } 
      httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "UTF-8"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      response = sb.toString(); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error: " + e.toString()); 
     } 

     return response; 

    } 
} 

这里是布局文件secondlayout.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:padding="5dp" 
     android:text="@string/User_info" 
     android:id="@+id/userInfo" 
     android:textSize="30sp" 
     android:textColor="@color/colorFont" 
     android:textStyle="bold" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true"/> 

    <TextView 
     android:layout_width="70dp" 
     android:layout_height="wrap_content" 
     android:text="Name:" 
     android:id="@+id/name_tV" 
     android:textColor="@color/colorFont" 
     android:layout_marginTop="24dp" 
     android:layout_below="@+id/userInfo" 
     android:layout_alignLeft="@+id/userInfo" 
     android:layout_alignStart="@+id/userInfo" /> 

    <TextView 
     android:layout_width="70dp" 
     android:layout_height="wrap_content" 
     android:text="Age:" 
     android:id="@+id/age_tV" 
     android:textColor="@color/colorFont" 
     android:layout_alignBottom="@+id/age_eT" 
     android:layout_alignLeft="@+id/name_tV" 
     android:layout_alignStart="@+id/name_tV" /> 

    <TextView 
     android:layout_width="70dp" 
     android:layout_height="wrap_content" 
     android:text="Gender" 
     android:id="@+id/gender_tV" 
     android:textColor="@color/colorFont" 
     android:layout_above="@+id/email_eT" 
     android:layout_alignLeft="@+id/age_tV" 
     android:layout_alignStart="@+id/age_tV" /> 

    <TextView 
     android:layout_width="70dp" 
     android:layout_height="wrap_content" 
     android:text="Email:" 
     android:id="@+id/email_tV" 
     android:textColor="@color/colorFont" 
     android:layout_alignBottom="@+id/email_eT" 
     android:layout_alignLeft="@+id/gender_tV" 
     android:layout_alignStart="@+id/gender_tV" 
     android:layout_marginTop="32dp"/> 

    <TextView 
     android:layout_width="70dp" 
     android:layout_height="wrap_content" 
     android:text="Phone" 
     android:id="@+id/phone_tV" 
     android:textColor="@color/colorFont" 
     android:layout_alignBottom="@+id/phone_eT" 
     android:layout_alignLeft="@+id/gender_tV" 
     android:layout_alignStart="@+id/gender_tV" /> 

    <EditText 
     android:layout_width="200dp" 
     android:layout_height="30dp" 
     android:layout_marginBottom="5dp" 
     android:inputType="textPersonName" 
     android:hint="@string/hint_required" 
     android:textColorHint="@color/colorBackground" 
     android:background="@drawable/border_style" 
     android:ems="10" 
     android:id="@+id/name_eT" 
     android:textColor="@color/inputFont" 
     android:layout_alignBottom="@+id/name_tV" 
     android:layout_alignRight="@+id/userInfo" 
     android:layout_alignEnd="@+id/userInfo" /> 

    <EditText 
     android:layout_width="200dp" 
     android:layout_height="30dp" 
     android:inputType="number" 
     android:ems="10" 
     android:hint="@string/hint_required" 
     android:textColorHint="@color/colorBackground" 
     android:background="@drawable/border_style" 
     android:id="@+id/age_eT" 
     android:textColor="@color/inputFont" 
     android:layout_below="@+id/name_eT" 
     android:layout_alignLeft="@+id/name_eT" 
     android:layout_alignStart="@+id/name_eT" /> 

    <CheckBox 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Male" 
     android:id="@+id/checkBoxMale" 
     android:onClick="onCheckboxClicked" 
     android:textColor="@color/colorFont" 
     android:layout_below="@+id/age_tV" 
     android:layout_alignLeft="@+id/age_eT" 
     android:layout_alignStart="@+id/age_eT" /> 

    <CheckBox 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Female" 
     android:id="@+id/checkBoxFemale" 
     android:onClick="onCheckboxClicked" 
     android:textColor="@color/colorFont" 
     android:layout_alignTop="@+id/checkBoxMale" 
     android:layout_alignRight="@+id/userInfo" 
     android:layout_alignEnd="@+id/userInfo" /> 

    <EditText 
     android:layout_width="200dp" 
     android:layout_height="30dp" 
     android:layout_marginBottom="5dp" 
     android:inputType="textEmailAddress" 
     android:ems="10" 
     android:id="@+id/email_eT" 
     android:hint="@string/hint_required" 
     android:textColorHint="@color/colorBackground" 
     android:textColor="@color/inputFont" 
     android:background="@drawable/border_style" 
     android:layout_below="@+id/checkBoxMale" 
     android:layout_alignLeft="@+id/checkBoxMale" 
     android:layout_alignStart="@+id/checkBoxMale" /> 

    <EditText 
     android:layout_width="200dp" 
     android:layout_height="30dp" 
     android:inputType="phone" 
     android:ems="10" 
     android:id="@+id/phone_eT" 
     android:textColor="@color/inputFont" 
     android:hint="@string/hint_required" 
     android:textColorHint="@color/colorBackground" 
     android:background="@drawable/border_style" 
     android:layout_below="@+id/email_eT" 
     android:layout_alignLeft="@+id/email_eT" 
     android:layout_alignStart="@+id/email_eT" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/incident_info" 
     android:id="@+id/incidentInfo" 
     android:textColor="@color/colorFont" 
     android:textStyle="bold" 
     android:textSize="30sp" 
     android:layout_centerVertical="true" 
     android:layout_centerHorizontal="true" /> 

    <Spinner 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/spinner" 
     android:prompt="@array/incident_type" 
     android:entries="@array/incident_type" 
     android:layout_below="@+id/incidentInfo" 
     android:layout_alignLeft="@+id/phone_eT" 
     android:layout_alignStart="@+id/phone_eT" 
     android:layout_alignRight="@+id/phone_eT" 
     android:layout_alignEnd="@+id/phone_eT" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:padding="5dp" 
     android:text="@string/incident_type_DD" 
     android:textColor="@color/colorFont" 
     android:id="@+id/incident_DD" 
     android:layout_below="@+id/incidentInfo" 
     android:layout_toLeftOf="@+id/spinner" 
     android:layout_toStartOf="@+id/spinner" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:padding="5dp" 
     android:text="@string/description" 
     android:id="@+id/description_tV" 
     android:textColor="@color/colorFont" 
     android:layout_below="@+id/spinner" 
     android:layout_alignLeft="@+id/phone_tV" 
     android:layout_alignStart="@+id/phone_tV" /> 

    <EditText 
     android:layout_width="300dp" 
     android:layout_height="60dp" 
     android:inputType="textMultiLine" 
     android:ems="10" 
     android:id="@+id/descr_eT" 
     android:hint="@string/descr_hint" 
     android:textColorHint="@color/colorBackground" 
     android:gravity="top" 
     android:background="@drawable/border_style" 
     android:textColor="@color/inputFont" 
     android:layout_below="@+id/description_tV" 
     android:layout_alignLeft="@+id/description_tV" 
     android:layout_alignStart="@+id/description_tV" /> 

    <Button 
     android:layout_width="match_parent" 
     android:layout_height="60dp" 
     android:layout_margin="5dp" 
     android:text="SUBMIT" 
     android:onClick="SubmitButton" 
     android:textStyle="bold" 
     android:textSize="35sp" 
     android:id="@+id/subm_btn" 
     android:background="@drawable/custom_btn" 
     android:textColor="@color/buttonFont" 
     android:layout_alignParentBottom="true"/> 


</RelativeLayout> 

这里是我的submit.php文件:

<?php 
// array for JSON response 
$response = array(); 

// check for required fields 
if (isset($_POST['Name']) && isset($_POST['Age']) && isset($_POST['Email']) && isset($_POST['Phone']) && isset($_POST['Description'])) { 

    $Name = $_POST['Name']; 
    $Age = $_POST['Age']; 
    $Gender = $_POST['Gender']; 
    $Email = $_POST['Email']; 
    $Phone = $_POST['Phone']; 
    $Incident Type = $_POST['Incident Type']; 
    $Description = $_POST['Description']; 

    // include db connect class 
    require_once __DIR__ . '/db_connect.php'; 

    // connecting to db 
    $db = new DB_CONNECT(); 

    // mysql inserting a new row 
    $result = mysql_query("INSERT INTO user(Name, Age, Email, Phone, Description VALUES('$Name', '$Age', '$Email', '$Phone', '$Description')"); 

    // check if row inserted or not 
    if ($result) { 
     // successfully inserted into database 
     $response["success"] = 1; 
     $response["message"] = "Product successfully created."; 

     // echoing JSON response 
     echo json_encode($response); 
    } else { 
     // failed to insert row 
     $response["success"] = 0; 
     $response["message"] = "Oops! An error occurred."; 

     // echoing JSON response 
     echo json_encode($response); 
    } 
} else { 
    // required field is missing 
    $response["success"] = 0; 
    $response["message"] = "Required field(s) is missing"; 

    // echoing JSON response 
    echo json_encode($response); 
} 

?> 
+0

请更新您的代码属性,你不能比UI线程其他UI组件访问由args[]提到他们。你也声明了相同的字符串变量2次,所以更新你的代码。让我知道你更新后得到什么错误 – Alok

+0

嗨,帮助我确定哪个变量,我宣布2次?我只是从我研究复制粘贴。我仍然无法将数据保存到mysql数据库。 – user6181358

回答

0

不能使用的UI元素getText()(你的EditText-S)作为AsyncTask.doInBackground()运行中单独的线程并且无法访问UI元素。 你实际上是在做正确的new SubmitData().execute(Name, Age, Gender, Email, Phone, IncidentType, Description);,并从里面doInBackground()

+0

嗨,你是什么意思的单独线程?以及如何使用AsyncTask.doInBackground()?请帮助。 – user6181358

+0

从'doInBackgorund()'移除此 'String Name = name_eT.getText()。toString(); String Age = age_eT.getText()。toString(); String Email = email_eT.getText()。toString(); String Phone = phone_eT.getText()。toString(); 字符串描述= descr_eT.getText()。toString();' 并将此值赋予您已经传递给'execute()'的变量 –

+0

嗨,这是正确的吗?我仍然无法连接到我的数据库。请帮助我:( new submitData()。execute(Name,Age,Email,Phone,Description); – user6181358