简体   繁体   中英

insert a record in mysql db using php

am working on a project of surveys on android, it's about login ( this part works)and inserting data this part doesn't work is the questionnaire, when the man of survey log in to the application, there is a survey to do, in this project i started with 5 question with yes or no answers as a prototype, he must answer the questions and while clicking the save button they must be added to the mysql database. but this doesn't work ( the logcat is below) here's the class questionnaire.java:

public class Questionnaire extends Activity implements LocationListener {
// Progress Dialog
    private ProgressDialog pDialog;
//latitude et longitude
    private LocationManager lm;
    Location location;
    double longitude = 0;
    double latitude = 0;
    private double altitude;
    private float accuracy;
    int i;
    JSONParser jsonParser = new JSONParser();
    Button enregistrer;
    EditText zone;
    RadioGroup mRadioGroup1, mRadioGroup2, mRadioGroup3, mRadioGroup4, mRadioGroup5;
    RadioButton b1, b2, b3, b4, b5;
// url to create new product
    private static String url_insertion = "http://10.0.2.2/android/insertion.php";
// JSON Node names
    private static final String TAG_SUCCESS = "success";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.questions);
        Bundle params = getIntent().getExtras();
        i = params.getInt("compteur");
        i++;

        // Edit zone text
        EditText zone1 = (EditText) findViewById(R.appreciation.zone);

        // edit latitude longitude
        latitude = location.getLatitude();
        longitude = location.getLongitude();

        // edit radiogroup
        mRadioGroup1 = (RadioGroup) findViewById(R.appreciation.rep1);
        mRadioGroup2 = (RadioGroup) findViewById(R.appreciation.rep2);
        mRadioGroup3 = (RadioGroup) findViewById(R.appreciation.rep3);
        mRadioGroup4 = (RadioGroup) findViewById(R.appreciation.rep4);
        mRadioGroup5 = (RadioGroup) findViewById(R.appreciation.rep5);

        //edit radio button
        b1 = (RadioButton) findViewById(mRadioGroup1.getCheckedRadioButtonId());
        b2 = (RadioButton) findViewById(mRadioGroup2.getCheckedRadioButtonId());
        b3 = (RadioButton) findViewById(mRadioGroup3.getCheckedRadioButtonId());
        b4 = (RadioButton) findViewById(mRadioGroup4.getCheckedRadioButtonId());
        b5 = (RadioButton) findViewById(mRadioGroup5.getCheckedRadioButtonId());

        // Create button
        Button enregistrer = (Button) findViewById(R.appreciation.enregistrer);

        // button click event
        enregistrer.setOnClickListener(new OnClickListener() {

            public void onClick(View view) {
                new InsertAppreciation().execute();
            }
        });
    }

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

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

        /**
         * Creating appreciation
         * */
        protected String doInBackground(String... args) {
            String zone1 = zone.getText().toString();
            //  String latitude = String.valueOf(latitude).toString();
            //  String longitude = String.valueOf(longitude).toString();
            String rep1 = b1.getText().toString();
            String rep2 = b2.getText().toString();
            String rep3 = b3.getText().toString();
            String rep4 = b4.getText().toString();
            String rep5 = b5.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("zone", zone1));
            //  params.add(new BasicNameValuePair("latitude", latitude));
            //   params.add(new BasicNameValuePair("longitude", longitude));
            params.add(new BasicNameValuePair("rep1", rep1));
            params.add(new BasicNameValuePair("rep2", rep2));
            params.add(new BasicNameValuePair("rep3", rep3));
            params.add(new BasicNameValuePair("rep4", rep4));
            params.add(new BasicNameValuePair("rep5", rep5));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_insertion,
                    "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 appreciation
                    Toast.makeText(getBaseContext(), "Successful insertion", Toast.LENGTH_SHORT).show();
                    if (i < 5) {
                        Intent intent1 = new Intent(Questionnaire.this, Questionnaire.class);
                        intent1.putExtra("compteur", i);
                        startActivity(intent1);
                    } else {
                        Intent intent2 = new Intent(Questionnaire.this, Endsurvey.class);
                        startActivity(intent2);
                    }

                } else {
                    // failed to create appreciation
                    Toast.makeText(getBaseContext(), "failed insertion", Toast.LENGTH_SHORT).show();
                }
            } 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();

        }
    }
}

sorry i know it's too long but i don't have any choice. here's the logcat:

08-15 22:15:31.620: D/AndroidRuntime(241): Shutting down VM
08-15 22:15:31.630: W/dalvikvm(241): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
08-15 22:15:31.640: E/AndroidRuntime(241): Uncaught handler: thread main exiting due to uncaught exception
08-15 22:15:31.671: E/AndroidRuntime(241): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.stage.sondage/com.stage.sondage.Questionnaire}: java.lang.NullPointerException
08-15 22:15:31.671: E/AndroidRuntime(241):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
08-15 22:15:31.671: E/AndroidRuntime(241):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
08-15 22:15:31.671: E/AndroidRuntime(241):  at android.app.ActivityThread.access$2200(ActivityThread.java:119)
08-15 22:15:31.671: E/AndroidRuntime(241):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
08-15 22:15:31.671: E/AndroidRuntime(241):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-15 22:15:31.671: E/AndroidRuntime(241):  at android.os.Looper.loop(Looper.java:123)
08-15 22:15:31.671: E/AndroidRuntime(241):  at android.app.ActivityThread.main(ActivityThread.java:4363)
08-15 22:15:31.671: E/AndroidRuntime(241):  at java.lang.reflect.Method.invokeNative(Native Method)
08-15 22:15:31.671: E/AndroidRuntime(241):  at java.lang.reflect.Method.invoke(Method.java:521)
08-15 22:15:31.671: E/AndroidRuntime(241):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
08-15 22:15:31.671: E/AndroidRuntime(241):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
08-15 22:15:31.671: E/AndroidRuntime(241):  at dalvik.system.NativeStart.main(Native Method)
08-15 22:15:31.671: E/AndroidRuntime(241): Caused by: java.lang.NullPointerException
08-15 22:15:31.671: E/AndroidRuntime(241):  at com.stage.sondage.Questionnaire.onCreate(Questionnaire.java:73)
08-15 22:15:31.671: E/AndroidRuntime(241):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-15 22:15:31.671: E/AndroidRuntime(241):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
08-15 22:15:31.671: E/AndroidRuntime(241):  ... 11 more
08-15 22:15:31.730: I/dalvikvm(241): threadid=7: reacting to signal 3
08-15 22:15:31.730: E/dalvikvm(241): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
08-15 22:15:35.341: I/Process(241): Sending signal. PID: 241 SIG: 9
08-15 22:15:36.380: E/ActivityThread(282): Failed to find provider info for com.google.settings
08-15 22:15:36.390: E/ActivityThread(282): Failed to find provider info for com.google.settings
08-15 22:15:36.430: E/ActivityThread(282): Failed to find provider info for com.google.settings
08-15 22:15:36.982: D/dalvikvm(282): GC freed 1983 objects / 133688 bytes in 137ms
08-15 22:15:37.110: D/LocationManager(282): Constructor: service = android.location.ILocationManager$Stub$Proxy@44ea4f80
08-15 22:15:37.212: D/LocationManager(282): removeUpdates: listener = com.google.android.maps.MyLocationOverlay@44e9db00
08-15 22:15:37.222: I/Maps.MyLocationOverlay(282): Request updates from gps
08-15 22:15:37.360: D/SensorManager(282): found sensor: Goldfish 3-axis Accelerometer, handle=0
08-15 22:15:37.520: D/SensorManager(282): found sensor: Goldfish 3-axis Magnetic field sensor, handle=1
08-15 22:15:37.672: D/SensorManager(282): found sensor: Goldfish Orientation sensor, handle=2
08-15 22:15:37.830: D/SensorManager(282): found sensor: Goldfish Temperature sensor, handle=3
08-15 22:15:37.970: I/MapActivity(282): Handling network change notification:CONNECTED
08-15 22:15:37.980: E/MapActivity(282): Couldn't get connection factory client
08-15 22:15:38.460: D/dalvikvm(282): GC freed 5048 objects / 299360 bytes in 90ms
08-15 22:16:00.971: D/dalvikvm(282): GC freed 13338 objects / 892160 bytes in 200ms

here's the php file:

    <?php
    //turn off error reporting
     error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);

    //Create fields for the database
    //server, username, password, database

    $dbhost = "localhost";
    $dbuser = "root";
    $dbpass = "";
    $dbdb = "survey";

    //connect to mySQL
    $connect = mysql_connect($dbhost, $dbuser, $dbpass) or die("connection error");

    //Select the database
    mysql_select_db($dbdb)or die("database selection error");

    //Retrieve the login details via POST
    $zone = $_POST['zone'];
    $latitude = $_POST['latitude'];
    $longitude = $_POST['longitude'];
    $rep1 = $_POST['rep1'];
    $rep2 = $_POST['rep2'];
    $rep3 = $_POST['rep3'];
    $rep4 = $_POST['rep4'];
    $rep5 = $_POST['rep5'];

    // mysql inserting a new row
    $result = mysql_query("INSERT INTO appreciation(id, zone, latitude, longitude,                    rep1, rep2, rep3, rep4, rep5) VALUES('', '$zone1', '', '', '$rep1', '$rep2', '$rep3',  '$rep4', '$rep5' )");



    // 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);
    //close the connection
    mysql_close();


         }



          ?>

please help it's really urgent. thanks

Firstly as others have said in the comments, please please look at PDO as your database interactions are very un-safe.

The exception trace you provided says that an uncaught (start using try/catch ) exception occurred in the onCreate method of the Questionnaire activity. I expect (please check via debugging) that the error is thrown when you look at compteur in the intents bundle for the second time (you are going from Questionnaire to Questionnaire activities).

I can see that you are putting an object into the bundle when you fire the intent, but you are haven't checked that it isn't null before working on it.

Unable to open stack trace file '/data/anr/traces.txt': Permission denied

您是否在清单xml文件中添加了从SD卡读取的权限?

<uses-permission  android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM