DEVELOPMENT

Fetching of data from your server and showing on user's android system is one of the basic functionality many of the application dealing with networks must be having. There are many way to fetch data from a particular server. Xml is a good option, but now days JSON(JavaScript Object Notation) are getting a good attention by android coders because of its merits such as lightweighted, easy for humans to read and write, language independent making it an ideal data-interchange language.

screenshot android

json.php - place this file on your server. For your convienence i've pasted below the snapshot showing output of the same.

json android

<?php
header('content-type: application/json; charset=utf-8');

$conn=mysql_connect("","","") or die("ERROR");
$db=mysql_select_db("",$conn) or die("ERROR");



$query="SELECT * from srch";
$result=mysql_query($query);
$num=mysql_numrows($result);

mysql_close();

$i=0; $temp="";
$s=0;
while($i<$num)
{
 
 $t = mysql_result($result,$i,'title');
 $s_t= mysql_result($result,$i,'subtitle');

 
 $arr[$i]['t']=$t;
 $arr[$i]['s']=$s_t;
 
 $i++;
 
}
 echo json_encode($arr);
?>
now lets move to android part...

build.gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.example.tut.tut_7_6"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
  //  compile 'com.android.support:appcompat-v7:22.2.0'
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example.tut.tut_7_6" >
<uses-permission android:name="android.permission.INTERNET" />
 <application
 android:allowBackup="true"
 android:icon="@mipmap/ic_launcher"
 android:label="@string/app_name"
 >
 <activity
 android:name=".MainActivity"
 android:label="@string/app_name" >
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />

 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>
 </application>

</manifest>
    
searchlist.xml - defines the views for the list item.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical" >

 <TextView
 android:id="@+id/title1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />

 <TextView
 android:id="@+id/subtitle1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/title1"
 android:textSize="10dp" />
 </RelativeLayout>
MainActivity.java
package com.example.tut.tut_7_6;

        import java.io.BufferedReader;
        import java.io.IOException;
        import java.io.InputStream;
        import java.io.InputStreamReader;
        import java.util.ArrayList;
        import java.util.HashMap;
        import java.util.Map;
        import org.apache.http.HttpEntity;
        import org.apache.http.HttpResponse;
        import org.apache.http.StatusLine;
        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.json.JSONArray;
        import org.json.JSONObject;
        import android.app.Activity;
        import android.os.AsyncTask;
        import android.os.Bundle;
        import android.util.Log;
        import android.view.View;
        import android.widget.ListView;
        import android.widget.ProgressBar;
        import android.widget.SimpleAdapter;
        import android.widget.TextView;


public class MainActivity extends Activity {

    private TextView txtQuery;
    ProgressBar pb;
    ListView lstView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lstView = (ListView)findViewById(R.id.list1);
        new ReadJSONFeedTask().execute("/json.php"); //your url
        pb=(ProgressBar)findViewById(R.id.progressBar1);
        txtQuery = (TextView) findViewById(R.id.txtQuery);
    }
    
    public String readJSONFeed(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
        try {
            HttpResponse response = client.execute(httpGet);
            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) {
                    stringBuilder.append(line);
                }
            } else {
                Log.e("JSON", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    private class ReadJSONFeedTask extends AsyncTask<String, Integer, String> {
        ArrayList<Map<String, String>> arrlist = new ArrayList<Map<String, String>>();
        Map<String, String> m = null;

        protected String doInBackground(String... urls) {
            return readJSONFeed(urls[0]);
        }

        protected void onPostExecute(String result) {
            pb.setVisibility(View.GONE);

            try {

                JSONArray jsonArray = new JSONArray(result);

                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    m = new HashMap<String, String>();
                    m.put("title", jsonObject.getString("t"));
                    m.put("subtitle", jsonObject.getString("s"));
                    arrlist.add(m);
                }

                lstView.setAdapter(new SimpleAdapter(MainActivity.this, arrlist, R.layout.searchlist, new String[]{"title", "subtitle"}, new int[]{R.id.title1, R.id.subtitle1}));

            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        protected void onProgressUpdate(Integer... progress) {
            pb.setProgress(progress[0]);
        }
    }

}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical" >

 <TextView
 android:id="@+id/txtQuery"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />
 <TextView
 android:id="@+id/nf"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />
 <ProgressBar
 android:id="@+id/progressBar1"
 style="?android:attr/progressBarStyleSmall"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content" />
 <ListView
 android:id="@+id/list1"
 android:layout_width="match_parent"
 android:layout_height="match_parent" >
 </ListView>

</LinearLayout>


Leave a Comment  
Download Code(39)





All rights reserved, the content is copyrighted to the author.

RELATED POST