Android, Parse Json Data From A Web Server And Display On Listview
I am trying to display JSON result from JSON url link. Currently when I load up, it display nothing, just blank page. This is the source where I got information about JSON. This is
Solution 1:
I happen to encounter similar problem. Here is the code that help me find resolution. Hope this will help you.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayoutxmlns: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"><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="SEND GET REQUEST"android:id="@+id/sendGet"android:onClick="sendGetRequest"android:layout_alignParentStart="true" /><ScrollViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/scrollView"android:layout_below="@+id/sendGet"android:layout_centerHorizontal="true"><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Response ....."android:id="@+id/showOutput"android:layout_alignEnd="@+id/scrollView"android:layout_marginEnd="34dp" /></ScrollView></RelativeLayout>
MainActivity.java
import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.appindexing.Action;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
publicclassMainActivityextendsAppCompatActivity {
private ProgressDialog progress;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/// private GoogleApiClient client;@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ATTENTION: This was auto-generated to implement the App Indexing API.// See https://g.co/AppIndexing/AndroidStudio for more information.// client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
publicvoidsendGetRequest(View View) {
newGetClass(this).execute();
}
@OverridepublicvoidonStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.// See https://g.co/AppIndexing/AndroidStudio for more information.// client.connect();ActionviewAction= Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type."Main Page", // TODO: Define a title for the content shown.// TODO: If you have web page content that matches this app activity's content,// make sure this auto-generated web page URL is correct.// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.example.gunawardena.get_post_demo/http/host/path")
);
// AppIndex.AppIndexApi.start(client, viewAction);
}
@OverridepublicvoidonStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.// See https://g.co/AppIndexing/AndroidStudio for more information.ActionviewAction= Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type."Main Page", // TODO: Define a title for the content shown.// TODO: If you have web page content that matches this app activity's content,// make sure this auto-generated web page URL is correct.// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.example.gunawardena.get_post_demo/http/host/path")
);
// AppIndex.AppIndexApi.end(client, viewAction);// client.disconnect();
}
privateclassGetClassextendsAsyncTask<String, Void, Void> {
privatefinal Context context;
publicGetClass(Context c) {
this.context = c;
}
protectedvoidonPreExecute() {
progress = newProgressDialog(this.context);
progress.setMessage("Loading Get Method.....");
progress.show();
}
@Overrideprotected Void doInBackground(String... params) {
try {
finalTextViewoutputView= (TextView) findViewById(R.id.showOutput);
URLurl=newURL("https://dvlasearch.appspot.com/DvlaSearch?licencePlate=mt09nks&apikey=DvlaSearchDemoAccount");
HttpURLConnectionconnection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
intresponseCode= connection.getResponseCode();
finalStringBuilderoutput=newStringBuilder("Request URL " + url);
output.append(System.getProperty("line.separator") + "Response Code " + responseCode);
output.append(System.getProperty("line.separator") + "Type " + "GET");
BufferedReaderbr=newBufferedReader(newInputStreamReader(connection.getInputStream()));
Stringline="";
StringBuilderresponseOutput=newStringBuilder();
System.out.println("output===============" + br);
while ((line = br.readLine()) != null) {
responseOutput.append(line);
}
br.close();
output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());
MainActivity.this.runOnUiThread(newRunnable() {
@Overridepublicvoidrun() {
outputView.setText(output);
progress.dismiss();
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
returnnull;
}
}
}
Output on the Emulator
HTH
References:
Post a Comment for "Android, Parse Json Data From A Web Server And Display On Listview"