Show Image From URL in Android? - android

How can I convert Image URL to any showable type, I want to show it with my CustomAdapter just like "Category_Name" and "Category_Description" as in the following code ;
JSONArray jsonResponse = new JSONArray(result); // Result is my JSON
asd = new String[3][jsonResponse.length()];
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < jsonResponse.length(); i++) {
JSONObject js = jsonResponse.getJSONObject(i);
asd[0][i]= js.getString("Category_Name"); // Fetch Category Name
asd[1][i]= js.getString("Category_Description"); // Fetch Category Description
asd[2][i]= js.getString("Image"); // Fetch Image URL
RowItem item = new RowItem(R.drawable.abc_ab_bottom_solid_dark_holo, asd[0][i], asd[1][i]);
// I delivered asd[0][i] as a title and asd[1][0] as a post content..
rowItems.add(item);
}
adapter = new CustomListViewAdapter(MainActivity.this,R.layout.list_item, rowItems);
listView.setAdapter(adapter);
How Can I use Fetched Image URL and show it just like title , post content.
Custom Adapter ;
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtDesc.setText(rowItem.getDesc()); // RowItem Setter Getter Method
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
return convertView;
}
}

You will have to download the image and set it to the imageView
To download and set the image:
public void downloadImageFromUrl(ImageView iv, String path){
InputStream in =null;
Bitmap bmp=null;
int responseCode = -1;
try{
URL url = new URL(path);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoInput(true);
con.connect();
responseCode = con.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK)
{
//download the image
in = con.getInputStream();
bmp = BitmapFactory.decodeStream(in);
in.close();
if(bmp!=null)
iv.setImageBitmap(bmp);
}
}
catch(Exception e){
Log.e("Exception",e.printStackTrace());
}
}

Try this .It helped me a lot in parsing image and making my custom adapter.Hope it will also help you.

Related

How to download and show images Asynchronously on a listview with CursorAdapter from bindView method

How to implement downloading images from server and showing them on a listview with Cursor adapter. I am able to download the images from url by executing AsyncTask from the bindView method of the CursorAdapter Class by passing the image url and ImageView in the constructor of the AsyncTask. But the problem is all the rows are getting populated with the same image and when the list is scrolled , the AsyncTask gets executed again for the rows that appear again after scrolling. I know this is a very common issue when downloading and showing images asynchronously in listview from getview (of ArrayAdapter) method as the Imageview reference in not provided to the Asynctask thread properly , all the solutions i found on web for this is provided for ArrayAdapter (using viewHolders or Weakreferences hashmaps etc) but i am not able to find any same work around with bindView method of CursorAdapter. Any help would be greatful.
My code goes here...
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = mLayoutInflater.inflate(R.layout.friend_row, parent, false);
ViewHolder holder = new ViewHolder();
holder.group_name = (TextView) v.findViewById(R.id.textView1);
holder.tvSteps = (TextView) v.findViewById(R.id.textView3);
holder.tvMobile = (TextView) v.findViewById(R.id.textView2);
holder.pic = (ImageView) v.findViewById(R.id.imageViewF1);
holder.mobtv = (TextView) v.findViewById(R.id.textView22);
holder.pbar = (ProgressBar) v.findViewById(R.id.prbar);
v.setTag(holder);
return v;
}
#Override
public void bindView(View v, Context context, Cursor c) {
//String mob = c.getString(c.getColumnIndexOrThrow(FriendsDataProvider.COL_ADMIN_MOB));
String group_name = c.getString(c.getColumnIndexOrThrow(FriendsDataProvider.COL_GROUP_NAME));
String admin_name = c.getString(c.getColumnIndexOrThrow(FriendsDataProvider.COL_ADMIN_NAME));
String image = c.getString(c.getColumnIndexOrThrow(FriendsDataProvider.COL_GROUP_IMAGE));
//int self_admin = c.getInt(c.getColumnIndexOrThrow(FriendsDataProvider.COL_SELF_ADMIN));
//int steps = c.getInt(c.getColumnIndexOrThrow(FriendsDataProvider.COL_STEPS));
//int group_id = c.getInt(c.getColumnIndexOrThrow(FriendsDataProvider.COL_GROUP_ID));
long date = c.getLong(c.getColumnIndexOrThrow(FriendsDataProvider.COL_CREATE_DATE));
/**
* Next set the title of the entry.
*/
holder = (ViewHolder) v.getTag();
/*TextView tvgroup_name = (TextView) v.findViewById(R.id.textView1);
TextView tvsteps_ = (TextView) v.findViewById(R.id.textView3);
TextView tvMobile = (TextView) v.findViewById(R.id.textView2);
ImageView grp_iv = (ImageView) v.findViewById(R.id.imageViewF1);
TextView mobtv = (TextView) v.findViewById(R.id.textView22);
ProgressBar pbar = (ProgressBar) v.findViewById(R.id.prbar);*/
holder.pbar.setVisibility(View.GONE);
holder.mobtv.setText("");
holder.group_name
.setText(Html
.fromHtml("<font color = '#442E5B'></font><font>"
+ group_name+ "</font>"));
SimpleDateFormat dateFormat = new SimpleDateFormat("d/MM/yy");
dateFormat.setTimeZone(Database.tz);
holder.tvSteps.setText("Created On : "+dateFormat.format(date));
holder.tvMobile.setText("Admin : "+admin_name+"\n " );
if(image!=null&&image.length()>0){
new GetImage(context, image, holder.pic, holder.pbar).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}else
holder.pic
.setBackgroundResource(R.drawable.user_add);
}
and the GetImage class as ...
public class GetImage extends AsyncTask<Void, Void, Void> {
private Bitmap bitmap ;
Context ctx;
private final WeakReference<ImageView> viewReference;
String photo_path;
ProgressBar pbar;
public GetImage(Context ctx,String image_path,ImageView iv,ProgressBar pbar) {
super();
this.ctx = ctx;
this.photo_path = image_path;
this.pbar = pbar;
viewReference = new WeakReference<ImageView>(iv);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pbar.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... objects) {
try
{
File file1 = new File(photo_path);
String path1 = file1.getAbsolutePath();
Bitmap bitmap1 = null;
if (path1 != null) {
bitmap1 = Profile.decodeFile(file1, 2);
}
if (bitmap1 != null) {
this.bitmap = bitmap1;
} else
{
Log.i("Profile", "photo text : "+photo_path);
String[] path = photo_path.split("/");
String urll = ctx.getResources().getString(R.string.url);
String image_url = urll+"/uploads/"+path[path.length-1];
Log.i("Profile", "image url : "+image_url);
URL url = new URL(image_url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
// String data1 = String.valueOf(String.format(u.photo));
File miDirs = new File(
Environment.getExternalStorageDirectory() + "/FITGEN/Images");
if (!miDirs.exists())
miDirs.mkdirs();
String imageFilePath = String.format(
Environment.getExternalStorageDirectory() + "/FITGEN/Images/"
+ path[path.length-1]);
File file = new File(imageFilePath);
try {
file.createNewFile();
Log.i("Profile", "File created name : "+file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream stream = new FileOutputStream(file);
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
byte[] byteArray = outstream.toByteArray();
stream.write(byteArray);
stream.close();
ImageView iv = viewReference.get();
iv.setDrawingCacheEnabled(true);
Bitmap screenshot = Bitmap.createBitmap(iv.getDrawingCache());
iv.setDrawingCacheEnabled(false);
Bitmap scaledPicture = Bitmap.createScaledBitmap(myBitmap, screenshot.getWidth(), screenshot.getHeight(), true);
bitmap = scaledPicture;
}
}
catch (Exception e)
{
Log.i("Profile", "error in getimage : "+e.getMessage());//e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void o) {
pbar.setVisibility(View.INVISIBLE);
if(bitmap!=null)
{
ImageView iv = viewReference.get();
bitmap = Statics.getRoundedCornerBitmap(bitmap, 10);
iv.setImageBitmap(bitmap);
}
}
}

Android load image from JSON to HorizontalListView

I've been looking into some answers regarding this matter in here and tried some of it combining with what I currently have in my code. I have some confusions on some parts. So, this are my codes:
MyMainActivity class. Parses json and sets the adapter.
RowItem is a POJO.
HorizontalListView is from dev-smart
.
.
.
HorizontalListView hListView;
List<RowItem> sItems;
public void onCreate(Bundle savedInstanceState){
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = getIntent();
String categoryId = intent.getStringExtra("id");
JSONParser parser = new JSONParser(this);
JSONObject json = parser.getJSONFromAssets("mylist.json");
shopItems = new ArrayList<ShopRowItem>();
try{
shops = json.getJSONArray(LIST_ARR);
for(int i = 0; i < shops.length(); i++){
JSONObject c = jsonArray.getJSONObject(i);
String sName = c.getString(NAME);
String sCatId = c.getString(ID);
String imageUrl = c.getString(IMAGE_URL);
RowItem item = new ShopRowItem(imageUrl, sName, sCatId);
sItems.add(item);
}
}catch(JSONException e){
throw new RuntimeException(e);
}
hListView = (HorizontalListView) findViewById(R.id.hlist_view);
ShopBaseAdapter adapter = new ShopBaseAdapter(this, sItems);
hListView.setAdapter(adapter);
Then, my CustomAdapter class extends to BaseAdapter.
.
.
.
Context context;
List<RowItem> rowItems;
private class ViewHolder{
ImageView imageView;
TextView txtName;
TextView txtId;
}
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder = null;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if(convertView == null){
convertView = inflater.inflate(R.layout.shop_list_layout, null);
holder = new ViewHolder();
holder.txtShopName = (TextView) convertView.findViewById(R.id.name);
holder.txtCatId = (TextView) convertView.findViewById(R.id.cat_id);
holder.imageView = (ImageView) convertView.findViewById(R.id.prof_pic);
holder.imageView.getLayoutParams().height = 120;
holder.imageView.getLayoutParams().width = 120;
holder.imageView.setPadding(5, 5, 5, 5);
holder.imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
RowItem sItem = (RowItem) getItem(position);
holder.txtShopName.setText(sItem.getName());
holder.txtCatId.setText(sItem.getCatId());
try{
**// I dont know what to do here
holder.imageView.setImageBitmap( ? ? ? ?)**
}catch(Exception e){
}
return convertView;
}
Then I have MyImageLoader class extends AsyncTask.
public class ShopImageLoader extends AsyncTask<Object, String, Bitmap>{
.
.
.
**protected Bitmap doInBackground(Object... params){
//how to get the url from other class? ?
//then loadBitmap(url);
// then set it for dispaly
//i'm really confuse on what to do here.
return bitmap; ??
}**
public static Bitmap loadBitmap(String url){
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try{
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
}catch(IOException e){
Log.e(TAG, "Could not load Bitmap from: "+ url);
}finally{
closeStream(in);
closeStream(out);
}
return bitmap;
}
private static void closeStream(Closeable stream){
if(stream != null){
try{
stream.close();
}catch(IOException e){
android.util.Log.e(TAG, "Could not close stream", e);
}
}
}
private static void copy(InputStream in, BufferedOutputStream out) throws IOException {
byte[] byt = new byte[IO_BUFFER_SIZE];
int read;
while((read = in.read(byt)) != -1){
out.write(byt, 0, read);
}
}
Well, this tutorial actually helped solve my problem.

i have one error passing of constructor as this in listfragments

I am newer to the fragments. In oncreate method i pass this value to Appetizerlist. but it shows an error. How to clear the error? Please help me.
public class MyListFragment1 extends ListFragment {
ImageView back;
String url = Main.url;
String Qrimage;
Bitmap bmp;
ListView list;
AppetiserFragment adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.applistviewfragment, null);
list = (ListView) view.findViewById(R.id.list);
return view;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
InputStream is = null;
String result = "";
JSONObject jArray = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url + "test.php3");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
// TODO: handle exception
Log.e("Log", "Error in Connection" + e.toString());
// Intent intent = new Intent(ViewQRCode.this, PimCarder.class);
// startActivity(intent);
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
jArray = new JSONObject(result);
JSONArray json = jArray.getJSONArray("appetiser");
adapter = new AppetiserFragment(this, json);
list.setAdapter(adapter);
} catch (Exception e) {
// TODO: handle exception
Log.e("log", "Error in Passing data" + e.toString());
}
}
}
AppetiserFragment.java
public class AppetiserFragment extends BaseAdapter {
String url = Main.url;
public Context Context;
String qrimage;
Bitmap bmp, resizedbitmap;
Bitmap[] bmps;
Activity activity = null;
private LayoutInflater inflater;
private ImageView[] mImages;
String[] itemimage;
TextView[] tv;
String itemname, price, desc, itemno;
String[] itemnames, checkeditems, itemnos;
String[] prices;
String[] descs;
HashMap<String, String> map = new HashMap<String, String>();
public AppetiserFragment(Context context, JSONArray imageArrayJson) {
Context = context;
// inflater =
System.out.println(imageArrayJson);
// (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(activity);
inflater = LayoutInflater.from(context);
this.mImages = new ImageView[imageArrayJson.length()];
this.bmps = new Bitmap[imageArrayJson.length()];
this.itemnames = new String[imageArrayJson.length()];
this.prices = new String[imageArrayJson.length()];
this.descs = new String[imageArrayJson.length()];
this.itemnos = new String[imageArrayJson.length()];
try {
for (int i = 0; i < imageArrayJson.length(); i++) {
JSONObject image = imageArrayJson.getJSONObject(i);
qrimage = image.getString("itemimage");
itemname = image.getString("itemname");
itemno = new Integer(i + 1).toString();
price = image.getString("price");
desc = image.getString("itemdesc");
System.out.println(price);
itemnames[i] = itemname;
prices[i] = price;
descs[i] = desc;
itemnos[i] = itemno;
byte[] qrimageBytes = Base64.decode(qrimage.getBytes());
bmp = BitmapFactory.decodeByteArray(qrimageBytes, 0,
qrimageBytes.length);
int width = 100;
int height = 100;
resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height,
true);
bmps[i] = bmp;
mImages[i] = new ImageView(context);
mImages[i].setImageBitmap(resizedbitmap);
mImages[i].setScaleType(ImageView.ScaleType.FIT_START);
// tv[i].setText(itemname);
}
System.out.println(map);
} catch (Exception e) {
// TODO: handle exception
}
}
public AppetiserFragment() {
// TODO Auto-generated constructor stub
}
public int getCount() {
return mImages.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder viewHolder;
if (view == null) {
view = inflater.inflate(R.layout.appetiserlistview, null);
System.out.println("prakash");
viewHolder = new ViewHolder();
viewHolder.image = (ImageView) view
.findViewById(R.id.appetiserimage);
viewHolder.text = (TextView) view.findViewById(R.id.appetisertext);
viewHolder.desc = (TextView) view.findViewById(R.id.appetiserdesc);
viewHolder.price = (TextView) view
.findViewById(R.id.appetiserprice);
viewHolder.appitemnum = (TextView) view
.findViewById(R.id.appitemno);
// viewHolder.checkbox = (CheckBox) view.findViewById(R.id.bcheck);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.image.setImageBitmap(bmps[position]);
viewHolder.appitemnum.setText(itemnos[position]);
viewHolder.price.setText(prices[position]);
viewHolder.desc.setText(descs[position]);
// viewHolder.checkbox.setTag(itemnames[position]);
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(itemnames[position]);
return view;
}
static class ViewHolder {
protected TextView text, price, desc, appitemnum;
protected ImageView image;
public static CheckBox checkbox = null;
}
}
i Given whole code i want custom listview using listfragments
In the above code in this line, I'm getting an error at adapter = new Appetizerlist(this, json); Please tell me how to solve the problem. Help me.
as onCreate called before onCreateView so list will null there in onCreate ...........
http://developer.android.com/guide/topics/fundamentals/fragments.html
in oncreate
list.setAdapter(adapter);
in onCreateView you initlized that
list = (ListView) view.findViewById(R.id.list);
......
so move this line list.setAdapter(adapter); in onCreateView
You have error in following line.
adapter = new Appetizerlist(this, json);
Change it to
adapter = new Appetizerlist(getActivity().getApplicationContext(), json);

How to display the custom listview using base adapter in listfragments?

I want do custom listview using base adapter in listfragment
I try this code:
public class MyListFragment1 extends ListFragment {
ImageView back;
String url = Main.url;
String Qrimage;
Bitmap bmp;
ListView list;
AppetiserFragment adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View tmp_view = inflater.inflate(R.layout.applistviewfragment, container, false);
ListView list = (ListView) tmp_view.findViewById(R.id.list);
InputStream is = null;
String result = "";
JSONObject jArray = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url + "test.php3");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
// TODO: handle exception
Log.e("Log", "Error in Connection" + e.toString());
// Intent intent = new Intent(ViewQRCode.this, PimCarder.class);
// startActivity(intent);
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
jArray = new JSONObject(result);
JSONArray json = jArray.getJSONArray("appetiser");
adapter = new AppetiserFragment(getActivity(), json);
list.setAdapter(adapter);
} catch (Exception e) {
// TODO: handle exception
Log.e("log", "Error in Passing data" + e.toString());
}
return tmp_view;
}
}
AppetiserFragment.java
public class AppetiserFragment extends BaseAdapter {
public static ArrayList<String> arr = new ArrayList<String>();
public static ArrayList<String> itemprice = new ArrayList<String>();
public static ArrayList<Bitmap> image = new ArrayList<Bitmap>();
String url = Main.url;
public Context Context;
String qrimage;
Bitmap bmp, resizedbitmap;
Bitmap[] bmps;
Activity activity = null;
private LayoutInflater inflater;
private ImageView[] mImages;
String[] itemimage;
TextView[] tv;
String itemname, price, desc, itemno;
String[] itemnames, checkeditems, itemnos;
String[] prices;
String[] descs;
HashMap<String, String> map = new HashMap<String, String>();
public AppetiserFragment(Context context, JSONArray imageArrayJson) {
Context = context;
// inflater =
System.out.println(imageArrayJson);
// (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(activity);
inflater = LayoutInflater.from(context);
this.mImages = new ImageView[imageArrayJson.length()];
this.bmps = new Bitmap[imageArrayJson.length()];
this.itemnames = new String[imageArrayJson.length()];
this.prices = new String[imageArrayJson.length()];
this.descs = new String[imageArrayJson.length()];
this.itemnos = new String[imageArrayJson.length()];
try {
for (int i = 0; i < imageArrayJson.length(); i++) {
JSONObject image = imageArrayJson.getJSONObject(i);
qrimage = image.getString("itemimage");
itemname = image.getString("itemname");
itemno = new Integer(i + 1).toString();
price = image.getString("price");
desc = image.getString("itemdesc");
**System.out.println(price);**
itemnames[i] = itemname;
prices[i] = price;
descs[i] = desc;
itemnos[i] = itemno;
byte[] qrimageBytes = Base64.decode(qrimage.getBytes());
bmp = BitmapFactory.decodeByteArray(qrimageBytes, 0,
qrimageBytes.length);
int width = 100;
int height = 100;
resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height,
true);
bmps[i] = bmp;
mImages[i] = new ImageView(context);
mImages[i].setImageBitmap(resizedbitmap);
mImages[i].setScaleType(ImageView.ScaleType.FIT_START);
// tv[i].setText(itemname);
}
System.out.println(map);
} catch (Exception e) {
// TODO: handle exception
}
}
public AppetiserFragment() {
// TODO Auto-generated constructor stub
}
public int getCount() {
return mImages.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder viewHolder;
if (view == null) {
view = inflater.inflate(R.layout.appetiserlistview, null);
viewHolder = new ViewHolder();
viewHolder.image = (ImageView) view
.findViewById(R.id.appetiserimage);
viewHolder.text = (TextView) view.findViewById(R.id.appetisertext);
viewHolder.desc = (TextView) view.findViewById(R.id.appetiserdesc);
viewHolder.price = (TextView) view
.findViewById(R.id.appetiserprice);
viewHolder.appitemnum = (TextView) view
.findViewById(R.id.appitemno);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.image.setImageBitmap(bmps[position]);
viewHolder.appitemnum.setText(itemnos[position]);
viewHolder.price.setText(prices[position]);
viewHolder.desc.setText(descs[position]);
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(itemnames[position]);
return view;
}
static class ViewHolder {
protected TextView text, price, desc, appitemnum;
protected ImageView image;
public static CheckBox checkbox = null;
}
}
I can able to print price value. If I do separately as custom listview I can able to image, text, desc, price. But in MyFragmentlist1 extends with listfragment means I cannot able to view in custom listview. I thought MyListFragment1 in this class only I have problem.
First Create a separate layout layout_txtview. I am just using a textview. You can create layout according to items you want to show in a single row.
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="#000000"
android:textAppearance="?android:attr/textAppearanceSmall" />
Now Use this layout to inflate in getView() method of your custom adapter.
Now in onCreate() method of MyListFragment1 class just set the adapter to your custom adapter
setAdapter(new MyListFragment1 (<apss your constructor argument>));
and its done.
Try moving the setAdapter in the onActivityCreated callback, in this way
#Override
public void onActivityCreated(Bundle savedInstanceState) {
ListView list = getListView();
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}

How to load ImageURL into Bitmap and to add it to ViewPager Collection in android

i followed this URL http://android-developers.blogspot.in/2011/08/horizontal-view-swiping-with-viewpager.html
here it works with Textview.
TextView tv = new TextView(cxt);
tv.setText("Bonjour PAUG " + position);
tv.setTextColor(Color.WHITE);
tv.setTextSize(30);
((ViewPager) collection).addView(tv,0);
return tv;
..............................................................
But i have set of imageURLs and then i need to load it to Bitmap and then i need to add this to ViewPager.....ANY IDEAS!!!
public Object instantiateItem(View collection, int position)
{
LayoutInflater inflater = (LayoutInflater) collection.getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
try
{
String saveimg= urls[position];
String url1 = saveimg ;
URL ulrn = new URL(url1);
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
InputStream is = con.getInputStream();
Bitmap bmp = BitmapFactory.decodeStream(is);
if (null != bmp)
{
ImageView Imgview=new ImageView(cxt);
Imgview.setImageBitmap(bmp);
((ViewPager) collection).addView(Imgview, 0);
int i=0;
return Imgview;
}
else
System.out.println("The Bitmap is NULL");
}
catch(Exception e)
{
int i=0;
}
Strongly suggest UniversalImageLoader

Categories

Resources