Related
I am trying to fetch the json into recyclerview in cardview but when i run the app the UI is not updating app is showing blank screen, i didn't get where is the error, tried possibles codes but didn't work.
The screen is still blank, so where is the exact error and what is the solution??
items.xml
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="8dp"
app:cardCornerRadius="5dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:padding="25dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/avatar"
android:layout_width="108dp"
android:layout_height="108dp"
android:padding="15dp"
tools:src="#mipmap/ic_launcher" />
<LinearLayout
android:paddingRight="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="15dp"
tools:text="LOGIN_USER" />
<TextView
android:id="#+id/type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="3dp"
tools:text="USER_TYPE" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
main_activity.java
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
UserAdapter mAdapter;
public ArrayList<User> users = new ArrayList();
RecyclerView.LayoutManager layoutManager;
private static final String JSON_URL = "https://api.github.com/users";
private static final String LOG_TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
mAdapter = new UserAdapter(users,this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(mAdapter);
UserAsyncTask task = new UserAsyncTask();
task.execute(JSON_URL);
}
public class UserAsyncTask extends AsyncTask<String, Void, List<User>>{
#Override
protected List<User> doInBackground(String... urls) {
if(urls.length < 1 || urls[0] == null ){
return null;
}
List<User> result = null;
try{
result = QueryUtils.fetchJson(urls[0]);
} catch (JSONException e) {
Log.e(LOG_TAG,"Error in fetching json",e);
}
return result;
}
#Override
protected void onPostExecute(List<User> users) {
//clear previous data
mAdapter.clear();
if(users != null){
mAdapter.addAll(users);
mAdapter.notifyDataSetChanged();
}
}
}
}
QueryUtils.java
public class QueryUtils {
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
public QueryUtils() {
}
public static List<User> fetchJson(String requestUrl) throws JSONException{
//create URL object
URL url = createUrl(requestUrl);
//perform http request to the URL and receive a json
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG,"problem in making http request",e);
}
List<User> users = extractJson(jsonResponse);
return users;
}
/**
* Returns new URL object from the given string URL.
*/
private static URL createUrl(String stringUrl){
URL url = null;
try{
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG,"Error in creating Url",e);
}
return url;
}
/**
* Make an HTTP request to the given URL and return a String as the response.
*/
private static String makeHttpRequest(URL url) throws IOException{
String jsonResponse = "";
//if url == null, return early
if(url == null){
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("GET");
if(urlConnection.getResponseCode() == 200){
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}else {
Log.e(LOG_TAG,"Error response code" + urlConnection.getResponseCode());
}
}catch (IOException e){
Log.e(LOG_TAG,"Problem in retrieving Json Response",e);
}finally {
if (urlConnection != null){
urlConnection.disconnect();
}
if (inputStream !=null){
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if(inputStream != null){
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null){
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
private static List<User> extractJson(String json) throws JSONException{
// If the JSON string is empty or null, then return early.
if(TextUtils.isEmpty(json)){
return null;
}
//create an empty arrylist
List<User> users = new ArrayList<>();
try{
JSONArray jsonArray = new JSONArray();
for (int i = 0; i<jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String login = jsonObject.getString("login");
String type = jsonObject.getString("type");
String avatar = jsonObject.getString("avatar_url");
User user = new User(login,type,avatar);
users.add(user);
}
}catch (JSONException e){
Log.e(LOG_TAG,"Error in parsing the JSON",e);
}
return users;
}
}
UserAdapter
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserViewHolder> {
ArrayList<User> users = new ArrayList<>();
Context context;
public UserAdapter(ArrayList<User> users, Context context) {
this.users = users;
this.context = context;
}
#Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items,parent,false);
return new UserViewHolder(view);
}
#Override
public void onBindViewHolder(UserViewHolder holder, int position) {
holder.login.setText(users.get(position).getUser_login());
holder.type.setText(users.get(position).getType());
Picasso.with(context).load(String.valueOf(users.get(position))).into(holder.avatar);
}
#Override
public int getItemCount() {
return users.size();
}
public class UserViewHolder extends RecyclerView.ViewHolder {
TextView login;
TextView type;
ImageView avatar;
public UserViewHolder(View itemView) {
super(itemView);
login = (TextView)itemView.findViewById(R.id.login);
type = (TextView)itemView.findViewById(R.id.type);
avatar = (ImageView)itemView.findViewById(R.id.avatar);
}
}
//for clearing previous data in adapter
public void clear(){
int itemCount = getItemCount();
users.clear();
//notify the adapter that data has been changed
if(itemCount > 0){
notifyItemRangeRemoved(0,itemCount);
}
}
//for adding items to the adapter
public void addAll(List<User> addUser){
for (User user : addUser){
users.add(1,user);
}
//notify adapter that data has changed
notifyItemInserted(users.size());
}
}
User.java
public class User {
private String user_login;
private String type;
private String url;
public User(String user_login, String type, String url) {
this.user_login = user_login;
this.type = type;
this.url = url;
}
public String getUser_login() {
return user_login;
}
public String getType() {
return type;
}
public String getUrl() {
return url;
}
}
Change your main_activity.java
recyclerView.setLayoutManager(new LinearLayoutManager(this));
to
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(mAdapter);
and in UserAdapter Do not create the object of ArrayList.
ArrayList<User> users;
Context context;
Put Log and check is ArrayList have data :
mAdapter = new UserAdapter(users,this);
Log.e("SIZE",""+users.size());
you can try with this
public void addAll(List<User> addUser){
this.users = addUser
notifyDataSetChanged();
}
and remove the below line from code
mAdapter.notifyDataSetChanged();
Change this
#Override
protected void onPostExecute(List<User> users) {
//clear previous data
mAdapter.clear();
if(users != null){
mAdapter.addAll(users);
mAdapter.notifyDataSetChanged();
}
}
to this
#Override
protected void onPostExecute(List<User> newUsers) {
//clear previous data
users.clear();
if(newUsers!= null){
// Add new set of users
users.addAll(newUsers);
mAdapter.notifyDataSetChanged();
}
}
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
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
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
I am trying to parse the data into the list View in android
JSON:: http://54.218.73.244:7000/
It has a JSON output :: [{"restaurantID":1,"restaurantNAME":"CopperChimney"},{"restaurantID":2,"restaurantNAME":"Aroy"},{"restaurantID":3,"restaurantNAME":"MarkBoulevard"}]
I am trying to display the CopperChimney, Aroy, MarkBoulevard in a
list view
I figured some small parts but can someone help me fill
AndroidJSONParsingActivity.java part of the code which invoolves putting data in a collection and displaying it
Any ideas ?
JSONParser
public class JSONParser {
static InputStream is = null;
static JSONArray jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(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 JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Item.java
public class Item{
private String Name;
public Item(String name){
this.Name = name;
}
public String getName(){
return Name;
}
}
ListAdapter.java
public class ListAdapter extends ArrayAdapter<Item> {
private List<Item> items;
public ListAdapter(Context context, int resource, List<Item> items) {
super(context, resource, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView tt = null;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.itemlistrow, null);
tt = (TextView) v.findViewById(R.id.RestaurantNameID);
}
Item p = items.get(position);
if (p != null) {
if (tt != null) {
tt.setText(""+p.getName());
}
}
return v;
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listViewID"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center">
</ListView>
</LinearLayout>
itemlistrow.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" android:orientation="vertical"
android:layout_width="fill_parent">
<TableRow android:layout_width="fill_parent"
android:id="#+id/TableRow01"
android:layout_height="wrap_content">
<TextView
android:id="#+id/RestaurantNameID"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="name" android:textStyle="bold"
android:gravity="left"
android:layout_weight="1"
android:typeface="monospace"
android:height="40sp"/>
</TableRow>
</TableLayout>
AndroidJSONParsingActivity.java
public class AndroidJSONParsingActivity extends Activity {
private static String url = "http://54.218.73.244:7000/";
//
//
//
//
/------ CODE -Trying to ADD ------ /
//
//
}
CODE I TRIED FOR AndroidJSONParsingActivity.java
public class AndroidJSONParsingActivity extends Activity {
// url to make request
private static String url = "http://54.218.73.244:7000/";
List<Item> yourData = new ArrayList<Item>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
try {
for (int i = 0; i < json.length(); i++) {
JSONObject c = json.getJSONObject(i);
// Storing each json item in variable
String NAME=c.getString("restaurantNAME");
yourData.add(new Item(NAME));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ListView yourListView = (ListView) findViewById(R.id.listViewID);
ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, yourData);
yourListView.setAdapter(customAdapter);
yourListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
if(position == 0)
{
//code specific to first list item
Intent myIntent = new Intent(AndroidJSONParsingActivity.this,Employee1.class);
startActivity(myIntent);
}else if(position == 1)
{
Intent myIntent = new Intent(AndroidJSONParsingActivity.this,Employee2.class);
startActivity(myIntent);
}
}
});
}
}
public class AndroidJSONParsingActivity extends ListActivity {
ArrayList <Item> list = new ArraList <Item>();
#Override
public void onStart() {
super.onStart();
new GetHttpData().execute();
}
private class GetHttpData extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
private static String url = "http://54.218.73.244:7000/";
JSONArray jArray = getJSONFromUrl(url);
int len = jArray.length();
for(int i = 0; i < len; i++) {
JSONObject restaurant = jArray.getJSONObject(i);
list.add(new Item(restaurant.getString("restaurantNAME"));
}
return null;
}
#Override
protected void onPostExecute(Void result) {
setListAdapter(new ListAdapter(AndroidJSONParsingActivity.this, android.R.layout.simple_list_item_1, list));
}
}
}
This is just one way to parse it, you should also do all HttpRequests and JSON parsing in a separate thread, see http://developer.android.com/reference/android/os/AsyncTask.html
Edited:
You can also check this Example