2016-12-28 110 views
-1

我正在註冊表格中,我必須填寫所有的字段和EditText輸入數據應該去使用json解析器數據庫。但我面臨的問題在這裏..當我嘗試示例fn.gettext().toString() ..它給我紅線「方法getText()必須從UI線程調用,目前推斷的線程是工人」。現在一切都很好,只有這條線給我error.i不知道這是否是正確的方式發送數據作爲即時通訊新手在這裏。如何使用json,android將edittext輸入數據添加到sql數據庫?

這裏是我的Registration.java類:

public class RegistrationForm extends AppCompatActivity { 

    EditText fn,ln,mb,em,pw,cpw,dob,gen; 
    Switch sw; 
    RadioGroup male,feml; 
    Switch swth; 
    private ProgressDialog pDialog; 



    private static String url_create_book = "http://cl...com/broccoli/creatinfo.php"; 

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




    JSONParser jsonParser = new JSONParser(); 
    private int serverResponseCode = 0; 
    Context c; 
    int i=0; 


    Button sub; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_registration_form); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 


     fn=(EditText)findViewById(R.id.fnm) ; 
     ln=(EditText)findViewById(R.id.lnm) ; 
     mb=(EditText)findViewById(R.id.mobile) ; 
     em=(EditText)findViewById(R.id.email) ; 
     pw=(EditText)findViewById(R.id.pass) ; 
     cpw=(EditText)findViewById(R.id.cpass) ; 
     RadioButton male=(RadioButton)findViewById(R.id.rgm) ; 

     RadioButton feml=(RadioButton)findViewById(R.id.rgf) ; 

     Switch swth=(Switch)findViewById(R.id.mySwitch) ; 









     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
     sub=(Button)findViewById(R.id.sub2); 

     sub.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 


       new CreateNewProduct().execute(); 



       // startActivity(new Intent(RegistrationForm.this, Home.class)); 


      } 
     }); 


    } 



    class CreateNewProduct extends AsyncTask<String, String, String> { 

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




     protected String doInBackground(String... args) { 
      String fname = fn.getText().toString(); 
      String lname = ln.getText().toString(); 
      String email = em.getText().toString(); 

      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 
      params.add(new BasicNameValuePair("First_Name", fname)); 
      params.add(new BasicNameValuePair("Last_Name",lname)); 
      params.add(new BasicNameValuePair("email", email)); 


      // getting JSON Object 
      // Note that create product url accepts POST method 
      JSONObject json = jsonParser.makeHttpRequest(url_create_book, 
        "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(), Login.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(); 
     } 

    } 

這裏是將數據添加我的PHP文件:

<?php 

/

// array for JSON response 

include ('config.php'); 


// check for required fields 

if (isset($_POST['First_Name']) && isset($_POST['Last_Name']) && isset($_POST['email'])) { 

    $fname = $_POST['First_Name']; 
    $lname = $_POST['Last_Name']; 
    $email = $_POST['email']; 



    // mysql inserting a new row 
    $result = mysql_query("INSERT INTO UserInfo(First_Name, Last_Name, email) VALUES('$fname', '$lname ', '$email')"); 

    // 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); 
} 
?> 

我試圖添加幾個字段,如果這將work..i將增加全字段。

here is my logcat: 

2-28 14:11:44.201 3245-3504/com.example.zeba.broccoli E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2 
                     Process: com.example.zeba.broccoli, PID: 3245 
                     java.lang.RuntimeException: An error occured while executing doInBackground() 
                      at android.os.AsyncTask$3.done(AsyncTask.java:304) 
                      at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) 
                      at java.util.concurrent.FutureTask.setException(FutureTask.java:222) 
                      at java.util.concurrent.FutureTask.run(FutureTask.java:242) 
                      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
                      at java.lang.Thread.run(Thread.java:818) 
                      Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference 
                      at com.example.zeba.broccoli.RegistrationForm$CreateNewProduct.doInBackground(RegistrationForm.java:147) 
                      at com.example.zeba.broccoli.RegistrationForm$CreateNewProduct.doInBackground(RegistrationForm.java:107) 
                      at android.os.AsyncTask$2.call(AsyncTask.java:292) 
                      at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
                      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)  
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)  
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)  
                      at java.lang.Thread.run(Thread.java:818)  
12-28 14:11:44.341 3245-3354/com.example.zeba.broccoli D/mali_winsys: new_window_surface returns 0x3000, [540x960]-format:1 
12-28 14:11:44.456 3245-3245/com.example.zeba.broccoli I/Timeline: Timeline: Activity_idle id: [email protected] time:209884695 
12-28 14:11:44.736 3245-3245/com.example.zeba.broccoli E/WindowManager: android.view.WindowLeaked: Activity com.example.zeba.broccoli.RegistrationForm has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{6dda29d V.E..... R......D 0,0-501,174} that was originally added here 

回答

0

更新您的createNewProduct這樣:

class CreateNewProduct extends AsyncTask<String, String, String> { 
    private String fname; 
    private String lname; 
    private String email; 

    /** 
    * Before starting background thread Show Progress Dialog 
    * */ 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(RegistrationForm.this); 
     pDialog.setMessage("Creating books.."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
     fname = fn.getText().toString(); 
     lname = ln.getText().toString(); 
     email = em.getText().toString(); 
    } 




    protected String doInBackground(String... args) { 


     // Building Parameters 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair("First_Name", fname)); 
     params.add(new BasicNameValuePair("Last_Name",lname)); 
     params.add(new BasicNameValuePair("email", email)); 


     // getting JSON Object 
     // Note that create product url accepts POST method 
     JSONObject json = jsonParser.makeHttpRequest(url_create_book, 
       "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(), Login.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(); 
    } 

} 

在的AsyncTask,onPreExecute和onPostExecute在主線程中運行,而doInBackground在其中您不能執行任何UI相關的操作後臺線程中運行。

+0

嗨,我收到錯誤時,我應用你的代碼 –

+0

什麼錯誤。提供更多詳細信息 – Anjali

+0

確定將顯示logcat –

-1

這裏這種類型的代碼,你想從edittext..my錯誤添加數據CORRCT PHP是用GET和POST METHODE ...

<?php 
include ('config.php'); 


$fname = $_POST['First_Name']; 
$lname = $_POST['Last_Name']; 
$email = $_POST['email']; 



$stmt = mysqli_query($conn,"INSERT INTO UserInfo(First_Name,Last_Name,email) VALUES ('$fname','$lname','$email')"); 



/*now only submenu items of given type will be selected*/ 
    if ($stmt) { 
     // 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); 
}*/ 
//echo json_encode($arr); 

?> 
0

你是做UI活動doInBackground

protected String doInBackground(String... args) { 
      String fname = fn.getText().toString(); 
      String lname = ln.getText().toString(); 
      String email = em.getText().toString(); 
........ 
} 

getText()應該在onPreExecute或onCreate方法中。全局定義上述所有字符串。

+0

appriciate它,BT我已經GT D解決方案 –

+0

http://stackoverflow.com/questions/41362239/我怎麼可以發送無線電按鈕值和切換案例選擇服務器使用JSON的...你可以做到這一點? –