android: create json object or array? - android

I'm learning everyday a little bit more about android developing and json code.
But now I'm stuck on this;
I can get my values from my online database and show it but I see the entire json code.
And I would like to see just the part I want it to show.
this is my code, I think it's really basic but i'm also learning :)
As you can see I'm just getting the value from the webpage and putting it in my textview, but I would like to put it in a JSONObject or JSONArray don't know witch one is better.
can somebody please assist me with this?
With kind regards
public class Bordje extends Activity{
public void onCreate (Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.bordje);
//This is out textview element, obtained by id from XML Layout
TextView myListView = (TextView)findViewById(R.id.netResult2);
//Lets connect to the internet
try {
String result = "";
//create new client object
HttpClient httpclient = new DefaultHttpClient();
//now post to the url
HttpPost httppost = new HttpPost("http://www.wvvzondag2.nl/android/leesbordje.php");
//execute url
HttpResponse response = httpclient.execute(httppost);
//get message from the response
HttpEntity entity = response.getEntity();
//get the content from message
InputStream webs = entity.getContent();
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(webs, "iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
//slow our inputstream
webs.close();
//puts the resut into a string
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//Parsing the JSON Data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
json_data.getString("introtext");
//Get an output to the screen
//then here should be some code that displays text?
//myListView.setText(Html.fromHtml(json_data)); ?
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
}
catch (Exception e)
{
//this is the line of code that sends a real error message to the log
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
}
}

It's not really a question of which one is better. A JSON object and JSON array are two different things.
A JSON Array is an ordered sequence of (like) items (http://www.json.org/javadoc/org/json/JSONArray.html).
JSONArray jsonArray = new JSONArray("[JSON TEXT]");
String textToDisplay = jsonArray.getString(index); //return String at index
A JSON Object is a map (http://www.json.org/javadoc/org/json/JSONObject.html).
JSONObject jsonObj = new JSONObject("[JSON TEXT]");
String textToDisplay = jsonObj.getString("key"); //returns String value
Then after you have the data, set it in the text view like before.
myListView.setText(textToDisplay);

If you are getting valid json from server you can simply make a JSONArray or JSONObject of it depending on whose object you are getting so there is no point of saying which one is better. However in your case it will most probably be a JSONArray.
Well to achieve that you can use gson to convert a valid json string into JSONObject or JSONArray.
you will be working with .toJson() and .fromJSON(object) methods.

Related

json to android could not connect to database

i'm trying to parse the information of a json array into android.
I use the below code, and i get info from a webservice, if i open the php file it's all ok, but in android i get could not connect to database. I do have set permissions to access the internet...
Here is the code i use:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.enableDefaults(); //STRICT MODE ENABLED
resultView = (TextView) findViewById(R.id.result);
getData();
}
public void getData(){
String result = "";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.10.28/albana/getAllCustomers.php"); //YOUR PHP SCRIPT ADDRESS
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
resultView.setText("Couldnt connect to database");
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s +
"Name : "+json.getString("FirstName")+" "+json.getString("LastName")+"\n"+
"Age : "+json.getInt("Age")+"\n"+
"Mobile Using : "+json.getString("Mobile")+"\n\n";
}
resultView.setText(s);
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
}
I get the message "Could not connect to database";
No errors on the Log Cat...
Please someone suggest me..
You are trying to connect to 192.168.10.28, which is a private or non-routable network address. You can only connect to it if you're on that network (or a network that specifically connects to it). Are you connected through wifi to the network? If so, I would expect it to work so try opening the URL in your web browser and see if you get a json response. If you're connected to it by your mobile network I wouldn't expect it to work.
I'm pretty sure you don't want to use a HttpPost here. Try HttpGet instead, syntax stays the same.
Also check Dave's answer.
In httpd.conf file make the following changes
change:
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
to:
Allow from all
and restart all the services, works like a charm.

How do I prevent my app from crashing unexpectedly, "force close", when using JSON data, and handle the exception instead?

In my application, I have a food activity in which the user enters his/her food, and the app requests the food, by the name entered by the user, from a MYSQL database. In the case that the entered food not exist, the string returned by the database should be null.
Currently, when this happens, an exception to occurs since the null value cannot be parsed to a JSON array. My question is: "Is there a way to prevent my app from force closing? Can I handle the exception and display a toast notifying the user that the requested food was not found?" I would like to prevent the app from crashing, and, rather, fail gracefully.
Please help me.
I've shown the relevant code in my application..
private class LoadData extends AsyncTask<Void, Void, String>
{
private JSONArray jArray;
private String result = null;
private InputStream is = null;
private String entered_food_name=choice.getText().toString().trim();
protected void onPreExecute()
{
}
#Override
protected String doInBackground(Void... params)
{
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/food.php");
nameValuePairs.add(new BasicNameValuePair("Name",entered_food_name));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
//convert response to string
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);
}
is.close();
result =sb.toString();
result = result.replace('\"', '\'').trim();
}
catch(Exception e){
Log.e("log_tag", " connection" + e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result)
{
try{
String foodName="";
int Description=0;
jArray = new JSONArray(result); // here if the result is null an exeption will occur
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
foodName=json_data.getString("Name");
.
.
.
.
.
}
catch(JSONException e){
**// what i can do here to prevent my app from crash and
// make toast " the entered food isnot available " ????**
Log.e("log_tag", "parssing error " + e.toString());
}
}
}
This will fix your code:
jArray = (result == null) ? new JSONArray() : new JSONArray(result);
Now that you have an empty JSONArray, you will be able to test for null JSONObjects later in your program. Many of the JSON methods return a JSONObject if one is found, of null if none exists.
You might also want to initialize your JSONObject with the no-argument JSON constructor, rather than simply setting it to null. It will avoid problems when passing it to other JSON methods (such as using it in a constructor to a JSONArray():
JSONObject json_data = new JSONObject();
Finally, if you're still getting JSONExceptions, it's because you're not actually passing a valid JSON string to the constructor. You can print out the value of result to the log:
Log.d("JSON Data", result);
You may see some SQL error text or if you retrieve from a web server, then an HTTP error code (404 is common if you don't have your url correct).
If your result does look like JSON, then you can verify whether it's actually valid JSON or not using the JSONLint validator. It will help you catch any errors you may have, especially if you're formatting the JSON yourself.
Are you looking to capture the Exception and log it (remotely) to aid in crash reporting and debugging? I've used this package to remotely capture Exceptions and it works pretty good:
http://code.google.com/p/android-remote-stacktrace/

How to fix "Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONArray" in my program

I am very new to android and I'm trying to make a program that shows you results from a database that I have. So when I type in a first name and the database sends the information of that person to me. However, when I look at the LogCat it says
"09-09 22:05:39.544: ERROR/log_tag(8813): Error parsing data org.json.JSONException: Value
This is my code:
public class PS extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//get the two controls we created earlier, also with the resource reference and the id
final EditText et_Text = (EditText)findViewById(R.id.et_Text);
//add new KeyListener Callback (to record key input)
et_Text.setOnKeyListener(new OnKeyListener()
{
//function to invoke when a key is pressed
public boolean onKey(View v, int keyCode, KeyEvent event)
{
//check if there is
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
//check if the right key was pressed
if (keyCode == KeyEvent.KEYCODE_ENTER)
{
InputStream is = null;
String result = "";
//the name data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name",et_Text.getText().toString()));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myIPaddress/sampleDB/testSend.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());
}
// At this point is should be set, if it isn't, tell user what went wrong
if (is != null) {
//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","PersonID: "+json_data.getInt("personID")+
", FirstName: "+json_data.getString("FirstName")+
", LastName: "+json_data.getString("LastName")+
", Age: "+json_data.getInt("Age")
);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}} else {Log.i("log_tag", "Something went wrong!"//I don't know what to put here);} ;
et_Text.setText("");
//and clear the EditText control
return true;
}
}
return false;
}
});
}
}
This is my php code:
<?php
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("_usersDB", $con);
$q=mysql_query("SELECT * FROM Persons WHERE FirstName='".$_REQUEST['name']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close($con);
?>
The output it's parsing on is when I input "Eric" then It'll give me personID of 1, FirstName of Eric, LastName of (my last name), and age of 15. I'm not sure if you were asking for that...
First of all, it may not be wise to share your database connection details with the rest of the world. Second of all, it's not a great idea to do networking operations on the UI Thread.
Lastly (which is what you want to know), it looks likes the output on the server may be different than what the client is expecting. Can you post the output it is parsing on? I'll revise this answer once you do so.
It looks as if the server is prepending an XML declaration to the JSON (). You might want to examine the HTTP traffic output by the web server (via logging or wireshark) as a first step to see if the problem lies with the client or the server.

Android app using data from webservice

I want to write an Android application that can display some data received(polled) from an internet resource.
I guess that I need to write some logic that will periodically call and get data from some endpoint, parse the response and display it. Is there a good tutorial for all this steps?
I know very little about Android programming at the momment and maybe it is better to start with something simpler. I just want to know what to look for while learning an gather some resources on this.
What you want to do is developing a rest api that provides data for your android app. E.g. you website has some content that you want use in your app, then you could write a php script that just returns that data in a specific format.
E.g. mysite.net/rest/fetchAllLocations.php?maybe_some_parameters
This would return locations in e.g. json format, here is an example how that looks like:
[{"id":1,"shop_lng":8.5317153930664,"shop_lat":52.024803161621,"shop_zipcode":33602,"shop_city":"Bielefeld","shop_street":"Arndtstra\u00dfe","shop_snumber":3,"shop_name":"M\u00fcller","shop_desc":"Kaufhaus"}]
Here is an example for a rest api request:
http://shoqproject.supervisionbielefeld.de/public/gateway/gateway/get-shops-by-city/city/Bielefeld
So when you have your rest api set up you can deal with receiving that data with your android phone. I use a static method to get this data:
public class JsonGrabber{
public static JSONArray receiveData(){
String url = "your url";
String result = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(url);
HttpResponse res = null;
try {
res = client.execute(method);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try{
InputStream is = res.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"));
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());
}
JSONArray jArray = null;
try{
jArray = new JSONArray(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
Well thats all, once you have your data in json format you just have to parse it:
JSONArray test = (JSONArray) JsonGrabber.receiveData()
try {
for(int i=0;i<test.length();i++){
JSONObject json_data = test.getJSONObject(i);
int id = json_data.getInt("id");
}
}
The web request should run in another thread, because it can be a time consuming process. So you need to deal with AsyncTask. Here are some resources:
Painless Threading
Multithreading for performance
Hello Android Tutorial

Updateing Android application content via internet?

i want to develop an Android application that will take the content from internet (server) and present it in the application.
(ex. i take the todays weather forecast, put the numbers in SQLite database or .txt file , put the database/txt file on internet server so when i open the application, the app connects&downloads the database via the net and presents me with todays forecast)
If you can references me to some example/video tutorial/book that deals with this issue i will be very thankful!
What you want to do is developing a rest api that provides data for your android app. E.g. you website has some content that you want use in your app, then you could write a php script that just returns that data in a specific format.
E.g. mysite.net/rest/fetchAllLocations.php?maybe_some_parameters
This would return locations in e.g. json format, here is an example how that looks like:
[{"id":1,"shop_lng":8.5317153930664,"shop_lat":52.024803161621,"shop_zipcode":33602,"shop_city":"Bielefeld","shop_street":"Arndtstra\u00dfe","shop_snumber":3,"shop_name":"M\u00fcller","shop_desc":"Kaufhaus"}]
Here is an example for a rest api request:
http://shoqproject.supervisionbielefeld.de/public/gateway/gateway/get-shops-by-city/city/Bielefeld
So when you have your rest api set up you can deal with receiving that data with your android phone. I use a static method to get this data:
public class JsonGrabber{
public static JSONArray receiveData(){
String url = "your url";
String result = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(url);
HttpResponse res = null;
try {
res = client.execute(method);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try{
InputStream is = res.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"));
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());
}
JSONArray jArray = null;
try{
jArray = new JSONArray(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
Well thats all, once you have your data in json format you just have to parse it:
JSONArray test = (JSONArray) JsonGrabber.receiveData()
try {
for(int i=0;i<test.length();i++){
JSONObject json_data = test.getJSONObject(i);
int id = json_data.getInt("id");
}
}
The web request should run in another thread, because it can be a time consuming process. So you need to deal with AsyncTask. Here are some resources:
Painless Threading
Multithreading for performance
Hello Android Tutorial

Categories

Resources