I have two applications, one I send long. and latitude coordinates to a php file and the other application retrieves the long. and lat. coords. In order to test and see if I could get the first working I create a function I posted the latitude and long. coords two the php service and I got them back in the same Application. I placed them in a toast to see if it works. I even implemented location listener to upload the coordinates and retrieve them in the same application to test before trying to receive them in the other application. It works fine. But when I try to use the same code in the other application for receiving the coordinates, I receive blank coordinates. I debugged it and its just blank, as if when I make the call to the server from the other application it erases the current values in the php service.
Code for placing the coordinates in application one:
public void postData(String longCord, String latCord) throws JSONException{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(".../android/serverFile.php");
JSONObject json = new JSONObject();
try {
// JSON data:
json.put("longitude", longCord);
json.put("latitude", latCord);
JSONArray postjson=new JSONArray();
postjson.put(json);
// Post the data:
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
// Execute HTTP Post Request
//System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
// for JSON:
if(response != null)
{
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
JSONObject jsonObj = new JSONObject(jsonStr);
// grabbing the menu object
String longitudecord = jsonObj.getString("lon");
String latitudecord = jsonObj.getString("lat");
Toast.makeText( getApplicationContext(),longitudecord,Toast.LENGTH_SHORT).show();
Toast.makeText( getApplicationContext(),latitudecord,Toast.LENGTH_SHORT).show();
}
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
php file:
<?php
$json = $_SERVER['HTTP_JSON'];
$data = json_decode($json);
$lon = $data->longitude;
$lat = $data->latitude;
$variable = array( 'lon' => "$lon", 'lat' => "$lat" );
// One JSON for both variables
echo json_encode($variable);
?>
Now when I run this code on the other application...Its the same as above minus posting the coordinates...I get lon:"" and lat:"". Sort of like by making the request it has somehow erased the info that was posted by other application. Is this the case?
public void recieveData() throws JSONException{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(".../android/serverFile.php");
try {
HttpResponse response = httpclient.execute(httppost);
// for JSON:
if(response != null)
{
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String jsonStr = sb.toString();
JSONObject jsonObj = new JSONObject(jsonStr);
// grabbing the menu object
String longitudecord = jsonObj.getString("lon");
String latitudecord = jsonObj.getString("lat");
Toast.makeText( getApplicationContext(),longitudecord,Toast.LENGTH_SHORT).show();
Toast.makeText( getApplicationContext(),jsonStr,Toast.LENGTH_SHORT).show();
}
Try to access your URL in browser and make sure your PHP script does not give any errors in the following lines (since you don't supply any JSON input in the second application):
$data = json_decode($json);
$lon = $data->longitude;
$lat = $data->latitude;
Also, it would be nice to hear, how'd you save your lat/lon on the server, so they persist between the calls.
For example, you may use this PHP code:
$db_host = "localhost";
$db_name = "********";
$db_user = "********";
$db_pass = "********";
// connect to MySQL
$db = mysql_connect($db_host, $db_user, $db_pass);
if( !$db ) {
die( 'Unable to connect to server : ' . mysql_error() );
}
// select the DB
if( !mysql_select_db($db_name) ) {
die( 'Unable to select DB : ' . mysql_error() );
}
// create table, if not exists
if( !mysql_query( "CREATE TABLE IF NOT EXISTS `locations` (
`id` int(11) NOT NULL auto_increment,
`latitude` double NOT NULL COMMENT 'latitude',
`longitude` double NOT NULL COMMENT 'longitude',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;"
) ) {
die( 'Unable to create table : ' . mysql_error() );
}
// save values
mysql_query( "INSERT INTO locations (`latitude`, `longitude`) VALUES ( '$lat', '$lon')" );
// read them back
$track = array()
$result = mysql_query( "SELECT * FROM locations" );
while( $data = mysql_fetch_assoc($result) ) {
$track[] = array(
'latitude' => $data['latitude'],
'longitude' => $data['longitude'] );
}
// here you may convert `track` into JSON / XML and send coordinates list to your application
Related
i want to send all contacts with contact name and number in one row in one array in my android application like
john => "+92312xxxxxxx" ,
Right now i'm using namevaluepairs to post two arrays but it's not working like :
public class ContactList extends Activity {
public TextView outputText;
String phoneNumber = null;
String names = null;
String[] keyValue;
String[] kes;
int Count;
String s = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
outputText = (TextView) findViewById(R.id.textView1);
fetchContacts();
//Http connection
InputStream is=null;
List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>(1);
for (int i = 0; i < Count ; i++)
{
nameValuePairs.add(new BasicNameValuePair("CN[]", keyValue[i]));
nameValuePairs.add(new BasicNameValuePair("names[]",kes[i]));
Log.i("Response", "you sent :" +kes[i]+" :"+ keyValue[i] + "\n ");
}
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.107/older/ContactList.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(ClientProtocolException e)
{
Log.e("ClientProtocol","Log_tag");
e.printStackTrace();
System.out.println("Excep: "+e);
}
catch(IOException e)
{
Log.e("Log_tag","IOException");
e.printStackTrace();
}
String result = "";
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");
}
reader.close();
is.close();
result=sb.toString();
Log.i("Response", "result "+ result);
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
//result = "[{\"0\":\"Muhaimin\",\"1\":\"3\",\"2\":\"o+\"}]";
try
{
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++)
{
s= s +";"+ jArray.getString(i) + "\n";
}
}
catch (Exception e)
{
Log.e("Response", "error fetching indexes" + e);
}
String[] friends= s.split(";");
StringBuffer output = new StringBuffer();
for (int i = 0; i < friends.length; i++)
{
Log.i("List","Your friends namee"+friends[i]);
output.append("\n Your friend's number"+ friends[i]);
}
}
//Fetch Contacts
public void fetchContacts() {
// String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
// Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
//String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
// String DATA = ContactsContract.CommonDataKinds.Email.DATA;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);
// Loop for every contact in the phone
Count = cursor.getCount();
if (cursor.getCount() > 0) {
keyValue= new String[Count];
kes= new String[Count];
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));
if (hasPhoneNumber > 0) {
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);
while (phoneCursor.moveToNext())
{
int i=0;
String stu = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
phoneNumber +=":"+ stu;
names +=":" + name;
Log.i("List",stu + name +"\n" );
}
phoneCursor.close();
}
}
}
keyValue = phoneNumber.split(":");
kes = names.split(":");
Log.i("List","24th"+keyValue[23]);
Toast.makeText(getApplicationContext(), "99th "+keyValue[909] ,Toast.LENGTH_LONG).show();
}
PHP after receiving contacts will match them and return only those which have a match with database contacts. And then it returns contacts with names
i'm stuck with sending and receving part
Here is php code
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'verification');
define('DB_USER','root');
define('DB_PASSWORD','');
// 1. Create a database connection
$connection = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD);
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
$PhoneNum= $_POST["CN"];
$i=0;
$j=0;
$friends = array();
$Invite = array();
unset ($PhoneNum[0]);
foreach ($PhoneNum as $i=> $element){
//or do whatever you need to do to that variable
$query="SELECT Number FROM `user` WHERE Number=$element";
$query_exec = mysqli_query($connection ,$query);
if (!$query_exec)
{ echo mysql_error(); }
ELSE {
if(mysqli_num_rows($query_exec)>0)
{
$friends["$j"]= $PhoneNum[$i];
$j++;
}
else
{
;
}}
}
echo (json_encode($friends));
?>
You'll get a URL now that would look like:
www.example.com/yourscript?CN[]=keyValue1&names[]=key1&CN[]=keyValue2&names[]=key2 etc.. going on untill your whole list has looped.
I doubt that is what your PHP script wants to receive, you probably want to send the POST for each time you increment the loop. But thats just conjecture untill you post more information/code.
Instead send a JSON array as the value of the nameValuePair and convert it to a PHP array using json_decode function in the server side.
Hi i am new in android php client server. At present, i am doing the response from php sql server sending to Android client multiple result from sql row. Previously, i sending a simple string and receive android like below:
$result_data = array(
'ResultArray' => 'success',
);
#Output the JSON data
echo json_encode($result_data);
Then in android:
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
String resultLoging = jsonObject.getString("ResultArray");
Now i want to receive from database having 3 columns: id, phone, name. How would i do that? Thank for your helping
use the following format in php
$result = mysql_query("SELECT *FROM tablename") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0)
{
// looping through all results
// products node
$response["details"] = array();
while ($row = mysql_fetch_array($result))
{
// temp user array
$product = array();
$product["id"] = $row["id"];
$product["name"] = $row["name"];
array_push($response["details"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
In android
get success value
int success = json.getInt(TAG_SUCCESS);
get the datas using following format
JSONArray spi = json.getJSONArray("details");
Use a for loop to get the object values in the array
for (int i = 0; i < spi.length(); i++)
{
JSONObject c = spi.getJSONObject(i);
id = c.getString("id");
}
Use JSONArray for multiple json result :
JSONArray jsonArray = jsonObject.getJSONArray("ResultArray");
Iterate JSONArray and get value from JSONObject :
for (int i=0;i<jsonArray.length();i++){
JSONObject json = jsonArray.getJSONObject(i);
String id = json.getString("id");
String phone = json.getString("phone");
String name = json.getString("name");
}
just found this, would be the best for my question
https://stackoverflow.com/a/3563464/1345454
$results = array();
while($row = mysql_fetch_array($sql))
{
$results[] = array(
'title' => base64_decode($row['title']),
'price' => $row['price'],
'seller_user' => $row['user']
);
}
$json = json_encode($results);
try this
$result_data = array(
'ResultArray' => 'success',
);
echo json_encode(array('result'=>$result_data));
in android
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl("url of php file");
JsonArray arry = json.getJSONArray("result");
JSONObject c = arry .getJSONObject(0);
String resultarr= c.getString("ResultArray");
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();
// System.out.println(json);
} 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;
}
}
What I am trying is I get my current location (the coordinates) and i want to post those coordinates on a server. I have made a server using WAMP. I have written php code and the code in java but its showing me error in the POST word. Please tell me if its correct or if i can modify it!!
PHP CODE
<?php
echo 'Hello, world!';
$json = $_GET['jsonpost'];//get the post you sent...
$data = json_decode($json); //decode the json formatted string...
print_r($data);
$id = $data->id;
$devid = $data->devid;
$latitude = $data->latitude;
$longitude = $data->longitude;
$service = $data->service;
$con = mysql_connect("","","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("a5234826_ul", $con);
$devid = $_POST['devid'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
echo "devid" +$devid;
echo "latitude" + $latitude;
echo "longitude" + $longitude;
$sql = "INSERT INTO `a5234826_ul`.`locations` (
`id` ,
`devid` ,
`latitude` ,
`longitude` ,
`service`
)
VALUES (
NULL , '$devid', '$latitude', '$longitude', '$service'
)";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
echo json_encode($variable);
?>
EDITED
LocationService.java
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "lock");
wl.acquire();
context = this;
final String who = intent.getStringExtra("who");
final LocationManager locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
final LocationListener listener = new LocationListener(){
// start location changed
public void onLocationChanged(Location loc) {
double latitude = loc.getLatitude();
double longitude = loc.getLongitude();
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://.../serverFile.php");
JSONObject json = new JSONObject();
TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
String devid = telephonyManager.getDeviceId();
String postData = "{\"request\":{\"type\":\"locationinfo\"},\"userinfo\":{\"latitude\":\""+latitude+"\",\"longitude\":\""+longitude+"\",\"devid\":\""+devid+"\"}}";
try {
json.put("longitude", longitude);//place each of the strings as you did in postData method
json.put("latitude", latitude);
json.put("devid", devid);
JSONArray postjson=new JSONArray();
postjson.put(json);
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
HttpResponse response = httpclient.execute(httppost);
// for JSON retrieval:
if(response != null)
{
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String jsonStr = sb.toString(); //take the string you built place in a string
JSONObject rec = new JSONObject(jsonStr);
String longitudecord = rec.getString("lon");
String latitudecord = rec.getString("lat");
// ...
}
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (who.equals("me")){
Intent i = new Intent(context.getPackageName()+".LocationReceived");
i.putExtra("lat", String.valueOf(latitude));
i.putExtra("longitude", String.valueOf(longitude));
i.putExtra("accuracy", String.valueOf(loc.getAccuracy()));
context.sendBroadcast(i);
Notification notif = new Notification();
NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notif.tickerText = "Location Found!";
notif.icon = R.drawable.ic_launcher;
notif.flags = Notification.FLAG_AUTO_CANCEL;
notif.when = System.currentTimeMillis();
Intent notificationIntent = new Intent(context, TestLocatorActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
notificationIntent.putExtra("lat", String.valueOf(latitude));
notificationIntent.putExtra("longitude", String.valueOf(longitude));
notificationIntent.putExtra("accuracy", String.valueOf(loc.getAccuracy()));
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notif.setLatestEventInfo(context, "Location Found!", "Click to open.", contentIntent);
nm.notify(0, notif);
} else {
SmsManager smsMan = SmsManager.getDefault();
smsMan.sendTextMessage(who, null, "http://maps.google.com/maps?q=loc:"+latitude+","+longitude, null, null);
smsMan.sendTextMessage(who, null, "Latitude: "+latitude+"\nLongitude: "+longitude, null, null);
}
locMan.removeUpdates(this);
try {
wl.release();
} catch (Exception e){
e.printStackTrace();
}
stopSelf();
}
public void onProviderDisabled(String provider){
}
public void onProviderEnabled(String provider) {
//Log.i(tag, "GPS IS ON");
}
public void onStatusChanged(String provider, int status, Bundle extras){
switch(status) {
case LocationProvider.OUT_OF_SERVICE:
case LocationProvider.TEMPORARILY_UNAVAILABLE:
case LocationProvider.AVAILABLE:
break;
}
} };
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
return 2;
}
}
The main problem I can see here is that You are talking about POST but in Your android LocationService You are creating an HttpGet object:
HttpGet httppost = new HttpGet("http://.../serverFile.php");
and then from nowhere a httpost variable is used as post:
post.setHeader("json",json.toString());
post.getParams().setParameter("jsonpost",postjson);
In PHP I'm not sure what are You trying to achieve by this:
$_SERVER['HTTP_JSON'];
cos I'm sure there is no such index. Instead call
$_POST['jsonpost']; // <-- that is the parameter name from Your JAVA code...
or
$_GET['jsonpost']; // <-- that is the parameter name from Your JAVA code...
It almost looks like You COPY + PASTE the code from similar question here (which this one should be a duplicate of!): Sending Data From Android To Server with JSON data .
EDIT : OK, let's assume that Your android JAVA code is OK and You are sending data through GET. Then You will have to repair Your PHP - try this:
<?php
echo 'Hello, world!';
$json = $_GET['jsonpost']; // get the json you sent through GET...
$data = json_decode($json); // decode the json formatted string...
print_r($data); // print out the $data variable to see whether everything is OK...
$devid = $data->devid;
$longitude = $data->longitude;
$latitude = $data->latitude;
$con = mysql_connect("","","") or die('Could not connect: ' . mysql_error());
mysql_select_db("a5234826_ul", $con);
echo "devid" +$devid;
echo "latitude" + $latitude;
echo "longitude" + $longitude;
$sql = "INSERT INTO `a5234826_ul`.`locations` (
`devid`,
`latitude`,
`longitude`
) VALUES (
'$Devid',
'$latitude',
'$longitude'
);";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
mysql_close($con);
echo json_encode($variable);
You should proceed with the print_r($data); and see whether the data arrived and whether the JSON was decoded and also to see what properties it contains.
EDIT 2 Due to posted logcat: Did You read the error from the logcat? It is so clear!!! Programmer should of course understand what an error message is saying and should thing about what he is doing, not just copy+pasting pieces of code from somewhere without thinking of it... In Your manifest.xml You need to add a permision READ_PHONE_STATE - read about permissions here: http://developer.android.com/reference/android/Manifest.permission.html and about adding permissions to manifest.xml here: http://developer.android.com/guide/topics/security/security.html#permissions.
Im a newbie to android, I am learning to connect to a server through android client using Php, MySql and JSON. For testing purpose im running on localhost.
So for here's what I've done.
Database demo.php
public class Database_demo extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
List<String> r = new ArrayList<String>();
try{
//http post
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/PhpAndMySql/category.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
}
//Convert response to string
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e)
{
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
}
//END Convert response to string
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
r.add(json_data.getString("category"));
}
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, r));
}
catch(JSONException e1){
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
}
}
}
category.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$q=mysql_query("SELECT * FROM category ORDER BY 'category'.'category' ASC");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
MySQL
CREATE TABLE `test`.`category` (
`category_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`category` VARCHAR( 255 ) NOT NULL
) ENGINE = MYISAM ;
I am getting a NullPointer Exception, when I execute in android.
Is the Php File correct?
Please I need your help with this!
Thanks
I'm thinking your php should be as follows (instead of quotes on the table.column use backticks).
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$q=mysql_query("SELECT * FROM category ORDER BY `category` ASC");
$output = array();
while($row = mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
I am currently trying to develop an app that among other things can send and receive data from a mysql server.
The app calls a php script which makes the connection to the mysql server. I have successfully developed the sending part and now I want to retrieve data from mysql and display it on an android phone.
The mysql table consists of 5 columns:
bssid
building
floor
lon
lat
The php file getdata.php contains:
<?php
$con = mysql_connect("localhost","root","xxx");
if(!$con)
{
echo 'Not connected';
echo ' - ';
}else
{
echo 'Connection Established';
echo ' - ';
}
$db = mysql_select_db("android");
if(!$db)
{
echo 'No database selected';
}else
{
echo 'Database selected';
}
$sql = mysql_query("SELECT building,floor,lon,lat FROM ap_location WHERE bssid='00:19:07:8e:f7:b0'");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close(); ?>
This part is working fine, when tested in a browser.
The java code for connecting to php:
public class Database {
public static Object[] getData(){
String db_url = "http://xx.xx.xx.xx/getdata.php";
InputStream is = null;
String line = null;
ArrayList<NameValuePair> request = new ArrayList<NameValuePair>();
request.add(new BasicNameValuePair("bssid",bssid));
Object returnValue[] = new Object[4];
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httppost = new HttpPost(db_url);
httppost.setEntity(new UrlEncodedFormEntity(request));
HttpResponse response = httpclient.execute(httppost, localContext);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection" +e.toString());
}
String result = "";
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error in http connection" +e.toString());
}
try
{
JSONArray jArray = new JSONArray(result);
JSONObject json_data = jArray.getJSONObject(0);
returnValue[0] = (json_data.getString("building"));
returnValue[1] = (json_data.getString("floor"));
returnValue[2] = (json_data.getString("lon"));
returnValue[3] = (json_data.getString("lat"));
}catch(JSONException e){
Log.e("log_tag", "Error parsing data" +e.toString());
}
return returnValue;
}
}
This is a modified code used to send data to the mysql server, but something is wrong.
I've tried to test it by setting different returnValues in the code and this shows me that the part with the httpclient connection does not run.
Can you guys help me?
I hope this is not too confussing, and if you want I can try to explain it futher.
Use HttpGet instead of HttpPost and parse your url.
Here is a class I always use to GET
public JSONObject get(String urlString){
URL currentUrl;
try {
currentUrl = new URL(currentUrlString);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
HttpURLConnection urlConnection = null;
InputStream in;
BufferedReader streamReader = null;
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
try {
urlConnection = (HttpURLConnection) currentUrl.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
while ((inputStr = streamReader.readLine()) != null) {
responseStrBuilder.append(inputStr);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
if(null != streamReader){
try {
streamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
return new JSONObject(responseStrBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Try to test with get("http://echo.jsontest.com/key/value");