I want to retrieve all the images and populate GridView from PHP MySql Database. I'm using JSON parsing.But in my grid view is nothing display images from PHP and also nothing any error.So then why not show the images in Gridview in my application.What is wrong with the code. Thanks to appreciate.
Here is my Adapter code.
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class GridViewAdapter extends BaseAdapter
{
private Context context;
public ArrayList<HashMap<String, String>> mThumbIds;
public GridViewAdapter (Context context,ArrayList<HashMap<String, String>> data )
{
this.context= context;
mThumbIds= data;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position ;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imageView = new ImageView(context);
imageView.setImageResource(mThumbIds.get(position).get("image"));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
Here is Activity code.
package com.photo_app;
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.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.GridView;
public class Photo_Gallery extends Activity
{
JSONObject jsonobject;
JSONArray jsonarray;
GridView gridview;
GridViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
JSONParser jsonParser = new JSONParser();
ProgressDialog pDialog;
private String URL_PHOTO_GALLERY = "http://192.168.1.102/timesofindia/admin/photo_gallery.php";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_gallery);
new DownloadJSON().execute();
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(Photo_Gallery.this);
mProgressDialog.setTitle("Wait");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
arraylist = new ArrayList<HashMap<String, String>>();
jsonobject = JSONfunctions.getJSONfromURL(URL_PHOTO_GALLERY);
System.out.println("Json String = " + jsonobject.toString());
try
{
jsonarray = jsonobject.getJSONArray("photo_gallary");
for (int i = 0; i < jsonarray.length(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
map.put("flag", jsonobject.getString("image"));
arraylist.add(map);
Log.e("arraylist","=");
}
}
catch (JSONException e)
{
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
gridview = (GridView) findViewById(R.id.photoGallery);
adapter = new GridViewAdapter();
gridview.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
}
You need to pass the data to the adapter. So, create a constructor which accepts the data and use it as you want in getView..
Pass the required data from the Activity to Adapter(it can be of any type. I have just given example to pass Integer[])
public GridViewAdapter (Context context,ArrayList<HashMap<String, Integer>> data )
{
this.context= context;
mThumbIds= data;
}
and pass it in you activity as :
GridViewAdapter adapter = new GridViewAdapter(this,your_data_array);
Update :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imageView = new ImageView(context);
imageView.setImageResource(mThumbIds.get(position).get("key")); // assuming key contains the resource id
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
Try with below code:
package com.photo_app;
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.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.GridView;
public class Photo_Gallery extends Activity
{
JSONObject jsonobject;
JSONArray jsonarray;
GridView gridview;
GridViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
JSONParser jsonParser = new JSONParser();
ProgressDialog pDialog;
private String URL_PHOTO_GALLERY = "http://192.168.1.102/timesofindia/admin/photo_gallery.php";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_gallery);
new DownloadJSON().execute();
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(Photo_Gallery.this);
mProgressDialog.setTitle("Wait");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
arraylist = new ArrayList<HashMap<String, String>>();
jsonobject = JSONfunctions.getJSONfromURL(URL_PHOTO_GALLERY);
System.out.println("Json String = " + jsonobject.toString());
try
{
jsonarray = jsonobject.getJSONArray("photo_gallary");
for (int i = 0; i < jsonarray.length(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
map.put("flag", jsonobject.getString("image"));
arraylist.add(map);
Log.e("arraylist","=" + arraylist.add(map) );
}
}
catch (JSONException e)
{
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
gridview = (GridView) findViewById(R.id.photoGallery);
adapter = new GridViewAdapter(Photo_Gallery.this,arraylist);
gridview.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
}
//Adapter Code:
package com.photo_app;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.androidquery.AQuery;
public class GridViewAdapter extends BaseAdapter
{
private Context context;
public ArrayList<HashMap<String,String>> mThumbIds=new ArrayList<HashMap<String, String>>();
AQuery aQuery;
private LayoutInflater mInflater;
public GridViewAdapter (Context context,ArrayList<HashMap<String,String>> data )
{
this.context= context;
mThumbIds= data;
aQuery=new AQuery(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mThumbIds.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.photo_gallery_list_item, null);
holder = new ViewHolder();
holder.imageView = (ImageView) convertView.findViewById(R.id.imageView);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
aQuery.id(holder.imageView).image(mThumbIds.get(position).get("flag"),true,true);
return convertView;
}
class ViewHolder {
ImageView imageView;
}
}
//photo_gallery_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp" >
<ImageView
android:id="#+id/imageView"
android:layout_width="70dp"
android:layout_height="70dp"
android:scaleType="centerCrop"
android:src="#drawable/ic_launcher"
android:adjustViewBounds="true"/>
</LinearLayout>
Related
I am trying to parse the images and text from url to list view.
I succesfully parse names but unable to parse Images. I follow these links....
I am getting bit map value null in image loader class..
I copied the MemoryCache and File Cache classes from the below links... Is there any mistake in my code?
My Json is: http://192.185.159.159/~charmmar/raj_spice/webservices/index.php?action=products
Is any problem for image parsing if json is large?
http://www.androidbegin.com/tutorial/android-json-parse-images-and-texts-tutorial/
http://luchfilip.wordpress.com/2014/02/25/android-how-to-parse-json-and-show-images-and-texts-in-a-listview/comment-page-1/
http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/
in these links all contained ImageLoader, FileCache, MemoryCache classes but I am unable to parse images... is any special library needed for this?
My class:
package com.example.dellizia;
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.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ListView;
public class RecipesJson extends Helper {
private String url = com.example.dellizia.Utility.urlpath + "products";
ArrayList<HashMap<String, String>> productList;
ProgressDialog pdialog;
final String TAG_DATA = "data";
final String TAG_ID = "id";
final static String TAG_NAME = "name";
final static String TAG_IMAGE = "images";
ListView listview;
RecipeJsonAdapter adapter;
SharedPreferences preferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
PrefEdit("pref__footer", "img_recipe");
footerBlock();
new DownloadJSON().execute();
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
pdialog = new ProgressDialog(RecipesJson.this);
// Set progressdialog title
// pdialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
pdialog.setMessage("Loading...");
pdialog.setIndeterminate(false);
// Show progressdialog
pdialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
productList = new ArrayList<HashMap<String, String>>();
try {
String res = JsonFunction.getJSONfromURL(url);
Log.e("","resvalue--------"+res);
JSONObject jsonobj = new JSONObject(res);
String id = jsonobj.getString("status");
Log.e("","id value in parse json--------"+id);
if (id.equals("1")) {
JSONArray userdata = jsonobj.getJSONArray("data");
for (int i = 0; i < userdata.length(); i++) {
HashMap<String, String> pdata = new HashMap<String, String>();
JSONObject obj = userdata.getJSONObject(i);
String catid = userdata.getJSONObject(i).getString("id");
String name = userdata.getJSONObject(i).getString("name");
String image = userdata.getJSONObject(i).getString("images");
pdata.put(TAG_ID, catid);
Log.e("", "TAG_ID---" + TAG_ID);
pdata.put(TAG_NAME, name);
Log.e("", "TAG_NAME---" + TAG_NAME);
Log.e("", "name---" + name);
pdata.put(TAG_IMAGE, image);
Log.e("", "TAG_IMAGE---" + TAG_IMAGE);
Log.e("", "image-----------" + image);
productList.add(pdata);
Log.e("", "product list----" + productList);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.recipeslist);
// Pass the results into ListViewAdapter.java
adapter = new RecipeJsonAdapter(RecipesJson.this, productList);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
pdialog.dismiss();
}
}
}
My adapter class:
package com.example.dellizia;
import java.util.ArrayList;
import java.util.HashMap;
import com.example.androidhive.ImageLoader;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
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 RecipeJsonAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public RecipeJsonAdapter(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.recipeitems, 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 thumb_image=(ImageView)vi.findViewById(R.id.recipeimage); // thumb image
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
// Setting all values in listview
Log.e("","names values ------------"+song.get(RecipesJson.TAG_NAME));
title.setText(song.get(RecipesJson.TAG_NAME));
//artist.setText(song.get(CustomizedListView.KEY_ARTIST));
// duration.setText(song.get(CustomizedListView.KEY_DURATION));
Log.e("","images values ------------"+song.get(RecipesJson.TAG_IMAGE));
imageLoader.DisplayImage(song.get(RecipesJson.TAG_IMAGE), thumb_image);
return vi;
}
}
This is my link for all classes.. http://ge.tt/8keNUh62?c. In this link all my used classes are available.
Please help!
Hello I'm working on an app which has an edittext to search for items on the listview. If the user types a letter in the edittext the listview is getting filtered perfectlty.Have used Adapter also.Now i have following issues:
1)when i m clearing letters edittext my listview is not getting Updated..
2) if i enter wrong letter or letter which does not corrorsponds to any item of a listview the listview is getting clear.
Have gone thorugh exmaples in SO
Android filter listview custom adapter
And googled also for same problem but not getting solved it..Plz anybody help me..
Here is my code:
package com.AAAAA.AAAAA;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.AdapterView.OnItemClickListener;
import com.AAAAA.adapter.UpdateSingleItemViewActivity;
import com.AAAAA.adapter.UpdatesAdapterList;
import com.AAAAA.local.database.DBController;
import com.AAAAA.AAAAA.AAAAA.constant.Constant;
import com.AAAAA.AAAAA.AAAAA.utils.Utility;
public class Cardiology_updates extends Activity implements OnClickListener,
OnRefreshListener {
EditText et ;
private Context appContext;
// ProgressDialog mProgressDialog;
private Dialog dialog;
private boolean isFinish = false;
String result = "";
JSONObject jsonobject;
JSONArray jsonArray;
ArrayList<HashMap<String, String>> UpdatesHmList;
public static ArrayList<HashMap<String, String>> FinalLocalDataList;
ArrayList<HashMap<String, String>> LocalDataList;
DBController controller = new DBController(this);
HashMap<String, String> queryValues;
ListView list;
UpdatesAdapterList adapter;
public static String UpdateID = "UpdateID";
public static String UpdateTitle = "Title";
/*
* public static String UpdateDescription = "Description"; public static
* String POPULATION = "UpdateDate"; public static String UpdateImage =
* "Photo";
*/
public static String UpdateDescription = "Description";
public static String POPULATION = "Title";
public static String UpdateImage = "Complete_imagePath";
public static String Complete_imagePath;
public static String Title;
public static String Description;
SwipeRefreshLayout swipeLayout;
private ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cardiology_updates);
// controller.deleteAllJsonData();
appContext = this;
animationView();
initComponent();
}
private void animationView() {
// TODO Auto-generated method stub
progressbar = (ProgressBar) findViewById(R.id.loading);
}
private void initComponent() {
// TODO Auto-generated method stub
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
dialog = new Dialog(appContext);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.alert_dialog);
((Button) findViewById(R.id.Button01)).setOnClickListener(this);
((Button) dialog.findViewById(R.id.btnOk)).setOnClickListener(this);
new GetUpdatesInfo().execute();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.Button01) {
finish();
// finishActivity() ;
} else if (v.getId() == R.id.btnOk) {
dialog.dismiss();
if (isFinish) {
this.finish();
}
}
}
public class GetUpdatesInfo extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
super.onPreExecute();
if (progressbar.getVisibility() != View.VISIBLE) {
progressbar.setVisibility(View.VISIBLE);
}
}
#Override
protected String doInBackground(String... params) {
// Create an array
UpdatesHmList = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
String url = null;
url = Constant.serverUrl + "/GetUpdateList";
result = Utility.postParamsAndfindJSON(url);
Log.e("result doInBackground", "" + result);
if (!(result == null)) {
try {
controller.deleteAllJsonData();
// Locate the array name in JSON
jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonArray.getJSONObject(i);
// Retrive JSON Objects
map.put("UpdateID", jsonobject.getString("UpdateID"));
map.put("Title", jsonobject.getString("Title"));
String Upadates_Photo = jsonobject.optString("Photo")
.toString();
String Complete_imagePath = Constant.prifixserverUrl
+ Upadates_Photo;
String Title = jsonobject.getString("Title").toString();
String Description = jsonobject
.getString("Description").toString();
String noHtml = Description.replaceAll("<[^>]*>", "");
String parseResponse = noHtml.replaceAll(" ", "");
map.put("Photo", Complete_imagePath);
map.put("Description", Description);
map.put("UpdateDate",
jsonobject.getString("UpdateDate"));
Log.e("UpdateID ",
" "
+ jsonobject.getString("UpdateID")
.toString());
Log.e("Title ", " "
+ jsonobject.getString("Title").toString());
Log.e("Complete_imagePath ",
" " + Complete_imagePath.toString());
Log.e("Description ", " " + parseResponse);
Log.e("UpdateDate ",
" "
+ jsonobject.getString("UpdateDate")
.toString());
queryValues = new HashMap<String, String>();
queryValues.put("Complete_imagePath",
Complete_imagePath);
queryValues.put("Title", Title);
queryValues.put("Description", Description);
controller.insertAllJsonData(queryValues);
// Set the JSON Objects into the array
UpdatesHmList.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
// Locate the listview in listview_main.xml
if (progressbar.getVisibility() == View.VISIBLE) {
progressbar.setVisibility(View.GONE);
}
/*
* if (result == null) { //mProgressDialog.dismiss();
* localalldata();
*
* }
*/
localalldata();
/*
* list = (ListView) findViewById(R.id.list_Upadates); // Pass the
* results into ListViewAdapter.java adapter = new
* UpdatesAdapterList(Cardiology_updates.this, FinalLocalDataList);
* // Set the adapter to the ListView list.setAdapter(adapter);
*/
// Close the progressdialog
// mProgressDialog.dismiss();
}
}
#Override
public void onRefresh() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getSomeData();
// localalldata();
swipeLayout.setRefreshing(false);
}
}, 5000);
}
protected void getSomeData() {
// TODO Auto-generated method stub
// localalldata();
new GetUpdatesInfo().execute();
adapter.notifyDataSetChanged();
/*
* if (LocalDataList == null) { Log.e("LocalDataList inside if ",
* "LocalDataList inside if "); new GetUpdatesInfo().execute();
*
* } else { // adapter.imageLoader.clearCache();
* Log.e("LocalDataList else ", "LocalDataList else ");
*
* adapter.notifyDataSetChanged(); }
*/
}
private void localalldata() {
// TODO Auto-generated method stub
LocalDataList = controller.getAllJsonData();
FinalLocalDataList = new ArrayList<HashMap<String, String>>();
for (HashMap<String, String> hashMap : LocalDataList) {
System.out.println(hashMap.keySet());
HashMap<String, String> map = new HashMap<String, String>();
for (String key : hashMap.keySet()) {
System.out.println(hashMap.get(key));
Complete_imagePath = hashMap.get("Complete_imagePath");
Title = hashMap.get("Title");
Description = hashMap.get("Description");
map.put("Complete_imagePath", Complete_imagePath);
map.put("Title", Title);
map.put("Description", Description);
Log.v("All Json CodiateUpdate Title", "" + Complete_imagePath);
Log.v("All Json CodiateUpdate Title", "" + Title);
}
FinalLocalDataList.add(map);
}
list = (ListView) findViewById(R.id.list_Upadates);
// Pass the results into ListViewAdapter.java
adapter = new UpdatesAdapterList(Cardiology_updates.this,
FinalLocalDataList);
// Set the adapter to the ListView
list.setTextFilterEnabled(true);
list.setAdapter(adapter);
// adapter.notifyDataSetChanged();
et = (EditText) findViewById(R.id.search);
// Capture Text in EditText
et.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
adapter.filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
//String text = et.getText().toString().toLowerCase(Locale.getDefault());
//adapter.getFilter().filter(arg0);
}
});
}
}
Here is my Adapter:
package com.AAAA.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import com.AAAA.AAAA.Cardiology_updates;
import com.AAAA.AAAA.R;
import com.AAAA.imageloader.ImageLoader;
public class UpdatesAdapterList extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
public ImageLoader imageLoader;
private Activity activity;
//HashMap<String, String> resultp = new HashMap<String, String>();
private ArrayList<HashMap<String,String>> filterData;
public UpdatesAdapterList(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context.getApplicationContext());
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.data);
}
#Override
public int getCount() {
return filterData.size();
}
#Override
public Object getItem(int position) {
return filterData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.listview_updateitem, null);
holder.UpdateTitle = (TextView) convertView.findViewById(R.id.txtUpdatetitle);
holder.UpdateImage = (ImageView) convertView.findViewById(R.id.list_UpdateImage);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.UpdateTitle.setText(filterData.get(position).get(Cardiology_updates.UpdateTitle));
imageLoader.DisplayImage(filterData.get(position).get(Cardiology_updates.UpdateImage), holder.UpdateImage);
// Capture ListView item click
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
//resultp = data.get(position);
Intent intent = new Intent(context, UpdateSingleItemViewActivity.class);
// Pass all data rank
intent.putExtra("UpdateTile", filterData.get(position).get(Cardiology_updates.UpdateTitle));
// Pass all data country
intent.putExtra("UpdateDescription", filterData.get(position).get(Cardiology_updates.UpdateDescription));
// Pass all data population
intent.putExtra("population",filterData.get(position).get(Cardiology_updates.POPULATION));
// Pass all data flag
intent.putExtra("UpdateImage", filterData.get(position).get(Cardiology_updates.UpdateImage));
// Start SingleItemView Class
intent.putExtra("position", position);
context.startActivity(intent);
}
}); return convertView;
}
class ViewHolder{
TextView UpdateTitle;
ImageView UpdateImage;
}
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(data);
}else{
for (HashMap<String,String> row: data) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
}
Activity opens on cliking listview items:
package com.AAAAA.adapter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import com.AAAAA.AAAAA.Cardiology_updates;
import com.AAAAA.AAAAA.R;
public class UpdateSingleItemViewActivity extends Activity {
int position;
String UpdateTile;
String UpdateDescription;
String population;
String UpdateImage;
//String position;
ViewPager viewPager;
PagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_update_single_item_view);
Log.e("UpdateSingleItemViewActivity class",
"UpdateSingleItemViewActivity class");
/*
* WebView webview = new WebView(this); setContentView(webview);
*/
Button btnback = (Button) findViewById(R.id.Button01);
btnback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
//WebView webview = (WebView) findViewById(R.id.webview);
Intent i = getIntent();
// Get the result of rank
UpdateTile = i.getStringExtra("UpdateTile");
// Get the result of country
UpdateDescription = i.getStringExtra("UpdateDescription");
// Get the result of population
population = i.getStringExtra("population");
// Get the result of flag
UpdateImage = i.getStringExtra("UpdateImage");
//i.putExtra("POSITION_KEY", position);
position = i.getExtras().getInt("position");
//webview.loadData(UpdateDescription, "text/html", null);
viewPager = (ViewPager) findViewById(R.id.viewpager_layout);
// Pass results to ViewPagerAdapter Class
adapter = new ViewPagerAdapter(UpdateSingleItemViewActivity.this, Cardiology_updates.FinalLocalDataList);
// Binds the Adapter to the ViewPager
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);
}
}
its Corrosponding adapter:
package com.AAAAA.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import com.AAAAA.AAAAA.Cardiology_updates;
import com.AAAAA.AAAAA.R;
import com.AAAAA.imageloader.ImageLoader;
import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.LinearLayout;
public class ViewPagerAdapter extends PagerAdapter {
String UpdateTile;
String UpdateDescription;
//String population;
String UpdateImage;
String position;
LayoutInflater inflater;
Context context;
ArrayList<HashMap<String, String>> data;
public ImageLoader imageLoader;
private Activity activity;
//HashMap<String, String> resultp = new HashMap<String, String>();
ArrayList<HashMap<String,String>> filterData;
public ViewPagerAdapter(Context context, ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.data);
}
#Override
public int getCount() {
return filterData.size();
}
public Object getItem(int position) {
return filterData.get(position);
}
public long getItemId(int position) {
return position;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
WebView webview;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item, container,
false);
//resultp =data.get(position);
webview=(WebView)itemView.findViewById(R.id.webview1);
//webview.setText(webview[position]);
webview.loadData(filterData.get(position).get(Cardiology_updates.UpdateDescription), "text/html", null);
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((LinearLayout) object);
}
}
When used custom adapter always try to implement ViewHolder design pattern for ListView performance and use custom filter function instead Filterable implementation :
Custom filter funcation required two array list one is filterable data list and another one is for orignal data list :
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(orignalData);
}else{
for (HashMap<String,String> row: orignalData) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
Example :
et.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
adapter.filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) {
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {
}
});
public class UpdatesAdapterList extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String,String>> filterData;
private ArrayList<HashMap<String,String>> orignalData;
public ImageLoader imageLoader;
public UpdatesAdapterList(Context context,ArrayList<HashMap<String, String>> orignalData) {
this.context = context;
this.orignalData = orignalData;
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.orignalData);
imageLoader = new ImageLoader(this.context);
}
#Override
public int getCount() {
return filterData.size();
}
#Override
public Object getItem(int position) {
return filterData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.listview_updateitem, null);
holder.UpdateTitle = (TextView) convertView.findViewById(R.id.txtUpdatetitle);
holder.UpdateImage = (ImageView) convertView.findViewById(R.id.list_UpdateImage);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.UpdateTitle.setText(filterData.get(position).get(Cardiology_updates.UpdateTitle));
imageLoader.DisplayImage(filterData.get(position).get(Cardiology_updates.UpdateImage), holder.UpdateImage);
// Capture ListView item click
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, UpdateSingleItemViewActivity.class);
// Pass all data rank
intent.putExtra("UpdateTile", filterData.get(position).get(Cardiology_updates.UpdateTitle));
// Pass all data country
intent.putExtra("UpdateDescription", filterData.get(position).get(Cardiology_updates.UpdateDescription));
// Pass all data population
intent.putExtra("population",filterData.get(position).get(Cardiology_updates.POPULATION));
// Pass all data flag
intent.putExtra("UpdateImage", filterData.get(position).get(Cardiology_updates.UpdateImage));
// Start SingleItemView Class
intent.putExtra("position", position);
context.startActivity(intent);
}
});
return convertView;
}
class ViewHolder{
TextView UpdateTitle;
ImageView UpdateImage;
}
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(orignalData);
}else{
for (HashMap<String,String> row: orignalData) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
}
I am new android now I want to display image from an url. I am using imageview in listview. I want to add the list of images into the each row of the list item. I used SimpleAdapter but the imageview shows blank.
Here's the main activity:
package com.example.mysqltest;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ReadComments extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// testing on Emulator:
private static final String READ_COMMENTS_URL = "http://192.168.30.198/test/webservice/comments.php";
// JSON IDS:
private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
private static final String TAG_POST_ID = "post_id";
private static final String TAG_USERNAME = "username";
private static final String TAG_MESSAGE = "message";
private static final String TAG_IMAGE = "image";
// An array of all of our comments
private JSONArray mComments = null;
// manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mCommentList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// note that use read_comments.xml instead of our single_post.xml
setContentView(R.layout.read_comments);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// loading the comments via AsyncTask
new LoadComments().execute();
}
public void addComment(View v) {
Intent i = new Intent(ReadComments.this, AddComment.class);
startActivity(i);
}
/**
* Retrieves recent post data from the server.
*/
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
try {
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
// gets the content of each tag
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
String image = c.getString(TAG_IMAGE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
map.put(TAG_IMAGE, image);
// adding HashList to ArrayList
mCommentList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_post, new String[] { TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME,TAG_IMAGE }, new int[] { R.id.title, R.id.message,
R.id.username, R.id.imageView1 });
// I shouldn't have to comment on this one:
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ReadComments.this);
pDialog.setMessage("Loading Comments...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
Okay. So I assume here that you insist on using SimpleAdapter. No probem, problem solved, just follow the steps:
First lets create our custom row.xml for our ListView which will consist of only one ImageView.(You can add whatever you like to it later on but now i'll assume that you only wanna load the ImageView)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:src="#drawable/ic_launcher" />
</RelativeLayout>
Second lets create our custom SimpleAdapter
package com.example.helpstack;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
public class MySimpleAdapter extends SimpleAdapter {
private Context mContext;
public LayoutInflater inflater = null;
public MySimpleAdapter(Context context,
List<? extends Map<String, ?>> data, int resource, String[] from,
int[] to) {
super(context, data, resource, from, to);
mContext = context;
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.row, null);
HashMap<String, Object> data = (HashMap<String, Object>) getItem(position);
new DownloadTask((ImageView) vi.findViewById(R.id.imageView1))
.execute((String) data.get("uri"));
return vi;
}
}
Third lets create our DownloadTask, this class will download the image:
package com.example.helpstack;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
public class DownloadTask extends AsyncTask<String, Void, Boolean> {
ImageView v;
String url;
Bitmap bm;
public DownloadTask(ImageView v) {
this.v = v;
}
#Override
protected Boolean doInBackground(String... params) {
url = params[0];
bm = loadBitmap(url);
return true;
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
v.setImageBitmap(bm);
}
public static Bitmap loadBitmap(String url) {
try {
URL newurl = new URL(url);
Bitmap b = BitmapFactory.decodeStream(newurl.openConnection()
.getInputStream());
return b;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Now the DownloadTask is being used from inside the getView() in SimpleAdapter
Fourth lets run our amazing small project from our MainActivity.java
package com.example.helpstack;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class MainActivity extends Activity {
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();
map.put("uri",
"http://upload.wikimedia.org/wikipedia/commons/thumb/f/f9/Wiktionary_small.svg/350px-Wiktionary_small.svg.png");
//here u can add as many uri as u want
data.add(map);
MySimpleAdapter adapter = new MySimpleAdapter(MainActivity.this, data,
R.layout.row, new String[] {}, new int[] {});
lv.setAdapter(adapter);
}
}
You can use any image cache library. Example, Picasa, Universal Image Loader..
You can cache the images from the URL and then you can use the images in your app.
You can find the libraries in the following links
http://square.github.io/picasso/ and https://github.com/nostra13/Android-Universal-Image-Loader
You can use multiple thread to download and decode bitmap .please follow this website and try to learn how android Developer use thread pool executer to execute different image in thread.
http://developer.android.com/training/multiple-threads/create-threadpool.html
1) To set the image Uri to the ImageView you can use a ViewBinder
You have to implement the abstract class and override setViewValue
2) You can use Picasso to load the images in a background thread and cache them.
The setViewValue method would look like this:
boolean setViewValue (View view, Object data, String textRepresentation) {
if(view.getId() == R.id.imageView1) {
Picasso.with(view.getContext()).load(textRepresentation).into((ImageView) view);
return true;
}
return false;
}
You return true if you want to take care of the binding. You return false for the default behavior.
3) Set your adapter to use the ViewBinder by calling adapter.setViewBinder(ViewBinder);
for now, my suggestion for you is:
1. download the image from url
2. save it as drawable in the storage
3. set this drawable to the image src of imageview
(I didn't see you do this part of job from your code...)
This tutorial is the best example to parse image using json parsing and show it in a listview: http://www.androidbegin.com/tutorial/android-json-parse-images-and-texts-tutorial/
Some other:
http://imagelistviewdynamic.blogspot.in/2012/12/image-parsed-from-json-using-async-into.html
http://www.java2s.com/Open-Source/Android_Free_Code/JSON/Download_Free_code_Android_JSON_Parse_Images_and_Texts_Tutorial.htm
I suggest you use Universal Image Loader, it uses asynchronous image downloading, caching and displaying, there you can find examples how to implement it. After you do it you dont have to concern about the number of images, or its size.
If you download the project you will find this example that does all the work you want:
/**
* #author Sergey Tarasevich (nostra13[at]gmail[dot]com)
*/
public class ImageListActivity extends AbsListViewBaseActivity {
DisplayImageOptions options;
String[] imageUrls;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_list);
// here you get a String array with images URL
Bundle bundle = getIntent().getExtras();
imageUrls = bundle.getStringArray(Extra.IMAGES);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.cacheInMemory(true)
.cacheOnDisc(true)
.considerExifParams(true)
.displayer(new RoundedBitmapDisplayer(20))
.build();
listView = (ListView) findViewById(android.R.id.list);
((ListView) listView).setAdapter(new ItemAdapter());
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startImagePagerActivity(position);
}
});
}
#Override
public void onBackPressed() {
AnimateFirstDisplayListener.displayedImages.clear();
super.onBackPressed();
}
// it gets the position of listView and opens that image in a new Activity
private void startImagePagerActivity(int position) {
Intent intent = new Intent(this, ImagePagerActivity.class);
intent.putExtra(Extra.IMAGES, imageUrls);
intent.putExtra(Extra.IMAGE_POSITION, position);
startActivity(intent);
}
class ItemAdapter extends BaseAdapter {
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
private class ViewHolder {
public TextView text;
public ImageView image;
}
#Override
public int getCount() {
return imageUrls.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = getLayoutInflater().inflate(R.layout.item_list_image, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.text);
holder.image = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.text.setText("Item " + (position + 1));
// here is the place where is loaded the image using Universal ImageLoader , imageUrls[position] is a list of images URL
imageLoader.displayImage(imageUrls[position], holder.image, options, animateFirstListener);
return view;
}
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
We are working on a project where data is coming from webservice.I am dispalying that data in listview.The data icludes images as image path.I have displayed all the iformation but i couldt display the image.How to display the images from webservices.
my code is:
package com.example.doctreachapp;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.doctreachapp.JSONParser;
import com.example.doctreachapp.R;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class GeneralHospitals extends ListActivity {
private Context context;
private static String url = "my Url";
// private static final String ID = "ID";
String TAG_user_detail = "DentalHospitals";
private static final String Img = "Img";
private static final String Location = "Location";
private static final String URL = "URL";
private static final String Name = "Name";
private static final String Distance = "Distance";
String imagestack;
Bitmap image;
JSONArray user_detail_jsonarray = null;
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
lv = (ListView) findViewById(android.R.id.list);
new ProgressTask().execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPostExecute(final Boolean success) {
setListView();
// select single ListView item
// lv = getListView();
}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
// get JSON data from URL
// JSONObject jobject = new JSONObject(result);
JSONObject json = jParser.getJSONFromUrl(url);
Log.d("json", json.toString());
try {
user_detail_jsonarray = json.getJSONArray("DentalHospitals");
Log.d("jsonarray", user_detail_jsonarray.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for (int i = 0; i < user_detail_jsonarray.length(); i++) {
try {
JSONObject c = user_detail_jsonarray.getJSONObject(i);
String img = c.getString(Img);
String name = c.getString(Name);
String loc = c.getString(Location);
String url = c.getString(URL);
String dis = c.getString(Distance);
HashMap<String, String> map = new HashMap<String, String>();
// Add child node to HashMap key & value
map.put(Img, img);
map.put(Name, name);
map.put(Location, loc);
map.put(URL, url);
map.put(Distance, dis);
jsonlist.add(map);
// Log.d("list",jsonlist);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSONList", jsonlist.toString());
}
return true;
}
}
public class CustomListAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> listData;
private LayoutInflater layoutInflater;
public CustomListAdapter(Context context,
ArrayList<HashMap<String, String>> jsonlist) {
this.listData = jsonlist;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.Name = (TextView) convertView
.findViewById(R.id.name);
holder.Location = (TextView) convertView
.findViewById(R.id.loc);
holder.URL = (TextView) convertView
.findViewById(R.id.url);
holder.Distance = (TextView) convertView
.findViewById(R.id.dis);
holder.Img = (ImageView) convertView
.findViewById(R.id.image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//System.out.println(listData.get(position).get("Img"));
System.out.println(listData.get(position).get("Name"));
holder.Img.setImageURI(listData.get(position).get("Img"));
holder.Name.setText(listData.get(position).get("Name"));
holder.Location.setText(listData.get(position).get("Location"));
holder.URL.setText(listData.get(position).get("URL"));
holder.Distance.setText(listData.get(position).get("Distance"));
//WebView image = holder.Img;
//imagestack = listData.get(position).get("Img");
//image = BitmapFactory.decodeStream((listData.get(position).get("Img")).openStream());
Log.d("image",imagestack);
return convertView;
}
}
public static class ViewHolder {
ImageView Img;
TextView Location;
TextView Name;
TextView URL;
TextView Distance;
}
public void setListView() {
// TODO Auto-generated method stub
CustomListAdapter adapter = new CustomListAdapter(this, jsonlist);
Log.d("ABCD", "" + lv.getVisibility());
lv.setAdapter(adapter);
}
}
Please help me.
Write below code in your getView() where you have initialized holder.Img ImageView
new DownloadImageTask(holder.Img)
.execute(listData.get(position).get("Img"));
Below is the AsyncTask to download the image and to display it in the ImageView
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
If you have small number of items in the ListView then use the above code else it recommendable to use LazyList .
In my application I have search tab which display images with their name in grid view and now I want to implement search functionality. I have been searching in google for past two days but I didn't get any solution. Any idea or tutorial 0r how can I achieve this?
Anyone help me with this.
Thanks in advance.
mainactivity
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import com.example.diceapp.R;
public class SearchActivity extends Activity
{
JSONArray results;
JSONObject jobj;
SearchCustomAdapter adapter1;
ImageButton ib;
ArrayList<String> a1,a2,a3,a4;
ArrayList<String> name=new ArrayList<String>();
ArrayList<String> description=new ArrayList<String>();
ArrayList<String> image=new ArrayList<String>();
ArrayList<String> price=new ArrayList<String>();
Button add;
String pid;
GridView gView;
EditText src;
int textlength = 0;
ArrayList<String> p_name = new ArrayList<String>();
ArrayList<String> p_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.search_activity);
a1=new ArrayList<String>();
a2=new ArrayList<String>();
a3=new ArrayList<String>();
a4=new ArrayList<String>();
src=(EditText)findViewById(R.id.srcetxt);
/*src.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
SearchActivity.this.adapter1.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});*/
new Searchtask().execute();
gView = (GridView)findViewById(R.id.gridView1);
gView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
System.out.println("outside on click"+position);
}
});
ib=(ImageButton)findViewById(R.id.imageButton1);
}
private class Searchtask extends AsyncTask<String, String, JSONObject>
{
private ProgressDialog pDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(SearchActivity.this);
pDialog.setMessage("Loading Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args)
{
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl("http:link.php");
return json;
}
#Override
protected void onPostExecute(JSONObject json)
{
System.out.println("---------------return name list json------------"+json);
pDialog.dismiss();
try
{
jobj=json.getJSONObject("response");
// Getting Array of Contacts
results = jobj.getJSONArray("obejects");
System.out.println("In product Activity after JSON");
// looping through All Contacts
for(int i = 0; i < results.length(); i++)
{
JSONObject c = results.getJSONObject(i);
name.add(c.getString("name"));
image.add(c.getString("image"));
price.add(c.getString("price"));
description.add(c.getString("Description"));
}
}
catch (JSONException e)
{
e.printStackTrace();
}
adapter1 = new SearchCustomAdapter(getApplicationContext(), R.layout.gridlistimg, name, image,description,price);
gView.setAdapter(adapter1);
}
}
}
baseadapter class
package com.example.diceapp.search;
import java.util.ArrayList;
import android.content.Context;
import android.content.Intent;
import android.sax.StartElementListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import com.example.diceapp.AAAMainActivity;
import com.example.diceapp.R;
import com.example.diceapp.category.ImageLoader;
public class SearchCustomAdapter extends BaseAdapter
{
Context context;
LayoutInflater inflater;
ArrayList<String> aaaa1,bbbb1,cccc1;
ArrayList<String> c_pname;
ArrayList<String> c_pimage;
ArrayList<String> c_pprice;
ArrayList<String> c_pdescription;
String[] data_text;
String[] data_image;
ImageLoader iloader;
public SearchCustomAdapter(Context c, int productDescribe,ArrayList<String> pname, ArrayList<String> pimage,
ArrayList<String> productdescription, ArrayList<String> pprice)
{
// TODO Auto-generated constructor stub
this.context=c;
this.c_pname=pname;
this.c_pprice=pprice;
this.c_pdescription=productdescription;
this.c_pimage=pimage;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
iloader= new ImageLoader(context.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return c_pname.size();
//return data_text.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int pos) {
// TODO Auto-generated method stub
//return c_pname.indexOf(getItem(pos));//arg0;
return pos;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
View row=convertView;
ViewHolder vh;
if(row==null)
{
row=inflater.inflate(R.layout.custom_search_activity, parent, false);
vh=new ViewHolder();
vh.pname=(TextView)row.findViewById(R.id.product_name);
vh.pprice=(TextView)row.findViewById(R.id.textView2);
vh.image1=(ImageView) row.findViewById(R.id.imageView1);
vh.btn=(Button)row.findViewById(R.id.p_custom_tv);
/*row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
System.out.println("outside on click"+position);
ArrayList<String> sendingary=new ArrayList<String>();
sendingary.add(c_pname.get(position));
sendingary.add(c_pprice.get(position));
sendingary.add(c_pimage.get(position));
sendingary.add(c_pdescription.get(position));
Intent cp=new Intent(context.getApplicationContext(),product_details.class);
cp.putStringArrayListExtra("aryvalue", sendingary);
cp.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(cp);
}
});*/
row.setTag(vh);
}
else
{
vh = (ViewHolder) row.getTag();
row=convertView;
}
vh.pname.setText(c_pname.get(position));
vh.pprice.setText("KD "+c_pprice.get(position));
iloader.DisplayImage(c_pimage.get(position), vh.image1);
return row;
}
public static class ViewHolder
{
TextView pname,pprice;
ImageView image1;
Button btn;
}
public SearchCustomAdapter getFilter() {
// TODO Auto-generated method stub
return null;
}
}
If you use ArrayAdapter as your gridview's adapter, you can override getFilter() method and return your own Filter, which is able to filter items according to entered text. See e.g. this link to learn how to work with Filter. Good luck. :-)
Hi I just edit your code please replace and check it
SearchActivity.java
import java.util.ArrayList;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
public class SearchActivity extends Activity {
JSONArray results;
JSONObject jobj;
SearchCustomAdapter adapter1;
ImageButton ib;
ArrayList<String> a1, a2, a3, a4;
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> description = new ArrayList<String>();
ArrayList<String> image = new ArrayList<String>();
ArrayList<String> price = new ArrayList<String>();
Button add;
String pid;
GridView gView;
EditText src;
int textlength = 0;
ArrayList<String> p_name = new ArrayList<String>();
ArrayList<String> p_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.search_activity);
a1 = new ArrayList<String>();
a2 = new ArrayList<String>();
a3 = new ArrayList<String>();
a4 = new ArrayList<String>();
src = (EditText) findViewById(R.id.srcetxt);
src.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
if (src.getText().toString().trim().length() > 0) {
applySearch(src.getText().toString().trim());
} else {
adapter1.setC_pname(name);
adapter1.setC_pdescription(description);
adapter1.setC_pimage(image);
adapter1.setC_pprice(price);
adapter1.notifyDataSetChanged();
}
}
});
new Searchtask().execute();
gView = (GridView) findViewById(R.id.gridView1);
gView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
System.out.println("outside on click" + position);
}
});
ib = (ImageButton) findViewById(R.id.imageButton1);
}
private class Searchtask extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchActivity.this);
pDialog.setMessage("Loading Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl("http:link.php");
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
System.out.println("---------------return name list json------------" + json);
pDialog.dismiss();
try {
jobj = json.getJSONObject("response");
// Getting Array of Contacts
results = jobj.getJSONArray("obejects");
System.out.println("In product Activity after JSON");
// looping through All Contacts
for (int i = 0; i < results.length(); i++) {
JSONObject c = results.getJSONObject(i);
name.add(c.getString("name"));
image.add(c.getString("image"));
price.add(c.getString("price"));
description.add(c.getString("Description"));
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter1 = new SearchCustomAdapter(getApplicationContext(), R.layout.gridlistimg, name, image, description, price);
gView.setAdapter(adapter1);
}
}
private void applySearch(String searchStr) {
ArrayList<String> searchname = new ArrayList<String>();
ArrayList<String> searchdescription = new ArrayList<String>();
ArrayList<String> searchimage = new ArrayList<String>();
ArrayList<String> searchprice = new ArrayList<String>();
for (int i = 0; i < name.size(); i++) {
if (name.get(i).contains(searchStr)) {
searchname.add(name.get(i));
searchdescription.add(description.get(i));
searchimage.add(image.get(i));
searchprice.add(price.get(i));
}
}
adapter1.setC_pname(searchname);
adapter1.setC_pdescription(searchdescription);
adapter1.setC_pimage(searchimage);
adapter1.setC_pprice(searchprice);
adapter1.notifyDataSetChanged();
}
}
SearchCustomAdapter.java
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class SearchCustomAdapter extends BaseAdapter {
Context context;
LayoutInflater inflater;
ArrayList<String> aaaa1, bbbb1, cccc1;
ArrayList<String> c_pname;
ArrayList<String> c_pprice;
ArrayList<String> c_pdescription;
ArrayList<String> c_pimage;
public void setC_pname(ArrayList<String> c_pname) {
this.c_pname = c_pname;
}
public void setC_pimage(ArrayList<String> c_pimage) {
this.c_pimage = c_pimage;
}
public void setC_pprice(ArrayList<String> c_pprice) {
this.c_pprice = c_pprice;
}
public void setC_pdescription(ArrayList<String> c_pdescription) {
this.c_pdescription = c_pdescription;
}
String[] data_text;
String[] data_image;
ImageLoader iloader;
public SearchCustomAdapter(Context c, int productDescribe, ArrayList<String> pname, ArrayList<String> pimage, ArrayList<String> productdescription, ArrayList<String> pprice) {
// TODO Auto-generated constructor stub
this.context = c;
this.c_pname = pname;
this.c_pprice = pprice;
this.c_pdescription = productdescription;
this.c_pimage = pimage;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
iloader = new ImageLoader(context.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return c_pname.size();
// return data_text.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int pos) {
// TODO Auto-generated method stub
// return c_pname.indexOf(getItem(pos));//arg0;
return pos;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
ViewHolder vh;
if (row == null) {
row = inflater.inflate(R.layout.custom_search_activity, parent, false);
vh = new ViewHolder();
vh.pname = (TextView) row.findViewById(R.id.product_name);
vh.pprice = (TextView) row.findViewById(R.id.textView2);
vh.image1 = (ImageView) row.findViewById(R.id.imageView1);
vh.btn = (Button) row.findViewById(R.id.p_custom_tv);
/*
* row.setOnClickListener(new OnClickListener() {
*
* #Override public void onClick(View arg0) {
*
* System.out.println("outside on click"+position);
*
*
* ArrayList<String> sendingary=new ArrayList<String>();
*
* sendingary.add(c_pname.get(position));
*
* sendingary.add(c_pprice.get(position));
*
* sendingary.add(c_pimage.get(position));
*
* sendingary.add(c_pdescription.get(position));
*
* Intent cp=new
* Intent(context.getApplicationContext(),product_details.class);
*
* cp.putStringArrayListExtra("aryvalue", sendingary);
*
* cp.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
*
* context.startActivity(cp);
*
* } });
*/
row.setTag(vh);
} else {
vh = (ViewHolder) row.getTag();
row = convertView;
}
vh.pname.setText(c_pname.get(position));
vh.pprice.setText("KD " + c_pprice.get(position));
iloader.DisplayImage(c_pimage.get(position), vh.image1);
return row;
}
public static class ViewHolder {
TextView pname, pprice;
ImageView image1;
Button btn;
}
}