I have implement Custom List in which i have stored data -> class->Hash Map->List->Adapter.It Places data successfully and shows me list.But when i click on Item in list.I am unable to retrieve clicked value.my code is
public class asasa extends Activity {
//ListView listView;
Intent intent;
private ProgressDialog pDialog;
//Class Declartion DataHolder
DataHolder obj;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
static final String URL = "http://10.0.2.2/android_connect/get_all_products.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_NAME = "name";
private static final String TAG_Description = "description";
private static final String TAG_URL = "url";
private static final String TAG_Price = "price";
private static final String TAG_class = "DataHolider";
LazyAdapter adapter;
// flag for Internet connection status
Boolean isInternetPresent = false;
// products JSONArray
JSONArray products = null;
// Connection detector class
ConnectionDetector cd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*ListView l1 = (ListView) findViewById(R.id.sportsList);
l1.setAdapter(new MyCustomAdapter(text, image));
*/
// creating connection detector class instance
cd = new ConnectionDetector(getApplicationContext());
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
LoadAllProducts il = new LoadAllProducts();
il.execute(URL);
}
else
{
// Internet connection is not present
// Ask user to connect to Internet
Toast.makeText(asasa.this, "No Internet Connection You don't have internet connection.", Toast.LENGTH_LONG).show();
}
}
public void longToast(CharSequence message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater=null;
private ArrayList<HashMap<Integer, Object>> data;
//public ImageLoader imageLoader;
int i=0;
public LazyAdapter(Activity a, ArrayList<HashMap<Integer, Object>> 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 title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
ImageView imageview=(ImageView) vi.findViewById(R.id.list_image);
//ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
HashMap<Integer, Object> song = new HashMap<Integer, Object>();
song = data.get(position);
DataHolder objj=new DataHolder();
objj=(DataHolder) song.get(position);
Log.i("iiiiii "," " +i++);
Log.i("objj.GetName() ",objj.GetName());
Log.i("objj.GetDescription() ",objj.GetDescription());
Log.i("objj.GetPrice() ",objj.GetPrice());
title.setText(objj.GetName());
artist.setText(objj.GetDescription());
duration.setText(objj.GetPrice());
imageview.setImageBitmap(objj.Getimage());
//imageLoader.
return vi;
}
}
class LoadAllProducts extends AsyncTask<String, String, String> {
// creating new HashMap
ArrayList<HashMap<Integer, Object>> productsList=new ArrayList<HashMap<Integer,Object>>();
Bitmap decodedByte;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(asasa.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(URL, "GET", params);
// Check your log cat for JSON reponse
//Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
Log.i("products ",products.toString());
// looping through All Products
Log.i("LENGTHHHH "," "+products.length());
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
Log.i("ccccccccc ",c.toString());
// Storing each json item in variable
// String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
Log.i("name::",name);
String description = c.getString(TAG_Description);
Log.i("description::",description);
/*String URl = c.getString(TAG_URL);
Log.i("URl",URl);
*/
String price = c.getString(TAG_Price);
Log.i("price",price);
byte[] decodedString = Base64.decode(c.getString(TAG_URL), Base64.DEFAULT);
decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
obj=new DataHolder();
obj.setData(name, description, price, decodedByte);
HashMap<Integer, Object> map = new HashMap<Integer, Object>();
// adding each child node to HashMap key => value
map.put(i, obj);
/*map.put(TAG_Description, description);
map.put(TAG_URL, decodedByte);
map.put(TAG_Price, price);*/
//Log.i("MAP",map.toString());
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
/*Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);*/
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
ListView list;
// dismiss the dialog after getting all products
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
//adapter=new LazyAdapter(a, d)
adapter=new LazyAdapter(asasa.this, productsList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.i("Name---------------"," "+ productsList.get(view.getId()).get(position).getClass().getName());
}
});
if (pDialog.isShowing()) {
pDialog.dismiss();
// progressDialog.setCancelable(true);
}
}
}
public void onPause()
{
super.onPause();
}
public class DataHolder
{
String Name;
String Description;
String Price;
Bitmap image;
public void setData(String Name,String Descipton,String Price,Bitmap iamage)
{
this.Name=Name;
this.Description=Descipton;
this.Price=Price;
this.image=iamage;
}
public String GetName()
{return Name;}
public String GetDescription()
{return Description;}
public String GetPrice()
{return Price;}
public Bitmap Getimage()
{return image;}
}
}
i want help in this part of code
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.i("Name---------------"," "+ productsList.get(view.getId()).get(position).getClass().getName());
}
});
Q2:why GetView is called infinitely at back-end though list is displayed successfully
i HAVE SOLVED MY PROBLEM THIS WAY
HashMap<String, Object> item = productsList.get(position);
DataHolder Data= new DataHolder();
Data= (DataHolder) item.get(ITEMTITLE);
Log.i("productsListID ", Data.Get_Id())
;
Related
I'm new in android developer, I've problem in my custom Listview, the condition is when I click on my listview it should be go to detail activity. and yes, it works!
but the detail data and image isn't appear. only detail.xml without data and image.
Ymainactivity.java
private class GetData extends AsyncTask<String, Void, String> {
JSONArray str_json = null;
JSONObject json = null;
JSONParser jParser = new JSONParser();
ListView listx;
LazyAdapter adapter;
ArrayList<HashMap<String, String>> data_map = new ArrayList<HashMap<String, String>>();
ProgressDialog dialog = new ProgressDialog(YmainActivity.this);
protected void onPreExecute() {
super.onPreExecute();
this.dialog.setMessage("Memuat Item..");
this.dialog.show();
}
protected String doInBackground(String... param) {
json = jParser.AmbilJson(link_url);
try {
str_json = json.getJSONArray("berita");
for(int i = 0; i < str_json.length(); i++){
JSONObject ar = str_json.getJSONObject(i);
String kodebrg = "kode barang : "+ar.getString("kodebrg");
String gambar = ar.getString("gambar2");
String nama = ar.getString("nama");
String stok = "Stok : "+ar.getString("stok")+" "+ar.getString("satauan");
String harga = "Rp. "+ar.getString("harga")+" per "+ar.getString("satauan");
String info = ar.getString("info");
HashMap<String, String> map = new HashMap<String, String>();
map.put(in_nama, nama);
map.put(in_stok, stok);
map.put(in_kodebrg, kodebrg);
map.put(in_gambar, gambar);
map.put(in_harga, harga);
map.put(in_info, info);
data_map.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
dialog.dismiss();
listx = (ListView)findViewById(R.id.listos);
adapter = new LazyAdapter(YmainActivity.this, data_map);
listx.setAdapter(adapter);
if (adapter.getCount()==0) {
Toast.makeText(YmainActivity.this,"data tidak ditemukan",Toast.LENGTH_SHORT).show();
}
listx.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
HashMap<String, String> map = (HashMap<String, String>) adapter.getItem(position);
String kodebrgs = ((TextView) view.findViewById(R.id.kodebrgs)).getText().toString();
Intent inx = new Intent(YmainActivity.this, DetailActivity.class);
inx.putExtra(kodebrgs, map2.get(in_kodebrg));
startActivity(inx);
}
DetailActivity.java
private class GetData extends AsyncTask<String, Void, String> {
JSONArray artikel = null;
JSONObject json = null;
JSONParser jParser = new JSONParser();
Intent ins = getIntent();
String kode1s = ins.getStringExtra(in_kodebrg);
String link_url = "http:// my php file that call all data using primary id from table in my database mySQL"+kode1s;
ProgressDialog dialog = new ProgressDialog(DetailActivity.this);
protected void onPreExecute() {
super.onPreExecute();
this.dialog.setMessage("Memuat Detail Produk..");
this.dialog.show();
}
protected String doInBackground(String... params) {
json = jParser.AmbilJson(link_url);
return null;
}
protected void onPostExecute(String result) {
dialog.dismiss();
try {
artikel = json.getJSONArray("artikel");
for(int i = 0; i < artikel.length(); i++){
JSONObject ar = artikel.getJSONObject(i);
TextView judul1 = (TextView) findViewById(R.id.judul2);
TextView detail1 = (TextView) findViewById(R.id.detail2);
TextView isi1 = (TextView) findViewById(R.id.isi2);
TextView info1 = (TextView) findViewById(R.id.infobarang2);
TextView kodebarang1 = (TextView) findViewById(R.id.kodenyabrg2);
String judul_1 = ar.getString("nama");
String detail_1 = "harga Rp. "+ ar.getString("harga");
String isi_1 = "Stok Barang : "+ ar.getString("stok")+" "+ar.getString("satauan");
String info_1 = "Info : "+ar.getString("info");
String kodebarang_1 = "Kode Barang : "+ar.getString(in_kodebrg);
judul1.setText(judul_1);
detail1.setText(detail_1);
isi1.setText(isi_1);
info1.setText(info_1);
kodebarang1.setText(kodebarang_1);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
LazyAdapter.java
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 data.get(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.listimage_item, null);
TextView nama = (TextView)vi.findViewById(R.id.namas);
TextView stok = (TextView)vi.findViewById(R.id.stoks);
TextView kodebrg = (TextView)vi.findViewById(R.id.kodebrgs);
TextView harga = (TextView)vi.findViewById(R.id.hargas);
TextView info = (TextView)vi.findViewById(R.id.infos);
ImageView gambar=(ImageView)vi.findViewById(R.id.gambars);
HashMap<String, String> berita = new HashMap<String, String>();
berita = data.get(position);
nama.setText(berita.get(YmainActivity.in_nama));
stok.setText(berita.get(YmainActivity.in_stok));
kodebrg.setText(berita.get(YmainActivity.in_kodebrg));
harga.setText(berita.get(YmainActivity.in_harga));
info.setText(berita.get(YmainActivity.in_info));
imageLoader.DisplayImage(berita.get(YmainActivity.in_gambar), gambar);
return vi;
}
}
this is my custom listiview pict
http://cdn.gudangimages.com/v1/2015/06/05/gambarlistview.png
and this is detail xml when I clicked one of the list in my custom listview the result is blank, no data and image.
http://cdn.gudangimages.com/v1/2015/06/05/gambardetail.png
I don't know what's wrong with the code, because when I run the program it didn't force close.
first ,you need to debug on the detailActivity to find out whether getIntent() has got the data you desire , if you have got ,then use the view to contain these data ,if not , you need to think about whether the onitemclicklistener is ok
I think the problem is with inx.putExtra(kodebrgs, map2.get(in_kodebrg));
you should use key which doesn't change...
Intent i = new Intent(<currentActivity>.this,
<newactivity>.class);
i.putExtra("ticket", ticket);
i.putExtra("ticketid", tid);
startActivity(i);
and in other intent:
String ticketid = getIntent().getStringExtra("ticketid").toString();
String ticket = getIntent().getStringExtra("ticket").toString();
you can also send each string with different key and get them in detail page with help of key.
I am new to Android. I am using Fedor's Lazy Loading List. Is it possible to get all the values from a HashMap (values were retrieved from mysql) and store it to private String[] drinkImages?
String[] drinkImages' values will be passed to adapter Lazy_Adapter.
Or is there any other way to pass the value to Lazy_Adapter?
Code:
Lazy_ListItem.java
public class Lazy_ListItem extends Activity {
ListView list;
Lazy_Adapter adapter;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> drinksList;
// url to get all products list
private static String url_all_drinks = "http://10.0.2.2/restosnapp/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DRINKS = "drinks";
private static final String TAG_RID = "rid";
private static final String TAG_DRK_ID = "drk_id";
private static final String TAG_DRK_NAME = "drk_name";
private static final String TAG_DRK_DESC = "drk_desc";
private static final String TAG_DRK_PRICE = "drk_price";
private static final String TAG_DRK_AVAIL = "drk_avail";
private static final String TAG_DRK_IMAGE = "drk_image";
// products JSONArray
JSONArray drinks = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
list = (ListView) findViewById(R.id.list);
adapter = new Lazy_Adapter(this, drinkImages);
list.setAdapter(adapter);
// Button b = (Button) findViewById(R.id.button1);
// b.setOnClickListener(listener);
}
#Override
public void onDestroy() {
list.setAdapter(null);
super.onDestroy();
}
/*
* public OnClickListener listener = new OnClickListener() {
*
* #Override public void onClick(View arg0) {
* adapter.imageLoader.clearCache(); adapter.notifyDataSetChanged(); } };
*/
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
/*
* #Override protected void onPreExecute() { super.onPreExecute();
*
* pDialog = new ProgressDialog(Lazy_Adapter.this, Lazy_ListItem.class);
* pDialog.setMessage("Loading drinks. Please wait...");
* pDialog.setIndeterminate(false); pDialog.setCancelable(false);
* pDialog.show();
*
* //final ProgressDialog dialog; // dialog =
* ProgressDialog.show(getActivity, "Title", "Message", true); }
*/
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_drinks, "GET",
params);
// Check your log cat for JSON response
Log.d("All Drinks: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
drinks = json.getJSONArray(TAG_DRINKS);
// looping through All Products
for (int i = 0; i < drinks.length(); i++) {
JSONObject c = drinks.getJSONObject(i);
// Storing each json item in variable
String drk_image = c.getString(TAG_DRK_IMAGE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DRK_IMAGE, drk_image);
// adding HashList to ArrayList
drinksList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
}
private String[] drinkImages = {
"http://webitprojects.com/restaurant/images/drinks/drk_coffee.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_calamansijuice.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_blackgulaman.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_avocadoshake.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_durianshake.jpg" }; }
Lazy_Adapter.java
public class Lazy_Adapter extends BaseAdapter {
String drk_name, drk_desc, drk_price, drk_avail;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> drinksList;
// url to get all products list
private static String url_all_drinks = "http://10.0.2.2/restosnapp/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DRINKS = "drinks";
private static final String TAG_RID = "rid";
private static final String TAG_DRK_ID = "drk_id";
private static final String TAG_DRK_NAME = "drk_name";
private static final String TAG_DRK_DESC = "drk_desc";
private static final String TAG_DRK_PRICE = "drk_price";
private static final String TAG_DRK_AVAIL = "drk_avail";
private static final String TAG_DRK_IMAGE = "drk_image";
// products JSONArray
JSONArray drinks = null;
private Activity activity;
private String[] data;
private static LayoutInflater inflater = null;
public Lazy_ImageLoader imageLoader;
public Lazy_Adapter(Activity a, String[] d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new Lazy_ImageLoader(activity.getApplicationContext());
// Hashmap for ListView
drinksList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// ///
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_drinks, "GET",
params);
// Check your log cat for JSON response
Log.d("All Drinks: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
drinks = json.getJSONArray(TAG_DRINKS);
// looping through All Products
for (int i = 0; i < drinks.length(); i++) {
JSONObject c = drinks.getJSONObject(i);
// Storing each json item in variable
drk_name = c.getString(TAG_DRK_NAME);
drk_desc = c.getString(TAG_DRK_DESC);
drk_price = c.getString(TAG_DRK_PRICE);
drk_avail = c.getString(TAG_DRK_AVAIL);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DRK_NAME, drk_name);
map.put(TAG_DRK_DESC, drk_desc);
map.put(TAG_DRK_PRICE, drk_price);
map.put(TAG_DRK_AVAIL, drk_avail);
// adding HashList to ArrayList
drinksList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
#SuppressWarnings("unused")
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.item, null);
for (Map<String, String> menuItem : drinksList) {
ImageView image = (ImageView) vi.findViewById(R.id.image);
imageLoader.DisplayImage(data[position], image);
TextView tvMenuName = (TextView) vi.findViewById(R.id.tvMenuName);
tvMenuName.setText(drinksList.get(position).get(TAG_DRK_NAME));
TextView tvMenuDesc = (TextView) vi.findViewById(R.id.tvMenuDesc);
tvMenuDesc.setText(drinksList.get(position).get(TAG_DRK_DESC));
TextView tvMenuPrice = (TextView) vi.findViewById(R.id.tvMenuPrice);
tvMenuPrice.setText("P"
+ drinksList.get(position).get(TAG_DRK_PRICE));
TextView tvMenuAvail = (TextView) vi.findViewById(R.id.tvMenuAvail);
tvMenuAvail.setText(drinksList.get(position).get(TAG_DRK_AVAIL));
}
return vi;
}}
I hope you can help me. Thank you.
You can access perticular string on loacation with this code. Here i is an index number which may be 0,1,2 etc.
String yourstring = drinksList.get(i).get(TAG_DRK_IMAGE)
String[] drinkImages = (String[]) drinkList.get(0).values().toArray();
Yes, something like this will work .
public static void main(String[] args) {
Map<String, String> hm = new HashMap<String, String>(); // and yes. I am still using java 6 :(
hm.put("a", "a.jpg");
hm.put("b", "b.jpg");
String[] arr = new String[hm.size()];
hm.values().toArray(arr);
for (String s : arr) {
System.out.println(s);
}
}
O/P:
b.jpg
a.jpg
Try to iterate HashMap and build Array from HashMap value :
public String[] getStringArrayFromMap(HashMap<String,String> map){
String[] array = new String[map.size()];
int i=0;
for (String key : map.keySet()) {
array[i++] = map.get(key);
}
return array;
}
I am using a modified version of the contacts project from AndroidHive.
It basically just pulls n list of articles and their contact from a Joomla Site.
I am using a Image Plugin that gets a image from a url. i can successfully use it on the article detail activity view but i don't know how to add it to each List Item on the MainAcitivity file. I am new to Android development so please excuse the confusion.
The script to add the image is:
ImageView thumb = (ImageView) findViewById(R.id.thumb);
UrlImageViewHelper.setUrlDrawable(thumb, "https://www.site.co.za/test.png");
and my MainActivity which generated the ListView:
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get articles JSON
private static String url = "http://192.168.12.21/sebastian/broadcast/index.php/blog?format=json";
// JSON Node names
private static final String TAG_ARTICLES = "articles";
// Get the fields
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_SHORTTEXT = "shorttext";
private static final String TAG_FULLTEXT = "fulltext";
private static final String TAG_IMAGE = "image";
private static final String TAG_DATE = "date";
// articles JSONArray
JSONArray articles = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> articleList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
articleList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String shorttext = ((TextView) view.findViewById(R.id.shorttext)).getText().toString();
String fulltext = ((TextView) view.findViewById(R.id.fulltext)).getText().toString();
String image = ((TextView) view.findViewById(R.id.image)).getText().toString();
String date = ((TextView) view.findViewById(R.id.date)).getText().toString();
// Starting single article activity
Intent in = new Intent(getApplicationContext(),
SingleArticleActivity.class);
in.putExtra(TAG_TITLE, title);
in.putExtra(TAG_SHORTTEXT, shorttext);
in.putExtra(TAG_FULLTEXT, fulltext);
in.putExtra(TAG_IMAGE, image);
in.putExtra(TAG_DATE, date);
startActivity(in);
}
});
// Calling async task to get json
new GetArticles().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetArticles extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.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
articles = jsonObj.getJSONArray(TAG_ARTICLES);
// looping through All articles
for (int i = 0; i < articles.length(); i++) {
JSONObject c = articles.getJSONObject(i);
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String shorttext = c.getString(TAG_SHORTTEXT);
String fulltext = c.getString(TAG_FULLTEXT);
String image = c.getString(TAG_IMAGE);
String date = c.getString(TAG_DATE);
// tmp hashmap for single article
HashMap<String, String> article = new HashMap<String, String>();
// adding each child node to HashMap key => value
article.put(TAG_ID, id);
article.put(TAG_TITLE, title);
article.put(TAG_SHORTTEXT, shorttext);
article.put(TAG_FULLTEXT, fulltext);
article.put(TAG_IMAGE, image);
article.put(TAG_DATE, date);
// adding article to article list
articleList.add(article);
}
} 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 (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, articleList,
R.layout.list_item, new String[] {
TAG_TITLE,
TAG_SHORTTEXT,
TAG_FULLTEXT,
TAG_IMAGE,
TAG_DATE
},
new int[] {
R.id.title,
R.id.shorttext,
R.id.fulltext,
R.id.image,
R.id.date
});
setListAdapter(adapter);
}
}
}
**I don't know where in the MainActivity file do i add the script to add an image to each List Item.
I already got it working on the SingleArticleActivity but cannot get it to work on the List of Items**
Thanks for the help
UPDATE
What im trying to do:
foreach(ListItem in the List) {
ImageView thumb = (ImageView) findViewById(R.id.thumb);
UrlImageViewHelper.setUrlDrawable(thumb, "https://www.site.co.za/test.png");
}
You have to just use this one..
ImageView thumb = (ImageView) findViewById(R.id.thumb);
UrlImageViewHelper.setUrlDrawable(thumb, articleList.get(position).get(TAG_IMAGE));
CustomAdapter cdp = new CustomAdapter(YourActivityName.this , articleList);
setListAdapter(adapter);
Now make class of CustomAdapter extends with BaseAdapter
public class CustomAdapter extends BaseAdapter {
ArrayList<HashMap<String, String>> list;
Context ctx;
public CustomAdapter(Context c , ArrayList<HashMap<String, String>> articleList){
this.ctx = c;
this.list = articleList;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View view = convertView;
if (view == null) {
view = getLayoutInflater().inflate(R.layout.list_item,
parent, false);
holder = new ViewHolder();
assert view != null;
holder.imageView = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
UrlImageViewHelper.setUrlDrawable(thumb, articleList.get(position).get(TAG_IMAGE));
return view;
}
class ViewHolder {
ImageView imageView;
}
}
I am using this method in the getView method of my ListView adapter which returns a drawable which I later set it to my ImageView.
public Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return default_image;
}
}
Hope this helps.
Try this A powerful image downloading and caching library for Android Picasso
Images add much-needed context and visual flair to Android applications. Picasso allows for hassle-free image loading in your application-often in one line of code!
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
I already getting the string value from JSON but it seems to have the problem in Hash map or something, im getting null value on my List adapter. Can anyone help me or tell me if i did something wrong in my code. Thanks in advance.
Here is my code.
The Activity -
public class TestJSON extends Activity{
public static ListView lv;
public static ProgressDialog pDialog;
public static LazyAdapter adapter;
static final String KEY_ITEMS = "items";
static final String KEY_TITLE = "title";
static final String KEY_ID = "id";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test_json_view);
new AsyncInitial().execute();
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
lv = (ListView)findViewById(R.id.list);
//lv.setAdapter(new ArrayAdapter(getApplicationContext(), android.R.layout.simple_expandable_list_item_1, items));
}
private class AsyncInitial extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
ArrayList<HashMap<String, String>> menuItems;
#Override
protected void onPreExecute() {
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {
menuItems = new ArrayList<HashMap<String, String>>();
try {
//if (vid_num <= 0) {
// Get a httpclient to talk to the internet
HttpClient client = new DefaultHttpClient();
// Perform a GET request to YouTube for a JSON list of all the videos by a specific user
//https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc
HttpUriRequest request = new HttpGet("http://gdata.youtube.com/feeds/api/playlists/SP86E04995E07F6BA8?v=2&start-index=1&max-results=50&alt=jsonc");
// Get the response that YouTube sends back
HttpResponse response = client.execute(request);
// Convert this response into a readable string
String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
// Create a JSON object that we can use from the String
JSONObject json = new JSONObject(jsonString);
// For further information about the syntax of this request and JSON-C
// see the documentation on YouTube http://code.google.com/apis/youtube/2.0/developers_guide_jsonc.html
// Get are search result items
JSONArray jsonArray = json.getJSONObject("data").getJSONArray(KEY_ITEMS);
// Get the total number of video
//String vid_num = json.getJSONObject("data").getString("totalItems");
//System.out.println("vid_num-------->"+ vid_num);
// Loop round our JSON list of videos creating Video objects to use within our app
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonObject = jsonArray.getJSONObject(i);
// The title of the video
String title = jsonObject.getJSONObject("video").getString(KEY_TITLE);
System.out.println("Title-------->"+ title);
// A url to the thumbnail image of the video
// We will use this later to get an image using a Custom ImageView
//String TAG_thumbUrl = jsonObject.getJSONObject("video").getJSONObject("thumbnail").getString("sqDefault");
//System.out.println("thumbUrl-------->"+ thumbUrl);
String id = jsonObject.getJSONObject("video").getString(KEY_ID);
System.out.println("video_id-------->"+ id);
map.put(title, KEY_TITLE);
map.put(id, KEY_ID);
menuItems.add(map);
}
} catch (ClientProtocolException e) {
//Log.e("Feck", e);
} catch (IOException e) {
//Log.e("Feck", e);
} catch (JSONException e) {
//Log.e("Feck", e);
}
return menuItems;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
adapter = new LazyAdapter(TestJSON.this,menuItems);
lv.setAdapter(adapter);
pDialog.dismiss();
}
}
}
And The adapter
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater;
private ArrayList<HashMap<String, String>> data;
public LazyAdapter(TestJSON testJSON, ArrayList<HashMap<String, String>> menuItems) {
activity = testJSON;
data = menuItems;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(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)vi = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView)vi.findViewById(R.id.title);
TextView id = (TextView)vi.findViewById(R.id.artist);
HashMap<String, String> item = new HashMap<String, String>();
item = data.get(position);
title.setText(item.get(TestJSON.KEY_TITLE));
id.setText(item.get(TestJSON.KEY_ID));
return vi;
}
}
When I am clicking on my list items only the 1st item's id is going to the next activity. As I am getting patient name and id in this list fragment and passing the patient id to another activity, only the 1st list item's id is passing through even if I tap on another item... Hope you got my point...
Here is my ListFragment,
public class AllPatient extends ListFragment {
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList = new ArrayList<HashMap<String,String>>();
// url to get all products list
private static String url_all_patients = "http://192.168.44.208/get_all_patients.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PATIENT_ID = "patient_id";
private static final String TAG_PATIENT_NAME = "patient_name";
JSONArray products = null;
Context ctx;
String pid;
EditText inputSearch = null;
ListAdapter adapter;
ListView lv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.patient_list, container, false);
//ListView lv;
lv = (ListView)view.findViewById(android.R.id.list);
//ListView v = getListView();
new LoadAllPatients().execute();
return view;
}
#Override
public void onListItemClick(ListView lv, View v, int position, long id) {
// TODO Auto-generated method stub
onAttach(getActivity());
//lv.setAdapter(adapter);
String id1 = ((TextView) getView().findViewById(R.id.pid)).getText().toString();
System.out.println("all patient"+id1);
Bundle bundle = new Bundle();
bundle.putString("TAG_PATIENT_ID",id1 );
System.out.println("bundle"+id1);
Intent i = new Intent(getActivity(),DocPresc.class);
i.putExtras(bundle);
startActivity(i);
//passData(date);
Toast.makeText(
getActivity(),
getListView().getItemAtPosition(position).toString(),
Toast.LENGTH_LONG).show();
}
class LoadAllPatients extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_patients, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Patients: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PATIENT_ID).toUpperCase();
String name = c.getString(TAG_PATIENT_NAME).toUpperCase();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PATIENT_ID, id);
map.put(TAG_PATIENT_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
// pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
getActivity(), productsList,
R.layout.list_item1, new String[] { TAG_PATIENT_ID,
TAG_PATIENT_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
//setListAdapter(adapter);
setListAdapter(adapter);
}
});
}
}
}
Try this.
Change this line:
String id1 = ((TextView) getView().findViewById(R.id.pid)).getText().toString();
to
String id1 = ((TextView) v.findViewById(R.id.pid)).getText().toString();