[英]insert a record in mysql db using php
我正在android上進行調查的項目,這是關於登錄(此部分有效)並插入數據這一部分不起作用的是問卷,當調查人員登錄到應用程序時,需要進行調查,這個項目我從5個問題開始,以是或否的答案作為原型,他必須回答這些問題,並且在單擊“保存”按鈕時必須將其添加到mysql數據庫中。 但這是行不通的(下面是logcat),這里是類問卷調查表.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();
}
}
}
抱歉,我知道時間太長,但我別無選擇。 這是日志:
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
這是php文件:
<?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();
}
?>
請幫助,這真的很緊急。 謝謝
首先,正如其他人在評論中說的那樣,請查看PDO,因為您的數據庫交互非常不安全。
您提供的異常跟蹤表明,“ Questionnaire
活動的onCreate
方法中發生了未捕獲(使用try / catch開始)異常。 我期望(請通過調試檢查)當您第二次查看compteur
捆綁包中的compteur
時會拋出該錯誤(您將從Questionnaire
到Questionnaire
活動)。
我可以看到您在激發意圖時將對象放入捆綁包中,但是在進行操作之前尚未檢查它是否為null。
Unable to open stack trace file '/data/anr/traces.txt': Permission denied
您是否在清單xml文件中添加了從SD卡讀取的權限?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.