I am learning android programming
I want to create like this .? Can you help me hints
Tks.
P/s : I think use Viewpaper with custom dialog
package com.example.price.service;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.example.price.R;
import com.example.price.model.Photos_Json;
import com.example.price.model.Photos_List;
import com.example.price.model.Place;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;
public class MyAdapter_Place extends ArrayAdapter<Place> {
Dialog dialog;
Activity context=null;
ArrayList<Place> myArray=null;
int layoutId;
Gallery gallery ;
ArrayList<String> ImageUrl=new ArrayList<String>();
String url="http://social-nice-price.appspot.com/webservices/Places/";
public MyAdapter_Place(Activity context, int resource, ArrayList<Place> arr) {
super(context, resource, arr);
// TODO Auto-generated constructor stub
this.context=context;
this.layoutId=resource;
this.myArray= arr;
}
public View getView(int position, View convertView,
ViewGroup parent) {
// lay Layout
LayoutInflater inflater=context.getLayoutInflater();
convertView=inflater.inflate(layoutId, null);
// khai bao cac Phan tu de SETTing sau nay
TextView Txt_sellingPrice=(TextView)convertView.findViewById(R.id.Txt_sellingPrice);
TextView Txt_priceAfterDiscount=(TextView)convertView.findViewById(R.id.Txt_priceAfterDiscount);
TextView Txt_address=(TextView)convertView.findViewById(R.id.Txt_address);
TextView Txt_updateDate=(TextView)convertView.findViewById(R.id.Txt_updateDate);
TextView Txt_hotline=(TextView)convertView.findViewById(R.id.Txt_hotline);
TextView Txt_name=(TextView)convertView.findViewById(R.id.Txt_name);
TextView Txt_website=(TextView)convertView.findViewById(R.id.Txt_website);
gallery = (Gallery)convertView.findViewById(R.id.gallery1);
ImageView ChiDuong=(ImageView)convertView.findViewById(R.id.Imageview_chiduong);
// Lya phan tu tai vi tri position
Place place=myArray.get(position);
// Setting data
Txt_sellingPrice.setText("Giá Bán : "+place.getSellingPrice());
Txt_priceAfterDiscount.setText("Giá Đã Giảm : "+place.getPriceAfterDiscount());
Txt_address.setText("Địa Chỉ : "+place.getAddress());
//Txt_productCode.setText("Mã Sản Phẩm : "+place.getProductCode());
Txt_updateDate.setText("Ngày Cập Nhật : "+place.UpdateDate);
Txt_hotline.setText("Hotline : " +place.getHotLine());
Txt_name.setText("Tên Quán : " +place.getName());
Txt_website.setText("Website : "+place.getWebsite());
//hien thi anh viewpager
// lay du lieu json ,=> hinh anh
Gson(url+place.ProductCode+"/");
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
String temp=ImageUrl.get(position);
//Toast.makeText(context, temp, Toast.LENGTH_LONG).show();
// dialog hien khi click vao anh trong gallery
dialog = new Dialog(context);
dialog.setContentView(R.layout.custom_dialog);
ViewPager pager=(ViewPager)dialog.findViewById(R.id.pager);
pager.setAdapter(new ImagePagerAdapter(ImageUrl));
pager.setCurrentItem(0);
// ImageView imgselect=(ImageView)dialog.findViewById(R.id.Image_dialog);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.show();
//imageLoader.displayImage(temp, imgselect,options);
}
});
ChiDuong.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
return convertView;
}
public void Gson(String url){
String json ="";
try {
json = readUrl(url);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(json!="" && json!=null){
Gson gson = new Gson();
Photos_List page = gson.fromJson(json, Photos_List.class);
List<Photos_Json> temp=page.place.Photos;
int i=0;
for(Photos_Json a:temp){
ImageUrl.add(a.Link);
}
}
gallery.setAdapter(new ImageGalleryAdapter1());
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
}
});
}
public static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
ImageLoader imageLoader;
DisplayImageOptions options;
private class ImageGalleryAdapter1 extends BaseAdapter {
private int[] imageUrls1={R.drawable.ic_home,R.drawable.bestbuy};
#Override
public int getCount() {
return ImageUrl.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = (ImageView) convertView;
if (imageView == null) {
imageView = (ImageView)context.getLayoutInflater().inflate(R.layout.item_gallery_image, parent, false);
}
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisc(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
imageLoader=ImageLoader.getInstance();
File cacheDir = StorageUtils.getCacheDirectory(context);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.memoryCacheExtraOptions(480, 800) // default = device screen dimensions
.discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75, null)
.taskExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
.taskExecutorForCachedImages(AsyncTask.THREAD_POOL_EXECUTOR)
.threadPoolSize(3) // default
.threadPriority(Thread.NORM_PRIORITY - 1) // default
.tasksProcessingOrder(QueueProcessingType.FIFO) // default
.denyCacheImageMultipleSizesInMemory()
.memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // default
.memoryCacheSize(2 * 1024 * 1024)
.discCache(new UnlimitedDiscCache(cacheDir)) // default
.discCacheSize(50 * 1024 * 1024)
.discCacheFileCount(100)
.discCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
.imageDownloader(new BaseImageDownloader(context)) // default
.defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
.build();
imageLoader.init(config);
imageLoader.displayImage(ImageUrl.get(position), imageView, options);
//imageView.setImageResource(imageUrls[position]);
return imageView;
}
}
private class ImagePagerAdapter extends PagerAdapter {
private ArrayList<String> images=new ArrayList<String>();
private LayoutInflater inflater;
ImagePagerAdapter(ArrayList<String> images) {
this.images = images;
// inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
LayoutInflater inflater = (LayoutInflater) view.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View imageLayout = inflater.inflate(R.layout.item_paper_image, view, false);
assert imageLayout != null;
ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
imageLoader.displayImage("R.drawable.bestbuy", imageView, options);
view.addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
}
}
item_paper_image.xml
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:adjustViewBounds="true"
/>
<ProgressBar
android:id="#+id/loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone" />
custom_dialog.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" > <android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Related
I am using this code to show the cover of the songs in the listview:
package com.xrobotx.love.musicalbums;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
public class SongAdapter extends BaseAdapter {
private List<Song> songs;
private LayoutInflater songInf;
Context mContext;
public SongAdapter(Context c, List<Song> theSongs){
songs=theSongs;
songInf=LayoutInflater.from(c);
mContext = c;
}
#Override
public int getCount() {
return songs.size();
}
#Override
public Object getItem(int arg0) {
return songs.get(arg0);
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//map to song layout
RelativeLayout songLay = (RelativeLayout)songInf.inflate
(R.layout.song_layout, parent, false);
//get title and artist views
TextView songView = (TextView)songLay.findViewById(R.id.song_title);
TextView artistView = (TextView)songLay.findViewById(R.id.song_artist);
TextView durationView = (TextView)songLay.findViewById(R.id.song_duration);
ImageView coverView = (ImageView)songLay.findViewById(R.id.song_cover);
//get song using position
Song currSong = songs.get(position);
//get title and artist strings
songView.setText(currSong.getTitle());
artistView.setText(currSong.getArtist());
durationView.setText(String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes((long) currSong.getDuration()),
TimeUnit.MILLISECONDS.toSeconds((long) currSong.getDuration()) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) currSong.getDuration()))));
if(currSong.getCover() != null){
Glide.with(mContext).load(currSong.getCover()).override(50, 50).into(coverView);
}
songLay.setTag(position);
return songLay;
}
}
Not all covers are displayed correctly. Some covers infact are black.
Why ?
EDIT:
This is the code to get the Cover:
private static String getCoverArtPath(long albumId, Context context) {
Cursor albumCursor = context.getContentResolver().query(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Albums.ALBUM_ART},
MediaStore.Audio.Albums._ID + " = ?",
new String[]{Long.toString(albumId)},
null
);
boolean queryResult = albumCursor.moveToFirst();
String result = null;
if (queryResult) {
result = albumCursor.getString(0);
}
albumCursor.close();
return result;
}
I ran into this. Glide network requests like any other request it fails sometimes
So the solution i found is to make another request on failure.
Glide.with(context)
.load((currSong.getCover())
.asBitmap()
.into(new SimpleTarget<Bitmap>(width, height) {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
//handle Bitmap
coverview.setBitmap(resource);
}
#Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
Glide.with(mContext).load(currSong.getCover()).override(50, 50).into(coverView);
}
});
I got a source code about GridView.
But, I confused why some code were error.
These are the code. I got error on OnClick Method in MainActivity. Is here anyone help me? Thanks
public void onItemClick(AdapterView <? > AdapterView, View View, int Int, long Long) {
AdapterView = ((ImageItem) imageItems.get(Int)).getTitle();
toDetail(Int, AdapterView);
}
});
I want to each item that when it clicked shown the detailed image and text. I also get code like this but when I clicked "GingerBread" item, it goes to first item ("Astro")
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ImageItem item = (ImageItem) parent.getItemAtPosition(position);
//Create intent
Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
// intent.putExtra("android.intent.extra.TEXT", Integer.parseInt(getIntent().getStringExtra("android.intent.extra.TEXT")));
intent.putExtra("title", item.getTitle());
//Start details activity
startActivity(intent);
overridePendingTransition(R.anim.home_detail_entry, R.anim.home_detail_exit);
}
});
MainActivity.java
package com.acer.gridview;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends Activity {
public static String[] bitmapName = {
"Astro", "Bender", "Cupcake", "Donut", "Eclair",
"Froyo", "Gingerbread", "HoneyComb"
};
public static int[] bitmapId = {
R.drawable.Astro, R.drawable.Bender, R.drawable.Cupcake, R.drawable.Eclair,
R.drawable.Froyo, R.drawable.Gingerbread, R.drawable.HoneyComb
};
private GridViewAdapter gridAdapter;
private GridView gridView;
ArrayList < ImageItem > imageItems;
private ArrayList < ImageItem > getData() {
imageItems = new ArrayList();
BitmapFactory.Options localOptions = new BitmapFactory.Options();
localOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
int i = 0;
for (;;) {
if (i > 7) {
return imageItems;
}
Bitmap localBitmap = BitmapFactory.decodeResource(getResources(), bitmapId[i], localOptions);
imageItems.add(new ImageItem(localBitmap, bitmapName[i]));
i += 1;
}
}
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_grid);
gridView = (GridView) findViewById(R.id.gridView);
gridAdapter = new GridViewAdapter(this, R.layout.row_grid, getData());
gridView.setAdapter(gridAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView <? > AdapterView, View View, int Int, long Long) {
////////////This code shown error///////////////////
AdapterView = ((ImageItem) imageItems.get(Int)).getTitle();
toDetail(Int, AdapterView);
////////////This code shown error///////////////////
}
});
}
public void toDetail(int Int, String String) {
Intent localIntent = new Intent(this, DetailActivity.class);
localIntent.putExtra("android.intent.extra.TEXT", Integer.toString(Int));
localIntent.putExtra("title", String);
startActivity(localIntent);
}
/**
* A placeholder fragment containing a simple view.
*/
private boolean ActionBar(final Intent aIntent) {
try {
startActivity(aIntent);
return true;
} catch (ActivityNotFoundException e) {
return false;
}
}
public void showDialog() {
LayoutInflater inflater = getLayoutInflater();
View localView = inflater.inflate(R.layout.help_dialog, null);
((ImageView) localView.findViewById(R.id.imageView1)).setImageResource(R.drawable.makhrojulhuruf);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(localView);
builder.show();
}
#
Override
public boolean onCreateOptionsMenu(Menu menu) {}
#
Override
public boolean onOptionsItemSelected(MenuItem item) {
}
}
GridViewAdapter.java
package com.acer.gridview;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Acer on 08/02/2016.
*/
public class GridViewAdapter extends ArrayAdapter<ImageItem> {
private Context context;
private int layoutResourceId;
private ArrayList<ImageItem> data = new ArrayList();
public GridViewAdapter(Context context, int layoutResourceId, ArrayList<ImageItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.image = (ImageView) row.findViewById(R.id.image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
ImageItem item = (ImageItem) data.get(position);
holder.imageTitle.setText(item.getTitle());
holder.image.setImageBitmap(item.getImage());
return row;
}
static class ViewHolder {
TextView imageTitle;
ImageView image;
}
}
ImageItem.java
package com.acer.gridview;
import android.graphics.Bitmap;
/**
* Created by Acer on 08/02/2016.
*/
public class ImageItem {
private Bitmap image;
private String title;
public ImageItem(Bitmap Bitmap, String String)
{
setImage(Bitmap);
setTitle(String);
}
public Bitmap getImage()
{
return this.image;
}
public String getTitle()
{
return this.title;
}
public void setImage(Bitmap Bitmap)
{
this.image = Bitmap;
}
public void setTitle(String String)
{
this.title = String;
}
}
I am new in android and badly need to do animation in ExpandableLIstView in onGroupExpand and onGroupCollapse.
Please help me.
Given below is my code -
My MainActivity is
package comsam.myexpandablelistviedjsonapp;
import android.app.ProgressDialog;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.animation.PathInterpolatorCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ExpandListAdapter ExpAdapter;
private ExpandableListView ExpandList;
private Interpolator easeInOutQuart = PathInterpolatorCompat.create(0.77f, 0f, 0.175f, 1f);
private int lastExpandedPosition = -1;
ArrayList<Parent> list = new ArrayList<Parent>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView animatedButton = (ImageView) findViewById(R.id.parent_img);
ExpandList = (ExpandableListView)findViewById(R.id.exp_list);
new JSONAsyncTask().execute("http://local.agdits.com.bd/hrdemo/expandable.php");
ExpAdapter = new ExpandListAdapter(MainActivity.this, list);
ExpandList.setAdapter(ExpAdapter);
//to show which list has been clicked for Expand
ExpandList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(final int groupPosition) {
if (lastExpandedPosition != -1 && groupPosition != lastExpandedPosition) {
ExpandList.collapseGroup(lastExpandedPosition);
// setupLayoutAnimationClose(groupPosition);
// new AnimUtils().collapse(ExpandList);
}
lastExpandedPosition = groupPosition;
}
});
//to show which list has been clicked for Collapse
ExpandList.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int parentPosition) {
Toast.makeText(getBaseContext(), ExpAdapter.getGroupName(parentPosition) + " is collapse ", Toast.LENGTH_LONG).show();
}
});
//to show which Child has been clicked
ExpandList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int parentPosition, int childPosition, long id) {
Toast.makeText(getBaseContext(), ExpAdapter.getChildName(parentPosition, childPosition) + " from category " + ExpAdapter.getGroupName(parentPosition) + " is selected", Toast.LENGTH_LONG).show();
return false;
}
});
}
private void expand1() {
System.out.println("I am here expand");
}
private void collapse() {
System.out.println("I am here collapse");
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
//System.out.println(data);
ArrayList<Child> ch_list;
JSONArray jsonArray1 = new JSONArray(data);
for (int i = 0; i < jsonArray1.length(); i++) {
JSONObject object = jsonArray1.getJSONObject(i);
// System.out.println(object.getString("_id"));
Parent parent = new Parent();
parent.setParentName(object.getString("CategoryName"));
parent.setParentImage(object.getString("CatImage"));
//System.out.println(object.getString("CategoryName"));
//Make Child List Array
ch_list = new ArrayList<Child>();
JSONArray childArray = object.getJSONArray("child");
//System.out.println(childArray.length());
for (int j = 0; j < childArray.length(); j++) {
JSONObject childobject = childArray.getJSONObject(j);
Child child = new Child();
child.setName(childobject.getString("name"));
child.setImage(childobject.getString("image"));
ch_list.add(child);
}
// System.out.println(childArray);
//Child List to Parent Items
parent.setItems(ch_list);
list.add(parent);
}
return true;
}
//------------------>>
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
ExpAdapter.notifyDataSetChanged();
if(result == false) {
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
My ExpandListAdapter class is
package comsam.myexpandablelistviedjsonapp;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Created by tanvinn on 10/27/2015.
*/
public class ExpandListAdapter extends BaseExpandableListAdapter{
private Context context;
private ArrayList<Parent> parents;
public MainActivity activity;
public ImageLoader imageLoader;
public int lastExpandedGroupPosition=-1;
public ExpandListAdapter(Context context, ArrayList<Parent> parents) {
this.context = context;
this.parents = parents;
// Create ImageLoader object to download and show image in list
// Call ImageLoader constructor to initialize FileCache
imageLoader = new ImageLoader(activity);
}
#Override
public Object getChild(int parentPosition, int childPosition) {
ArrayList<Child> chList = parents.get(parentPosition).getItems();
return chList.get(childPosition);
}
#Override
public long getChildId(int parentPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int parentPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
Child child = (Child) getChild(parentPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_layout, null);
}
TextView tv = (TextView) convertView.findViewById(R.id.child_txt);
ImageView imageView = (ImageView)convertView.findViewById(R.id.child_img);
imageView.setImageResource(R.drawable.geofence1);
tv.setText(child.getName().toString());
//new DownloadImageTask(imageView).execute(child.getImage().toString());
imageLoader.DisplayImage(child.getImage().toString(), imageView);
return convertView;
}
#Override
public int getChildrenCount(int parentPosition) {
ArrayList<Child> chList = parents.get(parentPosition).getItems();
return chList.size();
}
#Override
public Object getGroup(int parentPosition) {
return parents.get(parentPosition);
}
#Override
public int getGroupCount() {
return parents.size();
}
#Override
public long getGroupId(int parentPosition) {
return parentPosition;
}
#Override
public View getGroupView(int parentPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
Parent parent1 = (Parent) getGroup(parentPosition);
if (convertView == null) {
LayoutInflater inf = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.parent_layout, null);
}
TextView tv = (TextView) convertView.findViewById(R.id.parent_txt);
ImageView imageView = (ImageView)convertView.findViewById(R.id.parent_img);
imageView.setImageResource(R.drawable.geofence1);
tv.setText(parent1.getParentName());
// new DownloadImageTask(imageView).execute(parent1.getParentImage().toString());
imageLoader.DisplayImage(parent1.getParentImage().toString(), imageView);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int parentPosition, int childPosition) {
return true;
}
public Object getGroupName(int parentPosition) {
Parent parent1 = (Parent) getGroup(parentPosition);
String parentName = parent1.getParentName();
return parentName;
}
public Object getChildName(int parentPosition, int childPosition) {
Child child = (Child) getChild(parentPosition, childPosition);
String childName = child.getName();
return childName;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
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);
}
}
}
Thanks in advance.
You can try with this AnimatedExpandableListView
listView = (AnimatedExpandableListView) findViewById(R.id.listView);
listView.setAdapter(YOUR_ADAPTER);
// In order to show animations, we need to use a custom click handler
// for our ExpandableListView.
listView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
// We call collapseGroupWithAnimation(int) and
// expandGroupWithAnimation(int) to animate group
// expansion/collapse.
if (listView.isGroupExpanded(groupPosition)) {
listView.collapseGroupWithAnimation(groupPosition);
} else {
listView.expandGroupWithAnimation(groupPosition);
}
return true;
}
});
Android ExpandableListView using animation
Animation for expandableListView
The following in item_animation_fall_down.xml (Place this xml file in res/anim folder)
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"android:duration="500">
<translate android:interpolator="#android:anim/accelerate_decelerate_interpolator"
android:fromYDelta="50%p" android:toYDelta="0" />
<alpha android:fromAlpha="0" android:toAlpha="1"
android:interpolator="#android:anim/accelerate_decelerate_interpolator" />
</set>
The following in getGroupView(....) {} block
convertView.setAnimation(AnimationUtils.loadAnimation(_context,R.anim.item_animation_fall_down));
The following in Activity class
expListView.setAnimation(AnimationUtils.loadAnimation(this,R.anim.item_animation_from_right));
The following in activity_home.xml ( to the root element)
android:fillAfter="true" android:fillEnabled="true"
I receive a JSON array from the server that looks like this,
[{"id":"3","name":"Spanish 101","uid":"54f22e5c87cbd3.52439435","did":"fba6a04d1d6375fbdbb102953e984002"},
{"id":"4","name":"Calc","uid":"54f22e5c87cbd3.52439435","did":"fb7f4ba1eae22eb396dc7cbd465a10b4"},
{"id":"5","name":"Stats 250","uid":"54f22e5c87cbd3.52439435","did":"f6adca44250056c17fec56530faee7c9"}]
I want to take this information and put it into a listview
This is my code that is suppose to process this JSON aray and put it into a listview
package com.example.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
public class FetchDataTask extends AsyncTask<String, Void, String>{
private final FetchDataListener listener;
private String msg;
public FetchDataTask(FetchDataListener listener) {
this.listener = listener;
}
#Override
protected String doInBackground(String... params) {
if(params == null) return null;
// get url from params
String url = params[0];
try {
// create http connection
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
// connect
HttpResponse response = client.execute(httpget);
// get response
HttpEntity entity = response.getEntity();
if(entity == null) {
msg = "No response from server";
return null;
}
// get response content and convert it to json string
InputStream is = entity.getContent();
return streamToString(is);
}
catch(IOException e){
msg = "No Network Connection";
}
return null;
}
#Override
protected void onPostExecute(String sJson) {
if(sJson == null) {
if(listener != null) listener.onFetchFailure(msg);
return;
}
try {
// convert json string to json array
JSONArray aJson = new JSONArray(sJson);
// create apps list
List<Application> apps = new ArrayList<Application>();
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
Application app = new Application();
app.setTitle(json.getString("name"));
// add the app to apps list
apps.add(app);
}
//notify the activity that fetch data has been complete
if(listener != null) listener.onFetchComplete(apps);
} catch (JSONException e) {
msg = "Invalid response";
if(listener != null) listener.onFetchFailure(msg);
return;
}
}
/**
* This function will convert response stream into json string
* #param is respons string
* #return json string
* #throws IOException
*/
public String streamToString(final InputStream is) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch (IOException e) {
throw e;
}
finally {
try {
is.close();
}
catch (IOException e) {
throw e;
}
}
return sb.toString();
}
}
FetchDataListener
package com.example.library;
import java.util.List;
public interface FetchDataListener {
public void onFetchComplete(List<Application> data);
public void onFetchFailure(String msg);
}
I am currently only trying to place the name into the listview, when I run this code what happens is only the first array gets put into the listview. So there is only one list item and it has the name Spanish 101.
Why aren't the other array names being put into the listview?
Application Adapter
package com.example.library;
import java.text.NumberFormat;
import java.util.List;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.R;
public class ApplicationAdapter extends ArrayAdapter<Application>{
private List<Application> items;
public ApplicationAdapter(Context context, List<Application> items) {
super(context, R.layout.app_custom_list, items);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.app_custom_list, null);
}
Application app = items.get(position);
if(app != null) {
TextView titleText = (TextView)v.findViewById(R.id.titleTxt);
if(titleText != null) titleText.setText(app.getTitle());
}
return v;
}
}
Get and Set
package com.example.library;
public class Application {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
MainActivity that has ListView
package com.example;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.R;
import com.example.library.Application;
import com.example.library.ApplicationAdapter;
import com.example.library.DatabaseHandler;
import com.example.library.FetchDataListener;
import com.example.library.FetchDataTask;
import com.example.library.UserFunctions;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends ListActivity implements FetchDataListener {
private ProgressDialog dialog;
ProgressDialog nDialog;
AlertDialog.Builder dlgAlert;
ListView listView ;
TextView tv;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
tv = (TextView) findViewById(R.id.tv);
nDialog = new ProgressDialog(MainActivity.this);
//Action bar information
android.app.ActionBar mActionBar = getActionBar();
assert mActionBar != null;
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null);
//FIX THISSSSS TO LOGOUT BUTTON
RelativeLayout settingButton = (RelativeLayout) mCustomView
.findViewById(R.id.settingButton);
settingButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
Intent startup = new Intent(getApplicationContext(), StartUp.class);
startup.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(startup);
finish();
}
});
mActionBar.setCustomView(mCustomView);
mActionBar.setDisplayShowCustomEnabled(true);
//End action bar information
}//End onCreate
private void initView() {
// show progress dialog
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap user = new HashMap();
user = db.getUserDetails();
String uid = user.get("unique_id").toString();
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "www.example.com";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
#Override
public void onFetchComplete(List<Application> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}//End Activity
This is how i deal with ListView and CustomAdapter
in onCreate() of Activity
//Photos Model List
photoList = new ArrayList<Photos>();
//ListView
lvGalleryPhotos = (ListView) parentView.findViewById(R.id.lvGalleryPhotos);
//My CustomAdapter
pgAdapter = new PhotoGalleryAdapter(photoList, getSherlockActivity());
//Setting adapter to GridView
lvGalleryPhotos.setAdapter(pgAdapter);
//Parsing JSON
for(int i=0;i<10;i++){
//each result contains details about a image
JSONObject result = results.getJSONObject(i);
//Real Parsing
int width = result.getInt("width");
int height = result.getInt("height");
String title = result.getString("titleNoFormatting");
String url = result.getString("unescapedUrl");
//Make it workable so replace \u003d with =
String tbUrl = result.getString("tbUrl").replace("\u003d", "=");
//Creating photo object and inserting all collected information into it.
Photos photo = new Photos();
photo.setHeight(height);
photo.setWidth(width);
photo.setTitle(title);
photo.setURL(url);
photo.setTbUrl(tbUrl);
//Adding each Photo Object to PhotoList
photoList.add(photo);
}
//Informing that data has changed
pgAdapter.notifyDataSetChanged();
My Custom Adapter
public class PhotoGalleryAdapter extends BaseAdapter {
ImageLoader mImageLoader;
List<Photos> photoList;
Context mContext;
BlowIt blw;
LayoutInflater mLInflater;
public PhotoGalleryAdapter(List<Photos> photoList,Context mContext){
this.photoList = photoList;
this.mContext = mContext;
blw = new BlowIt(mContext);
}
#Override
public int getCount() {
return photoList.size();
}
#Override
public Object getItem(int position) {
return photoList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//Creating layout inflater
if(mLInflater==null){
mLInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//Inflating Layout
if(convertView==null){
convertView = mLInflater.inflate(R.layout.gallery_single_photo,parent,false);
}
//Getting Object
final Photos photo = photoList.get(position);
//Single Image
NetworkImageView nivGalleryPhoto = (NetworkImageView) convertView.findViewById(R.id.nivGalleryPhoto);
TextView tvPhotoName = (TextView) convertView.findViewById(R.id.tvPhotoName);
TextView tvPhotoDesc = (TextView) convertView.findViewById(R.id.tvPhotoDesc);
final String photoDescr = photo.getHeight()+"x"+photo.getWidth();
nivGalleryPhoto.setImageUrl(photo.getTbUrl(), mImageLoader);
tvPhotoName.setText(photo.getTitle());
tvPhotoDesc.setText(photoDescr);
convertView.setTag(photo);
convertView.setId(position);
//This will trigger when ever the user clicks on a specific image
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//This will prompt automatically context menu
v.showContextMenu();
}
});
return convertView;
}
}
and the layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llPhotosFragmentRoot"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lvGalleryPhotos"
android:layout_height="wrap_content"
android:layout_width="match_parent"
></ListView>
</LinearLayout>
and the gallery_single_photo.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:padding="10dp"
android:layout_height="wrap_content" >
<!-- <com.android.volley.toolbox.NetworkImageView -->
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/nivGalleryPhoto"
android:layout_height="90dp"
android:scaleType="centerCrop"
android:layout_width="75dp"
android:contentDescription="#string/dummy_desc"
/>
<TextView
android:id="#+id/tvPhotoName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="bold"
android:layout_alignTop="#+id/nivGalleryPhoto"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/nivGalleryPhoto"
android:text="Large Text"/>
<TextView
android:id="#+id/tvPhotoDesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tvPhotoName"
android:layout_below="#+id/tvPhotoName"
android:text="Medium Text"
android:textSize="13sp"
android:textColor="#color/border_black" />
</RelativeLayout>
and all the above codes can make a listView with items like this
Use ViewHolder design pattern in your getView(...):
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if(v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.app_custom_list, null);
holder = new ViewHolder();
holder.titleText = (TextView)v.findViewById(R.id.titleTxt);
v.setTag(holder);
}
else
holder = (ViewHolder) v.getTag()
Application app = items.get(position);
if(app != null) {
if(titleText != null)
holder.titleText.setText(app.getTitle());
}
return v;
}
static class ViewHolder {
TextView titleText;
}
My project works without error, but upon loading, images are not loaded in the Listview.
Here is a sample image
sample at the first working image
But after dragging ListView, all images loads.
sample draggened image load
Please Help. Sorry bad english.
Categoryadapter.java
package com.medyasef.dernek.tjod;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
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;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by olkunmustafa on 26.09.2013.
*/
public class CategoryAdapter extends BaseAdapter {
private String LOG_NAME = "HATA";
private List<Categoryicerikler> list_view;
private HashMap<Integer,Bitmap> bitmaplist;
private Context mContext;
private Categories categories = new Categories();
public CategoryAdapter(List<Categoryicerikler> list_view, Context mContext) {
this.list_view = list_view;
this.mContext = mContext;
bitmaplist = new HashMap<Integer, Bitmap>();
for (int i = 0; i < list_view.size() ; i++) {
Categoryicerikler bitmap_icerikler = list_view.get(i);
setBitmapFromURL(bitmap_icerikler.getCategory_post_image(),i);
}
}
/*
Burada resimleri çekmek için thread oluşturuyoruz.
Resim linkini ve ImageView'i veriyoruz ve ekrana basmasını sağlıyoruz.
*/
public void setBitmapFromURL(final String src,final int value) {
new Thread(
new Runnable()
{
#Override
public void run() {
HttpURLConnection connection= null;
try {
URL url = new URL(src);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
InputStream input = connection.getInputStream();
final Bitmap myBitmap = BitmapFactory.decodeStream(input);
try {
bitmaplist.put(value,myBitmap);
}
catch (Exception e){
Log.d(LOG_NAME,e.getMessage());
Log.d(LOG_NAME,"Resim ekleme işlemi başarısız.");
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
connection.disconnect();
}
}
}).start();
}
#Override
public int getCount() {
return list_view.size();
}
#Override
public Object getItem(int position) {
return list_view.get(position);
}
#Override
public long getItemId(int position) {
return list_view.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertview, ViewGroup viewGroup) {
Categoryicerikler categoryicerikler = list_view.get(position);
ViewHolder holder = null;
if(convertview==null){
Log.d(LOG_NAME,"sonuc");
convertview = LayoutInflater.from(mContext).inflate(R.layout.categories,viewGroup,false);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertview.findViewById(R.id.category_posttitle);
holder.txtDate = (TextView) convertview.findViewById(R.id.category_postdate);
holder.imageView = (ImageView) convertview.findViewById(R.id.category_image);
convertview.setTag(holder);
Categories.categoryAdapter.notifyDataSetChanged();
}
else {
holder = (ViewHolder) convertview.getTag();
}
holder.txtTitle.setText(categoryicerikler.getCategory_posttitle());
holder.txtDate.setText(categoryicerikler.getCategory_postdate());
try {
holder.imageView.setImageBitmap(bitmaplist.get(position));
}
catch (Exception e){
}
return convertview;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDate;
}
}
Categoryicerikler.java
package com.medyasef.dernek.tjod;
import android.graphics.Bitmap;
import android.widget.ImageView;
/**
* Created by olkunmustafa on 26.09.2013.
*/
public class Categoryicerikler {
private String category_posttitle;
private String category_postdate;
private String category_post_content;
private String category_post_image;
public Categoryicerikler( String category_posttitle, String category_postdate, String category_post_content,String post_image) {
this.category_posttitle = category_posttitle;
this.category_postdate = category_postdate;
this.category_post_content = category_post_content;
this.category_post_image = post_image;
}
public String getCategory_posttitle() {
return category_posttitle;
}
public void setCategory_posttitle(String category_posttitle) {
this.category_posttitle = category_posttitle;
}
public String getCategory_postdate() {
return category_postdate;
}
public void setCategory_postdate(String category_postdate) {
this.category_postdate = category_postdate;
}
public String getCategory_post_content() {
return category_post_content;
}
public void setCategory_post_content(String category_post_content) {
this.category_post_content = category_post_content;
}
public String getCategory_post_image() {
return category_post_image;
}
public void setCategory_post_image(String category_post_image) {
this.category_post_image = category_post_image;
}
}
Categories.java
package com.medyasef.dernek.tjod;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.Html;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
/**
* Created by olkunmustafa on 25.09.2013.
*/
public class Categories extends Activity {
private List<Categoryicerikler> content_list;
public static CategoryAdapter categoryAdapter;
private ListView main_category;
private static HashMap<Integer,Bitmap> bitmaplist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_categories);
main_category = (ListView) findViewById(R.id.main_category);
new GetCategory().execute();
}
private class GetCategory extends AsyncTask<Void,Void,String> {
#Override
protected void onPreExecute() {
Toast.makeText(Categories.this, "İslem Baslıyor Bekleyiniz", Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(Void... voids) {
/*
Burada internete bağlanıp json veriyi string cinsinden çekiyoruz.
*/
InternetConnection internetcon = new InternetConnection();
String json_result = internetcon.get_json_data();
return json_result;
}
#Override
protected void onPostExecute(String data) {
/*
Gelen string veriyi json_to_list_view metoduna veriyorum
Bu metot gelen json verisinin içeriklerini doldurarak bana birt liste dönderir.
*/
try {
content_list = GetJson.json_to_list_view(data);
} catch (JSONException e) {
Log.d("Json_Error","Json çekilirken hata oluştu");
}
categoryAdapter = new CategoryAdapter(content_list,Categories.this);
main_category.setAdapter(categoryAdapter);
}
}
}
If you simply want to load images in a list view, I would recommend you to use Picasso
Its simple, fast and does nearly everything automatically for you. You also don't have to care about canceling request on activity destroy. So I guess this would be the best start for you, if you simply want to load images into a ImageView in a ListView.
for instance in your adapter you could use:
Picasso.with(context)
.load(url)
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.into(imageView);
Where imageview is the ImageView of your listview cell
Use universal image loader library and then following way
---------------------------------------------------------
1 - options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.physicalgift_normal)
.cacheInMemory()
.cacheOnDisc()
.displayer(new RoundedBitmapDisplayer(10))
.build();
imageLoader=ImageLoader.getInstance();
ImageLoaderConfiguration imgconfig=ImageLoaderConfiguration.createDefault(context);
imageLoader.init(imgconfig);
----------------------------------------------------------
2 - String url=list.get(position).getThumbUrl();
if(url != null && url !="")
imageLoader.displayImage(Utils.getEncodedUrl(url), holder.img, options);
------------------------------------------------------------
3 - SubCatAdapter adapter = new SubCatAdapter(SubCategoryActivity.this,
mlist);
list.setAdapter(adapter);
------------------------------------------------------------
full example is here
public class SubCatAdapter extends BaseAdapter {
private ArrayList<SubcategoryData> list;
private LayoutInflater inflator;
public ImageLoader imageLoader;
private DisplayImageOptions options;
public SubCatAdapter(Context context, ArrayList<SubcategoryData> mlist) {
super();
this.list = mlist;
this.inflator = LayoutInflater.from(context);
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.physicalgift_normal)
.cacheInMemory()
.cacheOnDisc()
.displayer(new RoundedBitmapDisplayer(10))
.build();
imageLoader=ImageLoader.getInstance();
ImageLoaderConfiguration imgconfig=ImageLoaderConfiguration.createDefault(context);
imageLoader.init(imgconfig);
}
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View view = convertView;
ViewHolder holder = null;
if (convertView == null) {
view = inflator.inflate(R.layout.row_subcat, null);
holder = new ViewHolder();
holder.txt_Name = (TextView) view.findViewById(R.id.txt_name);
holder.img=(ImageView)view.findViewById(R.id.img_row);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.txt_Name.setText(list.get(position).getName());
String url=list.get(position).getThumbUrl();
if(url != null && url !="")
imageLoader.displayImage(Utils.getEncodedUrl(url), holder.img, options);
return view;
}
static class ViewHolder {
TextView txt_Name;
ImageView img;
}
}