Android GridView Adapter using ArrayList - android

I'm stuck creating an Adapter for my Griview that accepts an ArrayList. I think the bad line in the Adapter class is: viewHldr.wcbc_image_iv.setImageResource(urlStrArrList.get(position)); and it appears that the call .setImageResource is the problem.
public class JGrid66 extends Activity {
JSONObject jsonOb;
JSONArray JSArrGallery = null;;
GridView grid65_gv;
JGrid66Adapter2 jGr7Adap;
ProgressDialog mProgressDialog;
ArrayList<String> idStrArrList = new ArrayList<String>();
ArrayList<String> urlStrArrList = new ArrayList<String>();
ArrayList<String> descrStrArrList = new ArrayList<String>();
// JSON Node names
private static final String TAG_GALLERY = "gallery";
private static final String TAG_GALLERYURL = "galleryurl";
private static final String TAG_ID = "id";
private static final String TAG_GALLERYDESCR = "gallerydescr";
static String FLAG = "flag";
private String jsonUrl = "http://www.mysite.com/apps/wcbc/galleryuil.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jgrid66);
grid65_gv = (GridView) findViewById(R.id.jgrid66_gv);
}//--- END onCreate
//--- DownloadJSON Class
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
JGrid4Adapter jParser = new JGrid4Adapter();
// getting JSON string from URL
JSONObject jsonOb = jParser.getJSONFromUrl(jsonUrl);
try {
JSArrGallery = jsonOb.getJSONArray(TAG_GALLERY);
// looping through All gallery images
for (int i = 0; i < JSArrGallery.length(); i++) {
JSONObject galleryJO = JSArrGallery.getJSONObject(i);
String idStr = galleryJO.getString(TAG_ID);
String urlStr = galleryJO.getString(TAG_GALLERYURL);
String descrStr = galleryJO.getString(TAG_GALLERYDESCR);
idStrArrList.add(idStr);
urlStrArrList.add(urlStr);
descrStrArrList.add(descrStr);
}// -- END for loop
} catch (JSONException e) {
e.printStackTrace();
}// --- END Try
return null;
}
#Override
protected void onPostExecute(Void args) {
jGr7Adap = new JGrid66Adapter2(JGrid66.this, urlStrArrList);
grid65_gv.setAdapter(jGr7Adap);
jGr7Adap.notifyDataSetChanged();
}
}
//--- END DownloadJSON Class
}
Here;s the Adapter:
public class JGrid66Adapter2 extends BaseAdapter {
private ArrayList<String> urlStrArrList;
Context context;
public JGrid66Adapter2(Context context,ArrayList<String> urlStrArrList) {
super();
this.urlStrArrList = urlStrArrList;
}
#Override
public int getCount() {
return urlStrArrList.size();
}
#Override
public String getItem(int position) {
return urlStrArrList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public static class ViewHolder
{
public ImageView wcbc_image_iv;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHldr;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
if(convertView==null){
viewHldr = new ViewHolder();
convertView = inflater.inflate(R.layout.jgrid66_item, null);
viewHldr.wcbc_image_iv = (ImageView) convertView.findViewById (R.id.jgrid66_iv);
convertView.setTag(viewHldr);
}
else
{
viewHldr = (ViewHolder) convertView.getTag();
}
//--- I commented this out because this is where it breaks.
//viewHldr.wcbc_image_iv.setImageResource(urlStrArrList.get(position));
return convertView;
}
}
Any help would be great!

private ArrayList<String> urlStrArrList;
is arraylist of strings. If you have the url you need to download the images and then set it to imageview.
setImageResource takes a resource id as a param which is an int value.
public void setImageResource (int resId)
Added in API level 1
Sets a drawable as the content of this ImageView.
You may consider using Lazy Loading Universal Image Loader or using picasso
Caching images and displaying

Related

Fetching image from database into Android GridView

I am trying to fetch a text and image link from the database and add it to an ArrayList and then use it to display the text and image in a grid view. But it doesn't show up. It seems like the list items seem to be null when I try to add it.
What am I missing? I have gone through some answers and wasn't able to figure it out.
public final class GridAdapter extends BaseAdapter {
public static final String showUrl = "http://netbigs.com/apps/fetch.php";
String myJSON;
public String mvname;
String mvinfo;
public String rdate,imglink;
private Context mContext;
private final List<Item> mItems = new ArrayList<Item>();
private final LayoutInflater mInflater;
private static final String TAG_RESULTS = "result";
private static final String TAG_ID = "mvid";
private static final String TAG_NAME = "mvname";
private static final String TAG_IMG = "imglink";
private static final String TAG_DATE = "rdate";
private static final String TAG_MOVINF = "mvinfo";
JSONArray movies = null;
public GridAdapter(Context context) {
mItems.add(new Item(mvname,imglink));
mContext=context;
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return mItems.size();
}
#Override
public Item getItem(int i) {
return mItems.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
ImageView picture;
TextView name;
getData();
if (v == null) {
v = mInflater.inflate(R.layout.grid_item, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView) v.getTag(R.id.picture);
name = (TextView) v.getTag(R.id.text);
Item item = getItem(i);
Picasso.with(this.mContext).load(item.drawableId).into(picture);
name.setText(item.name);
System.out.println(item.name);
return v;
}
private static class Item {
public final String name;
public final String drawableId;
Item(String name, String drawableId) {
this.name = name;
this.drawableId = drawableId;
}
}
protected void showList(){
try{
JSONObject jsonObj = new JSONObject(myJSON);
movies = jsonObj.getJSONArray(TAG_RESULTS);
for (int i=0;i<movies.length();i++){
JSONObject c = movies.getJSONObject(i);
String mvid = c.getString(TAG_ID);
mvname = c.getString(TAG_NAME);
System.out.println(mvname);
imglink = c.getString(TAG_IMG);
System.out.println(imglink);
rdate = c.getString(TAG_DATE);
mvinfo = c.getString(TAG_MOVINF);
try {
}
catch (Exception e){
e.printStackTrace();
}
}
}
catch (JSONException e){
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
String uri = showUrl;
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
InputStream inputStream = null;
String result = null;
inputStream = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
return sb.toString();
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
}
This is the fragment to which the GridAdapter is attached.
public class MovieFragment extends Fragment {
public MovieFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_movie, container, false);
GridView gridView = (GridView)view.findViewById(R.id.gridview);
gridView.setAdapter(new GridAdapter(getActivity()));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i;
switch (position){
case 0:
i = new Intent(MovieFragment.this.getActivity(),MovieDetail.class);
startActivity(i);
break;
case 1:
i = new Intent(MovieFragment.this.getActivity(),MovieDetail.class);
startActivity(i);
break;
case 2:
i = new Intent(MovieFragment.this.getActivity(),MovieDetail.class);
startActivity(i);
break;
case 3:
i = new Intent(MovieFragment.this.getActivity(),MovieDetail.class);
startActivity(i);
break;
}
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
You are calling getData() from your Adapter so it may possible that when you initialize it at that time your list is null.
Try calling that method form your activity or fragment and then pass the received data you received in your adapter class.
getView() is called multiple time when you scroll up or down so never call any api in that method
Provide the code where you are using this adapter.
the problem is you are not getting values from the DB.
you must get the values from the db first. by using Volley or some plugin like that(or Aysnc task. volley will be better i think.)

displaying picture using JSON and Coverflow Library

I have problem while diplayin pictures , nothing is dsplayed in the sceen , seems empty only data are displayed no pictures. I think that the problem while parsing JSON Data in pictures.
here in the Fragment of the hotel where i want to display picture gallery.
public class ViewHotels extends AppCompatActivity {
private Bitmap bitmap;
private TextView nom1;
private TextView grade;
private TextView tele;
private ImageView image;
private TextView sit;
private TextView add1;
private TextView email1;
private FloatingActionButton fab;
LinearLayout layout;
private String id;
public static final String URL="http://gabes.comlu.com/Base_Controle/getEmpdetail.php";
private FeatureCoverFlow coverFlow;
private CoverFlowAdapter adapter;
private ArrayList<Game> games;
String image2;
String addresses;
String subject;
public static final String TAG_JSON_ARRAY="result";
ImageView im;
private int imageSource;
public String stringUrl;
public String stringUrl1;
public String stringUrl2;
public String stringUrl3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hotelsdetails);
final Intent intent = getIntent();
layout=(LinearLayout) findViewById(R.id.layout);
coverFlow = (FeatureCoverFlow) findViewById(R.id.coverflow);
settingDummyData();
adapter = new CoverFlowAdapter(this, games);
coverFlow.setAdapter(adapter);
coverFlow.setOnScrollPositionListener(onScrollListener());
id = intent.getStringExtra("Type");
nom1 = (TextView) findViewById(R.id. nom);
grade = (TextView) findViewById(R.id. grade);
tele = (TextView) findViewById(R.id. tele);
image= (ImageView)findViewById(R.id.imageView);
sit=(TextView) findViewById(R.id.site);
add1=(TextView) findViewById(R.id.adde);
email1=(TextView)findViewById(R.id.email);
nom1.setText(id);
im =new ImageView (this);
getEmployee();
}
private void getEmployee(){
final String login11 = nom1.getText().toString().trim();
class GetEmployee extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewHotels.this,"Fetching...","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
showEmployee(s);
}
#Override
protected String doInBackground(Void... v) {
HashMap<String,String> params = new HashMap<>();
params.put("id",login11)
RequestHandler rh = new RequestHandler();
String res= rh.sendPostRequest(URL, params);
return res;
}
}
GetEmployee ge = new GetEmployee();
ge.execute();
}
private void showEmployee(String json){
try {
JSONArray result = new JSONArray(json);
JSONObject c = result.getJSONObject(0);
String name = c.getString("nom");
String tel = c.getString("tele");
String grade1 = c.getString("grade");
String image1 = c.getString("image");
image2 = c.getString("img1");
String image3 = c.getString("img2");
String image4 = c.getString("img3");
String site= c.getString("site");
String add11= c.getString("add");
String email11= c.getString("email");
tele.setText("Tel : \t"+tel);
grade.setText("Grade : \t"+grade1);
sit.setText("site: \t"+site);
add1.setText("adresse :\t" + add11);
email1.setText("email :\t"+ email11);
final ImageView im1 =new ImageView (this);
final ImageView im2 =new ImageView (this);
final ImageView im3 =new ImageView (this);
stringUrl = ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image1+".jpg");
stringUrl1 = ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image2+".jpg");
stringUrl2 = ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image3+".jpg");
stringUrl3 = ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image4+".jpg");
} catch (JSONException e) {
e.printStackTrace();
}
}
private FeatureCoverFlow.OnScrollPositionListener onScrollListener() {
return new FeatureCoverFlow.OnScrollPositionListener() {
#Override
public void onScrolledToPosition(int position) {
Log.v("ViewHotels", "position: " + position);
}
#Override
public void onScrolling() {
Log.i("ViewHotels", "scrolling");
}
};
}
private void settingDummyData() {
games = new ArrayList<>();
Game game1 = new Game("stringUrl","");
Game game2 = new Game("stringUrl1","");
Game game3 = new Game("stringUrl2","");
games.add(game1);
games.add(game2);
games.add(game3);
}
}
Here is the coverFlow adapter :
public class CoverFlowAdapter extends BaseAdapter {
private ArrayList<Game> data;
private AppCompatActivity activity;
public CoverFlowAdapter(AppCompatActivity context, ArrayList<Game> objects) {
this.activity = context;
this.data = objects;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Game 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) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_flow_view, null, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
try {
URL myFileUrl = new URL(data.get(position).getImageSource());
Log.e("TAG stringUri",myFileUrl+"" );
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
viewHolder.gameImage.setImageBitmap(BitmapFactory.decodeStream(is));
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
//viewHolder.gameImage.setImageResource(data.get(position).getImageSource());
viewHolder.gameName.setText(data.get(position).getName());
return convertView;
}
private static class ViewHolder {
private TextView gameName;
private ImageView gameImage;
public ViewHolder(View v) {
gameImage = (ImageView) v.findViewById(R.id.image);
gameName = (TextView) v.findViewById(R.id.name);
}
}
}
And this the Game class :
public class Game {
private String name;
private String imageSource;
public Game (String imageSource, String name) {
this.name = name;
this.imageSource = imageSource;
}
public String getName() {
return name;
}
public String getImageSource() {
return imageSource;
}
}
I think (one of) your problem(s) is this part:
Game game1 = new Game("stringUrl","");
Game game2 = new Game("stringUrl1","");
Game game3 = new Game("stringUrl2","");
You are handing over the String "stringUrlx" to your Game-constructor.
In Java, quotation marks("") are used to explicitly define a string, which means that you are handing over "stringUrl" instead of the variable stringUrl, which would have the correct content ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image1+".jpg").
so replace e.g.
Game game1 = new Game("stringUrl","");
by
Game game1 = new Game(stringUrl,"");
That should solve that one issue.
Other than that, you will also run into issues downloading your files and with memory management. I advise you to look into java specific tutorials, which use pre-built asynchronous image loading and caching libraries (such as Glide or Picasso !)

Cannot show image in listview from json

May be this question many times.
i am getting some data from server and showing in listview . every thing working fine but i am getting problem to show image in list view.
Here is my example code
public class MainActivity extends ListActivity {
private static String url = null;
private static final String book_name = "b_name";
private static final String book_detail = "b_publisher";
private static final String book_image = "b_image";
ProgressDialog progressDialog;
ListView lv;
String cus_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
url = getResources().getString(R.string.url);
/*----Receiving data from Splash Activity-----*/
Bundle b = getIntent().getExtras();
cus_id = b.getString("custom_id");
new ProgressTask(MainActivity.this).execute();
}
class ProgressTask extends AsyncTask<String, Integer, Boolean> {
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
public ProgressTask(ListActivity activity) {
context = activity;
}
private Context context;
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Processing...");
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... values) {
// set the current progress of the progress dialog
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(final Boolean success) {
progressDialog.dismiss();
}
protected Boolean doInBackground(final String... args) {
url = url + "?custom_iid=" + cus_id;
Log.d("Passing Url", url);
CustomListAdapter jParser = new CustomListAdapter();
JSONArray json = jParser.getJSONFromUrl(url);
if (json != null) {
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String b_image = c.getString("b_image");
String b_name = c.getString("b_name");
String b_detail = c.getString("b_publisher");
Log.d("detail", "" + b_image);
setBookImageUrl(b_image);
setBookName(b_name);
setBookDetail(b_detail);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return null;
}
public String getBookImageUrl() {
return book_image;
}
public CharSequence getBookName() {
return book_name;
}
public CharSequence getBookDetail() {
return book_detail;
}
public void setBookImageUrl(String imgeUrl) {
book_image = imgeUrl;
}
public void setBookName(String b_name) {
book_name = b_name;
}
public void setBookDetail(String b_detail) {
book_detail = b_detail;
}
}
BookListAdapter class:
public class BookListAdapter extends ArrayAdapter<MainActivity> {
private ArrayList<MainActivity> bookModels;
private Context context;
public BookListAdapter(Context context, int resource,
ArrayList<MainActivity> bookModels) {
super(context, resource, bookModels);
this.bookModels = bookModels;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.row_list_item, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.bookIcon = (ImageView) rowView.findViewById(R.id.icon);
viewHolder.bookName = (TextView) rowView.findViewById(R.id.b_name);
viewHolder.bookDetail = (TextView) rowView
.findViewById(R.id.b_detail);
rowView.setTag(viewHolder);
}
final MainActivity bookModel = bookModels.get(position);
ViewHolder holder = (ViewHolder) rowView.getTag();
Picasso.with(context).load(bookModel.getBookImageUrl())
.into(holder.bookIcon);
holder.bookName.setText(bookModel.getBookName());
holder.bookDetail.setText(bookModel.getBookDetail());
return rowView;
}
#Override
public int getCount() {
return bookModels.size();
}
static class ViewHolder {
public ImageView bookIcon;
public TextView bookName;
public TextView bookDetail;
}
}
i can show book name and book detail in listview finely but image is not showing ..
i am getting value for book_image is http:\/\/X.X.X.X\/admin\/book_images\/232513pic9.png how to show in listview from that path..
I think you will need to implement your own adapter and use some library to display the image from URL.
My recommendation is Picasso
This is an example to implement your own adapter
BookListAdapter.java
public class BookListAdapter extends ArrayAdapter<BookModel> {
private ArrayList<BookModel> bookModels;
private Context context;
public BookListAdapter(Context context, int resource, ArrayList<BookModel> bookModels) {
super(context, resource, bookModels);
this.bookModels = bookModels;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ViewHolder viewHolder;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.book_child_list, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.bookIcon = (ImageView) rowView
.findViewById(R.id.bookIcon);
viewHolder.bookName = (TextView) rowView
.findViewById(R.id.bookName);
viewHolder.bookDetail = (TextView) rowView
.findViewById(R.id.bookDetail);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) rowView.getTag();
}
final BookModel bookModel = bookModels.get(position);
Picasso.with(context).load(bookModel.getBookImageUrl()).into(viewHolder.bookIcon);
viewHolder.bookName.setText(bookModel.getBookName());
viewHolder.bookDetail.setText(bookModel.getBookDetail());
return rowView;
}
#Override
public int getCount() {
return bookModels.size();
}
static class ViewHolder {
public ImageView bookIcon;
public TextView bookName;
public TextView bookDetail;
}
}
BookModel.java
public class BookModel {
private String bookName;
private String bookDetail;
private String bookImageUrl;
public BookModel() {
bookName = "";
bookDetail = "";
bookImageUrl = "";
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookDetail() {
return bookDetail;
}
public void setBookDetail(String bookDetail) {
this.bookDetail = bookDetail;
}
public String getBookImageUrl() {
return bookImageUrl;
}
public void setBookImageUrl(String bookImageUrl) {
this.icons = bookImageUrl;
}
}
Where BookModel class is a class where you can wrap your data (book name, book detail, book image) and pass it as a list to the adapter.
for example :
protected Boolean doInBackground(final String... args) {
url = url + "?custom_iid=" + cus_id;
Log.d("Passing Url", url);
CustomListAdapter jParser = new CustomListAdapter();
JSONArray json = jParser.getJSONFromUrl(url);
ArrayList<BookModel> bookModelList = new ArrayList<BookModel>();
if (json != null) {
for (int i = 0; i < json.length(); i++) {
try {
BookModel bookModel = new BookModel();
JSONObject c = json.getJSONObject(i);
String b_image = c.getString("b_image");
String b_name = c.getString("b_name");
String b_detail = c.getString("b_publisher");
Log.d("detail", "" + b_image);
bookModel.setBookName(b_name);
bookModel.setBookDetail(b_detail);
bookModel.setBookImageUrl(b_image);
bookModelList.add(bookModel);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
if(bookModelList.size()>0) {
BookListAdapter bookListAdapter = new BookListAdapter(MainActivity.this, R.id.yourlistview, bookModelList );
}
return null;
}
I hope my answer can help you!
lv.setAdapter(adapter);
use AQuery lib.
and just write this code in your custom adapter:
AQuery aQuery = new AQuery(context);
aQuery.id(your image id).image(your url,true,true);

How to Clear The Previous Gridview Item and refill with new adapter in android?

how to clear the gridview when i request for another adapter if i use the lazy adapter here i put my code for gridview activity and lazyadapter i m use the asynctask for gridview items
here i put my code for gridview
Gridview Activity.java
public class VisitorActivity extends Activity implements OnClickListener{
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new visitormiddlelistasyntask.execute("");
}
public class VisitorMiddleListAsyncTask extends AsyncTask<String,ArrayList<HashMap<String, String>>,ArrayList<HashMap<String, String>>>
{
String city;
JsonParser jparser=new JsonParser();
String visitorurl="http://digitalhoteladnetwork.com/vixxa_beta/index.php/visitors/webvisitorlist";
//String visitorurl="http://digitalhoteladnetwork.com/vixxa_beta/index.php/visitors/websearch_visitor_guide";
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... params)
{
//For Get city
Geocoder geocoder = new Geocoder(VisitorActivity.this, Locale.getDefault());
try
{
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
Log.e("Addresses","-->"+addresses);
city = addresses.get(0).getSubAdminArea();
// Log.e("Cityname","--->"+city);
}
catch (IOException e)
{
e.printStackTrace();
// Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
WebServiceData wsd=new WebServiceData();
String visitorstring=wsd.VisitorGuide(city, visitorurl);
//Log.e("webservice visitorstring","-->"+wsd.VisitorGuide(city, visitorurl));
Log.e("webservice visitorstring","-->"+visitorstring);
try
{
JSONObject jobject=new JSONObject(visitorstring);
JSONArray jvisitorlist=jobject.getJSONArray(TAG_VISITORGUIDELIST);
for(int i=0;i<jvisitorlist.length();i++)
{
HashMap<String, String> map=new HashMap<String, String>();
String id=jvisitorlist.getJSONObject(i).getString(TAG_VISITORGUIDEID).toString();
//Log.e("Id","-->"+id);
String title=jvisitorlist.getJSONObject(i).getString(TAG_VISITORGUIDETITLE).toString();
//Log.e("Title","-->"+title);
String image=jvisitorlist.getJSONObject(i).getString(TAG_VISITORGUIDEIMAGE).toString();
//Log.e("Image","-->"+image);
//String show=jvisitorlist.getJSONObject(i).getString(TAG_VISITORTITLESHOW).toString();
map.put(TAG_VISITORGUIDEID,id);
map.put(TAG_VISITORGUIDETITLE,title);
map.put(TAG_VISITORGUIDEIMAGE, image);
//map.put(TAG_VISITORTITLESHOW,show );
visitormiddle.add(map);
}
//Log.e("Visitor Guide List","-->"+jvisitorlist);
}
catch (Exception e)
{
e.printStackTrace();
}
return visitormiddle;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result)
{
gridview=(GridView)findViewById(R.id.gridview);
adapter=new LazyAdapter(VisitorActivity.this, visitormiddle);
gridview.setAdapter(adapter);
}
}
}
LazyAdapter.java
public class LazyAdapter extends BaseAdapter {
private static final String TAG_VISITORGUIDELIST="visitorlist";
private static final String TAG_VISITORGUIDEID="visitor_guide_id";
private static final String TAG_VISITORGUIDETITLE="visitor_guide_cat_title";
private static final String TAG_VISITORGUIDEIMAGE="visitor_guide_cat_image";
//private static final String TAG_VISITORTITLESHOW="visitor_guide_cat_titleshow";
private Activity activity;
private ArrayList<HashMap<String, String>> result;
private static LayoutInflater inflater=null;
public GridImageLoader gridimageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> r) {
activity = a;
result=r;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gridimageLoader=new GridImageLoader(activity.getApplicationContext());
}
public int getCount() {
return result.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder{
public TextView text;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.griditem, null);
//vi = inflater.inflate(R.layout.griditem,parent,false);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.textview);;
holder.image=(ImageView)vi.findViewById(R.id.imageview);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText(result.get(position).get(TAG_VISITORGUIDETITLE));
holder.image.setTag(result.get(position).get(TAG_VISITORGUIDEIMAGE));
gridimageLoader.DisplayImage(result.get(position).get(TAG_VISITORGUIDEIMAGE), activity, holder.image);
return vi;
}
}
You can use ArrayAdapter and then call adapter.clear() to clear the grid view and then refill it with new data.
You can use same VisitorMiddleListAsyncTask to fill the data again.
To clear gridView you can set empty adapter or set it's visibility invisible or gone.

unable to set listview text

I am using json parser to pass image url and description into my listview. now i managed to load the images but how do i change the text for my list view? currently it just shows item 0, item 1 and so on.. how do i pass the description into the lazyadapter?
Main activity:
public class MainActivity extends Activity {
// CREATING JSON PARSER OBJECT
JSONParser jParser = new JSONParser();
JSONArray guide = null;
ListView list;
LazyAdapter adapter;
String[] mImageIds;
ArrayList<String> guideList =new ArrayList<String>();
ArrayList<String> descriptionList =new ArrayList<String>();
// GUIDE URL
private static String url_guide = "http://58.185.41.178/magazine_android/get_guide.txt";
private static final String TAG_GUIDES = "guides"; //the parent node of my JSON
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_IMAGE = "image";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// LOADING Guide IN BACKGROUND THREAD
new LoadGuide().execute();
list=(ListView)findViewById(R.id.list);
adapter=new LazyAdapter(this,guideList);
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 LoadGuide extends AsyncTask<String, String, String> {
/**
* getting All videos 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_guide, "GET", params);
// CHECKING OF JSON RESPONSE
Log.d("All guide: ", json.toString());
try {
guide = json.getJSONArray(TAG_GUIDES);
for (int i = 0; i < guide.length(); i++) {
JSONObject c = guide.getJSONObject(i);
//String title = c.getString(TAG_DESCRIPTION);
String image = c.getString(TAG_IMAGE);
String description = c.getString(TAG_DESCRIPTION);
guideList.add(image);
descriptionList.add(description);
System.out.println(guideList);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// UPDATING UI FROM BACKGROUND THREAD
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
adapter.notifyDataSetChanged();
}
});
}
}
}
Image adapter:
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<String> guideList) {
activity = a;
data=guideList;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item, null);
TextView text=(TextView)vi.findViewById(R.id.text);;
ImageView image=(ImageView)vi.findViewById(R.id.image);
text.setText("item "+position);
imageLoader.DisplayImage(data.get(position), image);
return vi;
}
}
In your adapter, you are making the TextView say "item 1", "item 2" etc specifically. What you need to do is add in the Adapter constructor your descriptionList
public LazyAdapter(Activity a, ArrayList<String> guideList, ArrayList<String> descriptionList) {
and then do
text.setText(descriptionList.get(position));
When your activity calls adapter.notifyDataSetChanged(), that forces a re-draw of every item in the list. That will trigger a call into the getView() method your adapter. So your logic belongs in the getView() method:
text.setText(descriptionList.get(position));
Use a single Hashmap for guidelist and descriptionlist and then pass that to the lazyadapter constructor. use the description part of the hashmap in the getview() method to the set the text.
#user1933630
descriptionList.add(description.subString(1,description.length()-1);

Categories

Resources