I currently have an android application with php and mysql, but my problem is that, my code always throws 0.000000 both longitude and latitude when it was passed to php and stored it in mysql.
this was my codes
**
class myLocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
double pLong = location.getLongitude();
double pLat = location.getLatitude();
textLat.setText(Double.toString(pLat));
textLong.setText(Double.toString(pLong));
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Sample.this);
pDialog.setMessage("Sending Location");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String latitude = textLong.getText().toString();
String longitude = textLat.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("latitude", latitude));
params.add(new BasicNameValuePair("longitude", longitude));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"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 product
Intent i = new Intent(getApplicationContext(), Echos.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
**
and this was for php
**
if ($_POST['latitude'] && $_POST['longitude'] != null) {
$db_connect = mysql_connect($db_host, $db_user, $db_password) or die(mysql_error());
$db = mysql_select_db($db_name);
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
// mysql inserting a new row
$result = mysql_query("INSERT INTO gpslocation(latitude, longitude) VALUES('latitude', 'longitude')");
// 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);
}
**
If someone knows something about this, please be kind to answer here, or tell me if I am misleading my question.
The problem seems to be with your PHP Code.
$result = mysql_query("INSERT INTO gpslocation(latitude, longitude) VALUES('$latitude', '$longitude')");
Change the above line to have $ sign and see.
Better yet use mysql_execute with prepared statements. See this post
Related
I've been trying to build a registration system for android using php and mysql but i have come across an error that i am unable to fix. Could someone have a look at it and see if they spot anything that i don't please.
register code:
public class RegisterActivity extends Activity implements OnClickListener {
private EditText user, pass;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://95.85.22.140/webservice/register.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
user = (EditText)findViewById(R.id.registerUsername);
pass = (EditText)findViewById(R.id.registerPassword);
mRegister = (Button)findViewById(R.id.btnRegisterDetails);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegisterActivity.this);
pDialog.setMessage("Creating User...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} 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 product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(RegisterActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
register.php
<?php
require("config.inc.php");
// If posted data is not empty
if(!empty($_POST))
{
// If the username or password submition is empty
if(empty($_POST['username']) || empty($_POST['password']))
{
// Create a JSON response
$response["success"] = 0;
$response["message"] = "Please enter a username and a password.";
die(json_encode($response));
}
// Check to see if there is already a user with the username
$query = "SELECT 1 FROM registration WHERE username = :user";
// update the empty :user variable
$query_params = array(':user' => $_POST['username']);
// run query against database
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex)
{
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//return username data if already in use
$row = $stmt->fetch();
if($row)
{
$response["success"] = 0;
$response["message"] = "I'm sorry, this username is already in use";
die(json_encode($response));
}
// Query to create a user
$query = "INSERT INTO registration (username, password) VALUES (:user, :pass)";
// Update variables with actual data
$query_params = array(':user' => $_POST['username'], ':pass' => $_POST['password']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
$response["success"] = 0;
$response["message"] = "Database Errror2. Please Try Again!";
die(json_encode($response));
}
// By this point, user has been added
$response["success"] = 1;
$response["message"] = "User Successfully Added!";
echo json_encode($response);
}
else{
?>
<h1>Register</h1>
<form action="register.php" method="post">
Username:<br />
<input type = "text" name="username" value ="" />
<br /><br />
Password:<br />
<input type="password" name="password" value="" />
<br /><br />
<input type="submit" value="Register New User" />
</form>
<?php
}
?>
logcat error:
04-05 13:35:53.441: W/dalvikvm(8373): threadid=11: thread exiting with uncaught exception (group=0x418b3898)
04-05 13:35:53.471: E/AndroidRuntime(8373): FATAL EXCEPTION: AsyncTask #1
04-05 13:35:53.471: E/AndroidRuntime(8373): java.lang.RuntimeException: An error occured while executing doInBackground()
04-05 13:35:53.471: E/AndroidRuntime(8373): at android.os.AsyncTask$3.done(AsyncTask.java:299)
Any help would be great thanks
I too had similar issue and i solved by changing it's onPostExecute method. just give a try to below code.
protected void onPostExecute(String file_url) {
if (pDialog != null) {
if (pDialog.isShowing()) {
pDialog.dismiss();
}
}
}
I am developing an Android app in which I am using JSon to get values from databas. In database there is particular text for each string A-Z. and when a string is returned from A-Z the corresponding result has to be displayed... I am giving the code for that.. but the problem result is not displayin.. I used PHP code for connceting..
PHP
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["costone"]))
{
$costone = $_GET['costone'];
// get a product from products table
$result = mysql_query("SELECT *FROM sletter WHERE costone = $costone");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["costone"] = $result["costone"];
$product["custone"] = $result["custone"];
$product["fvowel"] = $result["fvowel"];
$product["cornerstone"] = $result["cornerstone"];
$product["cupstone"] = $result["cupstone"];
$product["firstvowel"] = $result["firstvowel"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
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);
}
?>
Activity
String custone, costone;
TextView txtName9, txtNzme10;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String url_cup_stone = "http://iascpl.com/app/get_cup_stone.php";
private static final String url_first_vowel = "http://iascpl.com/app/get_first_vowel.php";
private static final String TAG_CUPSTONE = "cupstone";
private static final String TAG_FIRSTVOWEL = "firstvowel";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fullexplanation_xm);
txt27.setText(getIntent().getStringExtra("aChar"));
TextView txt28 = (TextView) findViewById(R.id.textView51);
txt28.setText(getIntent().getStringExtra("aChar1"));
costone = txt27.getText().toString();
custone = txt28.getText().toString();
/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(FullExplanation.this);
pDialog.setMessage("Loading the result... Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... args)
{
TextView txt27 = (TextView) findViewById(R.id.textView48);
TextView txt28 = (TextView) findViewById(R.id.textView51);
costone = txt27.getText().toString();
custone = txt28.getText().toString();
params.add(new BasicNameValuePair("costone", costone));
params.add(new BasicNameValuePair("custone", custone));
JSONObject json9 = jsonParser.makeHttpRequest(
url_corner_stone, "GET", params);
JSONObject json10 = jsonParser.makeHttpRequest(
url_cup_stone, "GET", params);
int success9 = json9.getInt(TAG_SUCCESS);
int success10 = json10.getInt(TAG_SUCCESS);
if (success9 == 1) {
// successfully received product details
JSONArray productObj = json9
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
final JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName9 = (TextView) findViewById(R.id.textView49);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
txtName9.setText(product.getString(TAG_CORNERSTONE));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} else {
// product with pid not found
}
if (success10 == 1) {
// successfully received product details
JSONArray productObj = json10
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
final JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName10 = (TextView) findViewById(R.id.textView52);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
txtName10.setText(product.getString(TAG_CUPSTONE));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} else {
// product with pid not found
}
}
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 got all details
pDialog.dismiss();
}
}
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();
This question already has answers here:
String.equals versus == [duplicate]
(20 answers)
Closed 10 years ago.
I have an AsyncTask class in my application but what I noticed is that whatever the result passed on to to the onPostExecute function is, it will still direct the application to go to the else{} even though it perfectly fits the if statement. Why is that happening?
Here is the AsyncTask I am running :
class CheckPassword extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ChooseTable.this);
pDialog.setMessage("Checking Password. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... p) {
String password = p[0];
int success;
String access = "";
try {
// Building Parameter
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("password", password));
//ipaddress of server
Intent i = getIntent();
Bundle b = i.getExtras();
ipaddress = b.getString("IP_Address");
if(ipaddress != "" || ipaddress != "...:")
{
// single table url
String url = "http://"+ipaddress+"/MenuBook/checkSpecial.php";
Log.d("URL", url + "");
JSONObject json = jsonParser.makeHttpRequest(
url, "GET", params);
Log.d("JSON OBJECT", json+"");
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received table details
JSONArray result = json
.getJSONArray("result"); // JSON Array
// get table availability from JSON Array
JSONObject accessObj = result.getJSONObject(0);
access= accessObj.getString("allowAccess");
}
else
{
status = "TABLE NOT FOUND";
}
}
else
{
status = "FAILED TO RETRIEVE SERVER IP ADDRESS";
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("ALLOW ACCESS", access+"");
return access;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
Log.d("RESULT", result+"");
if(result == "YES"){
Toast.makeText(ChooseTable.this, "ACCESS ALLOWED", Toast.LENGTH_LONG).show();
}else if (result== "NO"){
Toast.makeText(ChooseTable.this, "Access Denied", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(ChooseTable.this, status, Toast.LENGTH_LONG).show();
}
}
}
You need to use the equals method to compare two Strings:
if (result.equals("YES"))
and
if (result.equals("NO"))
Need help on android =( been stuck on this for ages! My codes are as shown.
public class AllUsersActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> usersList;
// url to get all users list
private static String url_all_users = "http://10.0.2.2/android_connect/get_all_users.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_USERS = "users";
private static final String TAG_UID = "UserID";
private static final String TAG_FIRSTNAME = "FirstName";
// users JSONArray
JSONArray users = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_users);
// Hashmap for ListView
usersList = new ArrayList<HashMap<String, String>>();
// Loading users in Background Thread
new LoadAllusers().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String uid = ((TextView) view.findViewById(R.id.uid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
UserDetailsActivity.class);
// sending uid to next activity
in.putExtra(TAG_UID, uid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllusers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllUsersActivity.this);
pDialog.setMessage("Loading users. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All users from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_users, "GET", params);
// Check your log cat for JSON reponse
Log.d("All users: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// users found
// Getting Array of users
users = json.getJSONArray(TAG_USERS);
// looping through All users
for (int i = 0; i < users.length(); i++) {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_UID);
String name = c.getString(TAG_FIRSTNAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_UID, id);
map.put(TAG_FIRSTNAME, name);
// adding HashList to ArrayList
usersList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all users
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllUsersActivity.this, usersList,
R.layout.list_item, new String[] { TAG_UID,
TAG_FIRSTNAME},
new int[] { R.id.uid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
Can anyone please help me! The error i've been getting is Error Parsing Data Org.json.JSONException: Value cannot be converted to JSONObject
Heres the JSON string
Array{"Users":[{"UserID":"1","FirstName":"lalawee","Email":"12345","Password":null},{"UserID":"2","FirstName":"shadowblade721","Email":"12345","Password":null},{"UserID":"3","FirstName":"dingdang","Email":"12345","Password":null},{"UserID":"4","FirstName":"solidsnake0328","Email":"12345","Password":null}],"success":1}
Is the error lying in the JSON parser class?
EDIT: here the code for the php script that outputs the array above. can anyone tell me what's wrong with the php script that outputs the word array before the json string? Sorry for the trouble. I'm new to coding. Been following online tutorials but stuck on this for a few days now.
<?php
/*
* Following code will list all the Users
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all Users from Users table
$result = mysql_query("SELECT * FROM Users") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// Users node
$response["Users"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$user[] = array();
$user["UserID"] = $row["UserID"];
$user["FirstName"] = $row["FirstName"];
$user["Email"] = $row["Email"];
$user["Password"] = $row["Password"];
// push single User into final response array
array_push($response["Users"], $user);
}
// success
$response["success"] = 1;
echo $response;
// echoing JSON response
echo json_encode($response);
}
else {
// no Users found
$response["success"] = 0;
$response["message"] = "No Users found";
// echo no users JSON
echo json_encode($response);
}
?>
Use GSON library instead, it is official Google and works like a charm. No HashMaps etc, immediate objects.
Take a look at it here.
As the error suggests, your JSON string does not represent a valid JSON object.
Try like this(without Array in the beginning):
{"Users":[{"UserID":"1","FirstName":"lalawee","Email":"12345","Password":null},{"UserID":"2","FirstName":"shadowblade721","Email":"12345","Password":null},{"UserID":"3","FirstName":"dingdang","Email":"12345","Password":null},{"UserID":"4","FirstName":"solidsnake0328","Email":"12345","Password":null}],"success":1}Array{"Users":[{"UserID":"1","FirstName":"lalawee","Email":"12345","Password":null},{"UserID":"2","FirstName":"shadowblade721","Email":"12345","Password":null},{"UserID":"3","FirstName":"dingdang","Email":"12345","Password":null},{"UserID":"4","FirstName":"solidsnake0328","Email":"12345","Password":null}],"success":1}
You can check the validity of your JSON String here: http://jsonlint.com/