How to manipulate data after its retrieved via remote database - java

So I've used code examples from all over the net and got my app to accurately call a .php file on my server, retrieve the JSON data, then parse the data, and print it.
The problem is that its just printing to the screen for sake of the tutorial I was following, but now I need to use that data in other places and need help figuring out that process.
The ultimate goal is to return my db query with map coordinates, then plot them on a google map. I have another app in which I manually plot points on a map, so I'll be integrating this app with that once I can get my head around how to correctly manipulate the data returned.
public class Remote extends Activity {
/** Called when the activity is first created. */
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a crude view - this should really be set via the layout resources
// but since its an example saves declaring them in the XML.
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Set the text and call the connect function.
txt.setText("Connecting...");
//call the method to run the data retreival
txt.setText(getServerData(KEY_121));
}
public static final String KEY_121 = "http://example.com/mydbcall.php";
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
//the year data to send
//ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//nameValuePairs.add(new BasicNameValuePair("year","1970"));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
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();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","longitude: "+json_data.getDouble("longitude")+
", latitude: "+json_data.getDouble("latitude")
);
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
}
So the code:
returnString += "\n\t" + jArray.getJSONObject(i);
is what is currently printing to the screen.
What I have to figure out is how to get the data into something I can reference in other spots in the program, and access the individual elements
ie:
double longitude = jArray.getJSONObject(3).longitude;
or something to that effect..
I figure the class getServerData will have to return a Array type or something?
Any help is appreciated, thanks.

First of all, you should not be making server calls on the UI thread. Use AsyncTask, or a Service to make remote calls on a separate thread.
Next, I don't know the exact structure of your returned Json, but it sounds like you want to convert it into a cleaner object model. Just create an object that has a field for each entry in your Json array, and replace your log statements with assignment statements. I.e:
class Location {
private double latitude;
private double longitude;
public Location(double latitude, double longitude) { ....}
}
private List<Location> getServerData(String returnString) {
List<Location> result = new ArrayList<Location>();
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
Location loc = new Location(json_data.getDouble("latitude"), json_data.getDouble("longitude"));
result.add(loc);
}
return result;
}

Related

httpclient (phpmyadmin) not working on Android 4.0+

I use this code below, it works perfectly in Android 2.3.3. However, in 4.0+ it can't connect to database somehow. I saw some posts about you need to get it in a asynch class. I also tried that, but I can't seems it to work. I probably use it wrong, but it is hard for me to understand.
public class connector extends Activity {
/** Called when the activity is first created. */
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getServerData(null);
}
//i use my real ip here
public String getServerData(String returnString) {
System.out.println("going to connector class");
InputStream is = null;
final String KEY_121 = "http://10.0.0.128/connector.php";
String result = "";
//the year data to send
// ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// nameValuePairs.add(new BasicNameValuePair("year","1970"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
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();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","ID: "+json_data.getInt("ID")+
", \nActara: "+json_data.getString("Actara")
);
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
}
Logcat error (on 4.0+):
11-12 12:02:35.658: E/log_tag(14083): Error in http connection android.os.NetworkOnMainThreadException
11-12 12:02:35.658: E/log_tag(14083): Error converting result java.lang.NullPointerException
11-12 12:02:35.663: E/log_tag(14083): Error parsing data org.json.JSONException: End of input at character 0 of
Only the first error line is important, because it can't connect to a database, it gives a nullPointer (2nd and 3rd error).
This is what I tried in Asynch:
public class connector extends Activity {
/** Called when the activity is first created. */
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new BackgroundAsyncTask().execute();
}
public class BackgroundAsyncTask extends
AsyncTask<Void, Integer, Void> {
InputStream is = null;
final String KEY_121 = "http://10.0.0.128/connector.php";
String result = "";
String returnString = "";
protected void onPostExecute(Void result) {
}
#Override
protected void onPreExecute() {
System.out.println("onPreExecute");
}
protected Void doInBackground(String... params) {
try{
System.out.println("background in progress");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
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();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","ID: "+json_data.getInt("ID")+
", \nActara: "+json_data.getString("Actara")
);
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return null;
}
protected void onProgressUpdate(Integer... values) {
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
}
}
Someone that can help me? I don't know for sure what the real cause is why it isn't working for 4.0+.
If you need more info, just say it, and I will post it.
Code can be a bit messy, I didn't really "clean" it up yet properly.
Since Android 3.0 you are not allowed to do network stuff on the main thread. Why? because network problems will lead to a slow ui. So you have to do all the http stuff in a new thread. You are on the right path but you made a mistake in your AsyncTask. Delete the empty doInBackground method in you async task and write #Override over your method.
android.os.NetworkOnMainThreadException
this eror comes With HoneyComb(3.0 or Later). you can not perform a networking operation on its main thread as documentation says. to getting ride of this you must use handler or asynctask. AFAIK There is no another way to do it.
you can See this for More Details WHY ICS Crashes your App
Try Using Below Code Snippet
new Thread(){
public void run(){
//do your Code Here
}
}.start();
Ok right...
After searching for few hours, making this question, then 10 minutes later, you find a solution...
Option 1:
I added this line:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
But I reccomend NOT to use option 1, this is a bad solution for real. Use option 2!
//===========================================================================
Option 2:
Used this tutorial to make a proper ASyncTask: http://www.elvenware.com/charlie/development/android/SimpleHttpGetThread.html
//===========================================================================
Used ASyncTask as final (option 2).
why you are passing null in function of web connection and web service .?
getServerData(null);

Does it counts as a REST?

I am trying to figuring out about REST method. I watched few videos from google conference about REST technology but what I saw was app's implementation of connectivity with database. So I would like to know if my code would count as a REST.
PHP code:
<?php
mysql_connect("localhost","*****","********");
mysql_select_db("********");
$cname = mysql_real_escape_string($_REQUEST['cname']);
$q=mysql_query("SELECT mdl_course_sections.summary FROM mdl_course, mdl_course_sections WHERE mdl_course.id = mdl_course_sections.course AND mdl_course.fullname = '$cname' AND mdl_course_sections.section > 0");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
JAVA code:
public class CourseSegmentsActivity extends ListActivity{
String courseName = null;
String segmentName = null;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Intent i = getIntent();
courseName = i.getStringExtra("courseName");
ArrayList<HashMap<String,String>> myCoursesList = new ArrayList<HashMap<String,String>>();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("cname",""+courseName));
InputStream is = null;
String result = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("****************");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-10"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
JSONArray jArray = new JSONArray(result);
for(int ii=0;ii<jArray.length();ii++){
JSONObject json_data = jArray.getJSONObject(ii);
segmentName = json_data.getString("summary");
HashMap<String,String> map = new HashMap<String, String>();
map.put("summary", segmentName);
myCoursesList.add(map);
}
} catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, myCoursesList,R.layout.course_segments_list_layout,
new String[] {"summary"}, new int[] { R.id.name});
setListAdapter(adapter);
}
}
If not what I am missing?
No, you are NOT. if you follow REST standards, you should be using http protocol efficiently. As per REST standard,
if you are reading data - use GET
if you are reading meta-data - use HEAD
if you are writing data - use POST
if you are modifying data - use PUT
if you are deleting - use DELETE,
please refer to the w3c specification of http protocol(RFC2616) for further info.
No, you are using POST to retrieve data. However, POST is meant to be used to edit existing data.
Query strings are also rather unlikely when using REST - usually you use the URL to specify resources
Have a look at http://en.wikipedia.org/wiki/REST#RESTful_web_services

mySQL to PHP to JSON: String Cannot be Converted to JSONObject

I am trying to get data from a mySQL database using PHP. This is my fist real attempt of getting data remotely & using JSON. The php file is functioning correctly because it outputs in a browser as a JSON string and i valadated it using JSONLint. So, I am not sure what I have wrong here. Any help would be greatly appreciated
This is what LogCat is throwing:
Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONObject
threadid=9: thread exiting with uncaught exception (group=0x401dce20)
FATAL EXCEPTION: Thread-10
java.lang.NullPointerException
at com.andaero.test.JSON.JSONMain$1.run(JSONMain.java:39)
at java.lang.Thread.run(Thread.java:1020)
UPDATE: I removed the echo method from the php file as Mark requested. I think it has to do with "JSONArray a = json.getJSONArray("regulatory"). I also tried everyone else's approach with no prevail.
Here are the classes:
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "regulatory";
JSONObject jArray = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
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();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
The List Activity:
public class JSONMain extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
final ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
new Thread(new Runnable() {
public void run() {
JSONObject json = JSONfunctions
.getJSONfromURL("http://192.168.1.34/andaero/regulatory_list_ASC.php");
try {
JSONArray a = json.getJSONArray("regulatory");
for (int i = 0; i < a.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = a.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("label", e.getString("label"));
map.put("title", e.getString("title"));
map.put("caption", e.getString("description"));
map.put("dummy", e.getString("gotoURL"));
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
}).start();
ListAdapter adapter = new SimpleAdapter(this, mylist,
R.layout.list_item, new String[] { "label", "title", "caption",
"dummy" }, new int[] { R.id.label, R.id.listTitle,
R.id.caption, R.id.dummy });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
Toast.makeText(JSONMain.this,
"ID '" + o.get("id") + "' was clicked.",
Toast.LENGTH_SHORT).show();
}
});
}
}
The PHP:
<?php
//MySQL Database Connect
include 'andaerologin.php';
mysql_select_db("andaero");
$sql=mysql_query("select * from regulatory_list");
$output = array();
while($row = mysql_fetch_assoc($sql)) {
$output['regulatory'][] = $row;
}
exit (json_encode($output));
mysql_close();
?>
Try changing your PHP to this:
$output = new stdClass();
$output->regulatory = array();
while($row = mysql_fetch_assoc($sql)) {
$output->regulatory[] = $row;
}
header('Content-type: application/json');
echo (json_encode($output));
Try changing your PHP script to this:
<?php
// Hide errors to prevent data corruption
ini_set('display_errors', 0);
// For debugging, uncomment these lines to show errors
//ini_set('display_errors', 0);
//error_reporting(E_ALL);
//MySQL Database Connect
require 'andaerologin.php';
if (!mysql_select_db("andaero")) {
// Use trigger_error() so you can find out in the server logs if something
// goes wrong
trigger_error('Unable to select MySQL database');
header('HTTP/1.1 500 Internal Server Error');
exit;
}
$query = "SELECT *
FROM regulatory_list";
if (!$result = mysql_query($query)) {
trigger_error('MySQL error: '.mysql_error());
header('HTTP/1.1 500 Internal Server Error');
exit;
}
if (!mysql_num_rows($query)) {
trigger_error('MySQL returned no results');
header('HTTP/1.1 500 Internal Server Error');
exit;
}
// Build an array of the results
$output = array();
while ($row = mysql_fetch_assoc($result)) {
$output[] = $row;
}
// Send the results back as JSON
exit(json_encode($output));
// Closing the database connection happens implicitly at the end of the
// script. Also, you don't need to have a closing PHP tag at the end of the
// file and omitting it is a good habit to get into as it can avoid problems
In your PHP code, change
json_encode($output)
to
json_encode($output, JSON_FORCE_OBJECT)
The JSON_FORCE_OBJECT option requires PHP version >= 5.3.0
Your problem seems to be at jArray = new JSONObject(result);
I don't know what the JSONObject constructor expects, but I know you are sending a JSON array to it, not an object.
Do you really need all those fields in the table?
I once did the same, SELECT * FROM table, and json_encode() all the results. jQuery seemed to have a problem reading the data even though the JSON result looks perfectly fine.
So I tried to limit the data and send only the required fields to the browser by SELECT field1, field2 FROM table, instead of all the fields.
Then everything worked fine. I could only suspect that there's a limit to the amount of JSON data jQuery can parse.
I know you aren't using jQuery but I'm just leaving my experience here just in case.

How to retrieve data from json array and display in textview?

I've been using the coding from an example from this link: The code is as shown below:
public class food extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String result = null;
InputStream is = null;
StringBuilder sb=null;
String result=null;
TextView fdi = (TextView)findViewById(R.id.textView1);
TextView fdn = (TextView)findViewById(R.id.textView2);
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://127.0.0.1/food.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
int fd_id;
String fd_name;
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
fd_id=json_data.getInt("FOOD_ID");
fd_name=json_data.getString("FOOD_NAME");
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Food Found", Toast.LENGTH_LONG).show();
}catch (ParseException e1){
e1.printStackTrace();
}
}
}
Now my question is how to pass this data to a list view, like for each iteration a list item must be added with the retrieved data.
Please help me
Thanks in advance
You are already getting strings in below code, Why don't you use that.
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
fd_id=json_data.getInt("FOOD_ID");
fd_name=json_data.getString("FOOD_NAME");
}
//fdname and fd_id you are getting it right,
If your code is not working then add what problem you are facing.
according to your response/result from the server below code is working for me and giving output in string ,
try {
String response ="[{\"FOOD_ID\":\"1\",\"FOOD_NAME\":\"Rice\"},{\"FOOD_ID\":\"2\",\"FOOD_NAME\":\"Daal\"}] ";
JSONArray array;
array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(0);
String id_fd = obj.getString("FOOD_ID");
String name_fd = obj.getString("FOOD_NAME");
Log.d("JSONArray", id_fd+" " +name_fd);
}} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
please use it according to your need.
The root cause of the error a NullPointerException. This means that you are trying to use an object that has the value null. Usually this is because the object has not yet been initialised.
In your case the nullpointer is caused by something at line 29 of your Food class, probably one of these two lines
TextView fdi = (TextView)findViewById(R.id.textView1);
TextView fdn = (TextView)findViewById(R.id.textView2);
Are you sure that both the R.id.textView1 and R.id.textView1 exist? They should be specified somewhere in a layout xml file, something like this:
<TextView
android:id="#+id/textView1"
....

Data from sql server

I want my android app to get data from an online database. Here are the two scenarios:
When I create my db with xampp and I am using the httpost function with my local machines' ip as argument I see as output what I expect to see (the database at logcat).
My question is: if I run the application from my phone, will it connect to my local machine server or not?
I also have a site (lets say mysite.com) and in order not to buy another server I am placing the php file and the database on that server. But then my android app connects (or so I think) to the server, but it prints out at logcat the whole html site. I am thinking that this is because the server requires a username and a password and I do not know if I provided them or not?
So, what do you suggest to do? I want my database being sent to my app (so as to use it later).
My code is shown below (I have in comments the only that changes between 2 scenarios)
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setImageClickListener();
}
private void setImageClickListener() {
ImageView map_image=(ImageView)findViewById(R.id.map_icon);
map_image.setOnTouchListener(new ImageView.OnTouchListener() {
//OnTouchListener listener = new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(!(event.getAction() == MotionEvent.ACTION_DOWN))
return false; //If the touch event was not putting the finger down on the screen, return false(Actions may be move, up, and so on)
final float x = event.getX();
final float y = event.getY();
//System.out.println("Coordinates of button pressed are: X is %d"+x+" and Y is %d"+ y);
if(x>335 && x<395 && y>225 && y< 235)
DoFirst();
return true;
}
});
}
#SuppressWarnings("null")
private void DoFirst() {
Log.d("SnowReportApp","Do first thing");
setContentView(R.layout.layout_1);
String result = "";
InputStream is = null;
StringBuilder sb=null;
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();//() before
nameValuePairs.add(new BasicNameValuePair("year","1980"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("192.168.1.67/test.php"); // only this changes to my server url : mysite.com/httpdocs/test.php
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse JSON data
try{
//JSONObject json_data_1 = new JSONObject(result);
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", name: "+json_data.getString("name")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
My php file located on either c:\xampp\htdocs or on mysite server is this:
<?php
mysql_connect("127.0.0.1","root","");
mysql_select_db("peopledata");
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();?>
My question is: if I run the application from my phone, will it
connect to my local machine server or not?
The answer is probably not. It really all depends on:
Whether you're using Wifi or Carrier data (3G, etc)
Whether your DB ports are open (PC firewall)
If Carrier data, is your PC reachable from the Internet (static IP)
You're better off using mysite.com for your DB and whatever backend you need.
As for your other questions, I cannot answer them as they're quite vague. Consider researching your problem some more and perhaps come back with a targeted set of questions.

Categories