0

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 ?

asked Feb 14, 2015 at 11:21
3
  • First of all, don't do HTTP requests in the main thread. You're subject to a NetworkOnMainThread exception. Move the code used to fetch the JSON datas to an asynctask. Commented Feb 14, 2015 at 11:42
  • and how can i do that ? @ZouZou Commented Feb 14, 2015 at 12:12
  • It's in the documentation: developer.android.com/training/basics/network-ops/… - you can also use an even simpler approach: there are several libraries that are made specifically for async networking like volley or retrofit Commented Feb 14, 2015 at 12:49

2 Answers 2

2

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...

answered Feb 14, 2015 at 12:12
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks a lot! , let me test it and i'll get back to you.
I edited some code, I think I made a mistake when declaring myArticleUrl, now should be fixed... Still cannot test though :(
I'm testing your code, but i changed HttpPost to HttpGet then i got this error : httpGet.setEntity(new UrlEncodedFormEntity(param)); "can't resolve method "setEntity"
Still not working, displaying "Downloading artile..." and the dialog never goes away
Ok, I edited again with tested code that works for me... Hope this works for you as well... Vote up if you like ;)
|
1

Instead of anal parsing, you can use GSON . You will get your publications are java objects.

answered Feb 14, 2015 at 12:19

1 Comment

Could you please define "anal parsing"?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.