如何使用json,android?

时间:2016-12-28 08:39:49

标签: android mysql json registration

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

这是我的getText()课程:

Registration.java

这是我的用于添加数据的php文件:

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

/

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

3 个答案:

答案 0 :(得分: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相关的操作。

答案 1 :(得分:0)

您正在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方法中。全局定义所有上述字符串。

答案 2 :(得分:-1)

这里是这类代码的corrct php,你想从edittext中添加数据..我的错误是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);

?>