Data from sql server - java

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.

Related

Android - Display data from MySQL

I'm very new to Android and I'm currently making an application wherein the user can enter and ID number once (that serves as a login) and he can use access the rest of the features of the app.
I'm currently stuck in the displaying of a data from the MySQL server. Using the ID that the user entered (which is unique and only the user's identificaton), I can display the information with of the user (through TextView or something).
This is my code so far:
public class MainActivity3Activity extends Activity {
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
TextView tv;
TextView tv2;
String get;
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity3);
tv = (TextView)findViewById(R.id.tv);
tv2 = (TextView)findViewById(R.id.tv2);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://usamobileapp.pe.hu/webservice/student_info.php");
SharedPreferences preferences = getSharedPreferences("rfid", Context.MODE_PRIVATE);
if(preferences.contains("rfid")){
get = preferences.getString("rfid", null);
}
}
So my question what do I do from here? I'm quite familiar about httpost but I'm wondering how do I display the user information using the previously entered ID during the login? I heard things like JSON parsing but I'm not quite sure on how to use it.
How do I get to display the information of the user matching the ID he entered? How to diplay using a TextView?
Thanks for the help.
PS. Please disregard the webview there. I only used it as a sample if my app really us connected to my php.
1) make a restful API on your server
2) receive API elements on your client (android), i suggest retrofit, its too easy
3) display your data! otto will help :)
want more? more ,
it might seem hard, but if you study for a few days you'll learn it.
To implement a login / registration system using MySql you need a server-side API, for example in PHP to manipulate the database.
You need something like that on the server side:
// check for tag type
if ($tag == 'login') {
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password'];
// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// user found
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = TRUE;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
And the function that queries the database:
public function getUserByEmailAndPassword($username, $password) {
$query = $this->dbh->prepare("SELECT * FROM users2 WHERE username = :username");
$query->bindParam(':username', $username);
$result = $query->execute();
// check for results
if ($query->rowCount() > 0) {
$result = $query->fetch(PDO::FETCH_ASSOC);
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
return $result;
}
} else {
// user not found
return false;
}
}
The android 'calls' the php scripts:
private static String login_tag = "login";
public void loginUser(String username, String password) throws ExecutionException, InterruptedException {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
jsonParser = new DbHandler(activity, this, params).execute();
}
And here is the DbHandler:
public DbHandler1(Activity activity, MyCallback dbIntf, List<NameValuePair> params) {
this.activity = activity;
intf = dbIntf;
this.params = params;
}
public JSONObject makeHttpRequest() {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(MainActivity.baseUrl);
//If database contains greek characters instantiate with UTF-8 Encoding
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (HttpHostConnectException e) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(activity, R.string.connection_error, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
}
try {
//If database contains greek characters instantiate with UTF-8 Encoding
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
#Override
protected JSONObject doInBackground(Void... params) {
jObj = makeHttpRequest();
return jObj;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
try {
intf.onRemoteCallComplete(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
So the php scripts 'catches' the tag and if the user exists it returns a JSON response to the device. For example:
{
"tag": "login",
"success": 1,
"error": 0,
}
The data transfered from the MySql server must be JSON encoded.
On the android device you must read the JSON Response and act accordingly.
Take a look here for more details.
login / registration system
json parsing
you need perform network operations on a separate thread from the UI.
reade aboute rest Google I/O 2010 - Developing Android REST client application
documentation
in the client, for rest api i like use retrofit + gsongroundy
or php, very easy create rest api using slim framework ─ How to create REST API for Android app using PHP, Slim and MySQL

Getting text from a url and displaying it (Almost works)

I am trying to get text from urls and display them as strings. Urls end with .txt as in www.gains.com/more.txt These text are long and they have a maximum size of 1MB. I am trying to it with AsyncTask. The problem is that the code sometimes works. It worked the first time I ran the code the second time it didn't display the text. Sometimes the app would display the text sometimes it wouldn't. What is going on here? Here is my code.
class RequestTask extends AsyncTask<String, String, String>{
#Override
// username, password, message, mobile
protected String doInBackground(String... url) {
// constants
int timeoutSocket = 5000;
int timeoutConnection = 5000;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpGet httpget = new HttpGet(url[0]);
try {
HttpResponse getResponse = client.execute(httpget);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK) {
Log.w("MyApp", "Download Error: " + statusCode + "| for URL: " + url);
return null;
}
String line = "";
StringBuilder total = new StringBuilder();
HttpEntity getResponseEntity = getResponse.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(getResponseEntity.getContent()));
while((line = reader.readLine()) != null) {
total.append(line);
}
line = total.toString();
story.add(line); //story is my array i use to display the text
return line;
} catch (Exception e) {
Log.w("MyApp", "Download Exception : " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String result) {
//This is empty i dont know what it does
}
}
Here is how i call it
new RequestTask().execute("www.gains.com/more.txt");
Also another smaller problem im having is that when the text is displayed I lose the format of the text as in i lose the spaces between paragraphs an get one huge paragraph. Is there a way to solve this? Should I use another method?
Http request don't always take the same exact time. Have you tried increasing the timeout? 5000 mil seconds is not a lot, especially if your files reach 1MB in size.
Call the display function that will display the text from the file saved after the file is downloaded.
Use onPostExecute
#Override
protected void onPostExecute(String result) {
//You add the code where you call the text from the file saved
}
You can call a function from the main activity that calls the thread.
This way, the view will only be displayed until the process of downloading and saving your text is finished.
Edit: Here's a sample
TextPage textPage; // the activity that calls the AsyncTask
List<String> story = new ArrayList<String>();
GetTextInfoTask(TextPage textPage) {
this.textPage = textPage;
}
... // your doInBackground function here
#Override
protected void onPostExecute(Object objR){
// A toast is displayed in the TextPage Activity once the data is finished downloading
Toast.makeText(textPage.getBaseContext(), story.get(0),
Toast.LENGTH_LONG).show();
}

Basic Android App Direction

I've created basic android apps in various programming classes that I have taken before using Eclipse and the Java Android SDK.
The app that I'd like to create would require users to enter information that would later be analyzed. I want people to be able to compare this data with other people's data so I'd like every entry that users make to be submitted to a database to later be queried when a person attempts to compare their data.
I'd like direction for how to accomplish this. Should I find a free hosting site and set up a Sql server or is there a better way to accomplish this?
Edit: Just for fun.
I am a very beginner android developer, and I have found that using cloud-stored online database like mongolab.com is very friendly for user submitted data. The communication between database and server will have to be done through JSON parsing and URI requests.
Here is example of code you can bind to a button that will send object stored in field tempData:
public void send(View view) {
String apiURI = "https://api.mongolab.com/api/1/databases/MYDATABASE/collections/USERSUBMITTEDDATA?apiKey="
+ apiKey;
try {
// make web service connection
final HttpPost request = new HttpPost(apiURI);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
// Build JSON string with GSON library
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(tempData);
String json = gson.toJson(jsonElement);
StringEntity entity = new StringEntity(json);
Log.d("****Parameter Input****", "Testing:" + json);
request.setEntity(entity);
// Send request to WCF service
final DefaultHttpClient httpClient = new DefaultHttpClient();
new AsyncTask<Void, Void, Void>() {
#Override
public Void doInBackground(Void... arg) {
try {
HttpResponse response = httpClient.execute(request);
Log.d("WebInvoke", "Saving: "
+ response.getStatusLine().toString());
// Get the status of web service
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity()
.getContent()));
// print status in log
String line = "";
while ((line = rd.readLine()) != null) {
Log.d("****Status Line***", "Webservice: " + line);
}
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
return null;
}
}.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
And here is an example of code used to retrieve elements in the database:
public void load() {
String apiURI = "https://api.mongolab.com/api/1/databases/MYDATABASE/collections/USERSUBMITTEDDATA"
+ "?apiKey=" + apiKey;
Log.d("****Status Line***", "" + apiURI);
try {
// make web service connection
final StringBuilder builder = new StringBuilder();
final HttpGet request = new HttpGet(apiURI);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
final DefaultHttpClient httpClient = new DefaultHttpClient();
new AsyncTask<Void, Void, String>() {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
doSomethingWithReceivedData(result); //THIS METHOD IS DEFINED IN BODY OF YOUR ACTIVITY
}
#Override
public String doInBackground(Void... arg) {
try {
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Log.d("****Status Line***", "Success");
return builder.toString();
} else {
Log.d("****Status Line***",
"Failed to download file");
}
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
return null;
}
}.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
You should have a data base to store the data. Like mentioned above, the data base is good to be in MySQL (SQL). Your application should have a method that can POST the results to the server, where the server will read the string send and retrieve and store the data.
A good start is to read about JSON
and read also about Asynctask
Also you need to know how to build your sever part. A good idea is to start with PHP, but I am not an expert on that field.
I hope this helps you start your project.
Simple, no DB required.
Usergrid by Apigee is exactly what you are looking for!
You can store each user's details
Retrieve stored data
Send events and receive event callbacks across devices
Best of all - no server side code. Only APIs
FYI This is the direction you should be heading even if you know how to code a server.
PS: I don't work for apigee or usergrid.

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);

How to manipulate data after its retrieved via remote database

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;
}

Categories