I have the following code:
package com.example.myfirstapp;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.UnknownHostException;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
public class FetchData extends Activity {
private TextView textView;
private JSONObject jObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fetch_data);
textView = (TextView) findViewById(R.id.TextView1);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
readWebpage(message);
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
mParseResponse(response);
}
#Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
public void readWebpage(String message) {
//Intent intent = getIntent();
//String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] {message});
}
ArrayList<String> year, title, details, director, rating, cover;
// For Parse Login Response From Server
public void mParseResponse(String response) throws UnknownHostException {
year=new ArrayList<String>();
title=new ArrayList<String>();
details=new ArrayList<String>();
director=new ArrayList<String>();
rating=new ArrayList<String>();
cover=new ArrayList<String>();
try {
JSONObject jObject = new JSONObject(response);
JSONObject jsonobjresults = jObject.getJSONObject("results");
JSONArray jsonarrayresult = jsonobjresults.getJSONArray("result");
for(int i=0;i<jsonarrayresult.length(); i++){
JSONObject mJsonObj = jsonarrayresult.getJSONObject(i);
year.add(mJsonObj.getString("year"));
title.add(mJsonObj.getString("title"));
details.add(mJsonObj.getString("details"));
director.add(mJsonObj.getString("director"));
rating.add(mJsonObj.getString("rating"));
cover.add(mJsonObj.getString("cover"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am getting confused as to how to create a custom adapter. Yes, i have gone thoeugh tutorials but confusion still exits. Plus, I am having an error when i make a call to mParseResponse. Any ideas where I am going wrong and how should i implement list view?
Perhaps this simple sample custom adapter listview will get on your feet with this stuff.
The main activity
public class MainActivity extends Activity {
String [] children = {
"Award 1",
"Award 2",
"Award 3",
"Award 4",
"Award 5",
"Award 6",
"Award 7",
"Award 8",
"Award 9",
"Award 10",
"Award 11",
"Award 12",
"Award 13",
"Award 14",
"Award 15"};
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list = (ListView) findViewById(R.id.listview);
CustomAdapter adapter = new CustomAdapter(this, children);
list.setAdapter(adapter);
}
The custom adapter
public class CustomAdapter extends BaseAdapter {
// you could have instead extend ArrayAdapter if you wished, i find it less fickle but less flexible
// extends CursorAdapter is available too for listviews backed by cursors
private LayoutInflater inflator;
private String[] children;
public CustomAdapter(Context context, String[] children) {
super();
// pass what you need into the constructor. in this case the string array and context.
// do as much as you can here and not in getView because getView acts for each row
// --> it will greatly help performance
this.children = children;
inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// v---- your listview won't show anything if this is left default (at 0).
return children.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// getView is where all the action takes place
// first inflate the xml that holds the row and somehow connect it to convertView, the parameter
// checking if null allows these views to be recycled when they go off-screen not just made one per row
// ---> it will greatly help performance
if (convertView == null) {
convertView = inflator.inflate(R.layout.row, parent, false);
}
// then find the individual views with this xml (everything just like onCreate)
ImageView img = (ImageView) convertView.findViewById(R.id.imageView1);
TextView tv = (TextView) convertView.findViewById(R.id.textView1);
// then perform your actions to the your views
// each textView is set to an element in the array based on position. this is my listview limiter here.
// each imageview is set to the same picture but you should now have an idea how to set different images (based on position)
// using listview position in correspondence with array/arraylist positions is a very useful technique.
img.setImageResource(R.drawable.ic_launcher);
tv.setText(children[position]);
// v---- return your view, it's important.
return convertView;
}
}
row.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="TextView" />
</RelativeLayout>
The result
To get super acquainted with listview check out this video:
http://www.youtube.com/watch?v=wDBM6wVEO70
As for your other issue, you're gonna have to post a logcat for better responses.
Related
I'm creating a Image Slider using Picasso + Viewpager.
I am able to swipe the slider base on the image size(counts).
But no images from array has been loaded even though i can swipe the screen with default images.
Please correct my mistakes if any founded. I am new to android.
Thanks in advance
My json array is like this
[
{
"guid": "C410B2AA-EC03-29E4-F5C0-CB48510ED9E5",
"id": "2",
"created_on": "2016-05-17 13:13:22",
"car_name": "Hundai",
"model": "C001",
"version": "i20",
"make_year": "2012",
"kms_driven": "2000",
"city": "Bangalore",
"pincode": "560072",
"expected_price": "200000",
"name": "Vishnu",
"email": "dreamvishnu#gmail.com",
"mobile": "9863265358",
"image": [
{
"newimage": "https://images.cardekho.com/car-images/carexteriorimages/large/Ford/Ford-Mustang/ford-mustang-exterior-047.jpg"
},
{
"newimage": "https://www.enterprise.com/content/dam/global-vehicle-images/cars/FORD_FOCU_2012-1.png"
},
{
"newimage": "https://imagecdn8.cartrade.com/img/800x600/car-data/big/bmw-i8-default-image.png"
}
]
}
]
In the postexecute of my activity i am setting the adapter as follow
protected void onPostExecute(Void v) {
try {
JSONArray object = new JSONArray(result);
ArrayList<String> items = new ArrayList<String>();
try {
for (int i = 0; i < object.length(); i++) {
JSONObject obj = object.getJSONObject(i);
vehicleSliderIamges = obj.getJSONArray("image");
guid = obj.getString("guid");
name = obj.getString("car_name");
model = obj.getString("version");
price = obj.getString("expected_price");
km = obj.getString("kms_driven");
fuel = obj.getString("model");
year = obj.getString("make_year");
location = obj.getString("city");
gear = obj.getString("name");
}
ArrayList<String> list = new ArrayList<String>();
if (vehicleSliderIamges != null) {
int len = vehicleSliderIamges.length();
for (int i=0;i<len;i++){
list.add(vehicleSliderIamges.get(i).toString());
}
}
viewPagerAdapter = new ViewPagerAdapter(SecondHandCarDetailsActivity.this,list);
viewPager.setAdapter(viewPagerAdapter);
vehicleName.setText(name);
vehicleModel.setText(model);
vehiclePrice.setText(price);
vehicleYear.setText(year);
vehicleFuel.setText(fuel);
vehicleKm.setText(km);
vehicleGear.setText(gear);
vehicleLocation.setText(location);
this.progressDialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
}
My ViewpagerAdapter is
import android.content.Context;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.support.v4.view.ViewPager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class ViewPagerAdapter extends PagerAdapter {
private Context context;
private ArrayList<String> IMAGES = new ArrayList<>();
public ViewPagerAdapter(Context context, ArrayList<String> IMAGES) {
this.IMAGES = IMAGES;
this.context = context;
}
#Override
public int getCount() {
return IMAGES.size();
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return true;
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.imagepager_layout,null);
((ViewPager) collection).addView(view);
final ImageView img = (ImageView) view.findViewById(R.id.img);
Picasso.with(context)
.load(IMAGES.get(position))
.placeholder(R.drawable.loading)
.into(img);
return view;
}
}
My secondcar_detail.xml is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#color/white"
>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="150dp"
android:orientation="vertical"
>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="150dp"></android.support.v4.view.ViewPager>
</LinearLayout>
</LinearLayout>
Replace get method call
vehicleSliderIamges.get(i).toString()
to getJSONObject method call:
vehicleSliderIamges.getJSONObject(i).get("newimage").toString()
get method call returns below strings:
{"newimage":"https:\/\/images.cardekho.com\/car-images\/carexteriorimages\/large\/Ford\/Ford-Mustang\/ford-mustang-exterior-047.jpg"}
You forgot to notify changes in your adapter using notifyDataSetChanged():
viewPagerAdapter = new ViewPagerAdapter(SecondHandCarDetailsActivity.this,list);
viewPager.setAdapter(viewPagerAdapter);
viewPagerAdapter.notifyDataSetChanged();
Apparently Picasso does not support https out of the box. See the Issue here.
1) Either you get a http url to the image or
2) You use a HTTP Client like OkHttpClient
OkHttpClient client = new OkHttpClient();
client.setProtocols(Arrays.asList(Protocol.HTTP_11));
Picasso picasso = new Picasso.Builder(context)
.downloader(new OkDownloader(client))
.build();
Use the following code:
ArrayList<String> list = new ArrayList<String>();
if (vehicleSliderIamges != null) {
for (JSONObject o: vehicleSliderIamges){
list.add(o.getString("newimage");
}
}
main xml containing horizontallistview
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#fff"
>
<com.example.newomolistview.HorizontalScrollView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ddd"
/>
</LinearLayout>
contain three textviews-for product name,original rate and offer rate
app_custom_list.xml
I think in this java class i have gone wrong
ApplicationAdapter.java
package com.example.newomolistview;
import java.text.NumberFormat;
import java.util.List;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.newomolistview.R;
import com.example.newomolistview.HorizontalScrollView;
public class ApplicationAdapter extends ArrayAdapter<Application>{
private List<Application> items;
public ApplicationAdapter(Context context, List<Application> items) {
super(context, R.layout.app_custom_list, items);
this.items = items;
}
// private BaseAdapter mAdapter = new BaseAdapter() {
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null) {
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.app_custom_list, null); //new code
// LayoutInflater li = LayoutInflater.from(getContext()); //original
// v = li.inflate(R.layout.app_custom_list, null); //original
// LayoutInflater li = (LayoutInflater) this._context
// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// convertView = li.inflate(R.layout.app_custom_list, null);
}
Application app = items.get(position);
if(app != null) {
TextView productName = (TextView)v.findViewById(R.id.textView1);
TextView originalRate = (TextView)v.findViewById(R.id.textView2);
TextView offerRate = (TextView)v.findViewById(R.id.textView3);
if(productName != null) productName.setText(app.getProductName());
if(originalRate != null) originalRate.setText(app.getOriginalRate());
if(offerRate != null) offerRate.setText(app.getOfferRate());
}
return v;
// View retval = LayoutInflater.from(parent.getContext()).inflate(R.layout.listitem, null);
// TextView title = (TextView) retval.findViewById(R.id.title);
// title.setText(dataObjects[position]);
//
// return retval;
}
// };
}
I need to populate horizontal listview with json data from database(product name, original rate and offer rate).I used array adapter to populate the horizontal listview. I think I have gone wrong somewhere in ApplicationAdapter.java and MainActivity.java
in this section also, i have gone wrong
MainActivity.java
package com.example.newomolistview;
import java.util.List;
import com.example.newomolistview.HorizontalScrollView;
import com.example.newomolistview.R;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.widget.BaseAdapter;
import android.widget.Toast;
public class MainActivity extends ListActivity implements FetchDataListener{
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// HorizontalScrollView listview = (HorizontalScrollView) findViewById(R.id.listview);
// listview.setAdapter(mAdapter);
initView();
}
private void initView() {
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String key="saasvaap123";
String cityid="1";
String url = "http://www.gooffers.in/omowebservices/index.php/webservice/Public_User/homePagepoffers?";
FetchDataTask task = new FetchDataTask(this);
task.execute(url,key,cityid);
}
#Override
public void onFetchComplete(List<Application> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
HorizontalScrollView listview = (HorizontalScrollView) findViewById(R.id.listview); //new code
// create new adapter
ApplicationAdapter mAdapter = new ApplicationAdapter(this, data);
listview.setAdapter(mAdapter); //new code
// set the adapter to list
// setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}
I need to populate horizontal listview with json data from database(product name, original rate and offer rate).I used array adapter to populate the horizontal listview. I think I have gone wrong somewhere in ApplicationAdapter.java and MainActivity.java
You can learn it from these tutorials :-
Populating a ListView from JSON
Loading Text in listview from http json data
I am making a listview, which shows data from a server. I get no errors in LogCat, but my ListView doesn't appear. This is my code:
package com.imptmd.charliemacdonald.desleutelaar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class SlotenFragment extends ListFragment {
private ProgressDialog nDialog;
// URL to get contacts JSON
private static String url = "http://charlenemacdonald.com/sloten.json";
// JSON Node names
private static final String TAG_SLOTEN = "slotenlijst";
private static final String TAG_SLOT = "Slot";
// contacts JSONArray
JSONArray sloten= null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> slotenLijst;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_sloten, container, false);
slotenLijst = new ArrayList<HashMap<String, String>>();
ListView lv = (ListView) rootView.findViewById(android.R.id.list);
// Listview on item click listener
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String Slot = ((TextView) rootView.findViewById(R.id.textviewslotnaam))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getActivity().getApplicationContext(),
SlotInfoScherm1.class);
in.putExtra(TAG_SLOT, Slot);
startActivity(in);
}
});
new GetSloten().execute();
// Calling async task to get json
return rootView;
}
/**
* Async task class to get json by making HTTP call
* */
private class GetSloten extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
nDialog = new ProgressDialog(getActivity());
nDialog.setMessage("Even geduld a.u.b., studenten worden geladen...");
nDialog.setCancelable(false);
nDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
sloten = jsonObj.getJSONArray(TAG_SLOTEN);
// looping through All Contacts
for (int i = 0; i < sloten.length(); i++) {
JSONObject c = sloten.getJSONObject(i);
String Slot = c.getString(TAG_SLOT);
// tmp hashmap for single contact
HashMap<String, String> sloten = new HashMap<String, String>();
// adding each child node to HashMap key => value
sloten.put(TAG_SLOT, Slot);
// adding contact to contact list
slotenLijst.add(sloten);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (nDialog.isShowing())
nDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(getActivity(), slotenLijst,
R.layout.sloten_info, new String[] { TAG_SLOT}, new int[] { R.id.textviewslotnaam});
setListAdapter(adapter);
}
}
}
The INTERNET permission is already added in the Manifest, just as WRITE EXTERNAL STORAGE and INTERNAL STORAGE. I get no errors in LogCat. The only error I get is in the ADB 'ADB rejected connection to client'. Is that why my ListView doesn't appear? Thanks in advance.
Hi can you update you code and test the below logic what you received.
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (nDialog.isShowing())
nDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
Log.d("DataSize: ",""+slotenLijst.size());
ListAdapter adapter = new SimpleAdapter(getActivity(), slotenLijst,
R.layout.sloten_info, new String[] { TAG_SLOT}, new int[] { R.id.textviewslotnaam});
setListAdapter(adapter);
}
Let us know what you get in log cat "DataSize".
Change your onCreateView(...) to be:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_sloten, container, false);
slotenLijst = new ArrayList<HashMap<String, String>>();
ListView lv = (ListView) rootView.findViewById(android.R.id.list);
new GetSloten().execute();
// Calling async task to get json
return rootView;
}
// ListFragment implement this in default
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
//getting values from selected ListItem
String Slot = ((TextView) rootView.findViewById(R.id.textviewslotnaam))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getActivity().getApplicationContext(),
SlotInfoScherm1.class);
in.putExtra(TAG_SLOT, Slot);
startActivity(in);
}
});
and your fragment layout fragment_sloten could be like:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<ListView android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00"
android:layout_weight="1"
android:drawSelectorOnTop="false"/>
... ...
</LinearLayout>
Hope this help!
This question already has answers here:
JSON Android And Listview
(3 answers)
Closed 9 years ago.
I'm a new programmer and I'm making an app which can get data from MYSQL to php and then display on android. I've been trying to find a solution but none of the tutorials I've seen so far seems to work for me, I've only managed to get one object from json into a single textview. But what I really need is to get data to be displayed on individual rows on listview.
here's my JSON output,
[{"id":"1","name":"darrel","password":"pass1234"},{"id":"2","name":"garrett","password":"important"},{"id":"3","name":"neoys","password":"yseniopass"},{"id":"4","name":"john","password":"mikel123"},{"id":"5","name":"owen","password":"mike4l"}]
and my java code which gets only one of the users displayed onto a textview.
package com.darre.jsonreader;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class Users extends ListActivity {
/** Called when the activity is first created. */
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//listView.setOnItemClickListener(new OnItemClickListener() {
// public void onItemClick(AdapterView<?> parent, View view,
// int position, long id) {
// When clicked, show a toast with the TextView text
// Toast.makeText(getApplicationContext(),
// ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://172.30.54.153/databases/");
TextView textView = (TextView)findViewById(R.id.textView1);
ListView listview = (ListView)findViewById(R.id.listView1);
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
JSONArray mArray = new JSONArray(jsonResult);
for (int i = 0; i < mArray.length(); i++) {
JSONObject object = mArray.getJSONObject(i);
String name = object.getString("name");
String password = object.getString("password");
textView.setText(name + " - " + password);
}
}
catch (JSONException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
Thanks in advance!!!
You can read this tutorial, it explains to ways of implement it, the first, a "direct" List adapter, the second, the way to customize your List.
http://www.mkyong.com/android/android-listview-example/
Also, you shouldn't work with JSON data, first, you have to create an Object for each Item, and then group it with some kind of List (ArrayList, for example).
You have to create ListView adapter:
Put this in your Code :
private String[] listArr;
public ArrayList<String> ary_name = new ArrayList<String>();
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
JSONArray mArray = new JSONArray(jsonResult);
for (int i = 0; i < mArray.length(); i++) {
JSONObject object = mArray.getJSONObject(i);
String name = object.getString("name");
String password = object.getString("password");
textView.setText(name + " - " + password);
ary_name.add(name);
}
listArr = new String[ary_name.size()];
listArr = ary_name.toArray(listArr);
MyArrayAdapter adapter = new MyArrayAdapter(this, listArr);
listView.setAdapter(adapter);
public class MyArrayAdapter extends ArrayAdapter<String> {
Activity context;
String[] listArr;
private TextView btnchkout;
// private final integer[] image;
public MyArrayAdapter(Activity context, String[] objects) {
super(context, R.layout.custmlayout, objects);
// TODO Auto-generated constructor stub
this.context = context;
listArr = objects;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custmlayout, null, true);
TextView textView = (TextView) view.findViewById(R.id.txtTicketNo);
textView.setText(listArr[position]);
return view;
}
}
If you want to use a ListView... then you should parse you JSON file into some kind of data structure like a List or an ArrayList and the n use an adapter to populate the ListView data.
Here is an example for ListView adapter:
private class MySecondAdapter extends ArrayAdapter<MiniTask>
{
private ArrayList<MiniTask> list;
public MySecondAdapter(Context context, int textViewResourceId, ArrayList<MiniTask> miniTaskList)
{
super(context, textViewResourceId, miniTaskList);
this.list = new ArrayList<MiniTask>();
this.list.addAll(miniTaskList);
}
public View getView(final int position, View convertView, ViewGroup parent)
{
miniTask = miniTaskList.get(position);
ViewHolder holder = new ViewHolder();
{
LayoutInflater inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.check_list_item_new, null);
holder.title = (TextView) convertView.findViewById(R.id.tvItemTitle);
holder.commentsPicturesButton = (ImageView) convertView.findViewById(R.id.iAddCommetOrPicture);
holder.commentsPicturesButton.setTag(position);
holder.commentsPicturesButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(getApplicationContext(), PicturesAndCommentsActivity.class);
intent.putExtra(TasksListActivity.KEY_ID, task.getId());
intent.putExtra("mini_task_text", miniTask.getTitle());
startActivity(intent);
}
});
holder.selected = (CheckBox) convertView.findViewById(R.id.cbCheckListItem);
holder.selected.setTag(position);
holder.selected.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
{
Log.d(TAG, "pressed the checkbox: " + v.getId() + " in position: " + position + " tag: " +v.getTag() +" and item from array: " + miniTaskList.get(position) );
CheckBox checkbox = (CheckBox) v;
miniTaskList.get(position).setSelected(checkbox.isChecked());
numOfCheckedMiniTasks = 0;
for(int i=0;i<miniTaskList.size();i++)
{
miniTask = miniTaskList.get(i);
if(miniTask.isSelected())
{
numOfCheckedMiniTasks ++;
}
}
int percent = (int)(numOfCheckedMiniTasks * 100.0f) / miniTaskList.size();
Log.d(TAG, "the percentage is: " +percent);
tasksRepository.get(tasksRepository.indexOf(task)).setMiniTasksPercentageComplete(percent);
}
}
});
}
holder.title.setText(miniTask.getTitle());
holder.selected.setChecked(miniTask.isSelected());
return convertView;
}
}
Check this tutorials for getting more information:
http://cyrilmottier.com/2012/02/16/listview-tips-tricks-5-enlarged-touchable-areas/
Long story short im trying to add the clickable functionality from the top half of the code below to the custom adapter below.
I found this tut(modified version of the source in the top part of the code below-currently not working):
http://wiresareobsolete.com/wordpress/2011/08/clickable-zones-in-listview-items/
but, my entire project uses the custom adapter from this tut(custom adapter at the bottom of the code below):
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
All I would like to do is maintain my ability to use my existing data structure(ArrayList w. hash maps ) via a listview that will allow me to click on
*The thumbnail imageview
*The bold title text(in the image its the textview that reads "someone like you"
*the list row ( all the area besides the imageview & textview)
I would prefer to keep my custom adapter from the second link and just add the functionality from the first link, but if that complicates things im cool with suggestions to anything that allows me to plug in my existing data set ( Arraylist>) while providing the described functionality.
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class MyActivity extends Activity implements AdapterView.OnItemClickListener, View.OnClickListener
{
// All static variables
// XML node keys
static final String KEY_FEED = "feed";
// parent node
static final String KEY_UID_FK = "uid_fk";
static final String KEY_FIRST_NAME = "first_name";
static final String KEY_LAST_NAME = "last_name";
static final String KEY_NAME = "name";
static final String KEY_MESSAGE = "message";
static final String KEY_CREATED = "created";
static final String KEY_THUMB_URL = "thumb_img";
private static final String TAG = "MyApp";
ListView list;
LazyAdapter adapter;
JSONArray feed = null;
Button add;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView list = new ListView(this);
setContentView(list);
ArrayList<HashMap<String, String>> feedList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
// Getting Array of Contacts
feed = json.getJSONArray(KEY_FEED);
// looping through All Contacts
for(int i = 0; i < feed.length(); i++){
JSONObject c = feed.getJSONObject(i);
// Storing each json item in variable
String uid = c.getString(KEY_UID_FK);
String first_name = c.getString(KEY_FIRST_NAME);
String last_name = c.getString(KEY_LAST_NAME);
String name = first_name + last_name;
String http = "http://10.0.2.2/CI_BUHZ/IMGS/";
String base_url = c.getString(KEY_THUMB_URL);
String thumb_url = http + base_url;
String message = c.getString(KEY_MESSAGE);
String created = c.getString(KEY_CREATED);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_UID_FK, uid);
map.put(KEY_NAME, name);
map.put(KEY_MESSAGE, message);
map.put(KEY_CREATED, created);
map.put(KEY_THUMB_URL, thumb_url);
// adding HashList to ArrayList
feedList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i(TAG, "I am logging something informational!");
//Supply this adapter with either R.layout.row_button, R.layout.row_view, or R.layout.row_view_noparent
ArrayAdapter<HashMap<String, String>> adapter = new ArrayAdapter<HashMap<String,String>>(this, R.layout.row_view,
feedList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
View left = row.findViewById(R.id.left);
left.setTag(position);
left.setOnClickListener(MyActivity.this);
View text = row.findViewById(R.id.text);
text.setTag(position);
text.setOnClickListener(MyActivity.this);
return row;
}
};
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.left:
Toast.makeText(this, "Left Accessory "+v.getTag(), Toast.LENGTH_SHORT).show();
break;
case R.id.text:
Toast.makeText(this, "text Accessory "+v.getTag(), Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(this, "Item Click "+position, Toast.LENGTH_SHORT).show();
} }
//previously I was using this custom adapter that extends base adapter:
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_row, null);
TextView name = (TextView)vi.findViewById(R.id.name); // title
TextView message = (TextView)vi.findViewById(R.id.message); // artist name
TextView created = (TextView)vi.findViewById(R.id.created); // duration
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
// Setting all values in listview
name.setText(update.get("name"));
message.setText(update.get("message"));
created.setText(update.get("created"));
imageLoader.DisplayImage(update.get("thumb_url"), thumb_image);
return vi;
}
}
from this tutorial : http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
Ruware was nice enough to do a Google Hangout with me to help me solve my problem. Extremely embarrassed I couldn't manage to figure this out myself:
Step 1. Import dl the project from link 2 in my original description & import it into Eclipse.
Step 2. LazyAdapter Class w. Clickable Imageview & Textview - Simply replace the lazy adapter from link 2 in my original description with the code below:
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_row, null);
TextView name = (TextView)vi.findViewById(R.id.name); // title
TextView message = (TextView)vi.findViewById(R.id.message); // artist name
TextView created = (TextView)vi.findViewById(R.id.created); // duration
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
// Setting all values in listview
name.setText(update.get("name"));
message.setText(update.get("message"));
name.setOnClickListener(new myOnClickListener(position));
created.setText(update.get("created"));
imageLoader.DisplayImage(update.get("thumb_url"), thumb_image);
thumb_image.setOnClickListener(new myOnClickListener(position));
return vi;
}
public class myOnClickListener implements OnClickListener{
private int position;
public myOnClickListener(int position){
this.position=position;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
HashMap<String, String> update = new HashMap<String, String>();
update = data.get(position);
Log.d("Testing Click", update.get("message"));
}
}
}
Step 3. list_row.xml - Replace the list_row layout w. the XML below:
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip">
android:layout_width="50dip"
android:layout_height="50dip"
android:src="#drawable/default_thumb"/>
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:text="Chuck Kelly"
android:textColor="#040404"
android:typeface="sans"
android:textSize="15dip"
android:textStyle="bold"/>
<TextView
android:id="#+id/message"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/name"
android:textColor="#343434"
android:textSize="10dip"
android:layout_marginTop="1dip"
android:layout_toRightOf="#+id/thumbnail"
android:text="This is a status Update" />
<TextView
android:id="#+id/created"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/message"
android:layout_below="#+id/message"
android:layout_marginRight="5dip"
android:text="5:45"
android:textColor="#10bcc9"
android:textSize="10dip"
android:textStyle="bold" />
<ImageView
android:id="#+id/close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="#drawable/closeicon"
android:visibility="invisible" />
You now have a listview w. click-able views in each row that also allows you to set the value of multiple views in each row similar to many of the popular social networks ( facebook , twitter , path ) Thanks again to Ruware for taking the time to help me with this.
If you set your parts of row as focusable (android:focusable="true") (default) than OnItemClickListener for ListView does not respond.
Try setting them all to false