I have a google map inside my android application, I have some saved data in mysql db with latitude and longitude and i want to read that data from mysql db.
I have wrote code but the app is still error .
myphp is :
<?php
$link = mysql_connect('localhost', 'root', '') or die('Cannot connect to the DB');
mysql_select_db('joe', $link) or die('Cannot select the DB');
/* grab the posts from the db */
$query = "SELECT lattitude, longitude FROM tracking";
$result = mysql_query($query, $link) or die('Errorquery: '.$query);
$rows = array();
while ($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
$data = "{joel:".json_encode($rows)."}";
echo $data;
?>
I have 3 java activities
public class lagiiiiteslagi extends ListActivity {
private static String url = "http://10.0.2.2/labiltrack/daftartracking.php";
// JSON Node names
private static final String TAG_lattitude = "lattitude";
private static final String TAG_longitude = "longitude";
// contacts JSONArray
JSONArray lattitude = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
lattitude = json.getJSONArray(TAG_lattitude);
// looping through All Contacts
for(int i = 0; i < lattitude.length(); i++) {
JSONObject c = lattitude.getJSONObject(i);
// Storing each json item in variable
String lattitude = c.getString(TAG_lattitude);
String longitude = c.getString(TAG_longitude);
// Phone number is agin JSON Object
//JSONObject phone = c.getJSONObject(TAG_PHONE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String,String>();
// adding each child node to HashMap key => value
map.put(TAG_lattitude, lattitude);
map.put(TAG_longitude, longitude);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e){
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.main,
new String[] { TAG_lattitude, TAG_longitude }, new int[] {
R.id.TextViewResult, R.id.TextViewResult1 });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
// TODO Auto-generated method stub
// getting values from selected ListItem
//String lattitude = ((TextView)) view.findViewById(R.id.TextViewResult)).getText().toString();
//String longitude = ((TextView)) view.findViewById(R.id.TextViewResult1)).getText(lattitude).toString();
String lattitude = ((TextView) view.findViewById(R.id.TextViewResult)).getText().toString();
String longitude = ((TextView) view.findViewById(R.id.TextViewResult1)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_lattitude, lattitude);
in.putExtra(TAG_longitude, longitude);
startActivity(in);
}
});
}
}
this JSONparser class :
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser(){
}
public JSONObject getJSONFromUrl(String url) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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;
}
}
this is use to display in listview :
public class SingleMenuItemActivity extends Activity {
// JSON node keys
private static final String TAG_lattitude = "lattitude";
private static final String TAG_longitude = "longitude";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String lattitude = in.getStringExtra(TAG_lattitude);
String longitude = in.getStringExtra(TAG_longitude);
// Displaying all values on the screen
TextView lbllattitude = (TextView) findViewById(R.id.listlat);
TextView lbllongitude = (TextView) findViewById(R.id.listlong);
lbllattitude.setText(lattitude);
lbllongitude.setText(longitude);
}
}
I just want to display that lattitude and longitude in listview but still error, I'm new to android, I hope some one help me,
Thank in advance !
check this link for json help...
I suggest to to use log like Log.e("JSON", json); in different place to find the point where the error actually happens.
Related
I have an app that is supposed to read a json file and inset its contents into a list view, I know this question was asked tons of times here but I can't understand why it's not working. I managed to narrow my problem to 1 line so far, JSONObject object = new JSONObject(readJSON());. This is all of my code:
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<Post> arrayList;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.lvPosts);
arrayList = new ArrayList<>();
try {
JSONObject object = new JSONObject(readJSON());
JSONArray array = object.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String productName = jsonObject.getString("productName");
String locationName = jsonObject.getString("locationName");
String price = jsonObject.getString("price");
String date = jsonObject.getString("date");
String description = jsonObject.getString("description");
String comment = jsonObject.getString("comment");
Log.i(TAG, price);
Post post = new Post();
post.setItemName(productName);
post.setLocationName(locationName);
post.setPrice(price);
post.setDate(date);
post.setDescription(description);
post.setExistingComment(comment);
arrayList.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
}
PostAdapter adapter = new PostAdapter(this, arrayList);
listView.setAdapter(adapter);
}
public String readJSON() {
String json = null;
try {
// Opening data.json file
InputStream inputStream = getAssets().open("MOCK_DATA.json");
int size = inputStream.available();
byte[] buffer = new byte[size];
// read values in the byte array
inputStream.read(buffer);
inputStream.close();
// convert byte to string
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return null;
}
return json;
}
}
My problem is that once I run the app my listView will remain empty and wont be populated with data.
if you are using java version >jdk1.7 then I would recommend you use Files class from "java.nio.file" package . you can easily read JSON file in a single line code.
public String readJSON() {
String jsontext="";
try{
jsontext= new String(Files.readAllBytes(Paths.get("<file path>"),StandardCharset.UTF_8);
}
catch(Exception ex){
ex.printStackTrace();
}
return jsontext;
}
after that you can use JSONObject to parse string like below:---
JSONObject object = new JSONObject(readJSON());
I'm using this code to fetch some data from PHP file and extract some data into my android application.
This code extract name, price and availability for each product and put each one in an String.
Now I need to have array of the product in java which that is included name,price and availability for each product and name them product1 product2 product3 so I'll be able to write rest of my code based on that.
How can I do that ?
public class MainActivity extends Activity {
private String jsonResult;
private String url = "xxxx/get_all_products.php";
private ListView listView;
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_FOUND = "found";
private static final String TAG_DESCRIPTION = "description";
ArrayList<HashMap<String, String>> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
productList = new ArrayList<HashMap<String, String>>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selval = ((TextView) view.findViewById(R.id.name)).getText().toString();
String selval1 = ((TextView) view.findViewById(R.id.price)).getText().toString();
String selval2 = ((TextView) view.findViewById(R.id.found)).getText().toString();
// Also I've found a solution on SO that a guy solved this problem doing soemthing like this :
// TextView txt = (TextView) parent.getChildAt(position - listview.firstVisiblePosition()).findViewById(R.id.sometextview);
// String keyword = txt.getText().toString();
Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
intnt.putExtra("selval", selval);
intnt.putExtra("selval1", selval1);
intnt.putExtra("selval2", selval2);
startActivity(intnt);
}
});
accessWebService();
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[]{url});
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> productList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("products");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("name");
String price = jsonChildNode.optString("price");
String found = jsonChildNode.optString("found");
// String outPut = name + "-" + number;
// String outPut = name + "-" + price + "-" + found;
// productList.add(createProduct("products", outPut));
HashMap<String, String> product = new HashMap<String, String>();
product.put(TAG_NAME, name);
product.put(TAG_FOUND, found);
product.put(TAG_PRICE, price);
productList.add(product);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, productList,
R.layout.list_item, new String[] { TAG_NAME, TAG_PRICE,
TAG_FOUND }, new int[] { R.id.name,
R.id.price, R.id.found });
listView.setAdapter(simpleAdapter);
}
}
its very simple, by using this code outside of the for loop
JSONObject pro1 = jsonMainNode.getJSONObject(0);
I am trying to display database record using java restful web service. I have able to create a login form using it but I cannot display the records on the database. I tried this code but its not working at all. When button is pressed nothing happens. Heres my code.
DriverDetails.java
class Details extends Activity {
TextView name1;
TextView plate1;
Button Btngetdata;
//URL to get JSON Array
private static String url = "http://192.168.254.108:8080/taxisafe/display/taxidetails";
//JSON Node Names
private static final String TAG_USER = "taxi";
private static final String TAG_NAME = "taxi_name";
private static final String TAG_EMAIL = "taxi_plate_no";
JSONArray user = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
name1 = (TextView)findViewById(R.id.name);
plate1 = (TextView)findViewById(R.id.plate);
}
#Override
protected JSONObject doInBackground(String... args) {
HttpConnection jParser = new HttpConnection();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
//Set JSON Data in TextView
name1.setText(name);
plate1.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
HttpConnection.java
public class HttpConnection {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public HttpConnection() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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;
}
}
I suggest adding Volley to your project
https://developer.android.com/training/volley/index.html
and following the example here https://developer.android.com/training/volley/request.html#request-json
You will not need to create your own HTTP request. Let Volley handle the network request using JSONObjectRequest
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();