【问题标题】:How to add edittext input data into sql database using json,android?如何使用json,android将edittext输入数据添加到sql数据库中?
【发布时间】:2017-05-12 12:21:47
【问题描述】:

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

这是我的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);
}
?>

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

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: 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

【问题讨论】:

    标签: android mysql json registration


    【解决方案1】:

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

    【讨论】:

    • 您好,请查看 logcat,如果需要任何文件,请告诉我
    • 您在以下行中遇到错误:Log.d("Create Response", json.toString());这意味着您没有得到服务器端的响应。检查服务器端代码
    • 我已经把我的php文件放在上面了..请看
    【解决方案2】:

    您正在 doInBackground 中进行 UI 活动

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

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

    【讨论】:

    【解决方案3】:

    这里是您想要从edittext添加数据的此类代码的corrct php。我的错误是使用GET和POST方法...

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-17
      • 2021-06-09
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 2020-09-06
      • 1970-01-01
      相关资源
      最近更新 更多