show selected listview row image to next activity - android

I am able to send selected listview text to another activity using xml parsing, but not able to fetch selected image to next activity, here I am placing my code, please find out the reason why I am not getting image to another activity:-
MainActivity Code:-
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = pizzaList.get(position);
Intent in = new Intent(MainActivity.this, SecondActivity.class);
in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
in.putExtra(KEY_DESCRIPTION, map.get(KEY_DESCRIPTION));
in.putExtra(KEY_THUMB_URL, map.get(KEY_THUMB_URL));
in.putExtra(KEY_COST, map.get(KEY_COST));
startActivity(in);
}
});
SecondActivity Code:-
Intent in = getIntent();
final String title = in.getStringExtra(KEY_TITLE);
final String description = in.getStringExtra(KEY_DESCRIPTION);
final String thumb_url = in.getStringExtra(KEY_THUMBURL);
final String cost = in.getStringExtra(KEY_COST);
TextView title = (TextView) findViewById(R.id.single_title);
TextView description = (TextView) findViewById(R.id.single_description);
TextView cost = (TextView) findViewById(R.id.single_cost);
ImageLoader imageLoader = new ImageLoader(getApplicationContext());
ImageView thumb = (ImageView) findViewById(R.id.single_image);
title.setText(title);
description.setText(description);
cost.setText(cost);
imageLoader.DisplayImage(thumb_url, thumb);

I think your KEY_THUMB_URL is your url just call this method in your second Activity this is return a bitmap then this bitmap set you on your image view
public static Bitmap loadBitmap(String imgPath) {
String imgUrlStr = imgPath ;
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(imgUrlStr).getContent());
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}

final String title = in.getStringExtra(KEY_TITLE);
final String description = in.getStringExtra(KEY_DESCRIPTION);
final String thumb_url = in.getStringExtra(KEY_THUMBURL);
log.i("log_tag","Image URl:"+thumb_url);
final String cost = in.getStringExtra(KEY_COST);
TextView title = (TextView) findViewById(R.id.single_title);
TextView description = (TextView) findViewById(R.id.single_description);
TextView cost = (TextView) findViewById(R.id.single_cost);
ImageView thumb = (ImageView) findViewById(R.id.single_image);
title.setText(title);
description.setText(description);
cost.setText(cost);
Drawable d = LoadImageFromWebOperations(ImageUrl);
imageView.setImageDrawable(d);
public static Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}

I found the reason why I was not getting an image into next activity.
I did very small mistake, see line below, which I was using earlier :
final String thumb_url = in.getStringExtra(KEY_THUMBURL);
And now I have tried with:
final String imageUri = in.getStringExtra(KEY_THUMBURL);
Because I am using this variable:
static final String KEY_THUMBURL = "imageUri";

Related

how use two getIntent in activity?

I need to get data from two activity by get intent but is not work.
this activiy1:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long viewId) {
TextView idTextView = (TextView) view.findViewById(R.id.id);
TextView titleTextView = (TextView) view.findViewById(R.id.title);
TextView descTextView = (TextView) view.findViewById(R.id.desc);
String id = idTextView.getText().toString();
String title = titleTextView.getText().toString();
String desc = descTextView.getText().toString();
Intent modify_intent = new Intent(getApplicationContext(), ShowDat.class);
modify_intent.putExtra("title1", title);
modify_intent.putExtra("desc1", desc);
modify_intent.putExtra("id1", id);
startActivity(modify_intent);
}
});
and this activity2:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long viewId) {
TextView idTextView = (TextView) view.findViewById(R.id.id);
TextView titleTextView = (TextView) view.findViewById(R.id.title);
TextView descTextView = (TextView) view.findViewById(R.id.desc);
String id = idTextView.getText().toString();
String title = titleTextView.getText().toString();
String desc = descTextView.getText().toString();
Intent modify_intent = new Intent(getApplicationContext(), ShowDat.class);
modify_intent.putExtra("title2", title);
modify_intent.putExtra("desc2", desc);
modify_intent.putExtra("id2", id);
startActivity(modify_intent);
}
});
and this activity than receive data:
TextView idTextView = (TextView) findViewById(R.id.id);
TextView titleTextView = (TextView) findViewById(R.id.title);
TextView descTextView = (TextView) findViewById(R.id.desc);
Intent intent = getIntent();
if(intent != null) {
intent = getIntent();
String id = intent.getStringExtra("id1");
String name = intent.getStringExtra("title1");
String desc = intent.getStringExtra("desc1");
try {
_id = Long.parseLong(id);
} catch (NumberFormatException e) {
_id = 0; // your default value
}
idTextView.setText(id);
titleTextView.setText(name);
descTextView.setText(desc);
}
else {
intent = getIntent();
String id = intent.getStringExtra("id2");
String name = intent.getStringExtra("title2");
String desc = intent.getStringExtra("desc2");
try {
_id = Long.parseLong(id);
} catch (NumberFormatException e) {
_id = 0; // your default value
}
idTextView.setText(id);
titleTextView.setText(name);
descTextView.setText(desc);
}
i try to use this code but like above code, just on put extra receive and other not work:
TextView idTextView = (TextView) findViewById(R.id.id);
TextView titleTextView = (TextView) findViewById(R.id.title);
TextView descTextView = (TextView) findViewById(R.id.desc);
Intent intent = getIntent();
if(getIntent() !=null) {
String id = intent.getStringExtra("id1");
String name = intent.getStringExtra("title1");
String desc = intent.getStringExtra("desc1");
try {
_id = Long.parseLong(id);
} catch (NumberFormatException e) {
_id = 0; // your default value
}
idTextView.setText(id);
titleTextView.setText(name);
descTextView.setText(desc);
}
else {
String id = intent.getStringExtra("id2");
String name = intent.getStringExtra("title2");
String desc = intent.getStringExtra("desc2");
try {
_id = Long.parseLong(id);
} catch (NumberFormatException e) {
_id = 0; // your default value
}
idTextView.setText(id);
titleTextView.setText(name);
descTextView.setText(desc);
}
please help.
first you need to check like this
if(getIntent().hasExtra("key_1"))
{
String data = getIntent().getString("key_1");
}
else if(getIntent().hasExtra("key_2"))
{
String msg = getIntent().getString("key_2");
}
......
You can do that with two way.
1)if(getIntent().hasExtra("your_key")) and
2) use same key in two activities for passing data
like modify_intent.putExtra("same_key", title);

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);
}
}
}

Implementing Picasso not loading image

After I decided to implement Universal Image Loader, because I had implemented a method that convert URL to Drawable, but since I don't know how many images it will return my SQLite query I decided to implement an Image Loader...
The thing is I'm stuck at the moment, cause I thought I did all what the GitHub say but at the time I load the Image it stays white and never loads.
On my Adapter class I've changed the line of the drawable as :
Picasso.with(context)
.load(Uri.parse(String.valueOf(item.icon)))
.resize(180, 180)
.placeholder(R.drawable.ic_launcher).into(viewHolder.ivIcon);
It works, beucase it shows yo me the ic_launcher icon... but never changes to the real image.
On my class where I fetch the data I have this (on my OnCreate()) :
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new MyAsyncTask().execute();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// progress.dismiss();
}
});
}
}).start();
}
Then I created an inner class where I fetch the data into my ListView... but it doesn't works. I don't know If I've to delte those methods since I've changed it to Picasso.
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
Conexion = new MarketSQLite(getActivity(), "market", null, 1);
mItems = new ArrayList<ListViewItem>();
db = Conexion.getReadableDatabase();
Cursor c;
c = db.rawQuery("Select NOM_OFER,PREU_OFERTA,DATA_F,FOTO,PERCENTDESCOMPTE from T_OFERTA", null);
c.moveToFirst();
if (c != null) {
do {
for (int i = 0; i < c.getColumnCount(); i++) {
Title = c.getString((c.getColumnIndex("NOM_OFER")));
Preu = c.getColumnIndex("PREU_OFERTA");
percent = c.getString((c.getColumnIndex("PERCENTDESCOMPTE")));
data_f = c.getString((c.getColumnIndex("DATA_F")));
URLTest = c.getString((c.getColumnIndex("FOTO")));
FOTO = Imagehandler(URLTest);
Log.e("", "" + c.getString(i));
// initialize and set the list adapter
// Toast.makeText(getActivity(), "Title" + Title + "Preu" + Preu + "Percent" + percent + "Cheese is " + data_f, Toast.LENGTH_LONG).show();
}
mItems.add(new ListViewItem(FOTO, Title, Preu.toString(), percent, data_f));
}while (c.moveToNext());
}
c.close();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
myAdapter = new ListViewDemoAdapter(getActivity(), mItems);
setListAdapter(myAdapter);
}
}
Where ImageHandler is a method that I've created before this is :
protected Drawable Imagehandler(String url) {
try {
url=url.replaceAll(" ", "%20");
InputStream is = (InputStream)this.fetch(url);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e)
{
System.out.println(url);
System.out.println("error at URI"+e);
return null;
}
catch (IOException e)
{
System.out.println("io exception: "+e);
System.out.println("Image NOT FOUND");
return null;
}
}
protected Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
I don't know why isn't the image loading on my ListView if it shows all of the rest of data...
Instead of Drawable, try to get url string in your adapter like
Change From
public ListViewItem(Drawable icon, String title, String precio, String descuento, String date) {
this.icon = icon;
this.title = title;
this.precio = precio;
this.descuento = descuento;
this.date = date;
}
To
public ListViewItem(String icon_url, String title, String precio, String descuento, String date) {
this.icon_url = icon_url;
this.title = title;
this.precio = precio;
this.descuento = descuento;
this.date = date;
}
and use Picasso where you are loading your imageview like this -
Picasso.with(context)
.load(icon_url))
.resize(180, 180)
.placeholder(R.drawable.ic_launcher).into(viewHolder.ivIcon);
1) Your ListViewItem class should be like this -
public class ListViewItem {
public final String icon; // the drawable for the ListView item ImageView
public final String title; // the text for the ListView item title
public final String precio; // the price for the ListView item
public final String descuento; // the price for the discount for the ListView item
public final String date; //the date for the sale for the ListView item
// the text for the ListView item description
public ListViewItem(String icon_url, String title, String precio, String descuento, String date) {
this.icon = icon_url;
this.title = title;
this.precio = precio;
this.descuento = descuento;
this.date = date;
}
}
2) ListViewDemoAdapterClass
public class ListViewDemoAdapter extends ArrayAdapter<ListViewItem> {
Context context;
public ListViewDemoAdapter(Context context, List<ListViewItem> items) {
super(context, R.layout.listview_item, items);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null) {
// inflate the GridView item layout
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.listview_item, parent, false);
// initialize the view holder
viewHolder = new ViewHolder();
viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
viewHolder.tvPrice = (TextView) convertView.findViewById(R.id.tvPrice);
viewHolder.tvDiscount = (TextView) convertView.findViewById(R.id.tvDiscount);
viewHolder.tvDate = (TextView) convertView.findViewById(R.id.tvDatas);
convertView.setTag(viewHolder);
} else {
// recycle the already inflated view
viewHolder = (ViewHolder) convertView.getTag();
}
// update the item view
ListViewItem item = getItem(position);
Picasso.with(context)
.load(item.icon)
.resize(180, 180)
.placeholder(R.drawable.ic_launcher).into(viewHolder.ivIcon);
viewHolder.tvTitle.setText(item.title);
viewHolder.tvDiscount.setText(item.descuento);
viewHolder.tvPrice.setText(item.precio);
viewHolder.tvDate.setText(item.date);
return convertView;
}
private static class ViewHolder {
ImageView ivIcon;
TextView tvTitle;
TextView tvDiscount;
TextView tvPrice;
TextView tvDate;
}
}
ListFragment code, just add this
Cursor c;
c = db.rawQuery("Select
NOM_OFER,PREU_OFERTA,DATA_F,FOTO,PERCENTDESCOMPTE from T_OFERTA", null);
c.moveToFirst();
if (c != null) {
do {
for (int i = 0; i < c.getColumnCount(); i++) {
Title = c.getString((c.getColumnIndex("NOM_OFER")));
Preu = c.getColumnIndex("PREU_OFERTA");
percent = c.getString((c.getColumnIndex("PERCENTDESCOMPTE")));
data_f = c.getString((c.getColumnIndex("DATA_F")));
URLTest = c.getString((c.getColumnIndex("FOTO")));
Hope this helps :)
you just need to add your picasso code snippet as the following in your ImageHandler method and nothing else-
Picasso.with(context)
.load(url))
.resize(180, 180)
.placeholder(R.drawable.ic_launcher).into(your_imageview);
you don't need to download the image or make the bitmap or convert that into drawable to load from url. hope this helps you.

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.

How to send listview item image from one activity to another using xml parser

I have made an app in which I am retrieving data from weburl using xmlparsing in a listview (with image and few text fields) and I wrote code for onItemClick and values displays to another activity, but I am not able to send image from one activity to another, but sending text data by using listview item.
Can someone guide me and write some code, with little bit of description also?
Here is some of my code:
MainActivity Code:
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById
(R.id.title)).getText().toString();
String artist = ((TextView) view.findViewById
(R.id.artist)).getText().toString();
String duration = ((TextView) view.findViewById
(R.id.duration)).getText().toString();
String image=((ImageView)view.findViewById
(R.id.list_image)).getImageMatrix().toString();
//byte[] array=null;
//Bitmap bMap = BitmapFactory.decodeByteArray
// (array, 0, array.length);
// Starting new intent
Intent in = new Intent
(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, title);
in.putExtra(KEY_ARTIST, artist);
in.putExtra(KEY_DURATION, duration);
in.putExtra(KEY_THUMB_URL, image);
startActivity(in);
}
});
}
}
SingleMenuItemActivity Code:-
public class SingleMenuItemActivity extends Activity {
// XML node keys
private static final String KEY_TITLE = "title";
private static final String KEY_ARTIST = "artist";
private static final String KEY_DURATION = "duration";
private static final String KEY_THUMB_URL = "thumb_url";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent
String title = in.getStringExtra(KEY_TITLE);
String artist = in.getStringExtra(KEY_ARTIST);
String duration = in.getStringExtra(KEY_DURATION);
String image = in.getStringExtra(KEY_THUMB_URL);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.email_label);
TextView lblDesc = (TextView) findViewById(R.id.mobile_label);
ImageView lblImage = (ImageView) findViewById(R.id.image_label);
lblName.setText(title);
lblCost.setText(artist);
lblDesc.setText(duration);
//Getting error in below line
//the method setImageResource(int) is the type
//Image View is not applicable for the argument(string)
lblImage.setImageResource(image);//(R.drawable.rihanna);
}
}
Convert this image to bitmap and pass it as bundle using Intent.putExtra() to the next activity.
You don't have to pass the image through Bundle, instead pass the image path as String data, and in each activity, wherever you require image, create image from that image path.
in.putExtra(KEY_IMAGE, image);
where image is byte[] ..Any image can be converted to a bytearray..
and while retieving
Bitmap bMap = BitmapFactory.decodeByteArray(array, 0, array.length);
`

Categories

Resources