Simple JSON Parsing Example in Android (리스트뷰, 그리드뷰 아님)

프로그래밍/Android (Java)|2015. 11. 11. 17:18
반응형

In this blog post, ill show you how to Retrieving JSON data and Displaying it in Android TextView.

My Other blog post on JSON Tutorial.

  1. Part I – What is JSON and how to code JSON data on Php
  2. Part II – How to retrieve a simplest JSON data in Android
  3. Part III – How to retrieve a JSON data to ListView in Android
  4. Part IV – How to retrieve a complex typed JSON data in Android
  5. Part V – How to retrieve a JSON data from a Secured Site with Basic Authentication
  6. Part VI – How to Pass a JSON data to Php as a Parameters

 

Please read Part I of this blog, there you can create JSON data in php. I’m using Example 1 from that blog in this tutorial for making this blog to be simple. Hope you have created JSON data in php, so lets get started with retrieving in Android.

Step 1: Create a new project File -> Android Project. While creating a new project give activity name as MainActivity and copy paste this code.

1 import org.json.JSONException;
2 import org.json.JSONObject;
3  
4 import android.app.Activity;
5 import android.app.ProgressDialog;
6 import android.os.AsyncTask;
7 import android.os.Bundle;
8 import android.widget.TextView;
9  
10 public class MainActivity extends Activity {
11 /** Called when the activity is first created. */
12  
14 String name, version;
15 TextView tv1;
16  
17 @Override
18 public void onCreate(Bundle savedInstanceState) {
19 super.onCreate(savedInstanceState);
20 setContentView(R.layout.activity_main);
21  
22 new JSONParse().execute();
23 }
24  
25 private class JSONParse extends AsyncTask<String, String, JSONObject> {
26 private ProgressDialog pDialog;
27 @Override
28 protected void onPreExecute() {
29 super.onPreExecute();
30 tv1 = (TextView) findViewById(R.id.textView1);
31  
32 pDialog = new ProgressDialog(MainActivity.this);
33 pDialog.setMessage("Loading Data ...");
34 pDialog.setIndeterminate(false);
35 pDialog.setCancelable(true);
36 pDialog.show();
37 tv1.setText("Getting Values Pls wait..");
38 }
39  
40 @Override
41 protected JSONObject doInBackground(String... args) {
42 JsonParser jParser = new JsonParser();
43 // Getting JSON from URL
44 JSONObject json = jParser.getJSONFromUrl(url);
45 return json;
46 }
47  
48 @Override
49 protected void onPostExecute(JSONObject json) {
50 try {
51 pDialog.dismiss();
52 name = json.getString("name");
53 version = json.getString("version");
54 tv1.setText(name + " - " + version);
55 } catch (JSONException e) {
56 e.printStackTrace();
57 }
58 }
59 }
60 }

Step 2: Create a new class, JsonParser.java and copy paste this code.

1 import java.io.BufferedReader;
2 import java.io.IOException;
3 import java.io.InputStream;
4 import java.io.InputStreamReader;
5 import java.io.UnsupportedEncodingException;
6  
7 import org.apache.http.HttpEntity;
8 import org.apache.http.HttpResponse;
9 import org.apache.http.client.ClientProtocolException;
10 import org.apache.http.client.methods.HttpPost;
11 import org.apache.http.impl.client.DefaultHttpClient;
12 import org.json.JSONException;
13 import org.json.JSONObject;
14  
15 import android.util.Log;
16  
17 public class JsonParser {
18 static InputStream is = null;
19 static JSONObject jObj = null;
20 static String json = "";
21  
22 // constructor
23 public JsonParser() {
24 }
25  
26 public JSONObject getJSONFromUrl(String url) {
27 // Making HTTP request
28 try {
29 // defaultHttpClient
30 DefaultHttpClient httpClient = new DefaultHttpClient();
31 HttpPost httpPost = new HttpPost(url);
32 HttpResponse httpResponse = httpClient.execute(httpPost);
33 HttpEntity httpEntity = httpResponse.getEntity();
34 is = httpEntity.getContent();
35 } catch (UnsupportedEncodingException e) {
36 e.printStackTrace();
37 } catch (ClientProtocolException e) {
38 e.printStackTrace();
39 } catch (IOException e) {
40 e.printStackTrace();
41 }
42 try {
43 BufferedReader reader = new BufferedReader(new InputStreamReader(
44 is, "iso-8859-1"), 8);
45 StringBuilder sb = new StringBuilder();
46 String line = null;
47 while ((line = reader.readLine()) != null) {
48 sb.append(line + "n");
49 }
50 is.close();
51 json = sb.toString();
52 } catch (Exception e) {
53 Log.e("Buffer Error", "Error converting result " + e.toString());
54 }
55 // try parse the string to a JSON object
56 try {
57 jObj = new JSONObject(json);
58 } catch (JSONException e) {
59 Log.e("JSON Parser", "Error parsing data " + e.toString());
60 }
61 // return JSON String
62 return jObj;
63 }
64 }

Step 3: Open your activity_main.xml and copy paste this code:

1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent"
5 android:paddingBottom="@dimen/activity_vertical_margin"
6 android:paddingLeft="@dimen/activity_horizontal_margin"
7 android:paddingRight="@dimen/activity_horizontal_margin"
8 android:paddingTop="@dimen/activity_vertical_margin" >
9  
10 <TextView
11 android:id="@+id/textView1"
12 android:layout_width="wrap_content"
13 android:layout_height="wrap_content"
14 android:layout_centerHorizontal="true"
15 android:layout_centerVertical="true"
16 android:text="Medium Text"
17 android:textAppearance="?android:attr/textAppearanceMedium" />
18  
19 </RelativeLayout>

Step 4: Open your AndroidManifest.xml and add Internet Permission.

1 <?xml version="1.0" encoding="utf-8"?>
2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3 package="com.geeks.gallery.json_demoexample"
4 android:versionCode="1"
5 android:versionName="1.0" >
6  
7 <uses-sdk
8 android:minSdkVersion="16"
9 android:targetSdkVersion="19" />
10 <uses-permission android:name="android.permission.INTERNET"/>
11 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
12  
13 <application
14 android:allowBackup="true"
15 android:icon="@drawable/ic_launcher"
16 android:label="@string/app_name"
17 android:theme="@style/AppTheme" >
18 <activity
19 android:name=".MainActivity"
20 android:label="@string/app_name" >
21 <intent-filter>
22 <action android:name="android.intent.action.MAIN" />
23  
24 <category android:name="android.intent.category.LAUNCHER" />
25 </intent-filter>
26 </activity>
27 </application>
28  
29 </manifest>

ScreenShot:

Screenshot_2015-01-11-13-54-24

Download Source Code from here.

 

 

[출처] http://www.geeks.gallery/simple-json-parsing-example-in-android-part-ii/

 

반응형

댓글()