Thursday, August 20, 2015

Volley JsonArray ListView


.
Volley JsonArray ListView
Using Android Studio 1.4

1) Create New Project

Application Name: MyVolleyJsonArray2
Select API 14:Android 4.0 (IceCreamSandwich)
Follow the wizard to create New Empty Activity.
Select “Generate Layout File”

2) Import Volley Library Into Project

2.1) Download Volley Project

Download volley20151105.zip and unzip it.

2.2) Import using Android Studio

2.3) Add Dependencies

Build.Gradle(Module:App)
apply plugin'com.android.application'
android {
   compileSdkVersion 23
   buildToolsVersion "23.0.1"
   defaultConfig {
       applicationId "com.notarazi.myvolleyjsonarray2"
       minSdkVersion 14
       targetSdkVersion 23
       versionCode 1
       versionName "1.0"
   }
   buildTypes {
       release {
           minifyEnabled false
           proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
       }
   }
}
dependencies {
   compile fileTree(dir'libs'include: ['*.jar'])
   testCompile 'junit:junit:4.12'
   compile 'com.android.support:design:23.1.0'
   compile project(':volley')
}
Sync Project with Gradle Files

2.4) Add Permission

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.notarazi.myvolleyjsonarray2>
   <uses-permission android:name="android.permission.INTERNET"/>
   <application
      android:name="com.notarazi.myvolleyjsonarray2.MyApplication"
       android:allowBackup="true"
       android:icon="@mipmap/ic_launcher"
       android:label="@string/app_name"
       android:supportsRtl="true"
       android:theme="@style/AppTheme" >
       <activity
           android:name=".MainActivity"
           android:label="@string/app_name"
           android:theme="@style/AppTheme.NoActionBar" >
           <intent-filter>
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>
   </application>
</manifest>
If you missed this step, your debug message will tell you about this.

2.5) Create MyApplication.java

package com.notarazi.myvolleyjsonarray2;
import android.app.Application;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class MyApplication extends Application {
   private RequestQueue mRequestQueue;
   private static MyApplication mInstance;
   @Override
   public void onCreate() {
       super.onCreate();
       mInstance this;
   }
   public static synchronized MyApplication getInstance() {
       return mInstance;
   }
   public RequestQueue getReqQueue() {
       if (mRequestQueue == null) {
           mRequestQueue = Volley.newRequestQueue(getApplicationContext());
       }
       return mRequestQueue;
   }
   public <Tvoid addToReqQueue(Request<T> req, String tag) {
       getReqQueue().add(req);
   }
   public <Tvoid addToReqQueue(Request<T> req) {
       getReqQueue().add(req);
   }
   public void cancelPendingReq(Object tag) {
       if (mRequestQueue != null) {
           mRequestQueue.cancelAll(tag);
       }
   }
}

3) Add ListView and List Item Layout

3.1) res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
   android:layout_height="match_parent"android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin"tools:context=".MainActivity">
   <ListView
       android:id="@+id/list"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:dividerHeight="1dp"
       />
</RelativeLayout>

3.2) res/layout/items.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">
   <TextView
       android:id="@+id/txt"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       >
   </TextView>
</LinearLayout>

4) Edit MainActivity.java

package com.notarazi.myvolleyjsonarray2;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends Activity {
   String url "http://restcountries.eu/rest/v1";
   ProgressDialog PD;
   ArrayList<String> countries;
   ArrayAdapter<String> adapter;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       ListView listView=(ListView)findViewById(R.id.list);
       countries=new ArrayList<String>();
       adapter new ArrayAdapter(this,R.layout.items, R.id.tvcountries);
       listView.setAdapter(adapter);
       //countries = new ArrayList<String>();
       PD new ProgressDialog(this);
       PD.setMessage("Loading.....");
       PD.setCancelable(false);
       //adapter = new ArrayAdapter(this, R.layout.items, R.id.tv, countries);
       //setListAdapter(adapter);
       MakeJsonArrayReq();
   }
   private void MakeJsonArrayReq() {
       PD.show();
       JsonArrayRequest jreq = new JsonArrayRequest(url,
               new Response.Listener<JSONArray>() {
                   @Override
                   public void onResponse(JSONArray response) {
                       for (int i = 0; i < response.length(); i++) {
                           try {
                               JSONObject jo = response.getJSONObject(i);
                               String name = jo.getString("name");
                               countries.add(name);
                           } catch (JSONException e) {
                               e.printStackTrace();
                           }
                       }
                       PD.dismiss();
                       adapter.notifyDataSetChanged();
                   }
               }, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
           }
       });
       MyApplication.getInstance().addToReqQueue(jreq, "jreq");
   }
}
OUTCOME.

DOWNLOAD

REFERENCES



.

No comments:

Post a Comment