how to call a camera activity to another activity - android

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

Related

Android studios - How to pass image from gallery to another activity

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

java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference

I want put edittext from first activity to new secondactivity view text.
What to do when I have an erro like this displayed in android monitor :
com.example.xx.DrawerAddAd.seeAdd(DrawerAddAd.java:129)
com.example.xx.DrawerAddAd.access$100(DrawerAddAd.java:40)
com.example.xx.DrawerAddAd$2.onClick(DrawerAddAd.java:116)
also:
Render problem:
Couldn't resolve resource #id/visible
Tip: Try to refresh the layout.
DrawerAddAd class code:
package com.example.xx.drawer;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Camera;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import com.example.xx.R;
import com.example.xxx.model.POJO.view.ProductDetails;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import butterknife.BindView;
public class DrawerAddAd extends AppCompatActivity {
public static ArrayList<String> fragments = new ArrayList<>();
private final int REQUEST_CODE = 1;
private ImageButton camera_imageButton;
private Spinner spinner_category;
private Button button_seeAd_product;
private Button button_add_product;
#BindView(R.id.title_Ad_editText)
EditText titleAd_editText;
#BindView(R.id.text_Ad_editText)
EditText textAd_editText;
#BindView(R.id.price_editText)
EditText price_editText;
#BindView(R.id.checkBox_season)
CheckBox checkBox_season;
#BindView(R.id.checkBox_year)
CheckBox checkBox_year;
#BindView(R.id.checkBox_detail)
CheckBox checkBox_detail;
#BindView(R.id.checkBox_wholesale)
CheckBox checkBox_whoLesale;
private int REQUEST_CAMERA = 1, SELECT_FILE = 1;
private Button btnSelect;
private ImageView Image;
private String userChosenTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer_add_ad);
final TextInputLayout title_ad_layout = (TextInputLayout) findViewById(R.id.add_title_ad_layout);
final TextInputLayout text_ad_layout = (TextInputLayout) findViewById(R.id.add_text_ad_layout);
final TextInputEditText title_Ad_editText = (TextInputEditText) findViewById(R.id.title_Ad_editText);
final TextInputEditText text_Ad_editText = (TextInputEditText) findViewById(R.id.text_Ad_editText);
setTextWatcher(title_Ad_editText, title_ad_layout);
setTextWatcher(text_Ad_editText, text_ad_layout);
spinner_category = (Spinner) findViewById(R.id.spinner_category);
button_seeAd_product = (Button) findViewById(R.id.button_seeAd_product);
button_add_product = (Button) findViewById(R.id.button_ad_product);
camera_imageButton = (ImageButton) findViewById(R.id.camera_imageButton);
camera_imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
button_seeAd_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean error = false;
if (TextUtils.isEmpty(title_Ad_editText.getText().toString())) {
title_ad_layout.setError(getString(R.string.empty_field));
error = true;
}
if (TextUtils.isEmpty(text_Ad_editText.getText().toString())) {
text_ad_layout.setError(getString(R.string.empty_field));
error = true;
}
if (!error) {
seeAdd();
}
}
});
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.fragments, R.layout.support_simple_spinner_dropdown_item);
adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
spinner_category.setAdapter(adapter);
}
private void seeAdd() {
Intent intent = new Intent(getApplicationContext(), ProductDetails.class);
intent.putExtra("title",titleAd_editText.getText().toString());
intent.putExtra("text", textAd_editText.getText().toString());
// ImageView imageView =
// String title = titleAd_editText.getText().toString();
// String text = textAd_editText.getText().toString();
// String price = price_editText.getText().toString();
//
//
// intent.putExtra("titleAdd", title);
// intent.putExtra("textAdd", text);
// intent.putExtra("price", price);
startActivity(intent);
}
private void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
switch (view.getId()) {
case R.id.checkBox_season:
if (checked) {
} else {
}
break;
case R.id.checkBox_year:
if (checked) {
} else {
}
break;
case R.id.checkBox_detail:
if (checked) {
} else {
}
break;
case R.id.checkBox_wholesale:
if (checked) {
} else {
}
break;
}
}
private void setTextWatcher(final TextInputEditText editText, final TextInputLayout inputLayout) {
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (inputLayout.isErrorEnabled()) {
inputLayout.setErrorEnabled(false);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
private void selectImage() {
final CharSequence[] items = {"Zrób zdjęcie", "Wybierz z katalogu", "Anuluj"};
AlertDialog.Builder builder = new AlertDialog.Builder(DrawerAddAd.this);
builder.setTitle("Dodaj zdjęcie");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(DrawerAddAd.this);
if (items[item].equals("Zrób zdjęcie")) {
userChosenTask = "Zrób zdjęcie";
if (result)
cameraIntent();
} else if (items[item].equals("Wybierz z katalogu")) {
userChosenTask = "Wybierz z katalogu";
if (result)
galleryIntent();
} else if (items[item].equals("Anuluj")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Wybierz plik"), SELECT_FILE);
}
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm = null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
Image.setImageBitmap(bm);
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Image.setImageBitmap(thumbnail);
}
}
ProductDetails class code:
package com.example.xxx.model.POJO.view;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import com.example.xxx.R;
public class ProductDetails extends AppCompatActivity {
private TextView title, text, price, date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
title = (TextView) findViewById(R.id.title_textView);
text = (TextView) findViewById(R.id.text_textView);
Intent intent = getIntent();
// Bundle bundle = getIntent().getExtras();
String title_textView = intent.getStringExtra("titleAdd");
String text_textView = intent.getStringExtra("textAdd");
title.setText(title_textView);
text.setText(text_textView);
// price = (TextView) findViewById(R.id.price_textView);
// date = (TextView) findViewById(R.id.date_textView);
// String titleAdd = bundle.getString("titleAdd");
// String textAdd = bundle.getString("textAdd");
// String price = bundle.getString("price");
// title.setText(titleAdd);
// text.setText(textAdd);
// price.setText(price);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
I don't know what to do ...
Thanks, Slawek.
it means title_Ad_editText is null.
Check your xml file and title_Ad_editText variable.
couple things I could see, redo this:
private void seeAdd() {
Intent intent = new Intent(getApplicationContext(), ProductDetails.class);
intent.putExtra("title",titleAd_editText.getText().toString());
intent.putExtra("text", textAd_editText.getText().toString());
to this:
private void seeAdd() {
Intent intent = new Intent(DrawerAddAd.this, ProductDetails.class);
intent.putExtra("title",titleAd_editText.getText().toString());
intent.putExtra("text", textAd_editText.getText().toString());
then in your intent, you need to call the extra exactly as set, change this:
Intent intent = getIntent();
// Bundle bundle = getIntent().getExtras();
String title_textView = intent.getStringExtra("titleAdd");
String text_textView = intent.getStringExtra("textAdd");
to this:
Intent intent = getIntent();
// Bundle bundle = getIntent().getExtras();
String title_textView = intent.getStringExtra("title");
String text_textView = intent.getStringExtra("text");

NullPoint when start Activity [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have 1 problem and Who can help me?.
I have 1 Activity run when start App
package com.example.khuatduytan.doantotnghiep;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.Serializable;
public class MainActivity extends AppCompatActivity {
DatabaseHelper db;
Button btnLogin, btnRegister, btnFindPassword;
EditText editUsername, editPassword;
private static final int REQUEST_CODE = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHelper(this);
btnLogin = (Button) findViewById(R.id.button_login);
btnRegister = (Button) findViewById(R.id.button_register);
btnFindPassword = (Button) findViewById(R.id.button_findPassword);
editUsername = (EditText) findViewById(R.id.editText_username);
editPassword = (EditText) findViewById(R.id.editText_password);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarActivity);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Đăng nhập");
Login();
Register();
FindPassword();
}
public void Login(){
btnLogin.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = db.getDataTableUser();
int temp = 1;
if (res.getCount() == 0) {
showMessage("Error", "Tài khoản không tồn tại");
return;
}
while (res.moveToNext()) {
String username, password, idUser;
idUser = res.getString(0);
username = res.getString(1);
password = res.getString(2);
if (editUsername.getText().toString().equals(username) == true&&editPassword.getText().toString().equals(password) == true) {
doOpenManagePage(idUser);
temp = 0;
break;
}
}
if (temp==1){
showMessage("Error", "Account does not exist");
}
}
}
);
}
public void Register(){
btnRegister.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v) {
doOpenRegister();
}
}
);
}
public void FindPassword(){
btnFindPassword.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v) {
doOpenFindPasswordStep1();
}
}
);
}
public void doOpenRegister(){
Intent newIntent = new Intent(this, Register.class);
startActivity(newIntent);
}
public void doOpenFindPasswordStep1(){
Intent newIntent = new Intent(this, FindPasswordStep1.class);
startActivity(newIntent);
}
public void doOpenManagePage(String idUser){
Intent newIntent = new Intent(this, ManagePage.class);
newIntent.putExtra("IdUser", idUser);
startActivityForResult(newIntent, REQUEST_CODE);
}
public void showMessage(String title, String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_manage_page, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_logout) {
return true;
}
else if (id==R.id.action_search){
return true;
}
return super.onOptionsItemSelected(item);
}
}
Then it send IdUser to this Activity
package com.example.khuatduytan.doantotnghiep;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
public class ManagePage extends AppCompatActivity{
private static final int REQUEST_CODE = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_page);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.add_note);
Bundle extras = getIntent().getExtras();
final String idUser = extras.getString("IdUser");
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
doOpenInsertNote(idUser);
}
});
}
public String getIdUser(){
Bundle extras = getIntent().getExtras();
String idUser = extras.getString("IdUser");
return idUser;
}
public void doOpenInsertNote(String idUser){
Intent newIntent = new Intent(this, InsertNote.class);
newIntent.putExtra("IdUser", idUser);
startActivityForResult(newIntent, REQUEST_CODE);
}
}
When i run it 1st time, this app is ok, it can go to next Activity
package com.example.khuatduytan.doantotnghiep;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Calendar;
public class InsertNote extends AppCompatActivity implements View.OnClickListener {
private ImageButton insertDate;
private Calendar cal;
private int day;
private int month;
private int year;
private EditText et, content_InsertNote, money_InsertNote;
private Button btnSubmitNote, btnCancelNote;
private Spinner SelectTypeNote;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_note);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
insertDate = (ImageButton) findViewById(R.id.dateInsert);
cal = Calendar.getInstance();
et = (EditText) findViewById(R.id.dateInsert_editText);
btnSubmitNote = (Button) findViewById(R.id.insertNote);
btnCancelNote = (Button) findViewById(R.id.cancelNote);
content_InsertNote = (EditText) findViewById(R.id.noiDung);
money_InsertNote = (EditText) findViewById(R.id.soTien);
SelectTypeNote = (Spinner) findViewById(R.id.loai);
db = new DatabaseHelper(this);
cal = Calendar.getInstance();
day = cal.get(Calendar.DAY_OF_MONTH);
month = cal.get(Calendar.MONTH);
year = cal.get(Calendar.YEAR);
insertDate.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
final String idUser = extras.getString("IdUser");
setBtnSubmitNote(idUser);
setBtnCancelNote();
}
#Override
public void onClick(View v) {
showDialog(0);
}
#Override
#Deprecated
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(this, datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
et.setText(selectedDay + " / " + (selectedMonth + 1) + " / " + selectedYear);
}
};
private void setBtnSubmitNote(final String idUser){
btnSubmitNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
confirmDialog(idUser);
}
});
}
private void setBtnCancelNote(){
Intent newIntent = new Intent(this, ManagePage.class);
startActivity(newIntent);
}
private void confirmDialog(final String idUser) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setMessage("Are you sure?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String date = null, content = null, money = null, TypeNote_Selected;
int Type_Note = 0, id_User;
id_User = Integer.parseInt(idUser);
date = et.getText().toString();
content = content_InsertNote.getText().toString();
money = money_InsertNote.getText().toString();
TypeNote_Selected = SelectTypeNote.getSelectedItem().toString();
if(TypeNote_Selected.equals("Thu")){
Type_Note = 0;
} else{
Type_Note = 1;
}
if(date.equals("")||content.equals("")||money.equals("")){
Toast.makeText(InsertNote.this, "Bạn chưa nhập đủ dữ liệu", Toast.LENGTH_LONG).show();
}
else {
long isInserted = db.insertNoteTable(date, content, Type_Note, money, id_User);
if (isInserted == -1) {
Toast.makeText(InsertNote.this, "Thêm ghi chú không thành công", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(InsertNote.this, "Thêm ghi chú thành công", Toast.LENGTH_LONG).show();
}
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.show();
}
}
`
But when i run it second time, When i click button to open Activity
InsertNote, I receive a error
03-26 16:12:32.161 2614-2614/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.khuatduytan.doantotnghiep/com.example.khuatduytan.doantotnghiep.ManagePage}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.khuatduytan.doantotnghiep.ManagePage.onCreate(ManagePage.java:21)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 
at android.app.ActivityThread.access$600(ActivityThread.java:141) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:5041) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 
at dalvik.system.NativeStart.main(Native Method) 
I tried to print what i send from Activity Main to Activity ManagePage by Toast, it display exactly what i want to send.
But i dont know why this error display.
Can you help me?
Sorry about my English
You call setBtnCancelNote() method in the onCreate() method of your InsertNote activity. so as soon as InsertNote starts it tries to launch the ManagePage activity.
The problem is your ManagePage activity expects the value IdUser in the bundle received from the intent. But you do not pass this value to ManagePage activity when you start it from InsertNote activity.
You probably want to add this line to your setBtncancelNote() method in InsertPage activity -
newIntent.putExtra("IdUser", //The Values here);
If you pass this value then ManageNote will not crash.
please add more info like line numbers, otherwise its difficult to debug it remotely ..
Anyway, my guess is you have to check for null pointers when you do stuff like getIntent().getExtras()
just put some breakpoints there, and step by step and you'll figure it out

Passing Picture from activity to another activity

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

saving and then displaying camera photo on application

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

Categories

Resources