I get the "No Items found" toast on the ListActivity.
Note: When I change the PHP code to "Select * from items", the entire table shows up. But when I try to filter it with the param/cat_id value in Android/Java, I get a blank
Here is code, first: php
<?php
$sql=mysql_query("SELECT * FROM items WHERE cat_id = ' ".$_REQUEST['cat_id']." '");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
(I have confirmed that "cat_id", the value I am passing into the below activity through a bundle is what it needs to be.)
Android/Java:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cat_id = getIntent().getExtras().getString("category_id");
items = new ArrayList<String>();
new task().execute();
}
class task extends AsyncTask<String, String, Void> {
#Override
protected Void doInBackground(String... params) {
String url_select = "http://www.---.com/---/items.php";
param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("category_id", cat_id));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
//
}
and farther below
protected void onPostExecute(Void v) {
String item;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
item = json_data.getString("item");
items.add(item);
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No Items Found",
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
I get the "No Items found" toast on the ListActivity.
Note: When I change the PHP code to "Select * from items", the entire table shows up. But when I try to filter it with the param/cat_id value in Android/Java, I get a blank.
On the Java code you write
param.add(new BasicNameValuePair("category_id", cat_id));
but on the PHP code you write
$_REQUEST['cat_id']
you should change it to
$_REQUEST['category_id']
Related
I am fetching texts first and adding them to the ListView (This part is working).
Then for each item in the ListView I am fetching an image and need to add this image to the ImageView of each item which is already defined in the layout.
I am able to get all the images but don't know how to update the ListView with the same.
//AsyncTask For texts.
private class pgData extends AsyncTask<String, String, JSONArray> {
protected JSONArray doInBackground(String... params) {
publishProgress("Starting");
String result=null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxx.xxx/xxx.php");
HttpResponse response = null;
HttpEntity httpentity =null;
JSONArray t=null;
try{
response= httpclient.execute(httppost);
httpentity=response.getEntity();
result= EntityUtils.toString(httpentity);
t=new JSONArray(result);
}catch (Exception e){
publishProgress(e.toString());
this.cancel(true);
}
return t;
}
protected void onProgressUpdate(String... i) {
Toast.makeText(getBaseContext(), i[0], Toast.LENGTH_SHORT).show();
}
protected void onPostExecute(JSONArray result) {
String x[];
l = result.length();
pg_data = new pg[l];
JSONObject jsonObject;
for (int i = 0; i < l; i++) {
try {
jsonObject = result.getJSONObject(i);
x[0] = jsonObject.getString("xxx");
x[1]=jsonObject.getString("xxx");
x[2] = jsonObject.getString("xxxx");
x[3] = jsonObject.getString("rentMonthly");
pg_data[i] = new pg(
x[0],
x[1],
x[2],
x[3]
);
jdata.add(xxx_data[i]);
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
adapter = new pgAdapter(second.this,
R.layout.pg,
xxx_data);
lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(adapter);
new xxImage().execute(); //exexuting async task for fetching images.
}
}
//Async Task for fetching images
private class xxImage extends AsyncTask<String, String, JSONArray> {
protected JSONArray doInBackground(String... params) {
publishProgress("Getting Images");
String result=null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxx.xx/xx.php");
HttpResponse response = null;
HttpEntity httpentity =null;
JSONArray t=null;
try{
response= httpclient.execute(httppost);
httpentity=response.getEntity();
result= EntityUtils.toString(httpentity);
t=new JSONArray(result);
}catch (Exception e){
publishProgress(e.toString());
this.cancel(true);
}
return t;
}
protected void onProgressUpdate(String... i) {
Toast.makeText(getBaseContext(), i[0], Toast.LENGTH_SHORT).show();
}
protected void onPostExecute(JSONArray result) {
String image1;
l = result.length();
xx_image = new xxImage[l];
JSONObject jsonObject;
for (int i = 0; i < l; i++) {
try {
jsonObject = result.getJSONObject(i);
image1 = "\n" + jsonObject.getString("image1") + "\n";
xx_image[i] = new xxImage(
image1
);
jimage.add(xx_image[i]);
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
//I got all the Images in 'jimage'. Now how to update the ListView from here?
}
}
In your second AsyncTask do the following in the loop:
parse your image after getting it in image1.
get the item at i from the adapter.
from that item find the view with its id.
set the image on it.
Done. Try, hope it works for you.
You need to implement a custom ArrayAdapter for doing this. In you first asyncTask you set the adapter using the text data that you have but the adapter that you are using is of the form
ArrayAdapter(Context context, int resource, T[] objects)
In your case T is String (as far as I can see). But you want this T to be a custom object which also includes an image. You can do this by building your own custom adapter. Have a look at this answer.
Or another way is that your T object should be something like this.
CustomObject customObject = new CustomObject(text, image).
Try creating a list of these objects which you will then pass to the adapter instead of passing just the text array. But for this you will have to wait till all the images are loaded.
A better idea is to use Picasso. And implement a custom Adapter. Your current approach is very flawed.
I'm trying to check the username/psw on my phpmyadmin database
but I can't figure out the problem.
The logcat gives me this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONObject.getInt(java.lang.String)' on a null object reference
Java code:
public class MainActivity extends ActionBarActivity {
// Progress Dialog
private ProgressDialog pDialog;
private String password="";
private String userName="";
JSONParser jsonParser = new JSONParser();
// url to create new product
private static String url_login = "http://localhost/android_connect/get_login.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
Button btnSignIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSignIn=(Button)findViewById(R.id.buttonSignIN);
}
public void signIn(View V)
{
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the Refferences of views
final EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);
Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get The User name and Password
userName=editTextUserName.getText().toString();
password=editTextPassword.getText().toString();
new LoginUser().execute();
}
});
dialog.show();
}
class LoginUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Verificoo NomeUtente & Password ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Checking login
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("use_username", userName));
params.add(new BasicNameValuePair("use_psw", password));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_login,
"POST", params);
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS)
if (success == 1) {
//blablabla
} else {
Intent intent = getIntent();
finish();
Toast.makeText(MainActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
startActivity(intent);
}
} 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();
}
}
}
#miselking
here the class JsonParser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "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 == "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 (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
check json is not null
if(json!=null){do something}
Error at this line
httpPost.setEntity(new UrlEncodedFormEntity(params));
Use this line
if (params!=null)
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
and also in GET method use HTTP.UTF_8 instead of "utf-8"
my app which is supposed to transfer user input data to my SQL database. I am supposed to fill in all fields, then click save so that data gets updated in my sql databse. After cleaning up a lot of errors, i am finally stuck on 1 error that i cant resolve. any help provided would be extremely appreciated.Please advice what changes i can make to get rid of the error. The error is
08-04 05:47:48.799: E/JSON Parser(1506): Error parsing data [End of input at character 0 of ]
My codes below:
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputDriver;
EditText inputLicence;
EditText inputOfficer;
EditText inputSpeed;
EditText FineAppl;
EditText inputCategory;
TextView registerFine;
// url to create new fine
private static String url_create_fine = "http://192.168.1.1/android_api/create.php";
// JSON Node names/
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
speed = (EditText) findViewById(R.id.editText3);
Fine = (TextView)findViewById(R.id.editText4);
btnSelectDate=(Button)findViewById(R.id.buttonSelectDate);
btnSelectTime=(Button)findViewById(R.id.buttonSelectTime);
inputDriver = (EditText) findViewById(R.id.editText1);
inputLicence = (EditText) findViewById(R.id.editText2);
inputOfficer = (EditText) findViewById(R.id.editText5);
inputSpeed = (EditText) findViewById(R.id.editText3);
FineAppl = (EditText) findViewById(R.id.editText4);
inputCategory = (EditText) findViewById(R.id.editText6);
registerFine = (TextView) findViewById(R.id.fineregistered);
// Create button
Button btnRegisterfine = (Button) findViewById(R.id.savefine);
// button click event
btnRegisterfine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewFine().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewFine extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(FineCalc.this);
pDialog.setMessage("Registering Fine..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
String driver = inputDriver.getText().toString();
String licencenum = inputLicence.getText().toString();
String officer = inputOfficer.getText().toString();
String speed = inputSpeed.getText().toString();
String fine= FineAppl.getText().toString();
String category = inputCategory.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("driver", driver));
params.add(new BasicNameValuePair("licencenum", licencenum));
params.add(new BasicNameValuePair("officer", officer));
params.add(new BasicNameValuePair("speed", speed));
params.add(new BasicNameValuePair("fine", fine));
params.add(new BasicNameValuePair("category", category));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_fine, "POST", params);
// check log cat from response
//Log.d("Create Response", json.toString());
// check for success tag
try {
//if (json.getString(TAG_SUCCESS) != null) {
if(json != null && !(json).isNull(TAG_SUCCESS)){
registerFine.setText("");
String success = json.getString(TAG_SUCCESS);
// int success = json.getInt(TAG_SUCCESS);
// if (success == 1) {
if(Integer.parseInt(success) == 1){
// successfully created product
//Intent i = new Intent(getApplicationContext(), UserLogin.class);
//startActivity(i);
registerFine.setText("Successful");
// closing this screen
finish();
} else {
} // failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject makeHttpRequest(String url, String method,List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "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 == "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 (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, HTTP.UTF_8), 8);
//BufferedReader reader = new BufferedReader(new InputStreamReader(
// is, HTTP.UTF_8), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
// Log.e("JSON Parser", "Error parsing data " + e.toString());
Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
}
// return JSON String
return jObj;
}
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
And My php
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['driver'], $_POST['licencenum'], $_POST['officer'], $_POST['speed'] , $_POST['fine'],$_POST['category'])){
$driver = $_POST['driver'];
$licencenum = $_POST['licencenum'];
$officer = $_POST['officer'];
$speed = $_POST['speed'];
$fine = $_POST['fine'];
$category = $_POST['category'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO fineregister(driver,licencenum,officer,speed,fine,category) VALUES ('$driver','$licencenum','$officer','$speed','$fine', '$category')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Speed Ticket Successfully Registered.";
// 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);
}
?>
HttpResponse response = client.execute(httpPost);
String responseBody = EntityUtils.toString(response.getEntity());
pass the string into json array and get the response value
JSONArray jsArray = new JSONArray(responseBody);
JSONObject js = jsArray.getJSONObject(0);
String returnvalmsg = js.getString("message");
String returnvalsucc = js.getString("success");
Hint: pass success as "0" not 0
I have a php script that returns this json array.
{"PID":"1","PName":"Guitar","Brand":"Fender","Price":"110","Cat#":"1","Typ#":"1"}
I am making a simple app that places these results into several text views. only one product is returned each time as above.
when I run the app I get this Error: org.json.JSONException: Value
{"Typ#":"1","Brand":"test","Cat#":"1","PName":"Test","PID":"2","Price":"120"}
of type org.json.JSONObject cannot be converted to JSONArray.
Here is my code. Is there something wrong with the json result or the code?
public class MainActivity extends ActionBarActivity {
TextView tvname;
TextView tvbrand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvname = (TextView) findViewById(R.id.tvName);
tvbrand = (TextView) findViewById(R.id.tvBrand);
Button btnPost = (Button) findViewById(R.id.btnPost);
btnPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new getPro().execute();
}
});
}//end of on create
private class getPro extends AsyncTask<String,String,Void>{
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
getPro.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... strings) {
String url_select = "http://10.0.2.2/OnetoOne/getProduct.php";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("pid", "2"));
try {
// Set up HTTP post
// HttpClient is more then less deprecated. Need to change to URLConnection
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// Read content & Log
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
//parse JSON data
try {
JSONArray jArray = new JSONArray(result);
//JSONObject jObject = jArray.getJSONObject(0);
String anem = jArray.getJSONObject(0).getString("PName");
//String getname = jObject.getString("PName");
//String getbrand = jObject.getString("Brand");
tvname.setText(anem);
//tvbrand.setText(getbrand);
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
}
}
}//end of async
}//end of class
Any help would be greatly appreciated.
That's not an array it's an object
JSONObject jObject = new JSONObject(result);
String anem = jObject.getString("PName");
tvname.setText(anem);
{"Typ#":"1","Brand":"test","Cat#":"1","PName":"Test","PID":"2","Price":"120"} of type org.json.JSONObject cannot be converted to JSONArray.
You are trying to convert a JSONObject into a JSONArray, this is your error.
Use :
JSONOjbect jso = new JSONObject(result);
A JSONObject Start with { and end with }.
A JSONArray Start with [ and end with ].
I'm new to java and PHP, could someone please help my database only shows 0's ...
java code:
public class postData extends Activity {
//Progress Dialog
private ProgressDialog pDialog;
//JSONParser jsonParser = new JSONParser();
//url to update coordinates
private static String url_update_coordinates = "http://www.myurl.com";
//JSON Node names
private static final String TAG_SUCCESS = "Success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView (R.layout.post_coords);
final Context ctx = this;
//Create button
Button btnUploadCoordinates = (Button) findViewById(R.id.button5);
//Button click event
btnUploadCoordinates.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// updating coordinates on background thread
new UploadCoordinates(ctx).execute();
}
});
}
//Background Async Task to upload coordinates
class UploadCoordinates extends AsyncTask <String, String, String> {
// Before starting background thread Show Progress Dialog
private Context ctx;
public UploadCoordinates(Context ctx) {
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(postData.this);
pDialog.setMessage("Uploading Coordinates...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
//Creating Coordinates
#Override
protected String doInBackground(String... params) {
JSONArray json = new JSONArray();
MySQLite dbhelper = new MySQLite(ctx);
Cursor data = dbhelper.getlocations();
while(data.moveToNext()) {
int _id = data.getInt(0);
double latitude = data.getDouble(1);
double longitude = data.getDouble(2);
double altitude = data.getDouble(3);
double speed = data.getDouble(4);
double timestamp = data.getDouble(5);
JSONObject jo = new JSONObject();
try{
jo.put("_id", _id);
jo.put("latitude", latitude);
jo.put("longitude", longitude);
jo.put("altitude", altitude);
jo.put("speed", speed);
jo.put("timestamp", timestamp);
} catch(JSONException e) {
}
json.put(jo);
}
String json_data = json.toString();
// Adding the data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("coords", json_data));
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.myurl.com");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Check log for response
Log.d("Create response", json.toString());
return null;
}
// check for success tag
try {
int success = json_data.getInt(TAG_SUCCESS);
GIVING ME PROBLEMS HERE The method getInt(String) is undefined for the type String
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), GPSLoggerService.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
//After completion background task Dismiss progress dialog
protected void onPostExecute(String file_url) {
//dismiss the dialog once done
pDialog.dismiss();
}
}
}
php script:
<?php
ini_set('error_reporting', E_ALL); ini_set('display_errors','1');
//include dbconnect class
require_once (__DIR__ . '/db_connect.php');
//connecting to db
$db = new DB_CONNECT();
//decode array
$arr = (isset($_POST['coords']));
$decarr = json_decode($arr, true);
$count = count($decarr);
$values = array(); //hold array values so we do one single insert
$update_values = array(); //holds values for the ON DUPLICATE KEY UPDATE
for ($x=0; $x <$count; $x++)
{
$newrec = $decarr[$x];
$_id = $newrec['_id']; $_id = mysql_real_escape_string($_id);
$latitude = $newrec['latitude']; $_id = mysql_real_escape_string($latitude);
$longitude = $newrec['longitude']; $_id = mysql_real_escape_string($longitude);
$timestamp = $newrec['timestamp']; $_id = mysql_real_escape_string($timestamp);
$altitude = $newrec['altitude']; $_id = mysql_real_escape_string($altitude);
$speed = $newrec['speed']; $_id = mysql_real_escape_string($speed);
//create insert array
$values[] = "('".$_id."','".$latitude."','".$longitude."','".$timestamp."','".$altitude."','".$speed."')";
//For the duplicate updates
$update_values[]=
"latitude=VALUES(latitude), longitude=VALUES(longitude), timestamp=VALUES(timestamp), altitude=VALUES(altitude), speed=VALUES(speed)";
}
//insert records
$sql = "INSERT INTO logs(_id, latitude, longitude, timestamp, altitude, speed)
VALUES ".implode(',', $values)." ON DUPLICATE KEY UPDATE ".implode(',',$update_values);
$result = mysql_query($sql);
?>
Been trying for hours and can't figure out where the problem is, maybe this will be a silly one for many of yous out there.
thank you in advance for all your help.
Regards
V
UPDATE - Not sure if I should do this, but it will be easier as all the code is already here, my error is between blockquote... can't get my head around to see where the problem lyes ... any help appreciated.
The problem is that you use isset function and assign it's return value to $arr variable, and then using it as an array.
You should use this function to determine if a variable is set and is not NULL: it returns true or false.
In your PHP code, instead of lines 10 and 11, try this:
$decarr = isset($_POST['coords']) ? json_decode($_POST['coords'], true) : array();