GridView Image (from URL) to Second Activity by using Intent - android

First of all im giving the codes what i'm using currently
MainActivity
static final String URL = "http://my .com/images/rss.xml";
static final String KEY_TITLE = "item";
static final String KEY_THUMB_URL = "thumb_url";
// Click event for single list row
gridView.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("unchecked")
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map2 = (HashMap<String, String>) parent.getItemAtPosition(position);
Intent in = new Intent(getApplicationContext(), FullSize.class);
Bitmap b; // your bitmap
in.putExtra(KEY_TITLE, map2.get(KEY_TITLE));
in.putExtra(KEY_THUMB_URL, KEY_THUMB_URL);
startActivity(in);
}
});
2nd Activity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fullsize);
ImageView image = (ImageView) findViewById(R.id.fullsizeimg2);
TextView txtName = (TextView) findViewById(R.id.txt1);
Intent in = getIntent();
// Receiving the Data
String name = in.getStringExtra("item");
Bitmap bitmap =(Bitmap) in.getParcelableExtra("thumb_url");
// Displaying Received data
txtName.setText(name);
image.setImageBitmap(bitmap);
}
}
in this case, if i use the codes as above , the title works , i can see the text in txt but i cannot get img. i think i need to convert it to bitmap but also it didnt work for me. for converting bitmap i used this
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),"Image ID");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
////////for intent /////
intent.putExtra("imagepass", bytes.toByteArray());
/////////2nd activity//////////
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("imagepass");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView iv=(ImageView) findViewById(R.id.fullsizeimg);
iv.setImageBitmap(bmp);
but in main activity after decoderesource line, it was giving this error :
The method decodeResource(Resources, int) in the type BitmapFactory is not applicable for the arguments (Resources, String)
I will be very happy if you can help.

You are using String as the second parameter in BitmapFactory.decodeResource()
But according to your code the Bitmap creation should be like this
Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.yourImageId);

Related

cannot resolve putextra method

i'm trying to send an image from an arraylist one activity to another through intent in recyclerView. But in putextra method it shows error like cannot resolve method 'putextra(java.lang.string,android.widget.imageview)'
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ImageView img = images.get(position);
Intent intent = new Intent(context,Result.class);
intent.putExtra("Image",img);
context.startActivity(intent);
}
});
You cannot pass an ImageViewas an extra, the object you are passing must be a Parcelable or a Serialiazable.
Your ImageView is also relevant for this activity only. If you are trying to send an Image to another activity, it is better to send the path to the image.
You cannot send image directly because intent does not support it
Try this Solution
You can send image using ByteArray though eg
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ImageView img = images.get(position);
img.buildDrawingCache();
Bitmap bmp = ((BitmapDrawable)img.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Intent intent = new Intent(this, Result.class);
intent.putExtra("Image", byteArray);
context.startActivity(intent);
}
});
in onCreate() of Result Activity class
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("Image");
//convert it to bitmap again
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.imageView1);
//set image to bitmap
image.setImageBitmap(bmp);
SOURCE
Passing image from one activity another activity
At the end of the day finally i did it, you simply create an array of images(NOTE: don't create arrayList) in case u want to choose between multiple images and simply pass these images through an integer. below is the code...
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.image.setImageResource(images[position]);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int img = images[position];
Intent intent = new Intent(context,Result.class);
intent.putExtra("Images", img);
intent.putExtra("personName", Name);
intent.putExtra("Gender", Gender);
context.startActivity(intent);
}
});
}
//In targeted activity
public void getdata(){
if (getIntent().getExtras() !=null) {
gender = getIntent().getStringExtra("Gender");
Name = getIntent().getStringExtra("personName");
int image = getIntent().getIntExtra("Images",0);
mytext(gender,Name,image);
}
}
public void mytext(String gender,String Name,int img){
textView1 = findViewById(R.id.txt1);
textView2 =findViewById(R.id.txt2);
imageView = findViewById(R.id.Imagename);
textView1.setText(Name);
textView2.setText(gender);
imageView.setImageResource(img);
}
//then in onCreate method call "getdata();"

Can't store image from SQLite to ImageView

i have this annoying problem.Im trying to store image from drawable folder to database then retrieve it and set it in ImageView, but when i try to store it in the ImageView and run it its not changed from the default image that i put in first place, the ImageView is gone.
Here is the code for the activity where the ImageView is and the code for the DB handler. MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView img = (ImageView) findViewById(R.id.maintestImage);
images();
img.setImageBitmap(dbHandler.getImageDiet());
initNewProf();
initExercises();
}
public void images(){ //get the image from the drawable and store it in the base
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.abs)).getBitmap();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] photo = baos.toByteArray();
dbHandler.saveDiet(photo);
}` DB handler
public Bitmap getImageDiet(){ //retrive the image from the base
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.rawQuery("SELECT imagedata FROM "+ TABLE_DIET, null);
byte[] photo = hexStringToByteArray("e04fd020ea3a6910a2d808002b30309d");
while(c.moveToNext())
{
photo=c.getBlob(3);
}
ByteArrayInputStream imageStream = new ByteArrayInputStream(photo);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
imgView.setImageBitmap(theImage);
}

Android: How to convert ImageView to Bitmap and pass to another activity?

I am making a meme generator app for my android course. I've gotten an API to generate 100 popular memes, when one is clicked it takes you to the EditMemeActivity, where you can type in the upper and lower text. Then, there is a Create Meme button that will take you to the MemeActivity where you will eventually be able to save/share with friends. Currently, when the create meme button is clicked, the meme picture is converted to a Bitmap, and that displays fine on the next page. I want to be able to save the upper and lower text entered by the user on the image as a Bitmap. Because some meme images vary in size, I have a black background around them set to about 400X300 pixels, so I would love to be able to capture that entire imageview AND set put the inputted text in. Here's my code from the two activities:
public class EditMemeActivity extends AppCompatActivity {
#Bind(R.id.editMemeImage) ImageView mEditMemeImage;
#Bind(R.id.editUpperText) EditText mEditUpperText;
#Bind(R.id.editLowerText) EditText mEditLowerText;
#Bind(R.id.saveMeme) Button mSaveMeme;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_meme);
ButterKnife.bind(this);
Intent intent = getIntent();
String image = intent.getStringExtra("image");
final String upper = mEditUpperText.getText().toString();
final String lower = mEditLowerText.getText().toString();
final Bitmap memeBitmap = getBitmapFromURL(image);
Picasso.with(EditMemeActivity.this).load(image).into(mEditMemeImage);
mSaveMeme.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(EditMemeActivity.this, MemeActivity.class);
intent.putExtra("bitmap", memeBitmap);
intent.putExtra("upper", upper);
intent.putExtra("lower", lower);
startActivity(intent);
}
});
}
public static Bitmap getBitmapFromURL(String image) {
try {
URL url = new URL(image);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
public class MemeActivity extends AppCompatActivity {
#Bind(R.id.memeImageView) ImageView mMemeImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meme);
ButterKnife.bind(this);
Intent intent = getIntent();
String upperText = intent.getStringExtra("upper");
String lowerText = intent.getStringExtra("lower");
byte[] byteArray = getIntent().getByteArrayExtra("bitmap");
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
mMemeImageView.setImageBitmap(bitmap);
}
}
code to get bitmap from imageView
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
Bitmap implements Parcelable, so you could always pass it in the intent:
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("key", bitmap);
getting the bitmap in another activity
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("key");
try this
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putParcelable("bitmap",bitmap);
intent.putExtras(bundle);
You can use my code to convert image to Bitmap
public static Bitmap drawableToBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
int width = drawable.getIntrinsicWidth();
width = width > 0 ? width : 1;
int height = drawable.getIntrinsicHeight();
height = height > 0 ? height : 1;
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
And pass bitmap to another activity Link
Note : careful with large bitmap it
can cause errors
Solution :
Save image into SDCard and in next activity set this image into ImageView.
...

Converting image to string using the Base64 algorithm

I am new to android. I am trying to capture the image and store it in firebase. Since we need to convert the image to string and then store it in firebase, I am using the base64 algorithm.
The methods for capturing image and storing it in the database is :
public void capturePhoto(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(photo);
}
}
public void storeDatabase(View v)
{
EditText editRollno = (EditText) findViewById(R.id.rollno);
EditText editname = (EditText) findViewById(R.id.name);
EditText editmarks = (EditText) findViewById(R.id.marks);
Firebase ref1 = ref.child("student_information").child("Student" + n);
ref1.child("Name").setValue(editname.getText().toString());
ref1.child("Rollno").setValue(editRollno.getText().toString());
ref1.child("Marks").setValue(editmarks.getText().toString());
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.abc);//your image
ByteArrayOutputStream bYtE = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, bYtE);
bmp.recycle();
byte[] byteArray = bYtE.toByteArray();
imageFile = Base64.encodeToString(byteArray, Base64.DEFAULT);
ref1.child("Image").setValue(imageFile);
n++;
}
When I click on the submit button, it takes a lot of time to upload the values. Moreover, many a times I can see the line
Skipped 537 frames! The application may be doing too much work on its main thread.
in the Android Monitor.
If I comment the image processing lines, it is working all fine.
Can somebody please tell me how to avoid such error so that the image is uploaded instantly in my database.
For storing it to the database, I would definitely use AsyncTask for this one. So, what you could have is a separate class that does the following:
private class ImageDBManager extends AsyncTask< String, Integer, Void> {
protected Long doInBackground(String... items) {
int count = items.length;
String editRoll = items[0];
String editName = items[1];
String editMarks = items[2];
Firebase ref1 = ref.child("student_information").child("Student" + n);
ref1.child("Name").setValue(editname.getText().toString());
ref1.child("Rollno").setValue(editRoll);
ref1.child("Marks").setValue(editName);
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.abc);//your image
ByteArrayOutputStream bYtE = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, bYtE);
bmp.recycle();
byte[] byteArray = bYtE.toByteArray();
imageFile = Base64.encodeToString(byteArray, Base64.DEFAULT);
ref1.child("Image").setValue(imageFile);
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(){
}
}
And then call it like this:
public void storeDatabase(View v) {
ImageDBManager manager = new ImageDBManager();
EditText editRollno = (EditText) findViewById(R.id.rollno);
EditText editname = (EditText) findViewById(R.id.name);
EditText editmarks = (EditText) findViewById(R.id.marks);
manager.execute(new String[] { editRollno.getText(), editname.getText(), editmarks.getText() }
}
If you are capturing the image from the camera, the best reference is here
http://developer.android.com/training/camera/photobasics.html
it's the same idea of starting an activity and implementing onActivityForResult where you get the data from the extras in the result, so instead of getting the bitmap from the R.drawable.abc, you'd get it like this in onActivityForResult
Bitmap imageBitmap = (Bitmap) extras.get("data");

Assign the Intended bitmap value to an imageView

I'm using an adapter to load the items to a grid. then when the user select an item from the grid then it opens up the customizing screen. In that process I'm sending some data in the intent and later I can load the these in the customizing screen. Successfully I have loaded the other items other than the isVeg item. Response I'mgetting for isVeg , [false, true, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true] .
My problem is the way I have intented is correct or not. If it is correct how can I assign it to a ImageView.
adapter im using to send the data to next acitivty
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(
R.layout.pasta_single_item, parent, false);
holder.ivImage = (ImageView) convertView
.findViewById(R.id.grid_image);
holder.tvImageIcon = (ImageView) convertView
.findViewById(R.id.icon);
holder.tvHeader = (TextView) convertView
.findViewById(R.id.grid_text);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvHeader.setText(descriptions.get(position));
Picasso.with(this.context).load(imageUrls.get(position))
.into(holder.ivImage);
final String strIsVag=isVeg.get(position);
final Bitmap mBitmap;
if (strIsVag.contains("true")) {
mBitmap = BitmapFactory.decodeResource(
this.context.getResources(), R.drawable.veg);
} else {
mBitmap = BitmapFactory.decodeResource(
this.context.getResources(), R.drawable.nonveg);
}
holder.tvImageIcon.setImageBitmap(mBitmap);
Button customizePasta = (Button) convertView
.findViewById(R.id.bt_direct_customize);
customizePasta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent next = new Intent(context, ActivityPastaCustomize.class);
next.putExtra("description", descriptions.get(position));
next.putExtra("imageUrl", imageUrls.get(position));
next.putExtra("price", price.get(position));
next.putExtra("isVeg", mBitmap); //intent the image for selected item
context.startActivity(next);
((Activity) context).overridePendingTransition(
R.anim.slide_in_right, R.anim.slide_out_left);
}
});
return convertView;
}
private class ViewHolder {
private TextView tvHeader;
private ImageView ivImage;
private ImageView tvImageIcon;
}
}
receiving the data in activity
final String description = getIntent().getStringExtra("description");
String imageUrl = getIntent().getStringExtra("imageUrl");
final String Strprice = getIntent().getStringExtra("price");
String mBitmap = getIntent().getStringExtra("isVeg"); // recives the item
setting the recivied data
final TextView descriptionTV = (TextView) findViewById(R.id.grid_text);
descriptionTV.setText(description);
final TextView priceTV = (TextView) findViewById(R.id.pasta_price);
priceTV.setText("PRICE RS " + Strprice);
ImageView imageView = (ImageView) findViewById(R.id.grid_image);
Picasso.with(this).load(imageUrl).into(imageView);
Instead of sending Bitmap with intent send drawable id.make following changes in getView method:
1. Get selected String from isVeg List:
#Override
public void onClick(View view) {
...
next.putExtra("isVeg", isVeg.get(position));
context.startActivity(next);
....
}
2. Receive data in activity isVeg as String:
String strIsVag = getIntent().getStringExtra("isVeg");
3. Set Image to ImageView according to strIsVag :
Bitmap mBitmap;
if (strIsVag.contains("true")) {
mBitmap = BitmapFactory.decodeResource(
this.getResources(), R.drawable.veg);
} else {
mBitmap = BitmapFactory.decodeResource(
this.getResources(), R.drawable.nonveg);
}
ImageView imageView = (ImageView) findViewById(R.id.grid_image);
imageView.setImageBitmap(mBitmap);
I would suggest to convert Bitmap object to string and send to your desired activity like this:-
next.putExtra("isVeg", BitMapToString(mBitmap));
These this function write below ViewHolder class like this
private class ViewHolder {
private TextView tvHeader;
private ImageView ivImage;
private ImageView tvImageIcon;
}
public String BitMapToString(Bitmap bitmap){
ByteArrayOutputStream baos=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
byte [] b=baos.toByteArray();
String temp=Base64.encodeToString(b, Base64.DEFAULT);
return temp;
}
then in the receiving activity convert the string back to bitmap to use it to the imageview like this:-
String mBitmapString = getIntent().getStringExtra("isVeg");
Bitmap mBitmap=StringToBitMap(mBitmapString);
Assign where you want
image.setImageBitmap(mBitmap);
public Bitmap StringToBitMap(String encodedString){
try {
byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch(Exception e) {
e.getMessage();
return null;
}
After you download a image from url below is your code-
Picasso.with(this.context).load(imageUrls.get(position))
.into(holder.ivImage);
final String strIsVag=isVeg.get(position);
final Bitmap mBitmap;
if (strIsVag.contains("true")) {
mBitmap = BitmapFactory.decodeResource(
this.context.getResources(), R.drawable.veg);
} else {
mBitmap = BitmapFactory.decodeResource(
this.context.getResources(), R.drawable.nonveg);
}
after that store that bitmap in local storage.
and pass path of that storage dir by intent and display it in other activity a you want.
below is code for store image in local storage-
FileOutputStream out = new FileOutputStream(file);
mBitmap .compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
hope it will help you.
EDITED
create a file like -
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/app_name");
myDir.mkdirs();
String fname = "image.jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();

Categories

Resources