如何使用 json、android 将 edittext 输入数据添加到 sql 数据库?

How to add edittext input data into sql database using json,android?

我正在处理注册表,我必须填写所有字段,EditText 输入数据应使用 json 进入数据库 parser.but 我在这里遇到问题。 .当我尝试示例 fn.gettext().toString().. 它给了我红线“必须从 UI 线程调用方法 getText(),当前推断的线程是工作线程”。现在一切都很好,只有这个行给我 error.i 不知道这是否是发送数据的正确方法,因为我是新手。

这是我的 Registration.java class:

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

如果可行的话,我正在尝试添加几个字段..我将添加完整的字段。

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.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.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.call(AsyncTask.java:292)
                                                                             at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                             at android.os.AsyncTask$SerialExecutor.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: android.os.BinderProxy@2f0f4385 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

将您的 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 相关操作。

这里是您想要从 edittext 添加数据的此类代码的正确 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);

?>

您正在做 UI activity 在 doInBackground

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

getText() 应该在 onPreExecute 或 onCreate 方法中。全局定义以上所有字符串。