Reputation: 1494
I'm new to android and i'm developing an Android App, i want to get JSON data from a URL : URL
I have the following code:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
public class SingleContactActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.article);
String url = "http://ana.fm/api/article/256281468161349/";
TextView title = (TextView) findViewById(R.id.single_article_title);
TextView desc = (TextView) findViewById(R.id.single_article_desc);
String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpGet myConnection = new HttpGet(url);
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONObject parent_obj = new JSONObject(str);
JSONArray jArray= parent_obj.getJSONArray("article");
JSONObject json = jArray.getJSONObject(0);
title.setText(json.getString("title"));
desc.setText(json.getString("description"));
} catch ( JSONException e) {
e.printStackTrace();
}
}
}
And this is article.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Article Cover Photo -->
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/single_article_cover_photo"
android:layout_gravity="center_horizontal" />
<!-- Article Title -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/single_article_title"
android:layout_gravity="center_horizontal"
android:textColor="#acacac" />
<!-- Article Description -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/single_article_desc"
android:layout_gravity="center_horizontal" />
</LinearLayout>
And i have set the internet permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
But when i run the emulator i get: null null
I can't find anything wrong in my code.
I got it working with this code :
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.TextView;
import java.io.InputStream;
public class SingleContactActivity extends Activity {
public static String myArticleUrl = "http://ana.fm/api/article/256281468161349/";
TextView title;
TextView desc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.article);
title = (TextView) findViewById(R.id.single_article_title);
desc = (TextView) findViewById(R.id.single_article_desc);
new LoadAllArticles().execute();
}
// LOADING THE ARTICLE CONTENTS IN THE BACKGROUND
class LoadAllArticles extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(SingleContactActivity.this);
InputStream inputStream = null;
String result = "";
HttpResponse httpResponse;
HttpEntity httpEntity;
protected void onPreExecute() {
progressDialog.setMessage("Downloading article...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
LoadAllArticles.this.cancel(true);
}
});
}
@Override
protected Void doInBackground(String... params) {
String url_select = myArticleUrl;
// Set up HTTP Get
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url_select);
try {
httpResponse = httpClient.execute(httpGet);
result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void v) {
//parse JSON data
try {
JSONObject parent_obj = new JSONObject(result);
JSONArray jArray= parent_obj.getJSONArray("article");
JSONObject json = jArray.getJSONObject(0);
title.setText(json.getString("title"));
desc.setText(json.getString("description"));
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
}
}
}
But now i need to deal with the HTML tags, anybody know how i can handle HTML tags in JSON ?
Upvotes: 0
Views: 11964
Reputation: 3093
EDIT: Ok, I finally managed to get to my working PC so I corrected all the errors, this is now working:
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.TextView;
import java.io.InputStream;
import java.util.ArrayList;
public class SingleContactActivity extends Activity {
String myArticleUrl = "http://ana.fm/api/article/256281468161349/";
TextView txtTitle;
TextView txtDesc;
JSONParser jParser = new JSONParser();
JSONArray articles = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.article);
txtTitle = (TextView) findViewById(R.id.single_article_title);
txtDesc = (TextView) findViewById(R.id.single_article_desc);
new LoadAllArticles().execute();
}
// LOADING ALL ARTICLES IN THE BACKGROUND
class LoadAllArticles extends AsyncTask<String, String, String> {
private ProgressDialog progressDialog = new ProgressDialog(SingleContactActivity.this);
InputStream inputStream = null;
String result = "";
String title = "";
String description = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading articles...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
LoadAllArticles.this.cancel(true);
}
});
}
@Override
protected String doInBackground(String... params) {
String url_select = myArticleUrl;
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
JSONObject json = jParser.makeHttpRequest(url_select,
"GET", param); // Change "GET" to "POST" if you want the POST method
articles = json.getJSONArray("article");
JSONObject jsonObj = articles.getJSONObject(0);
title = jsonObj.getString("title");
description = jsonObj.getString("description");
}
catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
}
catch (JSONException e5) {
Log.e("JSONException", e5.toString());
e5.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
try {
String newTitle = Html.fromHtml(title).toString();
txtTitle.setText(newTitle);
String newDesc = Html.fromHtml(description).toString();
txtDesc.setText(newDesc);
progressDialog.dismiss();
} catch (Exception e) {
Log.e("JSONException", "Error: " + e.toString());
}
}
}
}
And you need the JSONParser
class:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
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();
} 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;
}
}
Try this, it is working for me, I can see a bunch of arabic text...
Upvotes: 2