如何使用json,android将edittext输入数据添加到sql数据库中? [英] How to add edittext input data into sql database using json,android?

查看:197
本文介绍了如何使用json,android将edittext输入数据添加到sql数据库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i am working on registration form where i have to fill all the fields and the EditText input data should go to the database using json parser.but am facing a problem here ..when i try example fn.gettext().toString()..it gives me red line that" Method getText() must be called from the UI thread, currently inferred thread is worker ".now everything is fine only this line gives me error.i don't know whether this is the correct way to send data as i m newbie here.

这是我的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文件,用于添加数据:

here is my php file for adding data :

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

如果这行得通,我正在尝试添加一些字段..i将添加完整的字段.

i am trying to add few fields if this will work..i will add full fields .

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

推荐答案

将您的createNewProduct更新为:

Update your createNewProduct to this:

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相关的操作.

In AsyncTask, onPreExecute and onPostExecute runs in main thread whereas doInBackground runs in background thread in which you are not able to perform any ui related operations.

这篇关于如何使用json,android将edittext输入数据添加到sql数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆