The first thing I should state is that I am fairly inexperienced in using PHP and JSON, so please be gentle.
I have built an android app which should store loan and user information in an android sqlite database. I have an activity which shows the stored user information in the form of a listview. I would then like to be able to sync this list of users to a remote database.
I have written a jsonParser java class, a syncAdmin Async Task class, and a php class which acts as the interface between the app and the remote database. So far, I am able to sync the first entry in the arrayList, but it will not proceed any further than that.
The app itself does not crash, and I am not presented with any errors in the LogCat. But the Logcat does contain my pre-written error codes from the php class.
JSONParser class:
public class JSONParser {
protected InputStream is = null;
protected JSONObject jObj;
static JSONArray jArr = null;
protected String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeObjHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method.equals("POST")){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method.equals("GET")){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
Log.i("From syncAdmins.php ", "["+json+"]");
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
syncAdmins class:
class syncUser extends AsyncTask<String, String, String> {
boolean failure = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(ShowAdmins.this);
progressDialog.setMessage("Syncing admin...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
progressDialog.show();
}
@Override
protected String doInBackground(String...args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
Boolean isSynced = false;
DBHandler dbAdapter = DBHandler.getDBHandlerInstance(getApplicationContext());
try {
dbAdapter.createDataBase();
} catch (IOException e) {
Log.i("*** select ", e.getMessage());
}
dbAdapter.openDataBase();
String query = "SELECT * FROM users";
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();
for (int i = 0; i < stringList.size(); i++) {
if (!isSynced) {
try {
ArrayList<String> list = stringList.get(i);
List<NameValuePair> nameValuePairs = new ArrayList<>(7);
nameValuePairs.add(new BasicNameValuePair("table_id", list.get(0)));
nameValuePairs.add(new BasicNameValuePair("type", list.get(1)));
nameValuePairs.add(new BasicNameValuePair("id_number", list.get(2)));
nameValuePairs.add(new BasicNameValuePair("name", list.get(3)));
nameValuePairs.add(new BasicNameValuePair("email", list.get(4)));
nameValuePairs.add(new BasicNameValuePair("course", list.get(5)));
nameValuePairs.add(new BasicNameValuePair("password", list.get(6)));
Log.d("Request!", "Starting!");
Log.d("Json Object Status", " jobj = " + jobj);
jobj = jsonParser.makeObjHttpRequest(REG_URL, "POST", nameValuePairs);
Log.d("Json Object Status", " jobj = " + jobj);
success = jobj.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("SYNCED!", jobj.toString());
isSynced = true;
return jobj.getString(TAG_MESSAGE);
} else {
Log.d("Sync failure!", jobj.getString(TAG_MESSAGE));
isSynced = false;
return jobj.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
i++;
}//else
}//forLoopEnds
return null;
}//doInBackground
syncAdmins.php
<?php
require_once 'config.php';
$response = array();
if(!empty($_POST)){
$row = $_POST['table_id'];
$type = $_POST['type'];
$id_num = $_POST['id_number'];
$name = $_POST['name'];
$email = $_POST['email'];
$course = $_POST['course'];
$password = $_REQUEST['password'];
$ins = mysql_query("INSERT INTO pi_prototype_inventory_30.users (table_id, type, id_number, name, email, course, password)
VALUES('$row','$type','$id_num','$name', '$email', '$course', '$password')");
try {
$stmt = $db->prepare($ins);
$result = $stmt->execute();
}
catch (PDOException $ex){
$response["success"]=0;
$response["message"]= "database error";
die(json_encode($response));
}
$response["success"] = 1;
$response["message"] = "User added!";
echo json_encode($response);
}
else {
echo (mysql_error());
}
?>
Logcat:
08-04 10:45:21.361 14097-14171/example.prguru.com.pi_prototype_30 D/Request!﹕ Starting!
08-04 10:45:21.361 14097-14171/example.prguru.com.pi_prototype_30 D/Json Object Status﹕ jobj = {}
08-04 10:45:21.637 14097-14171/example.prguru.com.pi_prototype_30 I/From syncAdmins.php﹕ [{"success":0,"message":"database error"}]
08-04 10:45:21.637 14097-14171/example.prguru.com.pi_prototype_30 D/Json Object Status﹕ jobj = {"success":0,"message":"database error"}
08-04 10:45:21.637 14097-14171/example.prguru.com.pi_prototype_30 D/Sync failure!﹕ database error
So, I understand that there must be some sort of a problem with parsing from android to php. But I'm confused as to why the program is able to insert the first entry in the list into my remote database, but nothing afterwards. Where am I going wrong?
Aucun commentaire:
Enregistrer un commentaire