I want to merge two different images of two different size and create a single image out of it and save it in sdcard.The image format what i am using is jpg.Is it possible to create merged image as jpg??
What do you mean by "merge"? You can load your two images as Bitmap objects, create a new Bitmap and an accompanying Canvas, draw your two images into the new Bitmap and then save it as a jpg using:
bitmap.compress(
CompressFormat.JPEG,
95, // or whatever compression ratio you want
new FileOutputStream("/some/location/image.jpg")
);
package com.example.imagemerging;
import java.io.FileNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnLoadImage1, btnLoadImage2;
TextView textSource1, textSource2;
Button btnProcessing;
ImageView imageResult;
final int RQS_IMAGE1 = 1;
final int RQS_IMAGE2 = 2;
Uri source1, source2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLoadImage1 = (Button)findViewById(R.id.loadimage1);
btnLoadImage2 = (Button)findViewById(R.id.loadimage2);
textSource1 = (TextView)findViewById(R.id.sourceuri1);
textSource2 = (TextView)findViewById(R.id.sourceuri2);
btnProcessing = (Button)findViewById(R.id.processing);
imageResult = (ImageView)findViewById(R.id.result);
btnLoadImage1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_IMAGE1);
}});
btnLoadImage2.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_IMAGE2);
}});
btnProcessing.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
if(source1 != null && source2 != null){
Bitmap processedBitmap = ProcessingBitmap();
if(processedBitmap != null){
imageResult.setImageBitmap(processedBitmap);
Toast.makeText(getApplicationContext(),
"Done",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),
"Upload The Image",
Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(getApplicationContext(),
"Select both image!",
Toast.LENGTH_LONG).show();
}
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
switch (requestCode){
case RQS_IMAGE1:
source1 = data.getData();
textSource1.setText(source1.toString());
break;
case RQS_IMAGE2:
source2 = data.getData();
textSource2.setText(source2.toString());
break;
}
}
}
private Bitmap ProcessingBitmap(){
Bitmap bm1 = null;
Bitmap bm2 = null;
Bitmap newBitmap = null;
try {
bm1 = BitmapFactory.decodeStream(
getContentResolver().openInputStream(source1));
bm2 = BitmapFactory.decodeStream(
getContentResolver().openInputStream(source2));
int w;
if(bm1.getWidth() >= bm2.getWidth()){
w = bm1.getWidth();
}else{
w = bm2.getWidth();
}
int h;
if(bm1.getHeight() >= bm2.getHeight()){
h = bm1.getHeight();
}else{
h = bm2.getHeight();
}
Config config = bm1.getConfig();
if(config == null){
config = Bitmap.Config.ARGB_8888;
}
newBitmap = Bitmap.createBitmap(w, h, config);
Canvas newCanvas = new Canvas(newBitmap);
newCanvas.drawBitmap(bm1, 0, 0, null);
Paint paint = new Paint();
paint.setAlpha(128);
newCanvas.drawBitmap(bm2, 0, 0, paint);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newBitmap;
}
}
//Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.imagemerging.MainActivity" >
<Button
android:id="#+id/loadimage1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/buttontext_loadimage1" />
<TextView
android:id="#+id/sourceuri1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/loadimage2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/buttontext_loadimage2" />
<TextView
android:id="#+id/sourceuri2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/processing"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/buttontext_processing" />
<ImageView
android:id="#+id/result"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Related
I rarely ask on stackoverflow, but I asked a questions recently and got a great answer! so I'll try again!
I've been working on a very simple photofilter app that adds the effect through code.
What I've been struggling with is to send a picture from whenever I open up gallery to choose a picture to another activity. I mean, I would like to choose a image from gallery, then send it to a preview activity.
Whenever I take a photo from the camera, it works and I get the photo with the added filter, but my problem is that whenever I choose an image from gallery, my app crashes. I tried to use URI instead but it didn't turn out well so I rather convert the picture I take to a bitmap and thereafter send it to the activity. Could anyone help me with this please?
Thank you!
MainAcitivty
package com.example.alek.leszealots;
import java.io.File;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import android.net.Uri;
public class MainActivity extends AppCompatActivity {
//Deklarasjoner for fremtidlig var
Button galleryButton;
Button cameraButton;
public static final int PICK_IMAGE = 1;
private static final int CAMERA_REQUEST = 1;
Bitmap thumbnail;
int CAPTURE_REQUEST;
Uri thumbFile;
File mTempFile;
int REQUEST_CODE_CHOOSE_PICTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Gjør klar menu knappene
galleryButton = (Button) findViewById(R.id.button);
cameraButton = (Button) findViewById(R.id.button2);
//Gallery knapp
galleryButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View view) {
/*Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});
startActivityForResult(chooserIntent, PICK_IMAGE);*/
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, false);
startActivityForResult(Intent.createChooser(photoPickerIntent,"Complete Action Using"), PICK_IMAGE);
}
});
//Camera knapp
cameraButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAPTURE_REQUEST);
}
});
}
//Sender lagret bilde i bitmap til sendImage som deretter sender videre til NextActivity i extra
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == CAPTURE_REQUEST) {
thumbnail = (Bitmap) data.getExtras().get("data");
sendImage();
}
else if (requestCode == PICK_IMAGE) {
thumbnail = (Bitmap) data.getExtras().get("data");
sendImage();
}
}
}
private void sendImage() {
Intent intent = new Intent(MainActivity.this, NextActivity.class);
intent.putExtra("image", thumbnail);
startActivity(intent);
}
}
NextActivity
package test.test;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class NextActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
ImageView imageView = (ImageView) findViewById(R.id.imageView);
//Ser ut som denne kan ta imot fra Gallery option også.
Bundle extras = getIntent().getExtras();
if (extras != null) {
Bitmap image = (Bitmap) extras.get("image");
if (image != null) {
imageView.setImageBitmap(changeBitmapContrastBrightness(image, 20, -255));
}
}
}
public static Bitmap changeBitmapContrastBrightness(Bitmap bmp, float contrast, float brightness)
{
ColorMatrix cm = new ColorMatrix(new float[]
{
contrast, 0, 0, 0, brightness,
0, contrast, 0, 0, brightness,
0, 0, contrast, 0, brightness,
0, 0, 0, 1, 0
});
Bitmap ret = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());
Canvas canvas = new Canvas(ret);
Paint paint = new Paint();
paint.setColorFilter(new ColorMatrixColorFilter(cm));
canvas.drawBitmap(bmp, 0, 0, paint);
return ret;
}
}
activity_next
<ImageView
android:id="#+id/imageView"
android:layout_width="330dp"
android:layout_height="369dp"
app:srcCompat="#mipmap/ic_launcher"
tools:layout_editor_absoluteX="38dp"
tools:layout_editor_absoluteY="37dp" />
</android.support.constraint.ConstraintLayout>
activity_main
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
tools:layout_editor_absoluteX="105dp"
tools:layout_editor_absoluteY="189dp" />
</android.support.constraint.ConstraintLayout>
Edit:
https://pastebin.com/Ukc2Ui4g
I would like to change an ImageView's image to black and white. The only thing is my code allows the user to take a photo, that photo is placed in the imageview. I would like that photo to be black and white. If anyone knows how I could do this, I would appreciate it.
MainActivity:
package com.example.triptych4;
import java.io.File;
import android.app.Activity;
import android.content.ContentResolver;
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.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
// label our logs "CameraApp3"
private static String logtag = "CameraApp3";
// tells us which camera to take a picture from
private static int TAKE_PICTURE = 1;
// empty variable to hold our image Uri once we store it
private Uri imageUri;
private Integer[] pics = { R.drawable.android, R.drawable.android3d,
R.drawable.background3 };
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
imageView = (ImageView) findViewById(R.id.imageView1);
gallery.setOnItemClickListener( new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getApplicationContext(), "pic:" + arg2,
Toast.LENGTH_SHORT).show();
imageView.setImageResource(pics[arg2]);
}
});
// look for the button we set in the view
ImageButton cameraButton = (ImageButton)
findViewById(R.id.button_camera);
// set a listener on the button
cameraButton.setOnClickListener(cameraListener);
}
// set a new listener
private OnClickListener cameraListener = new OnClickListener() {
public void onClick(View v) {
// open the camera and pass in the current view
takePhoto(v);
}
};
public void takePhoto(View v) {
// tell the phone we want to use the camera
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// create a new temp file called pic.jpg in the "pictures" storage area of the phone
File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "pic.jpg");
// take the return data and store it in the temp file "pic.jpg"
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
// stor the temp photo uri so we can find it later
imageUri = Uri.fromFile(photo);
// start the camera
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class ImageAdapter extends BaseAdapter{
private Context context;
int imageBackground;
public ImageAdapter(Context context){
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return pics.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
ImageView imageView =new ImageView(context);
imageView.setImageResource(pics[arg0]);
return imageView;
}
}
// override the original activity result function
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// call the parent
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
// if the requestCode was equal to our camera code (1) then...
case 1:
// if the user took a photo and selected the photo to use
if(resultCode == Activity.RESULT_OK) {
// get the image uri from earlier
Uri selectedImage = imageUri;
// notify any apps of any changes we make
getContentResolver().notifyChange(selectedImage, null);
// get the imageView we set in our view earlier
ImageButton imageButton = (ImageButton)findViewById(R.id.button_camera);
// create a content resolver object which will allow us to access the image file at the uri above
ContentResolver cr = getContentResolver();
// create an empty bitmap object
Bitmap bitmap;
try {
// get the bitmap from the image uri using the content resolver api to get the image
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);
// set the bitmap to the image view
imageButton.setImageBitmap(bitmap);
// notify the user
Toast.makeText(MainActivity.this, selectedImage.toString(), Toast.LENGTH_LONG).show();
} catch(Exception e) {
// notify the user
Toast.makeText(MainActivity.this, "failed to load", Toast.LENGTH_LONG).show();
Log.e(logtag, e.toString());
}
}
}
}
}
Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.triptych5.MainActivity" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="200dp"
android:layout_height="200dp"
android:scaleType="fitXY"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/button_camera"/>
<ImageButton
android:id="#+id/button_camera"
android:layout_width="230dp"
android:layout_height="235dp"
android:scaleType="fitXY"
android:rotation="-90"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#drawable/middle4" />
<Gallery
android:id="#+id/gallery1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/imageView1"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
You can simply achieve this by doing:
ImageView imageview = (ImageView) findViewById(R.id.imageView1);
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
imageview.setColorFilter(filter);
This is the Kotlin Version
imageView.colorFilter = ColorMatrixColorFilter(ColorMatrix().apply { setSaturation(0f)})
You can use android.graphics.ColorFilter for your purpose.
You can use this sample to suite your need.
Pass the imageView to the setBW method like
setBW(imageView);
and the the functionality is
private void setBW(ImageView iv){
float brightness = 10; // change values to suite your need
float[] colorMatrix = {
0.33f, 0.33f, 0.33f, 0, brightness,
0.33f, 0.33f, 0.33f, 0, brightness,
0.33f, 0.33f, 0.33f, 0, brightness,
0, 0, 0, 1, 0
};
ColorFilter colorFilter = new ColorMatrixColorFilter(colorMatrix);
iv.setColorFilter(colorFilter);
}
Try using this. Any concerns. Let me know. Thanks.
I would also suggest using Kotlin extensions:
private const val MAX_SATURATION = 1f
private const val MIN_SATURATION = 0f
fun ImageView.setMaxSaturation() {
val matrix = ColorMatrix()
matrix.setSaturation(MAX_SATURATION)
colorFilter = ColorMatrixColorFilter(matrix)
}
fun ImageView.setMinSaturation() {
val matrix = ColorMatrix()
matrix.setSaturation(MIN_SATURATION)
colorFilter = ColorMatrixColorFilter(matrix)
}
Java version in one line
imageview.setColorFilter(new ColorMatrixColorFilter(new ColorMatrix(){{setSaturation(0f);}}));
I have three Activity objects.
I want to transfer picture from FirstActivity To SecondActivity by passing in AlarmREceiver
This is my code of FirstActivity
package com.testcamera.hassanechafai.testcamera;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
public class FirstActivity extends ActionBarActivity {
private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
ImageView imgView;
private String imgPath;
Intent myIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
imgView = (ImageView) findViewById(R.id.ImageView);
Button butCamera = (Button) findViewById(R.id.Button1);
butCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
}
});
Button butGallery = (Button) findViewById(R.id.Button2);
butGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, ""),
PICK_IMAGE);
}
});
final EditText save = (EditText) findViewById(R.id.EditText1);
Button myBtn = (Button) findViewById(R.id.Save);
myBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int time = Integer.parseInt(save.getText().toString());
if (time > 0) {
myIntent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, time);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(getApplicationContext(), "Starting Activity in: " + time + " seconds", Toast.LENGTH_SHORT).show();
finish();
}
}
});
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory()
+ "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == PICK_IMAGE) {
selectedImagePath = getAbsolutePath(data.getData());
imgView.setImageBitmap(decodeFile(selectedImagePath));
} else if (requestCode == CAPTURE_IMAGE) {
selectedImagePath = getImagePath();
imgView.setImageBitmap(decodeFile(selectedImagePath));
Intent intent = new Intent(this, CallActivity.class);
intent.putExtra("BitmapImage", selectedImagePath);
} else {
super.onActivityResult(requestCode, resultCode,
data);
}
}
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of
// 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE
&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public String getAbsolutePath(Uri uri) {
String[] projection = { MediaColumns.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
This code of AlarmReceiver
package com.testcamera.hassanechafai.testcamera;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm time reached", Toast.LENGTH_SHORT).show();
Intent i = new Intent();
i.setClassName("com.testcamera.hassanechafai.testcamera", "com.testcamera.hassanechafai.testcamera.CallActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
This code of SecondAcitivy (I call it CallActivity)
package com.testcamera.hassanechafai.testcamera;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
public class CallActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call);
ImageView image = (ImageView)findViewById(R.id.ImageView);
}
I need to transfer photo from FirstActivity To SecondAcitivy by passing in AlarmActivity can someone help me ?
in your myBtn onClick you forgot to add myIntent.putExtra("theKeyUsed","yourConvertedStringUri");
then in your Receiver class you are missing that too.
IN your CallAcitvity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call);
String path = getIntent().getStringExtra("theKeyUsed"); // in your case "BitmapImage"
ImageView image = (ImageView)findViewById(R.id.ImageView);
// now set image using the path
}
In general pass your uri.toString() as a string extra with your intent to the preferred activity and retrieve..
feel free to delete the question if you find your solution
I'm trying to make a android app that will take a picture from the camera and display it on the same screen next to the "take picture button". I've been trying to use a tutorial but it is not working. whenever I take the picture and press save, the picture app fails. Also I don't know if it would display the photo on screen if I saved it. However, I am not sure of this since it always breaks after I press save.
Does anybody have any suggestions to help me save and display the photo on screen?
Thanks
Here's my xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.pictureproject.MainActivity"
android:orientation ="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/button_camera"
android:text="#string/button_camera"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<ImageView
android:id = "#+id/image_camera"
android:contentDescription="#string/image_cd_camera"
android:layout_width="fill_parent"
android:layout_height = "wrap_content"
/>
</LinearLayout>
and Heres my java:
package com.example.pictureproject;
import java.io.File;
import android.app.Activity;
import android.content.ContentResolver;
import android.view.View.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private static String logtag ="CameraApp8";
private static int TAKE_PICTURE = 1;
private Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button cameraButton = (Button)findViewById(R.id.button_camera);/*possibly button camera 1*/
cameraButton.setOnClickListener(cameraListener);
}
private OnClickListener cameraListener = new OnClickListener() {
public void onClick(View v){
takePhoto(v);
}
};
private void takePhoto(View v){
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"picture.jpg");
imageUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
if(resultCode == Activity.RESULT_OK){
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView)findViewById(R.id.image_camera);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try{
bitmap = MediaStore.Images.Media.getBitmap(cr,selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(MainActivity.this, selectedImage.toString(),Toast.LENGTH_LONG).show();
}catch(Exception e){
Log.e(logtag,e.toString());
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
try to add this code..
public class MyCameraActivity extends Activity {
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 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.setImageBitmap(photo);
}
}
}
I am doing an app that will let the imageButton to call a camera activity from my project capture an image and return the captured to the imageButton. My problem is I can't call the camera it keeps on getting all these errors.
ERRORS:
16:29:50.953: D/AndroidRuntime(644): Shutting down VM
08-10 16:29:50.953: W/dalvikvm(644): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
08-10 16:29:51.003: E/AndroidRuntime(644): FATAL EXCEPTION: main
08-10 16:29:51.003: E/AndroidRuntime(644): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bodapps.kinkytimefree/com.bodapps.kinkytimefree.Player_at_3_Spinner_Menu}: java.lang.ClassCastException: android.widget.ImageView cannot be cast to android.widget.ImageButton
08-10 16:29:51.003: E/AndroidRuntime(644): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
08-10 16:29:51.003: E/AndroidRuntime(644): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
08-10 16:29:51.003: E/AndroidRuntime(644): at android.app.ActivityThread.access$600(ActivityThread.java:130)
08-10 16:29:51.003: E/AndroidRuntime(644): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
08-10 16:29:51.003: E/AndroidRuntime(644): at android.os.Handler.dispatchMessage(Handler.java:99)
08-10 16:29:51.003: E/AndroidRuntime(644): at android.os.Looper.loop(Looper.java:137)
08-10 16:29:51.003: E/AndroidRuntime(644): at android.app.ActivityThread.main(ActivityThread.java:4745)
08-10 16:29:51.003: E/AndroidRuntime(644): at java.lang.reflect.Method.invokeNative(Native Method)
08-10 16:29:51.003: E/AndroidRuntime(644): at java.lang.reflect.Method.invoke(Method.java:511)
08-10 16:29:51.003: E/AndroidRuntime(644): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-10 16:29:51.003: E/AndroidRuntime(644): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-10 16:29:51.003: E/AndroidRuntime(644): at dalvik.system.NativeStart.main(Native Method)
08-10 16:29:51.003: E/AndroidRuntime(644): Caused by: java.lang.ClassCastException: android.widget.ImageView cannot be cast to android.widget.ImageButton
08-10 16:29:51.003: E/AndroidRuntime(644): at com.bodapps.kinkytimefree.Player_at_3_Spinner_Menu.onCreate(Player_at_3_Spinner_Menu.java:150)
08-10 16:29:51.003: E/AndroidRuntime(644): at android.app.Activity.performCreate(Activity.java:5008)
08-10 16:29:51.003: E/AndroidRuntime(644): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
08-10 16:29:51.003: E/AndroidRuntime(644): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
08-10 16:29:51.003: E/AndroidRuntime(644): ... 11 more
08-10 16:29:55.024: I/Process(644): Sending signal. PID: 644 SIG: 9
CODE:
package com.bodapps.kinkytimefree;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class Player_at_3_Spinner_Menu extends Activity
{
//Spinners for Players
// public Spinner spinner_1;
// public Spinner spinner_2;
// public Spinner spinner_3;
//TextView for Players
public TextView player_1;
public TextView player_2;
public TextView list_label;
public Animation fade;
//SFX
public static MediaPlayer game_signal, BG;
//Intent
public Intent next_intent;
//Button to Start
private Button play_it;
//For Displaying Text
public String SUMMON_PICK_UP_1, SUMMON_PICK_UP_2, SUMMON_PICK_UP_3;
//Integers
public int waited;
//Text Response from a Spinner
public final static String EXTRA_NEXT_MESSAGE_1 = "com.bodapps.kinkytime.LABEL_2_1";
public final static String EXTRA_NEXT_MESSAGE_2 = "com.bodapps.kinkytime.LABEL_2_2";
private static final int GET_CODE = 0;
//public ImageView image1, image2;
public ImageButton image1, image2;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.players_3);
//Setting the typeface. Put it before finding the ID of the text.
Typeface type_face = Typeface.createFromAsset(this.getAssets(), "fonts/MA Sexy.ttf");
//TextView Initialization
player_1 = (TextView) findViewById(R.id.player_1_spinner);
player_2 = (TextView) findViewById(R.id.player_2_spinner);
list_label = (TextView) findViewById(R.id.textView1);
play_it = (Button) findViewById(R.id.START_GAME);
//Typeface Settings
list_label.setTypeface(type_face);
player_1.setTypeface(null, Typeface.BOLD);
player_2.setTypeface(null, Typeface.BOLD);
//Getting proportional size according to the screen resolution to get the right dimension.
player_1.setTextSize(getResources().getDimension(R.dimen.textsize2));
player_2.setTextSize(getResources().getDimension(R.dimen.textsize2));
list_label.setTextSize(getResources().getDimension(R.dimen.textsize3));
//Set the SFX
game_signal = MediaPlayer.create(this, R.raw.female_sigh_moan);
BG = MediaPlayer.create(this, R.raw.chill_out);
//Play Sequence
BG.setLooping(true); //No loop.
BG.setVolume(22, 22); //Sets the loudness L/R.
//BG.start();
//Set intent.
Intent intent = getIntent();
next_intent = new Intent(Player_at_3_Spinner_Menu.this, Loading_Screen_to_Game.class);
//Searching for ID... (Button)
play_it = (Button) findViewById(R.id.START_GAME);
//Edit Color for Buttons and Text Views
play_it.setTextColor(Color.MAGENTA);
play_it.setBackgroundColor(Color.DKGRAY);
play_it.setTextSize(getResources().getDimension(R.dimen.textsize2));
list_label.setTextColor(Color.YELLOW);
//Adding listener to the button(s).
play_it.setOnClickListener(new trigger_happy_start());
//Retrieve the message.
SUMMON_PICK_UP_1 = intent.getStringExtra(from_3_players.EXTRA_MESSAGE_1);
SUMMON_PICK_UP_2 = intent.getStringExtra(from_3_players.EXTRA_MESSAGE_2);
//Display the retrieved names.
set_info_1(SUMMON_PICK_UP_1);
set_info_2(SUMMON_PICK_UP_2);
//Set the text for the next activity (KinkyTimeActivity.java).
String label_2_1 = player_1.getText().toString();
String label_2_2 = player_2.getText().toString();
next_intent.putExtra(EXTRA_NEXT_MESSAGE_1, label_2_1);
next_intent.putExtra(EXTRA_NEXT_MESSAGE_2, label_2_2);
//Set Animation
fade = AnimationUtils.loadAnimation(this, R.anim.fader);
fade.setFillAfter(true);
//images for the image avatar
image1 = (ImageButton) findViewById(R.id.imageBoy);
image2 = (ImageButton) findViewById(R.id.imageGirl);
}
public void handleClick(View v){
Intent intent = new Intent();
intent.setClass(this, Capture_Main_Activity.class);
startActivityForResult(intent, GET_CODE);
}
public void handleClickOne(View v){
Intent i = new Intent();
i.setClass(this, Capture_Main_Activity.class);
startActivityForResult(i, GET_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GET_CODE)
{
if(resultCode == RESULT_OK)
{
startActivity(getIntent());
}
}
}
//public void onClick(View v)
//{
//Call camera after info has been set
//switch(v.getId()){
//case R.id.imageBoy:
//startActivity(new Intent(Player_at_3_Spinner_Menu.this, Capture_Main_Activity.class));
//break;
//case R.id.imageGirl:
//startActivity(new Intent(Player_at_3_Spinner_Menu.this, Capture_Main_Activity.class));
//break;
//}
//return;
//}
//Set for Name of Player 1
public void set_info_1(String player1)
{
player_1.setText(SUMMON_PICK_UP_1);
}
//Set for Name of Player 2
public void set_info_2(String player2)
{
player_2.setText(SUMMON_PICK_UP_2);
}
private class trigger_happy_start implements OnClickListener
{
public void onClick(View v)
{
//BG.stop();
//Play Sequence
game_signal.setLooping(false); //No loop.
game_signal.setVolume(55, 55); //Sets the loudness L/R.
//game_signal.start();
//Logo played by the animation.
player_1.startAnimation(fade);
player_2.startAnimation(fade);
list_label.startAnimation(fade);
play_it.startAnimation(fade);
Thread entering = new Thread()
{
#Override
public void run()
{
try
{
waited = 0;
while(waited < 3000) //Waits for 3.0 seconds.
{
sleep(100);
waited += 100;
}
}
catch(InterruptedException e)
{
//Do nothing.
}
finally
{
finish();
startActivity(next_intent);;
}
}
};
entering.start();
}
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/imageGirl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/girl_6" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="68dp"
android:text="List of Players:"
android:textSize="15sp" />
<LinearLayout
android:id="#+id/spinner_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="20dp"
android:orientation="vertical" >
<TextView
android:id="#+id/player_1_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="empty"
android:textSize="15sp" />
<TextView
android:id="#+id/player_2_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="empty"
android:textSize="15sp" />
</LinearLayout>
<Button
android:id="#+id/START_GAME"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="51dp"
android:text="START GAME" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</LinearLayout>
<ImageButton
android:id="#+id/imageBoy"
android:layout_width="66dp"
android:layout_height="66dp"
android:layout_alignBottom="#+id/spinner_layout"
android:layout_alignParentRight="true"
android:src="#drawable/profilepicboy2"
android:onClick="handleClickOne"/>
<ImageButton
android:id="#+id/imageGirl"
android:layout_width="66dp"
android:layout_height="66dp"
android:layout_alignParentRight="true"
android:layout_below="#+id/spinner_layout"
android:src="#drawable/profilepicboy2"
android:onClick="handeClick" />
</RelativeLayout>
Camera Activity Code:
package com.bodapps.kinkytimefree;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Path;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class Capture_Main_Activity extends Activity
{
//Variables needed for the camera capture.
private Uri mImageCaptureUri;
private ImageView mImageView;
private String path;
private Bitmap bitmap;
//Camera Status
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.capture_layout);
//Array for the camera images.
final String [] items = new String [] {"Take from camera", "Select from gallery"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter( adapter, new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int item )
{
//Pick an image taken from the camera.
if (item == 0)
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { //pick from file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
}
} );
final AlertDialog dialog = builder.create();
Button button = (Button) findViewById(R.id.btn_crop);
mImageView = (ImageView) findViewById(R.id.iv_photo); //Checking for player one's image.
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
//saveBitmapToFile("/sdcard/bodapps/cropped_img.jpg", photo);
//Place player's image here!
mImageView.setImageBitmap(photo);
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) f.delete();
break;
}
}
//private void saveBitmapToFile(String string, Bitmap photo) {
// File file = new File(path);
//boolean res = false; if (!file.exists()) {
//try {
//FileOutputStream fos = new FileOutputStream(file); res = bitmap.compress(CompressFormat.JPEG, 100, fos); fos.close();
// } catch (Exception e) { }
//} return;
//}
//}
private void doCrop()
{
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0)
{
Toast.makeText(this, "Cannot find image crop app.", Toast.LENGTH_SHORT).show();
return;
}
else
{
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1)
{
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
}
else
{
for (ResolveInfo res : list)
{
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent= new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter( adapter, new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int item )
{
startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener()
{
public void onCancel( DialogInterface dialog )
{
if (mImageCaptureUri != null ) {
getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
}
in the code part you have written
image2 = (ImageButton) findViewById(R.id.imageGirl);
but in the XML you have defined
<ImageView
android:id="#+id/imageGirl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/girl_6" />
Here you are casting an ImageView into an ImageButton which isnt allowed and is hence throwing the exception.
You should change the ImageView in the XML to ImageButton.
The issue is that you use ImageView in xml and ImageButton in activity.
The error tells you not to cast ImageView to ImageButton.
Try changing it either in xml, either in activity.
package com.bodapps.kinkytimefree;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
//import android.widget.ImageView;
import android.widget.TextView;
public class Player_at_3_Spinner_Menu extends Activity
{
//Spinners for Players
// public Spinner spinner_1;
// public Spinner spinner_2;
// public Spinner spinner_3;
//TextView for Players
public TextView player_1;
public TextView player_2;
public TextView list_label;
public Animation fade;
//SFX
public static MediaPlayer game_signal, BG;
//Intent
public Intent next_intent;
//Button to Start
private Button play_it;
//For Displaying Text
public String SUMMON_PICK_UP_1, SUMMON_PICK_UP_2, SUMMON_PICK_UP_3;
//Integers
public int waited;
//Text Response from a Spinner
public final static String EXTRA_NEXT_MESSAGE_1 = "com.bodapps.kinkytime.LABEL_2_1";
public final static String EXTRA_NEXT_MESSAGE_2 = "com.bodapps.kinkytime.LABEL_2_2";
private static final int GET_CODE = 0;
//public ImageView image1, image2;
public ImageButton image1, image2;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.players_3);
//Setting the typeface. Put it before finding the ID of the text.
Typeface type_face = Typeface.createFromAsset(this.getAssets(), "fonts/MA Sexy.ttf");
//TextView Initialization
player_1 = (TextView) findViewById(R.id.player_1_spinner);
player_2 = (TextView) findViewById(R.id.player_2_spinner);
list_label = (TextView) findViewById(R.id.textView1);
play_it = (Button) findViewById(R.id.START_GAME);
//Typeface Settings
list_label.setTypeface(type_face);
player_1.setTypeface(null, Typeface.BOLD);
player_2.setTypeface(null, Typeface.BOLD);
//Getting proportional size according to the screen resolution to get the right dimension.
player_1.setTextSize(getResources().getDimension(R.dimen.textsize2));
player_2.setTextSize(getResources().getDimension(R.dimen.textsize2));
list_label.setTextSize(getResources().getDimension(R.dimen.textsize3));
//Set the SFX
game_signal = MediaPlayer.create(this, R.raw.female_sigh_moan);
BG = MediaPlayer.create(this, R.raw.chill_out);
//Play Sequence
BG.setLooping(true); //No loop.
BG.setVolume(22, 22); //Sets the loudness L/R.
//BG.start();
//Set intent.
Intent intent = getIntent();
next_intent = new Intent(Player_at_3_Spinner_Menu.this, Loading_Screen_to_Game.class);
//Searching for ID... (Button)
play_it = (Button) findViewById(R.id.START_GAME);
//Edit Color for Buttons and Text Views
play_it.setTextColor(Color.MAGENTA);
play_it.setBackgroundColor(Color.DKGRAY);
play_it.setTextSize(getResources().getDimension(R.dimen.textsize2));
list_label.setTextColor(Color.YELLOW);
//Adding listener to the button(s).
play_it.setOnClickListener(new trigger_happy_start());
//Retrieve the message.
SUMMON_PICK_UP_1 = intent.getStringExtra(from_3_players.EXTRA_MESSAGE_1);
SUMMON_PICK_UP_2 = intent.getStringExtra(from_3_players.EXTRA_MESSAGE_2);
//Display the retrieved names.
set_info_1(SUMMON_PICK_UP_1);
set_info_2(SUMMON_PICK_UP_2);
//Set the text for the next activity (KinkyTimeActivity.java).
String label_2_1 = player_1.getText().toString();
String label_2_2 = player_2.getText().toString();
next_intent.putExtra(EXTRA_NEXT_MESSAGE_1, label_2_1);
next_intent.putExtra(EXTRA_NEXT_MESSAGE_2, label_2_2);
//Set Animation
fade = AnimationUtils.loadAnimation(this, R.anim.fader);
fade.setFillAfter(true);
//images for the image avatar
ImageButton image1 = (ImageButton) findViewById(R.id.imageBoy);
ImageButton image2 = (ImageButton) findViewById(R.id.imageGirl);
}
public void handleClick(View v){
Intent intent = new Intent();
intent.setClass(this, Capture_Main_Activity.class);
startActivityForResult(intent, GET_CODE);
}
public void handleClickOne(View v){
Intent i = new Intent();
i.setClass(this, Capture_Main_Activity.class);
startActivityForResult(i, GET_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GET_CODE)
{
if(resultCode == RESULT_OK)
{
startActivity(getIntent());
}
}
}
//public void onClick(View v)
//{
//Call camera after info has been set
//switch(v.getId()){
//case R.id.imageBoy:
//startActivity(new Intent(Player_at_3_Spinner_Menu.this, Capture_Main_Activity.class));
//break;
//case R.id.imageGirl:
//startActivity(new Intent(Player_at_3_Spinner_Menu.this, Capture_Main_Activity.class));
//break;
//}
//return;
//}
//Set for Name of Player 1
public void set_info_1(String player1)
{
player_1.setText(SUMMON_PICK_UP_1);
}
//Set for Name of Player 2
public void set_info_2(String player2)
{
player_2.setText(SUMMON_PICK_UP_2);
}
private class trigger_happy_start implements OnClickListener
{
public void onClick(View v)
{
//BG.stop();
//Play Sequence
game_signal.setLooping(false); //No loop.
game_signal.setVolume(55, 55); //Sets the loudness L/R.
//game_signal.start();
//Logo played by the animation.
player_1.startAnimation(fade);
player_2.startAnimation(fade);
list_label.startAnimation(fade);
play_it.startAnimation(fade);
Thread entering = new Thread()
{
#Override
public void run()
{
try
{
waited = 0;
while(waited < 3000) //Waits for 3.0 seconds.
{
sleep(100);
waited += 100;
}
}
catch(InterruptedException e)
{
//Do nothing.
}
finally
{
finish();
startActivity(next_intent);;
}
}
};
entering.start();
}
}
}