Im working off the Android camera tutorial, SDK 11. For some reason I'm getting a Null Pointer within handleCameraPhoto(). The only thing I see is "Failure delivering result ResultInfo{who=null, request=100, result=-1, data=null} to activity", but I can't sort out why.
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
///Toast.makeText(this, "File Uri"+fileUri.toString(), Toast.LENGTH_LONG).show();
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
handleCameraPhoto(data);
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
finish();
} else {
// Image capture failed, advise user
finish();
Toast.makeText(this, "Image capture failed, quiting", Toast.LENGTH_LONG).show();
}
}
}
/**
*
* #param intent
*/
private void handleCameraPhoto(Intent data) {
Toast.makeText(this, "Image saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
}
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "Shindiggy");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("Shindiggy", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
Error Cat
11-19 11:39:06.782: W/dalvikvm(7719): threadid=1: thread exiting with uncaught exception (group=0x41549700)
11-19 11:39:06.782: E/AndroidRuntime(7719): FATAL EXCEPTION: main
11-19 11:39:06.782: E/AndroidRuntime(7719): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=null} to activity {com.shindiggy.shindiggy/com.shindiggy.shindiggy.CameraActivity}: java.lang.NullPointerException
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.ActivityThread.deliverResults(ActivityThread.java:3367)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3410)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.ActivityThread.access$1100(ActivityThread.java:141)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.os.Handler.dispatchMessage(Handler.java:99)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.os.Looper.loop(Looper.java:137)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-19 11:39:06.782: E/AndroidRuntime(7719): at java.lang.reflect.Method.invokeNative(Native Method)
11-19 11:39:06.782: E/AndroidRuntime(7719): at java.lang.reflect.Method.invoke(Method.java:525)
11-19 11:39:06.782: E/AndroidRuntime(7719): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-19 11:39:06.782: E/AndroidRuntime(7719): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-19 11:39:06.782: E/AndroidRuntime(7719): at dalvik.system.NativeStart.main(Native Method)
11-19 11:39:06.782: E/AndroidRuntime(7719): Caused by: java.lang.NullPointerException
11-19 11:39:06.782: E/AndroidRuntime(7719): at com.shindiggy.shindiggy.CameraActivity.handleCameraPhoto(CameraActivity.java:68)
11-19 11:39:06.782: E/AndroidRuntime(7719): at com.shindiggy.shindiggy.CameraActivity.onActivityResult(CameraActivity.java:51)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.Activity.dispatchActivityResult(Activity.java:5322)
11-19 11:39:06.782: E/AndroidRuntime(7719): at android.app.ActivityThread.deliverResults(ActivityThread.java:3363)
11-19 11:39:06.782: E/AndroidRuntime(7719): ... 11 more
It seems that handleCameraPhoto(asdf) is being called with an argument in your code (but you haven't shown us this part), and the problem is that the object asdf was not allocated with new. That means that there's no physical object in the program's memory.
So when the instructions of the method are executed, more especifically data.getData(), the crash happens because the name data doesn't refer to a valid object in your program's memory.
NullPointerException errors happen when we try to access members of an object that was not allocated properly. Make sure you allocate the object when calling handleCameraPhoto().
Sometimes when the phone is plugged into a USB cord, access to Camera files is blocked for security reasons. Also, check for null data when coming back to activity from Camera.
Thanks for the input guys, its helped me think of what I needed to look for.
Whenever you save an image by passing EXTRAOUTPUT with camera intent
the data parameter inside the onActivityResult always return null. So,
instead of using data to retrieve the image , use the filepath to
retrieve the Bitmap.
See onActivityResult returns null data for an Image Capture
So with that said, updated handleCameraPhoto to get the fileUri, and the app is back to working.
/**
*
* #param intent
*/
private void handleCameraPhoto(Intent data) {
Toast.makeText(this, "Image saved to:\n" +
this.fileUri, Toast.LENGTH_LONG).show();
}
Related
I'm trying to start a third party app(here is Launcher) by using this code:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
ResolveInfo resolveInfo = getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
String currentHomePackage = resolveInfo.activityInfo.packageName;
openApp(getApplicationContext(),currentHomePackage);
openApp:
public static boolean openApp(Context context, String packageName) {
PackageManager manager = context.getPackageManager();
try {
Intent i = manager.getLaunchIntentForPackage(packageName);
if (i == null) {
return false;
//throw new PackageManager.NameNotFoundException();
}
i.addCategory(Intent.CATEGORY_LAUNCHER);
context.startActivity(i);
return true;
} catch (Exception e) {
return false;
}
}
but I get a NullPointerException! This code gets my launcher package name correctly, but I can't open it! Help me please and don't get me negative points!
logcat:
07-30 18:59:47.206 16079-16079/ir.whiteapp.keepme E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at ir.whiteapp.keepme.AlertBox.openApp(AlertBox.java:80)
at ir.whiteapp.keepme.AlertBox$1.onClick(AlertBox.java:52)
at android.view.View.performClick(View.java:4204)
at android.view.View$PerformClick.run(View.java:17355)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
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)
There is no requirement that getLaunchIntentForPackage() return anything. Quoting the documentation:
Returns: A fully-qualified Intent that can be used to launch the main activity in the package. Returns null if the package does not contain such an activity, or if packageName is not recognized.
In particular, a home screen implementation does not need a launch Intent (ACTION_MAIN/CATEGORY_LAUNCHER), as normally it is not launched by other home screen implementations.
I'm new in android programming. I'm writing simple application that should execute sql file, in first run. But it seems that this process take couple of seconds so I figure that application should show progressDialog while it will be executing sql file. But when I try to run application, dialog is showing with message "app has stopped ...". Please help me.
#Override
public void onCreate(SQLiteDatabase database)
{
String CREATE_BIBLE_TABLE = "CREATE TABLE bible (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"book INTEGER, " +
"chapter INTEGER NOT NULL, " +
"verse INTEGER NOT NULL, " +
"content TEXT" +
")";
database.execSQL(CREATE_BIBLE_TABLE);
new FirstLoadAsyncTask(database).execute();
}
public class FirstLoadAsyncTask extends AsyncTask<Void, Void, Void>
{
private SQLiteDatabase database;
private ProgressDialog progressDialog;
public FirstLoadAsyncTask(SQLiteDatabase database)
{
this.database = database;
}
#Override
protected void onPreExecute()
{
((Activity) context).runOnUiThread(new Runnable()
{
#Override
public void run()
{
progressDialog = ProgressDialog.show(context, "Loading...", "");
}
});
}
#Override
protected Void doInBackground(Void... params)
{
try
{
InputStream inputStream = context.getAssets().open("bible.sql");
execSqlFile(database, inputStream);
} catch(IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.dismiss();
}
}
Class extends SQLiteOpenHelper.
Edit:
Logcat:
01-06 18:27:53.221 14118-14118/pl.several27.Biblia_Warszawska E/Trace﹕ error opening trace file: No such file or directory (2)
01-06 18:27:53.891 14118-14118/pl.several27.Biblia_Warszawska I/Adreno200-EGL﹕ <qeglDrvAPI_eglInitialize:299>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_JB_REL_2.0.3.04.01.02.21.081_msm7627a_JB_REL_2.0.3_CL2820657_release_AU (CL2820657)
Build Date: 01/22/13 Tue
Local Branch:
Remote Branch: quic/jb_rel_2.0.3
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_JB_REL_2.0.3.04.01.02.21.081 + NOTHING
01-06 18:27:54.001 14118-14118/pl.several27.Biblia_Warszawska E/copybit﹕ Error opening frame buffer errno=13 (Permission denied)
01-06 18:27:54.001 14118-14118/pl.several27.Biblia_Warszawska W/Adreno200-EGLSUB﹕ <updater_create_surface_state:342>: updater_create_surface_state failed to open copybit, error: -13
01-06 18:27:54.011 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x53be8000 size:1536000 offset:0 fd:61
01-06 18:27:54.021 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x5083a000 size:4096 offset:0 fd:63
01-06 18:27:54.381 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x541fb000 size:1536000 offset:0 fd:66
01-06 18:27:54.381 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x50a50000 size:4096 offset:0 fd:68
01-06 18:27:54.501 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x54472000 size:1536000 offset:0 fd:70
01-06 18:27:54.501 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x50c75000 size:4096 offset:0 fd:72
01-06 18:27:55.001 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x545e9000 size:1536000 offset:0 fd:74
01-06 18:27:55.001 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x50d4c000 size:4096 offset:0 fd:76
01-06 18:27:57.231 14118-14118/pl.several27.Biblia_Warszawska D/book choosen﹕ 1
01-06 18:27:57.581 14118-14118/pl.several27.Biblia_Warszawska W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40ca4540)
01-06 18:27:57.601 14118-14118/pl.several27.Biblia_Warszawska E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{pl.several27.Biblia_Warszawska/pl.several27.Biblia_Warszawska.ChapterActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2355)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
at android.app.ActivityThread.access$600(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
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:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
at pl.several27.Biblia_Warszawska.Database$FirstLoadAsyncTask.onPreExecute(Database.java:58)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at pl.several27.Biblia_Warszawska.Database.onCreate(Database.java:42)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
at pl.several27.Biblia_Warszawska.Database.countChapters(Database.java:148)
at pl.several27.Biblia_Warszawska.ChapterActivity.onCreate(ChapterActivity.java:32)
at android.app.Activity.performCreate(Activity.java:5066)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1101)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
at android.app.ActivityThread.access$600(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
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:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
01-06 18:27:59.511 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ killProcess, pid=14118
01-06 18:27:59.521 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ dalvik.system.VMStack.getThreadStackTrace(Native Method)
01-06 18:27:59.521 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ java.lang.Thread.getStackTrace(Thread.java:599)
01-06 18:27:59.521 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ android.os.Process.killProcess(Process.java:956)
01-06 18:27:59.521 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:108)
01-06 18:27:59.531 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
01-06 18:27:59.531 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
01-06 18:27:59.531 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ dalvik.system.NativeStart.main(Native Method)
Also I tried this way display progressdialog in non-activity class but it won't work too.
And here is whole application source code but without dialog: https://github.com/several27/BibliaWarszawska_Android
Please can anyone help me?
I do something like that on my application but I prefer to do that on background, so the user just don't have access to the screens that depend on my database...
You can try something like that:
public class BackgroundSyncService extends IntentService {
public static final String NOTIFICATION = "com.example.sync.service";
public static final String RESULT = "result";
public BackgroundSyncService() {
super("BackgroundSyncService");
}
#Override
protected void onHandleIntent(Intent intent) {
//Do here what you want with your database
//After all process you just notify your activitys
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
}
}
Create a receiver (I use a inner class on my project)
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
//Do what you want here , like enable a section of your app
}
}
};
Then you need to register the service to your activity adding :
registerReceiver(receiver, new IntentFilter(BackgroundSyncService.NOTIFICATION));
Don't forget to unregister the receiver:
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
Also don't forget to register your IntentService on the AndroidManifest.xml
<service android:name="com.example.service.BackgroundSyncService" />
EDIT
Also you need to include the call to start your service where you want, I start mine on App instance:
Intent intent = new Intent(this, BackgroundSyncService.class);
startService(intent);
EXPLANATION
First you are creating a service to do what you want, the service can do whatever you want, in your case you will fill a database...
After you have created this service, you will set when you want to start this service (the edit part)...
After that you will register your activity to listen the service thats why we have created the BroadcastReceiver, the BroadcastReceiver will be called when your Service execute the line:
//After all process you just notify your activitys
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
I guess the better way when the app starts you present the user with a message/ an activity that is not database related or just use the splash screen at the time that it is loading and estimate the time it normally finish loading to be the timer of the splash screen
im trying to put sound when splash screen open up, but the song.start() returns me nullpointerexception. Why is this happen? im using min api 11.
code :
public class Splash extends Activity{
MediaPlayer song;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.bg);
song = MediaPlayer.create(Splash.this, R.raw.splashmusic);
song.start();
Thread timer = new Thread(){//create thread to execute one class to another class within a time
public void run(){
try{
sleep(5000);//5 seconds of pausing
} catch (InterruptedException e){
e.printStackTrace();
}finally{
Intent openMain = new Intent("com.example.hapshare.DashboardActivity");
startActivity(openMain);
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
song.release();
finish();
}
Logcat :
11-19 09:42:02.631: E/AndroidRuntime(20289): FATAL EXCEPTION: main
11-19 09:42:02.631: E/AndroidRuntime(20289): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hapshare/com.example.hapshare.Splash}: java.lang.NullPointerException
11-19 09:42:02.631: E/AndroidRuntime(20289): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2517)
11-19 09:42:02.631: E/AndroidRuntime(20289): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2574)
11-19 09:42:02.631: E/AndroidRuntime(20289): at android.app.ActivityThread.access$600(ActivityThread.java:162)
11-19 09:42:02.631: E/AndroidRuntime(20289): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1413)
11-19 09:42:02.631: E/AndroidRuntime(20289): at android.os.Handler.dispatchMessage(Handler.java:99)
11-19 09:42:02.631: E/AndroidRuntime(20289): at android.os.Looper.loop(Looper.java:158)
11-19 09:42:02.631: E/AndroidRuntime(20289): at android.app.ActivityThread.main(ActivityThread.java:5789)
11-19 09:42:02.631: E/AndroidRuntime(20289): at java.lang.reflect.Method.invokeNative(Native Method)
Looks like your MediaPlayer is not created correctly (from the docs for MediaPlayer create()):
Returns
a MediaPlayer object, or null if creation failed
so check your R.raw.splashmusic
From the docs again:
In this case, a "raw" resource is a file that the system does not try to parse in any particular way. However, the content of this resource should not be raw audio. It should be a properly encoded and formatted media file in one of the supported formats.
You can also create MediaPlayer object this way:
try {
AssetFileDescriptor afd = this.getResources().openRawResourceFd(R.raw.splashmusic);
song = new MediaPlayer();
song.reset();
song.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
song.setAudioStreamType(AudioManager.STREAM_MUSIC);
song.prepare(); // might take long! (for buffering, etc)
song.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Remember though, that prepare() might take long, so it's not good idea to create MediaPlayer on your UI thread. You have 2 choices here:
create another thread and spawn MP there
use prepareAsync(), and when preparation is finished, onPrepared() method of the MediaPlayer.OnPreparedListener, configured through setOnPreparedListener() is called.
Please read more about MediaPlayer here
Also, when creating intent, instead of:
Intent openMain = new Intent("com.example.hapshare.DashboardActivity");
do this:
Intent openMain = new Intent(this, DashboardActivity.class);
You have the wrong media type, check the media types available developer.android.com/guide/appendix/media-formats.html as this would cause MediaPlayer.create to return null.
I'm having trouble with receiving the data capture from a Camera intent I have developed. I have used the code present in the android API guides. Can anyone tell where I am going wrong? I can see that the who=null and data=null parameters present in the LogCat printout are probably causing the error but I'm unsure as to why that is.
Camera Activity
//ESSENTIAL VARIABLES - DD - 29/04/2013
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private static final int MEDIA_TYPE_IMAGE = 1;
private Uri fileUri;
MenuItem item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snap_camera);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
/**
* Gets the OutputMediaFileUri and accepts media type as a parameter
* #param type
* #return
*/
private static Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* Method taking media type as a parameter and will save images taken to a public directory on users' device.
* #param type
* #return
*/
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "CrowdSnapCymru");
if(!mediaStorageDir.exists()){
if(! mediaStorageDir.mkdirs()){
Log.d("CrowdSnapCymru", "failed to create photo directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if(type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
}
else{
return null;
}
return mediaFile;
}
/**
* Receives the result of Camera intent.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if(resultCode == RESULT_OK){
Toast.makeText(this, "Image saved to: \n" + data.getData() , Toast.LENGTH_LONG).show();
}
else if(resultCode == RESULT_CANCELED){
Toast.makeText(this, "User canceled the image capture", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this, "Image capture failed. Please try again", Toast.LENGTH_LONG).show();
}
}
}
The code loads the Camera application and will produce the successful result if I cancel the application but if I accept the image or RESULT_OKAY the NullPointerException is produced.
LogCat Printout
05-01 09:57:48.894: E/AndroidRuntime(974): FATAL EXCEPTION: main
05-01 09:57:48.894: E/AndroidRuntime(974): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=null} to activity {rcahmw.prototype.crowdsnapcymru/rcahmw.prototype.crowdsnapcymru.SnapCamera}: java.lang.NullPointerException
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.ActivityThread.deliverResults(ActivityThread.java:3319)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3362)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.ActivityThread.access$1100(ActivityThread.java:141)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1282)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.os.Handler.dispatchMessage(Handler.java:99)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.os.Looper.loop(Looper.java:137)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-01 09:57:48.894: E/AndroidRuntime(974): at java.lang.reflect.Method.invokeNative(Native Method)
05-01 09:57:48.894: E/AndroidRuntime(974): at java.lang.reflect.Method.invoke(Method.java:511)
05-01 09:57:48.894: E/AndroidRuntime(974): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-01 09:57:48.894: E/AndroidRuntime(974): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-01 09:57:48.894: E/AndroidRuntime(974): at dalvik.system.NativeStart.main(Native Method)
05-01 09:57:48.894: E/AndroidRuntime(974): Caused by: java.lang.NullPointerException
05-01 09:57:48.894: E/AndroidRuntime(974): at rcahmw.prototype.crowdsnapcymru.SnapCamera.onActivityResult(SnapCamera.java:84)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.Activity.dispatchActivityResult(Activity.java:5293)
05-01 09:57:48.894: E/AndroidRuntime(974): at android.app.ActivityThread.deliverResults(ActivityThread.java:3315)
Any advice would be brilliant. Pretty new to using Camera application in android.
Save your fileUri variable somewhere and use it in onActivityResult instead of data.getData
Try passing Following File URI as EXTRA_OUTPUT as follow. Your onCreate would look like :
Uri picUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snap_camera);
String imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/picture.jpg";
File imageFile = new File(imageFilePath);
picUri = Uri.fromFile(imageFile); // convert path to Uri
intent.putExtra( MediaStore.EXTRA_OUTPUT, picUri );
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
Then onActivityResult use picUri to access image. Declare picUri as a instance variable in your activity. So it will be available in onActivityResult
I have been trying to program a twitter client for Android (using twitter4j). So far the idea is to have a simple GUI, and if there is not a file with the OAuth token in the SD Card, connect to the Twitter API using AsyncTask, get the URL for the authorization and open the default browser. However, the browser never runs. Depending on the different modifications I have made trying to fix this, either the Activity starts normally but the browser never starts or the Activity crashes. I have come to a point of a a little of frustation and confussion. Can someone point out what's wrong with my code?
public class StatusActivity extends Activity {
private static final String TAG = "StatusActivity";
EditText editText;
Button updateButton;
File oauthfile = null;
public Context context = getApplicationContext();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_status);
Log.d(TAG, "started");
// Find views
editText = (EditText) findViewById(R.id.editText); //
updateButton = (Button) findViewById(R.id.buttonUpdate);
oauthfile = new File("sdcard/auth_file.txt");
//Check if the file with the keys exist
if (oauthfile.exists()==false){
Log.d(TAG, "file not created");
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "file not created.", Toast.LENGTH_SHORT);
toast.show();
new Authorization(context).execute();
}
}
public void openBrowser (View v){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
Log.d(TAG, "onclick");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.status, menu);
return true;
}
}
class Authorization extends AsyncTask <String, Integer, String>{
String url = null;
private Context context;
Authorization(Context context) {
this.context = context.getApplicationContext();
}
public void onPreExecute() {
super.onPreExecute();
Toast.makeText(context, "Invoke onPreExecute()", Toast.LENGTH_SHORT).show();
}
#Override
public String doInBackground(String... params) {
ConfigurationBuilder configBuilder = new ConfigurationBuilder();
configBuilder.setDebugEnabled(true)
//I have eliminated the keys from the question :)
.setOAuthConsumerKey("XXXXXXXXXXXXXX")
.setOAuthConsumerSecret("XXXXXXXXXXXXXXX");
Twitter OAuthTwitter = new TwitterFactory(configBuilder.build()).getInstance();
RequestToken requestToken = null;
AccessToken accessToken = null;
do{
try {
requestToken = OAuthTwitter.getOAuthRequestToken();
url = requestToken.getAuthorizationURL();
}
catch (TwitterException ex) {
ex.printStackTrace();
}
}
while (accessToken==null);
return url;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(context, "Opening browser.", Toast.LENGTH_SHORT).show();
Intent browserIntent = new Intent(Intent.ACTION_ALL_APPS, Uri.parse(url));
context.startActivity(browserIntent);
}
}
I know that at least checks if the file for the tokens exists because the toast "file not created" appears, and that the activity is able to run the browser if I press the button. The app has permissions to write in the SD card and use the Internet. Thanks in advance.
Logcat Trace:
03-28 19:02:32.816: E/AndroidRuntime(278): FATAL EXCEPTION: main
03-28 19:02:32.816: E/AndroidRuntime(278): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.versec.pardinus/com.versec.pardinus.StatusActivity}: java.lang.NullPointerException
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.os.Handler.dispatchMessage(Handler.java:99)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.os.Looper.loop(Looper.java:123)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.reflect.Method.invokeNative(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.reflect.Method.invoke(Method.java:521)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-28 19:02:32.816: E/AndroidRuntime(278): at dalvik.system.NativeStart.main(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): Caused by: java.lang.NullPointerException
03-28 19:02:32.816: E/AndroidRuntime(278): at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:100)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.versec.pardinus.StatusActivity.<init>(StatusActivity.java:30)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.Class.newInstanceImpl(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.Class.newInstance(Class.java:1429)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
03-28 19:02:32.816: E/AndroidRuntime(278): ... 11 more
This is what is causing your crash.
public Context context = getApplicationContext();
You're not even using it when you need it, so you can just get rid of this line.
Btw, something else I noticed while looking at your code is this:
oauthfile = new File("sdcard/auth_file.txt");
Don't take the "sdcard/" path for granted. Use this instead:
File dir = Environment.getExternalStorageDirectory();
File oauthfile = new File(dir, "auth_file.txt");