Json parser example with listview - Get responce from URL

Below are your code snippets for this

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mihir.jsonprectice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.mihir.jsonprectice.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>
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.StrictMode;
import android.util.Log;
import com.google.api.client.http.HttpResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import okhttp3.internal.http.StatusLine;
public class JsonParser {
/**
* @param inputstream
* @return string value
* @author Mihir
* @descriptions used to convert inputstream to string
*/
@SuppressLint("NewApi")
public String InputStreamToString(InputStream inputstream) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
StringBuilder mStringBuilder = new StringBuilder();
try {
if (inputstream != null) {
BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(inputstream), 8);
String line = "";
while ((line = mBufferedReader.readLine()) != null) {
mStringBuilder.append(line + "\n");
}
inputstream.close();
return mStringBuilder.toString();
}
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* @param context
* @param URL
* @param cookies
* @return InputStream
* @author Mihir
* @description user to get json from URL
*/
public Object[] HTTP_GET(String url, String cookies) {
Object object[] = new Object[3];
// DefaultHttpClient
HttpClient mHttpClient = new DefaultHttpClient();
try {
//Log.d("URL", url);
HttpGet mHttpGet = new HttpGet(url);
if (cookies != null) {
mHttpGet.setHeader("Cookies", cookies);
}
HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
object[0] = getResponseStatusCode(mHttpResponse);
object[1] = getResponseStatusMessage(mHttpResponse);
HttpEntity mHttpEntity = mHttpResponse.getEntity();
object[2] = mHttpEntity.getContent();
// or
// object[0] = mHttpResponse.getStatusLine().getStatusCode();
// object[1] = mHttpResponse.getStatusLine().getReasonPhrase().toString();
// object[2] = mHttpResponse.getEntity().getContent().toString();
return object;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* @param response
* @return ResponseCode
* @author Mihir
* @description use to get http response code
*/
public int getResponseStatusCode(HttpResponse response) {
StatusLine statusLine = response.getStatusLine();
Log.d("STATUS_Message", statusLine.getReasonPhrase().toString());
return statusLine.getStatusCode();
}
/**
* @param response
* @return ResponseMessage
* @author Mihir
* @description use to get http response code
*/
public String getResponseStatusMessage(HttpResponse response) {
StatusLine statusLine = response.getStatusLine();
return statusLine.getReasonPhrase().toString();
}
/**
* @param Context context
* @param String errMsg
* @author mihir
* @description shows services error massage
*/
public static final void errorDialogMsg(Context context, String errMsg) {
errMsg = android.text.Html.fromHtml(errMsg).toString();
AlertDialog.Builder builder = new Builder(context);
builder.setTitle("Error");
builder.setMessage(errMsg);
builder.create();
builder.setPositiveButton("OK", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
/**
* @param context
* @param message
* @return
* @author Mihir
* @description use to check internet newtwork connection
* if network connection not available than alert for open network settings
*/
public static boolean isOnline(final Context context, boolean message) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
if (netInfo != null) {
if (netInfo.isConnectedOrConnecting()) {
return true;
}
}
if (message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Please check your network connection");
builder.setCancelable(false);
builder.setPositiveButton("Network Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
context.startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
}
});
builder.setNegativeButton("Wifi Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
context.startActivity(new Intent(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK)));
}
});
AlertDialog alert = builder.create();
alert.show();
return false;
}
return false;
}
}
view raw JsonParser.java hosted with ❤ by GitHub
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class ListAdepter extends BaseAdapter {
private LayoutInflater mLayoutInflater = null;
public ListAdepter() {
mLayoutInflater = LayoutInflater.from(MainActivity.this);
}
@Override
public int getCount() {
return mArrayListCity.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mLayoutInflater.inflate(R.layout.row_item, null);
}
TextView tv_list_item = (TextView) convertView.findViewById(R.id.tv_list_item);
tv_list_item.setText(mArrayListCity.get(position));
return convertView;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
view raw main.xml hosted with ❤ by GitHub
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.ArrayList;
public class MainActivity extends Activity {
private ListView roleList = null;
private ListAdepter mListAdepter = null;
private ArrayList<String> mArrayListCity = null;
private JsonParser mJsonParser = new JsonParser();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mArrayListCity = new ArrayList<String>();
roleList = (ListView) findViewById(R.id.listView1);
mListAdepter = new ListAdepter();
roleList.setAdapter(mListAdepter);
}
@Override
protected void onResume() {
super.onResume();
ClearArray();
if (JsonParser.isOnline(MainActivity.this, true)) {
new CityJson().execute("Get City");
}
}
private void ClearArray() {
mArrayListCity.clear();
}
private class CityJson extends AsyncTask<String, Void, Object[]> {
ProgressDialog mDialog = new ProgressDialog(MainActivity.this);
@Override
protected void onPreExecute() {
mDialog.show();
mDialog.setCancelable(false);
mDialog.setCanceledOnTouchOutside(false);
mDialog.setMessage("Please wait while loading....");
super.onPreExecute();
}
@Override
protected Object[] doInBackground(String... params) {
//passing Json URL
String url = "http://api.geonames.org/citiesJSON?north=44.1&amp;south=-9.9&amp;east=-22.4&amp;west=55.2&amp;lang=de&amp;username=demo";
//Get the HTTP response and return an object as result
return mJsonParser.HTTP_GET(url, null);
}
@Override
protected void onPostExecute(Object[] mObject) {
super.onPostExecute(mObject);
mDialog.dismiss();
try {
if (mObject != null) {
if ((Integer) mObject[0] == 200) {
String response = mJsonParser.InputStreamToString((InputStream) mObject[2]);
Log.d("City list Response", response);
if (response != null) {
JSONObject mJsonObject = new JSONObject(response);
JSONArray mJsonArray = mJsonObject.getJSONArray("geonames");
JSONObject mJsonObject2 = new JSONObject();
for (int i = 0; i < mJsonArray.length(); i++)
{
mJsonObject2 = mJsonArray.getJSONObject(i);
mArrayListCity.add(mJsonObject2.getString("toponymName"));
}
mListAdepter.notifyDataSetChanged();
} else {
Toast.makeText(MainActivity.this, "Server error occored.\nPlease, try after some time. ", Toast.LENGTH_SHORT).show();
}
} else {
JsonParser.errorDialogMsg(MainActivity.this, (String) mObject[1]);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
<?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/tv_list_item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="@string/item"
android:textSize="20sp" />
</LinearLayout>
view raw row.xml hosted with ❤ by GitHub

Comments

  1. You can Decode your json From http://json.parser.online.fr/

    ReplyDelete
  2. You can Get Sample URL for prectice from @http://www.geonames.org/export/JSON-webservices.html

    ReplyDelete

Post a Comment

Popular Posts