Show data in listview with Asynctask - android

I success show my data from web service JSON in listview, but I want to add Asyntask.
Where I can put code Asyntask in my code.
This my code to show data in list view
public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
String status ="";
String date = "";
String result = "";
String url = "http://10.0.2.2/remix/view_list.php";
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
try
{
r_js = json.getJSONArray("view_list");
for (int i =0; i < r_js.length(); i++)
{
String my_array = "";
JSONObject ar = r_js.getJSONObject(i);
status = ar.getString("st");
date = ar.getString("date");
result = ar.getString("result");
if (status.trim().equals("er"))
{
my_array += "Sorry "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
else
{
my_array += "Date : "+date+" "+"Result : "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
adapter_listview();
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
setListAdapter(adapter);
}
}
And this JSONParser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject AmbilJson(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Where can I put code for Asyntask?
Ok, I get sample code, and my code now like this
public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
private class myProses extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(Jadwal_remix.this, "", "Loading... Please wait", true);
}
protected Void doInBackground(Void... params) {
String status ="";
String date = "";
String result = "";
String url = "http://10.0.2.2/remix/view_list.php";
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
try
{
r_js = json.getJSONArray("view_list");
for (int i =0; i < r_js.length(); i++)
{
String my_array = "";
JSONObject ar = r_js.getJSONObject(i);
status = ar.getString("st");
date = ar.getString("date");
result = ar.getString("result");
if (status.trim().equals("er"))
{
my_array += "Sorry "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
else
{
my_array += "Date : "+date+" "+"Result : "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
protected void onPostExecute(Void unused) {
adapter_listview();
dialog.dismiss();
}
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
setListAdapter(adapter);
}
}
I'm get problem when server is die, it still loading.
How I can show message ex: can't connect to server?

Working ASyncTask tutorial,
Full ASyncTask Eclipse Project,
and here's some code that I think, when mixed with the above sample, will get you the result with the list that you desire (you'll have to adapt it to your needs a bit, though (pay attention to the list stuff, even though this is from a custom Dialog:
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Kies Facebook-account");
builder.setNegativeButton("Cancel", this);
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogLayout = inflater.inflate(R.layout.dialog, null);
builder.setView(dialogLayout);
final String[] items = {"Red", "Green", "Blue" };
builder.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.v("touched: ", items[which].toString());
}}
);
return builder.create();
}

This is my code please try this one,
MAinActivity.java
public class MyActivity extends Activity {
private ListView contests_listView;
private ProgressBar pgb;
ActivitiesBean bean;
ArrayList<Object> listActivities;
ActivityAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
contests_listView = (ListView) findViewById(R.id.activity_listView);
pgb = (ProgressBar) findViewById(R.id.contests_progressBar);
listActivities = new ArrayList<Object>();
new FetchActivitesTask().execute();
}
public class FetchActivitesTask extends AsyncTask<Void, Void, Void> {
int i =0;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pgb.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String url = "Your URL Here";
String strResponse = util.makeWebCall(url);
try {
JSONObject objResponse = new JSONObject(strResponse);
JSONArray jsonnodes = objResponse.getJSONArray(nodes);
for (i = 0; i < jsonnodes.length(); i++)
{
String str = Integer.toString(i);
Log.i("Value of i",str);
JSONObject jsonnode = jsonnodes.getJSONObject(i);
JSONObject jsonnodevalue = jsonnode.getJSONObject(node);
bean = new ActivitiesBean();
bean.title = jsonnodevalue.getString(title);
bean.image = jsonnodevalue.getString(field_activity_image_fid);
listActivities.add(bean);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pgb.setVisibility(View.GONE);
displayAdapter();
}
}
public void displayAdapter()
{
adapter = new ActivityAdapter(this, listActivities);
contests_listView.setAdapter(adapter);
contests_listView.setOnItemClickListener(new OnItemClickListener() {
//#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long id) {
// your onclick Activity
}
});
}
}
util.class
public static String makeWebCall(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
// HttpPost post = new HttpPost(url);
try {
HttpResponse httpResponse = client.execute(httpRequest);
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = httpResponse.getEntity();
InputStream instream = null;
if (entity != null) {
instream = entity.getContent();
}
return iStream_to_String(instream);
}
catch (IOException e) {
httpRequest.abort();
// Log.w(getClass().getSimpleName(), "Error for URL =>" + url, e);
}
return null;
}
public static String iStream_to_String(InputStream is1) {
BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String contentOfMyInputStream = sb.toString();
return contentOfMyInputStream;
}
}
ActivityBean.java
public class ActivitiesBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public String title;
public String image;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}

Related

How to show data JSON in Listview Android based on the same key JSON [duplicate]

I am new to android and java.Recently I am having problem with displaying fetched json data into listview using baseadapter.
At first I have used this code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new TheTask().execute();
}
class TheTask extends AsyncTask<Void,Void,String>
{
#Override
protected String doInBackground(Void... params) {
String str = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/BSDI/show.php");
HttpResponse response = httpclient.execute(httppost);
str = EntityUtils.toString(response.getEntity());
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
String response = result.toString();
try {
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray new_array = new JSONArray(response);
for(int i = 0, count = new_array.length(); i< count; i++)
{
try {
JSONObject jsonObject = new_array.getJSONObject(i);
stringArray.add(jsonObject.getString("title").toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String> (MainActivity.this,R.layout.test_tuh,stringArray);
ListView list= (ListView) findViewById(R.id.listView1);
list.setAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//tv.setText("error2");
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This code displays fetched json data sucessfully. But it only displays only one row. I need more than one (two) rows in listview. So I have tried this code
and it does not work, it shows a blank screen .
My code is below,
class TheTask extends AsyncTask<Void,Void,String>
{
#Override
protected String doInBackground(Void... params) {
String str = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/BSDI/show.php");
HttpResponse response = httpclient.execute(httppost);
str = EntityUtils.toString(response.getEntity());
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String response = result.toString();
try {
arrayList=new ArrayList<get_set>();
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray new_array = new JSONArray(response);
for(int i = 0, count = new_array.length(); i< count; i++)
{
try {
JSONObject jsonObject = new_array.getJSONObject(i);
stringArray.add(jsonObject.getString("title").toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
ListView listView;
adap= new BaseAdapter() {
LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView(int position, View view, ViewGroup viewgroup) {
if (view==null) {
view=inflater.inflate(R.layout.bsdi, null);
}
TextView title_tuh=(TextView) view.findViewById(R.id.title1);
TextView notice_tuh=(TextView) view.findViewById(R.id.notice1);
title_tuh.setText(arrayList.get(position).getTitle());
notice_tuh=.setText(arrayList.get(position).getNotice());
return view;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayList.get(position);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
};
listView=(ListView) findViewById(R.id.listView1);
listView.setAdapter(adap);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//tv.setText("error2");
}
}
As far I am realizing that , the problem is here
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray new_array = new JSONArray(response);
for(int i = 0, count = new_array.length(); i< count; i++)
{
try {
JSONObject jsonObject = new_array.getJSONObject(i);
stringArray.add(jsonObject.getString("title").toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
As far I am guesing that extracted json data is storing in stringArray but its not used later. If I try to use it like this , then I get error
title_tuh.setText(stringArray .get(position).getTitle());
notice_tuh=.setText(stringArray .get(position).getNotice());
If I try to not to use
ArrayList stringArray = new ArrayList();
and use
arrayList=new ArrayList(); instead , like this then I also get error.
arrayList=new ArrayList<get_set>();
JSONArray new_array = new JSONArray(response);
//JSONArray jsonArray = new JSONArray();
for(int i = 0, count = new_array.length(); i< count; i++)
{
try {
JSONObject jsonObject = new_array.getJSONObject(i);
arrayList.add(jsonObject.getString("title").toString());
// String in = mInflater.inflate(R.layout.custom_row_view, null);
}
catch (JSONException e) {
e.printStackTrace();
}
}
I can not finding out how to solve this problem.I have seen many online tutorials but those was not helpful for me. Please help me.
First u need t create row_listitem.xml file like:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:background="#drawable/list_selector"
android:orientation="vertical"
android:padding="5dp" >
<ImageView
android:id="#+id/iv_icon_social"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_centerVertical="true"
android:background="#drawable/image_border"
android:src="#drawable/sms_t"
android:visibility="gone" />
<LinearLayout
android:id="#+id/thumbnail"
android:layout_width="fill_parent"
android:layout_height="85dp"
android:layout_marginRight="50dp"
android:layout_marginTop="0dp"
android:layout_toRightOf="#+id/iv_icon_social"
android:gravity="center_vertical"
android:orientation="vertical"
android:padding="5dip"
android:visibility="visible" >
<TextView
android:id="#+id/txt_ttlsm_row"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:text="Sample text"
android:textSize="18dp"
android:textStyle="bold" />
<TextView
android:id="#+id/txt_ttlcontact_row2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="0dp"
android:layout_marginTop="3dp"
android:paddingLeft="10dp"
android:maxEms="20"
android:maxLines="2"
android:singleLine="false"
android:ellipsize="end"
android:text="Sample text2"
android:textColor="#808080"
android:textSize="15dp"
android:textStyle="normal"
android:visibility="visible" />
</LinearLayout>
</RelativeLayout>
Now, u need to create Custom BaseAdapter like:
public class BaseAdapter2 extends BaseAdapter {
private Activity activity;
// private ArrayList<HashMap<String, String>> data;
private static ArrayList title,notice;
private static LayoutInflater inflater = null;
public BaseAdapter2(Activity a, ArrayList b, ArrayList bod) {
activity = a;
this.title = b;
this.notice=bod;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return title.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.row_listitem, null);
TextView title2 = (TextView) vi.findViewById(R.id.txt_ttlsm_row); // title
String song = title.get(position).toString();
title2.setText(song);
TextView title22 = (TextView) vi.findViewById(R.id.txt_ttlcontact_row2); // notice
String song2 = notice.get(position).toString();
title22.setText(song2);
return vi;
}
}
Now, u can set up your main activity like:
public class MainActivity extends Activity {
ArrayList<String> title_array = new ArrayList<String>();
ArrayList<String> notice_array = new ArrayList<String>();
ListView list;
BaseAdapter2 adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView1);
new TheTask().execute();
}
class TheTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String str = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://10.0.2.2/BSDI/show.php");
HttpResponse response = httpclient.execute(httppost);
str = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
String response = result.toString();
try {
JSONArray new_array = new JSONArray(response);
for (int i = 0, count = new_array.length(); i < count; i++) {
try {
JSONObject jsonObject = new_array.getJSONObject(i);
title_array.add(jsonObject.getString("title").toString());
notice_array.add(jsonObject.getString("notice").toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter = new BaseAdapter2(MainActivity.this, title_array, notice_array);
list.setAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// tv.setText("error2");
}
}
}
}
#Allen Chun , actually its not in my mind currently that what I have changed in my code to run my code perfectly. But I am sharing all my codes which are working perfectly.
Its my layout code,
<?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/fsr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Notice Board"
android:textSize="20px" />
<TextView
android:id="#+id/err_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:gravity="center" />
<ListView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/list_notice2"
android:layout_gravity="center" />
</LinearLayout>
This is my custom listview layout codes,
<?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/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:paddingTop="10dp"
android:layout_gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium" />
/>
<TextView
android:id="#+id/notice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:paddingTop="5dp"
android:layout_gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
its my activity named "NoticeBoard" .
public class NoticeBoard extends Activity {
ArrayList<String> title_array = new ArrayList<String>();
ArrayList<String> notice_array = new ArrayList<String>();
ListView list;
base_adapter3 adapter;
TextView f,msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_notice);
list = (ListView) findViewById(R.id.list_notice2);
msg=(TextView) findViewById(R.id.err_msg);
new test_ays().execute();
}
class test_ays extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String str = null ;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/BSDI/show.php");
HttpResponse response = httpclient.execute(httppost);
str = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result!=null) // add this
{
String response = result.toString();
try {
JSONArray new_array = new JSONArray(response);
for (int i = 0, count = new_array.length(); i < count; i++) {
try {
JSONObject jsonObject = new_array.getJSONObject(i);
title_array.add(jsonObject.getString("title").toString());
notice_array.add(jsonObject.getString("notice").toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter = new base_adapter3(NoticeBoard.this, title_array, notice_array);
list.setAdapter(adapter);
// f=(TextView) findViewById(R.id.textTuh);
// f.setText(title_array);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// tv.setText("error2");
}
}
else{
msg.setText("You need a working data connection...");
}
}
}
}
And its my custom baseadapter codes,
public class base_adapter2 extends BaseAdapter {
private Activity activity;
//private ArrayList<HashMap<String, String>> data;
private static ArrayList title,notice;
private static LayoutInflater inflater = null;
public base_adapter2(Activity a, ArrayList b) {
activity = a;
this.title = b;
// this.notice=bod;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return title.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.bsdi_adapter, null);
TextView title2 = (TextView) vi.findViewById(R.id.txt1); // title
String song = title.get(position).toString();
title2.setText(song);
return vi;
}
}
In this example, I am connecting to Twitters public timeline JSON url.
package net.inchoo.demo.andy1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class HomeActivity extends ListActivity {
/** Called when the activity is first created. */
#SuppressWarnings({ "rawtypes", "unchecked" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, this.fetchTwitterPublicTimeline()));
}
public ArrayList<String> fetchTwitterPublicTimeline()
{
ArrayList<String> listItems = new ArrayList<String>();
try {
URL twitter = new URL(
"http://twitter.com/statuses/public_timeline.json");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
listItems.add(jo.getString("text"));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItems;
}
}
Please direct your attention on the listItems.add(jo.getString(“text”)); line. This is the part that I am grabbing a “text” attribute/property of single JSON object. To get a more “visual” picture of all available attributes/properties you might want to take a look at the XML version of twitters public timeline. This way you will get nice colored XML in your browser, where you can see all available attributes.
Link: http://inchoo.net/dev-talk/android-development/simple-android-json-parsing-example-with-output-into-listactivity/
Json parser:
public class jparser {
static InputStream istream = null;
static JSONObject jObj = null;
//static JSONArray jarray=null;
static String json = "";
//static JSONArray jarray = null;
// constructor
public jparser() {
}
public JSONObject getJFromUrl(String url) {
// Making HTTP request
//try {
// defaultHttpClient
StringBuilder builder = new StringBuilder();
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
/*HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
istream = httpEntity.getContent();*/
try{
HttpResponse response = httpClient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 400)
{
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
}
else
{
Log.e("==>", "Failed to download file");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(istream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
istream.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
// Parse String to JSON object
/*try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jarray;
}*/
}
}
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
#SuppressLint("NewApi")
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
<h1>Model</h1>
public class WorkModel {
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImagename() {
return imagename;
}
public void setImagename(String imagename) {
this.imagename = imagename;
}
String id,name,imagename;
public WorkModel(String s1,String s2,String s3)
{
this.id=s1;
name=s2;
imagename=s3;
}
}
<h1>listview fill</h1>
public class Work_in_process extends Fragment {
//////////////jsonparser implement
JSONParser jsonparser=new JSONParser();
JSONArray json_users=null;
JSONObject json;
/////////
ListView lst;
ArrayList<WorkModel> data=new ArrayList<WorkModel>();
WorkAdapter adapter;
Context con;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_work_in_process, container, false);
con=this.getActivity();
lst=(ListView)rootView.findViewById(R.id.work_listview);
new work_process().execute();
// Inflate the layout for this fragment
return rootView;
}
class work_process extends AsyncTask<String,String,String>
{
public Dialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(con);
pDialog.setMessage("Loading... Please wait...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
data.clear();
List<NameValuePair> params = new ArrayList<NameValuePair>();
json = jsonparser.makeHttpRequest("your url","POST", params);
try {
int success = json.getInt("status");
if (success == 0)
{
return "kbc";
}
else
{
json_users = json.getJSONArray("result");
// looping through All Products
for (int i = 0; i < json_users.length(); i++) {
JSONObject c = json_users.getJSONObject(i);
String t1 = c.getString("id");
String t2 = c.getString("work_title");
String t3 = c.getString("image_path");
WorkModel da=new WorkModel(t1,t2,t3);
data.add(da);
}
return "abc";
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pDialog.dismiss();
if(s.equals("abc"))
{
adapter = new WorkAdapter(con, data);
lst.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
else
{
}
}
}
}
<h1>Adapter fill listview</h1>
public class WorkAdapter extends BaseAdapter {
private LayoutInflater inflater1=null;
private static String string=null;
ArrayList<WorkModel> data=null;
Context activity;
DisplayImageOptions options;
protected ImageLoader imageLoader = ImageLoader.getInstance();
public WorkAdapter(Context act,ArrayList<WorkModel> da)
{
activity=act;
data=da;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
{
inflater1=(LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi=inflater1.inflate(R.layout.list_work,null);
}
TextView name;
ImageView img;
name=(TextView)vi.findViewById(R.id.list_work_name);
img= (ImageView)vi.findViewById(R.id.list_work_img);
WorkModel da=new WorkModel(string,string,string);
da=data.get(position);
final String p1,p2,p3;
p1=da.getId();
p2=da.getName();
p3=da.getImagename();
name.setText(p2);
imageLoader.init(ImageLoaderConfiguration.createDefault(activity));
final String imgpath=""+p3;
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.wp_loading)
.showImageForEmptyUri(R.drawable.wp_loading)
.showImageOnFail(R.drawable.wp_loading)
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
imageLoader.displayImage(imgpath, img,options);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DisplayImageOptions options;
final ImageLoader imageLoader = ImageLoader.getInstance();
final Dialog emailDialog =new Dialog(activity, android.R.style.Theme_DeviceDefault);
emailDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
emailDialog.setCancelable(true);
emailDialog.setContentView(R.layout.zoom_imge);
ImageView image = (ImageView) emailDialog.findViewById(R.id.zoom_image_img);
emailDialog.show();
final String imgpath=""+p3;
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.wp_loading)
.showImageForEmptyUri(R.drawable.wp_loading)
.showImageOnFail(R.drawable.wp_loading)
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
imageLoader.displayImage(imgpath, image, options);
}
});
return vi;
}
}
Get schedule
public class GetSchedule extends Activity {
// JSON Node Names
private static final String TAG_SNO = "sno";
private static final String TAG_STNCODE = "stnCode";
private static final String TAG_STATION = "station";
// private static final String TAG_ROUTENO= "routeNo";
private static final String TAG_ARRIVALTIME = "arrivalTime";
private static final String TAG_DEPTIME = "depTime";
private JSONArray station = null;
private ListView list;
//private static String url = "http://railpnrapi.com/api/route/train/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_schedule);
try {
ArrayList<HashMap<String, String>> stnNamelist = new ArrayList<HashMap<String, String>>();
// Getting JSON Array
// JSONObject job = new JSONObject();
//JSONArray jArray = ModuleClass.trainScheduleJSONObject.getJSONArray("stnName");
JSONObject json_data = null;
station= ModuleClass.trainScheduleJSONObject.getJSONArray(TAG_STATION);
for (int i = 0; i < station.length(); i++) {
json_data = station.getJSONObject(i);
// JSONObject c = stnName.getJSONObject(0);
// Storing  JSON item in a Variable
String sno = json_data.getString(TAG_SNO);
String stnCode = json_data.getString(TAG_STNCODE);
// String distance= c.getString(TAG_DISTANCE);
// String routeNo = c.getString(TAG_ROUTENO);
String arrivalTime = json_data.getString(TAG_ARRIVALTIME);
String depTime = json_data.getString(TAG_DEPTIME);
// String haltTime = c.getString(TAG_HALTTIME);
// String tday= c.getString(TAG_TDAY);
// String remark = c.getString(TAG_REMARK);
// Adding value HashMap key => value
stnNamelist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_SNO, sno);
map.put(TAG_STNCODE, stnCode);
map.put(TAG_DEPTIME, depTime);
map.put(TAG_ARRIVALTIME, arrivalTime);
// map.put(TAG_DEPTIME,depTime );
stnNamelist.add(map);
list = (ListView) findViewById(R.id.listView1);
final SimpleAdapter sd;
sd = new SimpleAdapter(this, stnNamelist, R.layout.activity_get_schedule,
new String[] { TAG_SNO, TAG_STNCODE, TAG_ARRIVALTIME, TAG_DEPTIME },
new int[] { R.id.textView1, R.id.textView2, R.id.textView3, R.id.textView4});
list.setAdapter(sd);
/*
* list.setOnItemClickListener(new
* AdapterView.OnItemClickListener() {
*
* #Override public void onItemClick(AdapterView<?> parent, View
* view, int position, long id) { Toast.makeText(
* MainActivity.this, "You Clicked at " +
* stnNamelist.get(+position).get( "name"), Toast.LENGTH_SHORT)
* .show(); } });
*/
}
// Set JSON Data in TextView
// uid.setText(id);
// name1.setText(name);
// email1.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.get_schedule, menu);
return true;
}
}
ListView from JSON data fetched using Retrofit2 service
JSON response
{
"results": [
{
"phone": "+9178XXXX66",
"name": "Olivia"
},
{
"phone": "+9178XXXX66",
"name": "Isla"
},
{
"phone": "+9178XXXX66",
"name": "Emily"
},
{
"phone": "+9178XXXX66",
"name": "Amelia"
},
{
"phone": "+9178XXXX66",
"name": "Sophia"
}],
"statusCode": "1",
"count": "2"
}
In MainActivity.java we will pass JSON data as ArrayList(dummyData)
customListAdapter = new CustomListAdapter(getApplicationContext(), dummyData);
listView = (ListView) findViewById(R.id.listShowJSONData);
listView.setAdapter(customListAdapter);
In custom BaseAdapter our
...
...
#Override
public MyModel getItem(int i) {
return this.users.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
if(view==null)
{
view= LayoutInflater.from(c).inflate(R.layout.json_data_list,viewGroup,false);
}
TextView mUserDetails = (TextView) view.findViewById(R.id.userDetails);
TextView mUserStatus = (TextView) view.findViewById(R.id.userStatus);
Object getrow = this.users.get(i);
LinkedTreeMap<Object,Object> rowmap = (LinkedTreeMap) getrow;
String name = rowmap.get("name").toString();
String phone = rowmap.get("phone").toString();
mUserDetails.setText(name);
mUserStatus.setText(phone);
return view;
}
...
...
Here MyModel will be used as custom mapping model of response we will get from service
See link for complete code explanation

How can i parse JSON from URL on Android and display it in listview [duplicate]

I am new to android and java.Recently I am having problem with displaying fetched json data into listview using baseadapter.
At first I have used this code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new TheTask().execute();
}
class TheTask extends AsyncTask<Void,Void,String>
{
#Override
protected String doInBackground(Void... params) {
String str = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/BSDI/show.php");
HttpResponse response = httpclient.execute(httppost);
str = EntityUtils.toString(response.getEntity());
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
String response = result.toString();
try {
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray new_array = new JSONArray(response);
for(int i = 0, count = new_array.length(); i< count; i++)
{
try {
JSONObject jsonObject = new_array.getJSONObject(i);
stringArray.add(jsonObject.getString("title").toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String> (MainActivity.this,R.layout.test_tuh,stringArray);
ListView list= (ListView) findViewById(R.id.listView1);
list.setAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//tv.setText("error2");
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This code displays fetched json data sucessfully. But it only displays only one row. I need more than one (two) rows in listview. So I have tried this code
and it does not work, it shows a blank screen .
My code is below,
class TheTask extends AsyncTask<Void,Void,String>
{
#Override
protected String doInBackground(Void... params) {
String str = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/BSDI/show.php");
HttpResponse response = httpclient.execute(httppost);
str = EntityUtils.toString(response.getEntity());
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String response = result.toString();
try {
arrayList=new ArrayList<get_set>();
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray new_array = new JSONArray(response);
for(int i = 0, count = new_array.length(); i< count; i++)
{
try {
JSONObject jsonObject = new_array.getJSONObject(i);
stringArray.add(jsonObject.getString("title").toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
ListView listView;
adap= new BaseAdapter() {
LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView(int position, View view, ViewGroup viewgroup) {
if (view==null) {
view=inflater.inflate(R.layout.bsdi, null);
}
TextView title_tuh=(TextView) view.findViewById(R.id.title1);
TextView notice_tuh=(TextView) view.findViewById(R.id.notice1);
title_tuh.setText(arrayList.get(position).getTitle());
notice_tuh=.setText(arrayList.get(position).getNotice());
return view;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayList.get(position);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
};
listView=(ListView) findViewById(R.id.listView1);
listView.setAdapter(adap);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//tv.setText("error2");
}
}
As far I am realizing that , the problem is here
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray new_array = new JSONArray(response);
for(int i = 0, count = new_array.length(); i< count; i++)
{
try {
JSONObject jsonObject = new_array.getJSONObject(i);
stringArray.add(jsonObject.getString("title").toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
As far I am guesing that extracted json data is storing in stringArray but its not used later. If I try to use it like this , then I get error
title_tuh.setText(stringArray .get(position).getTitle());
notice_tuh=.setText(stringArray .get(position).getNotice());
If I try to not to use
ArrayList stringArray = new ArrayList();
and use
arrayList=new ArrayList(); instead , like this then I also get error.
arrayList=new ArrayList<get_set>();
JSONArray new_array = new JSONArray(response);
//JSONArray jsonArray = new JSONArray();
for(int i = 0, count = new_array.length(); i< count; i++)
{
try {
JSONObject jsonObject = new_array.getJSONObject(i);
arrayList.add(jsonObject.getString("title").toString());
// String in = mInflater.inflate(R.layout.custom_row_view, null);
}
catch (JSONException e) {
e.printStackTrace();
}
}
I can not finding out how to solve this problem.I have seen many online tutorials but those was not helpful for me. Please help me.
First u need t create row_listitem.xml file like:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:background="#drawable/list_selector"
android:orientation="vertical"
android:padding="5dp" >
<ImageView
android:id="#+id/iv_icon_social"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_centerVertical="true"
android:background="#drawable/image_border"
android:src="#drawable/sms_t"
android:visibility="gone" />
<LinearLayout
android:id="#+id/thumbnail"
android:layout_width="fill_parent"
android:layout_height="85dp"
android:layout_marginRight="50dp"
android:layout_marginTop="0dp"
android:layout_toRightOf="#+id/iv_icon_social"
android:gravity="center_vertical"
android:orientation="vertical"
android:padding="5dip"
android:visibility="visible" >
<TextView
android:id="#+id/txt_ttlsm_row"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:text="Sample text"
android:textSize="18dp"
android:textStyle="bold" />
<TextView
android:id="#+id/txt_ttlcontact_row2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="0dp"
android:layout_marginTop="3dp"
android:paddingLeft="10dp"
android:maxEms="20"
android:maxLines="2"
android:singleLine="false"
android:ellipsize="end"
android:text="Sample text2"
android:textColor="#808080"
android:textSize="15dp"
android:textStyle="normal"
android:visibility="visible" />
</LinearLayout>
</RelativeLayout>
Now, u need to create Custom BaseAdapter like:
public class BaseAdapter2 extends BaseAdapter {
private Activity activity;
// private ArrayList<HashMap<String, String>> data;
private static ArrayList title,notice;
private static LayoutInflater inflater = null;
public BaseAdapter2(Activity a, ArrayList b, ArrayList bod) {
activity = a;
this.title = b;
this.notice=bod;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return title.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.row_listitem, null);
TextView title2 = (TextView) vi.findViewById(R.id.txt_ttlsm_row); // title
String song = title.get(position).toString();
title2.setText(song);
TextView title22 = (TextView) vi.findViewById(R.id.txt_ttlcontact_row2); // notice
String song2 = notice.get(position).toString();
title22.setText(song2);
return vi;
}
}
Now, u can set up your main activity like:
public class MainActivity extends Activity {
ArrayList<String> title_array = new ArrayList<String>();
ArrayList<String> notice_array = new ArrayList<String>();
ListView list;
BaseAdapter2 adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView1);
new TheTask().execute();
}
class TheTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String str = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://10.0.2.2/BSDI/show.php");
HttpResponse response = httpclient.execute(httppost);
str = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
String response = result.toString();
try {
JSONArray new_array = new JSONArray(response);
for (int i = 0, count = new_array.length(); i < count; i++) {
try {
JSONObject jsonObject = new_array.getJSONObject(i);
title_array.add(jsonObject.getString("title").toString());
notice_array.add(jsonObject.getString("notice").toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter = new BaseAdapter2(MainActivity.this, title_array, notice_array);
list.setAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// tv.setText("error2");
}
}
}
}
#Allen Chun , actually its not in my mind currently that what I have changed in my code to run my code perfectly. But I am sharing all my codes which are working perfectly.
Its my layout code,
<?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/fsr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Notice Board"
android:textSize="20px" />
<TextView
android:id="#+id/err_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:gravity="center" />
<ListView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/list_notice2"
android:layout_gravity="center" />
</LinearLayout>
This is my custom listview layout codes,
<?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/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:paddingTop="10dp"
android:layout_gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium" />
/>
<TextView
android:id="#+id/notice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:paddingTop="5dp"
android:layout_gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
its my activity named "NoticeBoard" .
public class NoticeBoard extends Activity {
ArrayList<String> title_array = new ArrayList<String>();
ArrayList<String> notice_array = new ArrayList<String>();
ListView list;
base_adapter3 adapter;
TextView f,msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_notice);
list = (ListView) findViewById(R.id.list_notice2);
msg=(TextView) findViewById(R.id.err_msg);
new test_ays().execute();
}
class test_ays extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String str = null ;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/BSDI/show.php");
HttpResponse response = httpclient.execute(httppost);
str = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result!=null) // add this
{
String response = result.toString();
try {
JSONArray new_array = new JSONArray(response);
for (int i = 0, count = new_array.length(); i < count; i++) {
try {
JSONObject jsonObject = new_array.getJSONObject(i);
title_array.add(jsonObject.getString("title").toString());
notice_array.add(jsonObject.getString("notice").toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter = new base_adapter3(NoticeBoard.this, title_array, notice_array);
list.setAdapter(adapter);
// f=(TextView) findViewById(R.id.textTuh);
// f.setText(title_array);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// tv.setText("error2");
}
}
else{
msg.setText("You need a working data connection...");
}
}
}
}
And its my custom baseadapter codes,
public class base_adapter2 extends BaseAdapter {
private Activity activity;
//private ArrayList<HashMap<String, String>> data;
private static ArrayList title,notice;
private static LayoutInflater inflater = null;
public base_adapter2(Activity a, ArrayList b) {
activity = a;
this.title = b;
// this.notice=bod;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return title.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.bsdi_adapter, null);
TextView title2 = (TextView) vi.findViewById(R.id.txt1); // title
String song = title.get(position).toString();
title2.setText(song);
return vi;
}
}
In this example, I am connecting to Twitters public timeline JSON url.
package net.inchoo.demo.andy1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class HomeActivity extends ListActivity {
/** Called when the activity is first created. */
#SuppressWarnings({ "rawtypes", "unchecked" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, this.fetchTwitterPublicTimeline()));
}
public ArrayList<String> fetchTwitterPublicTimeline()
{
ArrayList<String> listItems = new ArrayList<String>();
try {
URL twitter = new URL(
"http://twitter.com/statuses/public_timeline.json");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
listItems.add(jo.getString("text"));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItems;
}
}
Please direct your attention on the listItems.add(jo.getString(“text”)); line. This is the part that I am grabbing a “text” attribute/property of single JSON object. To get a more “visual” picture of all available attributes/properties you might want to take a look at the XML version of twitters public timeline. This way you will get nice colored XML in your browser, where you can see all available attributes.
Link: http://inchoo.net/dev-talk/android-development/simple-android-json-parsing-example-with-output-into-listactivity/
Json parser:
public class jparser {
static InputStream istream = null;
static JSONObject jObj = null;
//static JSONArray jarray=null;
static String json = "";
//static JSONArray jarray = null;
// constructor
public jparser() {
}
public JSONObject getJFromUrl(String url) {
// Making HTTP request
//try {
// defaultHttpClient
StringBuilder builder = new StringBuilder();
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
/*HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
istream = httpEntity.getContent();*/
try{
HttpResponse response = httpClient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 400)
{
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
}
else
{
Log.e("==>", "Failed to download file");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(istream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
istream.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
// Parse String to JSON object
/*try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jarray;
}*/
}
}
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
#SuppressLint("NewApi")
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
<h1>Model</h1>
public class WorkModel {
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImagename() {
return imagename;
}
public void setImagename(String imagename) {
this.imagename = imagename;
}
String id,name,imagename;
public WorkModel(String s1,String s2,String s3)
{
this.id=s1;
name=s2;
imagename=s3;
}
}
<h1>listview fill</h1>
public class Work_in_process extends Fragment {
//////////////jsonparser implement
JSONParser jsonparser=new JSONParser();
JSONArray json_users=null;
JSONObject json;
/////////
ListView lst;
ArrayList<WorkModel> data=new ArrayList<WorkModel>();
WorkAdapter adapter;
Context con;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_work_in_process, container, false);
con=this.getActivity();
lst=(ListView)rootView.findViewById(R.id.work_listview);
new work_process().execute();
// Inflate the layout for this fragment
return rootView;
}
class work_process extends AsyncTask<String,String,String>
{
public Dialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(con);
pDialog.setMessage("Loading... Please wait...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
data.clear();
List<NameValuePair> params = new ArrayList<NameValuePair>();
json = jsonparser.makeHttpRequest("your url","POST", params);
try {
int success = json.getInt("status");
if (success == 0)
{
return "kbc";
}
else
{
json_users = json.getJSONArray("result");
// looping through All Products
for (int i = 0; i < json_users.length(); i++) {
JSONObject c = json_users.getJSONObject(i);
String t1 = c.getString("id");
String t2 = c.getString("work_title");
String t3 = c.getString("image_path");
WorkModel da=new WorkModel(t1,t2,t3);
data.add(da);
}
return "abc";
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pDialog.dismiss();
if(s.equals("abc"))
{
adapter = new WorkAdapter(con, data);
lst.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
else
{
}
}
}
}
<h1>Adapter fill listview</h1>
public class WorkAdapter extends BaseAdapter {
private LayoutInflater inflater1=null;
private static String string=null;
ArrayList<WorkModel> data=null;
Context activity;
DisplayImageOptions options;
protected ImageLoader imageLoader = ImageLoader.getInstance();
public WorkAdapter(Context act,ArrayList<WorkModel> da)
{
activity=act;
data=da;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
{
inflater1=(LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi=inflater1.inflate(R.layout.list_work,null);
}
TextView name;
ImageView img;
name=(TextView)vi.findViewById(R.id.list_work_name);
img= (ImageView)vi.findViewById(R.id.list_work_img);
WorkModel da=new WorkModel(string,string,string);
da=data.get(position);
final String p1,p2,p3;
p1=da.getId();
p2=da.getName();
p3=da.getImagename();
name.setText(p2);
imageLoader.init(ImageLoaderConfiguration.createDefault(activity));
final String imgpath=""+p3;
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.wp_loading)
.showImageForEmptyUri(R.drawable.wp_loading)
.showImageOnFail(R.drawable.wp_loading)
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
imageLoader.displayImage(imgpath, img,options);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DisplayImageOptions options;
final ImageLoader imageLoader = ImageLoader.getInstance();
final Dialog emailDialog =new Dialog(activity, android.R.style.Theme_DeviceDefault);
emailDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
emailDialog.setCancelable(true);
emailDialog.setContentView(R.layout.zoom_imge);
ImageView image = (ImageView) emailDialog.findViewById(R.id.zoom_image_img);
emailDialog.show();
final String imgpath=""+p3;
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.wp_loading)
.showImageForEmptyUri(R.drawable.wp_loading)
.showImageOnFail(R.drawable.wp_loading)
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
imageLoader.displayImage(imgpath, image, options);
}
});
return vi;
}
}
Get schedule
public class GetSchedule extends Activity {
// JSON Node Names
private static final String TAG_SNO = "sno";
private static final String TAG_STNCODE = "stnCode";
private static final String TAG_STATION = "station";
// private static final String TAG_ROUTENO= "routeNo";
private static final String TAG_ARRIVALTIME = "arrivalTime";
private static final String TAG_DEPTIME = "depTime";
private JSONArray station = null;
private ListView list;
//private static String url = "http://railpnrapi.com/api/route/train/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_schedule);
try {
ArrayList<HashMap<String, String>> stnNamelist = new ArrayList<HashMap<String, String>>();
// Getting JSON Array
// JSONObject job = new JSONObject();
//JSONArray jArray = ModuleClass.trainScheduleJSONObject.getJSONArray("stnName");
JSONObject json_data = null;
station= ModuleClass.trainScheduleJSONObject.getJSONArray(TAG_STATION);
for (int i = 0; i < station.length(); i++) {
json_data = station.getJSONObject(i);
// JSONObject c = stnName.getJSONObject(0);
// Storing  JSON item in a Variable
String sno = json_data.getString(TAG_SNO);
String stnCode = json_data.getString(TAG_STNCODE);
// String distance= c.getString(TAG_DISTANCE);
// String routeNo = c.getString(TAG_ROUTENO);
String arrivalTime = json_data.getString(TAG_ARRIVALTIME);
String depTime = json_data.getString(TAG_DEPTIME);
// String haltTime = c.getString(TAG_HALTTIME);
// String tday= c.getString(TAG_TDAY);
// String remark = c.getString(TAG_REMARK);
// Adding value HashMap key => value
stnNamelist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_SNO, sno);
map.put(TAG_STNCODE, stnCode);
map.put(TAG_DEPTIME, depTime);
map.put(TAG_ARRIVALTIME, arrivalTime);
// map.put(TAG_DEPTIME,depTime );
stnNamelist.add(map);
list = (ListView) findViewById(R.id.listView1);
final SimpleAdapter sd;
sd = new SimpleAdapter(this, stnNamelist, R.layout.activity_get_schedule,
new String[] { TAG_SNO, TAG_STNCODE, TAG_ARRIVALTIME, TAG_DEPTIME },
new int[] { R.id.textView1, R.id.textView2, R.id.textView3, R.id.textView4});
list.setAdapter(sd);
/*
* list.setOnItemClickListener(new
* AdapterView.OnItemClickListener() {
*
* #Override public void onItemClick(AdapterView<?> parent, View
* view, int position, long id) { Toast.makeText(
* MainActivity.this, "You Clicked at " +
* stnNamelist.get(+position).get( "name"), Toast.LENGTH_SHORT)
* .show(); } });
*/
}
// Set JSON Data in TextView
// uid.setText(id);
// name1.setText(name);
// email1.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.get_schedule, menu);
return true;
}
}
ListView from JSON data fetched using Retrofit2 service
JSON response
{
"results": [
{
"phone": "+9178XXXX66",
"name": "Olivia"
},
{
"phone": "+9178XXXX66",
"name": "Isla"
},
{
"phone": "+9178XXXX66",
"name": "Emily"
},
{
"phone": "+9178XXXX66",
"name": "Amelia"
},
{
"phone": "+9178XXXX66",
"name": "Sophia"
}],
"statusCode": "1",
"count": "2"
}
In MainActivity.java we will pass JSON data as ArrayList(dummyData)
customListAdapter = new CustomListAdapter(getApplicationContext(), dummyData);
listView = (ListView) findViewById(R.id.listShowJSONData);
listView.setAdapter(customListAdapter);
In custom BaseAdapter our
...
...
#Override
public MyModel getItem(int i) {
return this.users.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
if(view==null)
{
view= LayoutInflater.from(c).inflate(R.layout.json_data_list,viewGroup,false);
}
TextView mUserDetails = (TextView) view.findViewById(R.id.userDetails);
TextView mUserStatus = (TextView) view.findViewById(R.id.userStatus);
Object getrow = this.users.get(i);
LinkedTreeMap<Object,Object> rowmap = (LinkedTreeMap) getrow;
String name = rowmap.get("name").toString();
String phone = rowmap.get("phone").toString();
mUserDetails.setText(name);
mUserStatus.setText(phone);
return view;
}
...
...
Here MyModel will be used as custom mapping model of response we will get from service
See link for complete code explanation

How to parse JSON dat with HTTP Post method in android studio

JSONParser.class
package com.example.diptiagravat.myapplication;
public class JSONParser {
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
public String sendHTTPData(String urlpath, String id) {
HttpURLConnection connection = null;
try {
URL url=new URL(urlpath);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
streamWriter.write(id);
streamWriter.flush();
StringBuilder stringBuilder = new StringBuilder();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(streamReader);
String response = null;
while ((response = bufferedReader.readLine()) != null) {
stringBuilder.append(response + "\n");
}
bufferedReader.close();
Log.d("test", stringBuilder.toString());
return stringBuilder.toString();
} else {
Log.e("test", connection.getResponseMessage());
return null;
}
} catch (Exception exception){
Log.e("test", exception.toString());
return null;
} finally {
if (connection != null){
connection.disconnect();
}
}
}
}
MainActivity.java
package com.example.diptiagravat.myapplication;
public class MainActivity extends AppCompatActivity {
private TextView txtid, txtcname;
Spinner spcnt, spstate;
public ArrayList<String> clist;
ArrayAdapter<String> cad;
public ArrayList<String> slist;
ArrayAdapter<String> sad;
public String strcnt;
private static String url = "http://urmiinfotech.com/demo/ifirst/app_api/get_country_list.php";
private static String stateUrl = "http://urmiinfotech.com/demo/ifirst/app_api/get_state_list.php";
private static final String TAG_USER = "country";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "country_name";
private ArrayList<Country> clistModels;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
CountryAsyncTask countryAsyncTask= new CountryAsyncTask();
countryAsyncTask.execute();
}
private void initViews() {
txtid = (TextView) findViewById(R.id.tvid);
txtcname = (TextView) findViewById(R.id.tvcname);
spcnt = (Spinner) findViewById(R.id.spcnt);
spstate = (Spinner) findViewById(R.id.spstate);
clist = new ArrayList<String>();
slist = new ArrayList<String>();
}
public class CountryAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = null;
try {
json = new JSONObject(jParser.getJSON(url, 5000));
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.i("Result Ravi", result);
try {
JSONObject obj = new JSONObject(result);
JSONArray cntArray = obj.getJSONArray("country");
if (cntArray.length() > 0) {
for (int i = 0; i < cntArray.length(); i++) {
final JSONObject temp = cntArray.getJSONObject(i);
// txtid.setText(temp.getString("id"));
// txtcname.setText(temp.getString("country_name"));
Country country = new Gson().fromJson(temp.toString(), Country.class);
clist = new ArrayList<String>();
clistModels = new ArrayList<Country>();
clistModels.add(new Country(temp.optString("id"), temp.optString("country_name"), "", null));
clist.add(temp.getString("country_name"));
cad = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, clist);
spcnt.setAdapter(cad);
spcnt.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
strcnt = clistModels.get(position).getId();
//strcnt = parent.getItemAtPosition(position).toString();
Log.i("id", strcnt);
new StatesAsyncTask().execute();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// txtid.setText(temp.getString(country.getId()));
// txtcname.setText(temp.getString(country.getCountryName()));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class StatesAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = null;
try {
json = new JSONObject(jParser.sendHTTPData(stateUrl, strcnt));
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject obj = new JSONObject(s);
JSONArray stArray = obj.getJSONArray("statelist");
if (stArray.length() > 0) {
for (int i = 0; i < stArray.length(); i++) {
final JSONObject temp = stArray.getJSONObject(i);
// txtid.setText(temp.getString("id"));
// txtcname.setText(temp.getString("country_name"));
Statelist stlist = new Gson().fromJson(temp.toString(), Statelist.class);
slist = new ArrayList<String>();
// clistModels = new ArrayList<Country>();
//clistModels.add(new Country(temp.optString("id"), temp.optString("country_name"), "", null));
slist.add(temp.getString("state_name"));
sad = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, slist);
spstate.setAdapter(sad);
spstate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// strcnt = clistModels.get(position).getId();
//strcnt = parent.getItemAtPosition(position).toString();
// Log.i("id", strcnt);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// txtid.setText(temp.getString(country.getId()));
// txtcname.setText(temp.getString(country.getCountryName()));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
My response is null?
HttpURLConnection is deprecated in Android Lollipop, so please try to use DefaultHttpClient instead. Also, check your logs, this is at your onPostExecute():
Log.i("Result Ravi", result);
For DefaultHttpClient check this post.
Another way is to try Retrofit

how to get json data from framework (Yii)

i'm trying to get json data from website that i build using Yii framework.
when i open mozilla and i go to http://localhost/restayii/index.php/employee/getemployee?id it's showing employee json data.
this is my employee jsondata :
{"employee":[{"id":"1","departmentId":"1","firstName":"Hendy","lastName":"Nugraha","gender":"female","birth_date":"1987-03-16","marital_status":"Single","phone":"856439112","address":"Tiban Mutiara View ","email":"hendy.nugraha87#yahoo.co.id","ext":"1","hireDate":"2012-06-30 00:00:00","leaveDate":"0000-00-00 00:00:00"},{"id":"2","departmentId":"2","firstName":"Jay","lastName":"Branham","gender":"male","birth_date":"0000-00-00","marital_status":"Single","phone":"0","address":"","email":"jaymbrnhm#labtech.org","ext":"2","hireDate":"0000-00-00 00:00:00","leaveDate":"0000-00-00 00:00:00"},{"id":"3","departmentId":"3","firstName":"Ahmad","lastName":"Fauzi","gender":"male","birth_date":"0000-00-00","marital_status":"Single","phone":"0","address":"","email":"ahmadfauzi#labtech.org","ext":"3","hireDate":"0000-00-00 00:00:00","leaveDate":"0000-00-00 00:00:00"},{"id":"4","departmentId":"1","firstName":"Henny","lastName":"Lidya Simanjuntak","gender":"female","birth_date":"1986-01-27","marital_status":"Married","phone":"2147483647","address":"Tiban Mutiara View ","email":"henokh_v#yahoo.com","ext":"1","hireDate":"0000-00-00 00:00:00","leaveDate":"0000-00-00 00:00:00"},{"id":"5","departmentId":"2","firstName":"sfg","lastName":"sfgsfg","gender":"male","birth_date":"2013-10-23","marital_status":"Single","phone":"356356","address":"sfgsfg","email":"sfgsfg","ext":"4","hireDate":"2012-05-30 00:00:00","leaveDate":"0000-00-00 00:00:00"}]}
this is on Android Activity.
Akses_Server_Aktivity :
public class Akses_Server_Activity extends Activity {
static String url ;
static final String Employee_ID = "id";
static final String Employee_Dept_ID = "departmentId";
static final String Employee_First_Name = "firstName";
static final String Employee_Last_Name = "lastName";
static final String Employee_Gender = "gender";
static final String Employee_Birth_Date = "birth_date";
static final String Employee_Marital_Status = "marital_status";
static final String Employee_Phone_Number = "phone";
static final String Employee_Address = "address";
static final String Employee_Email = "email";
static final String Employee_Ext = "ext";
static final String Employee_Hire_Date = "hireDate";
static final String Employee_Leave_Date = "leaveDate";
JSONArray employee = null;
JSONObject json_object;
Button callService;
EditText ip;
HashMap<String, String> map = new HashMap<String, String>();
String get_ip;
ProgressDialog pDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.service_resta);
ip = (EditText)findViewById(R.id.ip_address);
get_ip = ip.getText().toString();
callService = (Button) findViewById(R.id.call_services);
callService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
// masuk ke class Task
new Task().execute();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private class Task extends AsyncTask<String, Void, String>{
#Override
protected void onPreExecute(){
super.onPreExecute();
// tampilkan progress dialog
pDialog = new ProgressDialog(Akses_Server_Activity.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
JSONParser json_parse = new JSONParser();
url = "http://10.0.2.2/restayii/protected/controllers/EmployeeController.php";
employee= json_parse.GetJson(url);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result){
// masuk ke method LoadEmployee()
LoadEmployee();
}
}
public class JSONParser {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// Constructor
public JSONParser(){
}
public JSONObject GetJson(String url) {
// masuk ke class myasyntask
new MyAsynTask().execute();
return jObj;
}
public class MyAsynTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
return null;
}
protected void onPostExecute(JSONArray Result){
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void LoadEmployee(){
try {
employee = json_object.getJSONArray("employee");
TableLayout table_layout =(TableLayout) findViewById(R.id.table_layout);
table_layout.removeAllViews();
int jml_baris = employee.length();
String [][] data_employee = new String [jml_baris][13];
for(int i=0;i<jml_baris;i++){
JSONObject Result = employee.getJSONObject(i);
data_employee[i][0] = Result.getString(Employee_ID);
data_employee[i][1] = Result.getString(Employee_Dept_ID);
data_employee[i][2] = Result.getString(Employee_First_Name);
data_employee[i][3] = Result.getString(Employee_Last_Name);
data_employee[i][4] = Result.getString(Employee_Gender);
data_employee[i][5] = Result.getString(Employee_Birth_Date);
data_employee[i][6] = Result.getString(Employee_Marital_Status);
data_employee[i][7] = Result.getString(Employee_Phone_Number);
data_employee[i][8] = Result.getString(Employee_Address);
data_employee[i][9] = Result.getString(Employee_Email);
data_employee[i][10] = Result.getString(Employee_Ext);
data_employee[i][11] = Result.getString(Employee_Hire_Date);
data_employee[i][12] = Result.getString(Employee_Leave_Date);
}
TableLayout.LayoutParams ParameterTableLayout = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
for(int j=0; j<jml_baris; j++){
TableRow table_row = new TableRow(null);
table_row.setBackgroundColor(Color.BLACK);
table_row.setLayoutParams(ParameterTableLayout);
TableRow.LayoutParams ParameterTableRow = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
ParameterTableRow.setMargins(1,1,1,1);
for(int kolom = 0; kolom < 13; kolom++){
TextView TV= new TextView(null);
TV.setText(data_employee[j][kolom]);
TV.setTextColor(Color.BLACK);
TV.setPadding(1, 4, 1, 4);
TV.setGravity(Gravity.LEFT);
TV.setBackgroundColor(Color.BLUE);
table_row.addView(TV,ParameterTableRow);
}
table_layout.addView(table_row);
pDialog.dismiss();
}
} catch (Exception e) {
}
}
}
(On Android)
The problem is:
when this app launch, and i clicked button refresh, it's not showing table row that contains employee json data. but there's no error too on the logcat. Is it wrong with my url on class Task extends AsyncTask http://10.0.2.2/restayii/protected/controllers/EmployeeController.php ??
or should i replaced it with the same link just when i open it from mozilla http://localhost/restayii/index.php/employee/getemployee?id??
Edit:
I already change the url to http://localhost/restayii/index.php/employee/getemployee?id inside Task Class extends AsyncTask, but is still won't get employee json data from localhost.
please, Any help would be greatly apreciated. thanks
i already find an answer. my problem is in sub class Task extends asyntask and also in jsonParser sub class.
private class Task extends AsyncTask<JSONObject, Void, JSONObject>{
#Override
protected JSONObject doInBackground(JSONObject... params) {
try {
JSONParser json_parser = new JSONParser();
json_object = json_parser.getJson(url);
} catch (Exception e) {
e.printStackTrace();
}
return json_object;
}
#Override
protected void onPostExecute(JSONObject result){
LoadEmployee(result);
}
}
private class JSONParser {
.....
public JSONObject getJson(String url) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpget);
BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
StringBuffer hasil = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
hasil.append(line);
}
json = hasil.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
return jObj;
}
}
now i can get all json data from my Yii web service. hope it will help someone.
I know that, you have to refresh android screen when you called an ajax data...
May be this will show you the way...
Now you use wrong URL in the AsyncTask. The right URL is something like http://localhost/restayii/index.php/employee/getemployee?id

How implement search dialog on ListView MySql -Android

I'm practising with some tutorials I found on the web, I am communicating with a database for a listing, the unfold in a listview listview adapter as show you various names, I would like to add a search dialog, something like this Example Image but no where in the deploy, I have tried in various ways.
this is part of the code example:
LIST ACTIVITY:
public class List extends Activity {
private ProgressDialog pDialog;
public int i = 0;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> DaftarRS = new ArrayList<HashMap<String, String>>();
private static String url_daftar_rs = "my_url";
public static final String TAG_SUCCESS = "success";
public static final String TAG_DAFTAR_RS = "daftar_rs";
public static final String TAG_ID_RS = "id_rs";
public static final String TAG_NAMA_RS = "nama_rs";
public static final String TAG_LINK_IMAGE_RS = "link_image_rs";
public static final String TAG_ALAMA_RS = "alamat_rs";
public static final String TAG_TELEPONS_RS = "telepon_rs";
JSONArray daftar_rs = null;
ListView list;
ListAdapter adapter;
private ListadoActivity activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
DaftarRS = new ArrayList<HashMap<String, String>>();
new Activity().execute();
activity = this;
list = (ListView) findViewById(R.id.list);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String id_rs = ((TextView) view
.findViewById(R.id.id_rs)).getText().toString();
Intent in = new Intent(getApplicationContext(),
DetallesActivity.class);
in.putExtra(TAG_ID_RS, id_rs);
startActivityForResult(in, 100);
}
});
}
public void SetListViewAdapter(ArrayList<HashMap<String, String>> daftar) {
adapter = new ListAdapter(activity, daftar);
list.setAdapter(adapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class Activity extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(List.this);
pDialog.setMessage("wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
Conexion();
if (i == 0) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_daftar_rs, "GET",
params);
Log.d("All Products: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
daftar_rs = json.getJSONArray(TAG_DAFTAR_RS);
for (int i = 0; i < daftar_rs.length(); i++) {
JSONObject c = daftar_rs.getJSONObject(i);
String id_rs = c.getString(TAG_ID_RS);
String nama_rs = c.getString(TAG_NAMA_RS);
String link_image_rs = c
.getString(TAG_LINK_IMAGE_RS);
String alamat_rs = c.getString(TAG_ALAMAT_RS);
String telepon_rs = c.getString(TAG_TELEPON_RS);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID_RS, id_rs);
map.put(TAG_NAMA_RS, nama_rs);
map.put(TAG_LINK_IMAGE_RS, link_image_rs);
map.put(TAG_ALAMAT_RS, alamat_rs);
map.put(TAG_TELEPON_RS, telepon_rs);
DaftarRS.add(map);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else{ finish();
}
return null;
}
JSON PARSER:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
LISTADAPTER:
public class ListAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public ListAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.item_list_rs, null);
TextView id_rs = (TextView) vi.findViewById(R.id.id_rs);
TextView nama_rs = (TextView) vi.findViewById(R.id.nama_rs);
TextView link_image_rs = (TextView) vi.findViewById(R.id.link_image_rs);
TextView alamat_rs = (TextView) vi.findViewById(R.id.alamat_rs);
TextView telepon_rs = (TextView) vi.findViewById(R.id.telepon_rs);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.image_rs);
HashMap<String, String> daftar_rs = new HashMap<String, String>();
daftar_rs = data.get(position);
id_rs.setText(daftar_rs.get(ListadoActivity.TAG_ID_RS));
nama_rs.setText(daftar_rs.get(ListadoActivity.TAG_NAMA_RS));
link_image_rs.setText(daftar_rs.get(ListadoActivity.TAG_LINK_IMAGE_RS));
alamat_rs.setText(daftar_rs.get(ListadoActivity.TAG_ALAMAT_RS));
telepon_rs.setText(daftar_rs.get(ListadoActivity.TAG_TELEPON_RS));
imageLoader.DisplayImage(daftar_rs.get(ListadoActivity.TAG_LINK_IMAGE_RS),
thumb_image);
return vi;
}
}
Why don't you add an EditText to the layout xml and pass the text as an argument after the List<NameValuePair> params = new ArrayList<NameValuePair>();
Something like:
params.add(new BasicNameValuePair(TAG_NAME, name));

Categories

Resources