NullPointerException when use getLaunchIntentForPackage - java

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.

Related

Getting arraylist from Service in BroadcastReceiver gives NullpointerException

I have a AsyncTask in a Service. I send an ArrayList as broadcast from the AsyncTask.
When I get the ArrayList in onReceive() I get a NullpointerException.
This is how I send the ArrayList.
transits_list = new ArrayList<Transit>();
transits_list.add(trs);
Intent arrayListIntent = new Intent("arrayList");
Bundle extra = new Bundle();
extra.putSerializable("transArray", transits_list);
intent.putExtra("extra", extra);
sendBroadcast(arrayListIntent);
The Transit class implements Serializable.
Receiving the ArrayList
#Override
public void onReceive(Context context, Intent intent) {
ArrayList<Transit> myList;
Bundle extra = getIntent().getBundleExtra("extra");
ArrayList<Transit> transArrayListFromBroadCast = (ArrayList<Transit>) extra.getSerializable("transArray");
System.out.print("transArrayListFromBroadCast "+transArrayListFromBroadCast);
}
I get NullpointerException in this line:
ArrayList<Transit> transArrayListFromBroadCast = (ArrayList<Transit>) extra.getSerializable("transArray");
The exception from log:
FATAL EXCEPTION: main
java.lang.RuntimeException: Error receiving broadcast Intent { act=arrayList flg=0x10 } in com.prematix.tollsystem.avcc.AvccActivity$ArrayListReceiver#42003268
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:798)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5391)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.prematix.tollsystem.avcc.AvccActivity$ArrayListReceiver.onReceive(AvccActivity.java:271)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:788)
at android.os.Handler.handleCallback(Handler.java:800) 
at android.os.Handler.dispatchMessage(Handler.java:100) 
at android.os.Looper.loop(Looper.java:194) 
at android.app.ActivityThread.main(ActivityThread.java:5391) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:525)
Your method of getting the Intent is incorrect. I believe your BroadcastReceiver is in an activity class since, you are calling getIntent(). However, getIntent() will get you the Intent supplied to the activity and not the receiver. The Intent for receiver is provided to the method onReceive() itself. Make the following changes to your code:
Adding extra:
Intent arrayListIntent = new Intent("arrayList");
Bundle extra = new Bundle();
extra.putSerializable("transArray", transits_list);
intent.putExtra("extra", extra);
sendBroadcast(arrayListIntent);
Getting Extra:
#Override
public void onReceive(Context context, Intent intent) {
ArrayList<Transit> myList;
Bundle extra = intent.getBundleExtra("extra");
ArrayList<Transit> transArrayListFromBroadCast = (ArrayList<Transit>) extra.getSerializable("transArray");
// System.out.print("transArrayListFromBroadCast "+transArrayListFromBroadCast);
}

Camera NullPointerException

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

java.lang.RuntimeException: Unable to instantiate receiver : java.lang.ClassNotFoundException

I have tried to implement Auto Answer in my project using telephony manager and BroadCastReceiver .
Its working fine But Unfortuantly the APP Crashes when i power on mobile again. Herewith I have attached my code and manifest file also.kindly can any one help us for a solution
Code :
AutoAnswerReceiver .java
public class AutoAnswerReceiver extends BroadcastReceiver {
SharedPreferences mPrefs;
static String PREFS_NAMES = "AutoAnswer";
#Override
public void onReceive(Context context, Intent intent) {
mPrefs = context.getSharedPreferences(PREFS_NAMES, 0);
String AutoResult = mPrefs.getString("AutoAnswer", "FALSE");
// Check phone state
String phone_state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
if (phone_state.equals(TelephonyManager.EXTRA_STATE_RINGING) && AutoResult.equals("TRUE"))
{
context.startService(new Intent(context, AutoAnswerIntentService.class));
}
}
**AutoAnswerIntentService**
public class AutoAnswerIntentService extends IntentService {
public AutoAnswerIntentService() {
super("AutoAnswerIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Context context = getBaseContext();
// Let the phone ring for a set delay
try {
Thread.sleep(Integer.parseInt("5") * 1000);
} catch (InterruptedException e) {
// We don't really care
}
// Make sure the phone is still ringing
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (tm.getCallState() != TelephonyManager.CALL_STATE_RINGING) {
return;
}
// Answer the phone
try {
answerPhoneAidl(context);
}
catch (Exception e) {
e.printStackTrace();
Log.d("AutoAnswer","Error trying to answer using telephony service. Falling back to headset.");
answerPhoneHeadsethook(context);
}
// Enable the speakerphone
enableSpeakerPhone(context);
return;
}
private void enableSpeakerPhone(Context context) {
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(true);
}
private void answerPhoneHeadsethook(Context context) {
// Simulate a press of the headset button to pick up the call
Intent buttonDown = new Intent(Intent.ACTION_MEDIA_BUTTON);
buttonDown.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK));
context.sendOrderedBroadcast(buttonDown, "android.permission.CALL_PRIVILEGED");
// froyo and beyond trigger on buttonUp instead of buttonDown
Intent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON);
buttonUp.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
context.sendOrderedBroadcast(buttonUp, "android.permission.CALL_PRIVILEGED");
}
#SuppressWarnings("unchecked")
private void answerPhoneAidl(Context context) throws Exception {
// Set up communication with the telephony service (thanks to Tedd's Droid Tools!)
TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
Class c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
ITelephony telephonyService;
telephonyService = (ITelephony)m.invoke(tm);
// Silence the ringer and answer the call!
telephonyService.silenceRinger();
telephonyService.answerRingingCall();
}
}
Manifestfile
<receiver android:name=".AutoAnswerReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
<receiver android:name=".AutoAnswerBootReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name="AutoAnswerIntentService" />
It works fine when app is running.But in case of power on stage it shows the error like
ERROR
03-30 09:54:22.013: E/AndroidRuntime(200): Uncaught handler: thread main exiting due to uncaught exception
03-30 09:54:22.023: E/AndroidRuntime(200): java.lang.RuntimeException: Unable to instantiate receiver com.slet.routemytrips.beta.AutoAnswerBootReceiver: java.lang.ClassNotFoundException: com.slet.routemytrips.beta.AutoAnswerBootReceiver in loader dalvik.system.PathClassLoader#43b7dfd8
03-30 09:54:22.023: E/AndroidRuntime(200): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2616)
03-30 09:54:22.023: E/AndroidRuntime(200): at android.app.ActivityThread.access$3100(ActivityThread.java:119)
03-30 09:54:22.023: E/AndroidRuntime(200): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1913)
03-30 09:54:22.023: E/AndroidRuntime(200): at android.os.Handler.dispatchMessage(Handler.java:99)
03-30 09:54:22.023: E/AndroidRuntime(200): at android.os.Looper.loop(Looper.java:123)
03-30 09:54:22.023: E/AndroidRuntime(200): at android.app.ActivityThread.main(ActivityThread.java:4363)
03-30 09:54:22.023: E/AndroidRuntime(200): at java.lang.reflect.Method.invokeNative(Native Method)
03-30 09:54:22.023: E/AndroidRuntime(200): at java.lang.reflect.Method.invoke(Method.java:521)
03-30 09:54:22.023: E/AndroidRuntime(200): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
03-30 09:54:22.023: E/AndroidRuntime(200): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
03-30 09:54:22.023: E/AndroidRuntime(200): at dalvik.system.NativeStart.main(Native Method)
03-30 09:54:22.023: E/AndroidRuntime(200): Caused by: java.lang.ClassNotFoundException: com.slet.routemytrips.beta.AutoAnswerBootReceiver in loader dalvik.system.PathClassLoader#43b7dfd8
03-30 09:54:22.023: E/AndroidRuntime(200): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
03-30 09:54:22.023: E/AndroidRuntime(200): at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
03-30 09:54:22.023: E/AndroidRuntime(200): at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
03-30 09:54:22.023: E/AndroidRuntime(200): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2609)
03-30 09:54:22.023: E/AndroidRuntime(200): ... 10 more
03-30 09:54:22.083: I/Process(51): Sending signal. PID: 200 SIG: 3
03-30 09:54:22.102: I/dalvikvm(200): threadid=7: reacting to signal 3
03-30 09:54:22.102: E/dalvikvm(200): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
Here is the class file that's missing:
Create a file named AutoAnswerBootReceiver.java
package com.example.autoanswer; // Just change the package name to yours
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AutoAnswerBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
AutoAnswerNotifier notifier = new AutoAnswerNotifier(context);
notifier.updateNotification();
}
}

Activity closes when trying to asyncronously connect to twitter

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

How to access data in the previous activity?

Using StartActivity i reached SecondActivity from FirstActivity..Now i want to access object declared in the previous activity.
Is there any obvious mechanisms that i am missing.I cant use Parceable on the object(DropboxAPI) i want to pass since i do not have its source(i can't make it parceable).
Can i pass FirstActivity.this since i can make it Parceable using an intent?or like
Intent intent=new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("MyClass",FirstActivity.this);
startActivity (intent);
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.android.AndroidAuthSession;
import android.app.Application;
import android.hardware.Camera.Parameters;
import android.os.Parcel;
import android.os.Parcelable;
public class temp extends Application {
DropboxAPI<AndroidAuthSession> mApi;
public void onCreate() {
super.onCreate();
}
temp(DropboxAPI<AndroidAuthSession> Api)
{
mApi=Api;
}
public DropboxAPI<AndroidAuthSession> getName() {
return mApi;
}
public void setName(DropboxAPI<AndroidAuthSession> dropboxclient) {
this.mApi = dropboxclient;
}
}
Code in first class:
t = (temp)getApplication();
t.setName(mApi);
//basket.putParcelable("key", MCActivity.this);
Intent intent=new Intent(MCActivity.this,DownActivity.class);
//intent.putExtra("MyClass",t);
startActivity (intent);
Code in Second class:
public void onCreate(Bundle bun) {
// TODO Auto-generated method stub
super.onCreate(bun);
setContentView(R.layout.download);
mImage = (ImageView)findViewById(R.id.image_view);
//Bundle gotit=getIntent().getExtras();
t = (temp)getApplication();
int i=2;
i=5;
dApi=t.getName();
}
Logcat:
06-28 02:24:31.979: I/System.out(729): debugger has settled (1308)
06-28 02:25:08.387: D/AndroidRuntime(729): Shutting down VM
06-28 02:25:08.387: W/dalvikvm(729): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
06-28 02:25:08.705: E/AndroidRuntime(729): FATAL EXCEPTION: main
06-28 02:25:08.705: E/AndroidRuntime(729): java.lang.ClassCastException: android.app.Application
06-28 02:25:08.705: E/AndroidRuntime(729): at cloud.mobile.MCActivity$3.onClick(MCActivity.java:164)
06-28 02:25:08.705: E/AndroidRuntime(729): at android.view.View.performClick(View.java:2408)
06-28 02:25:08.705: E/AndroidRuntime(729): at android.view.View$PerformClick.run(View.java:8816)
06-28 02:25:08.705: E/AndroidRuntime(729): at android.os.Handler.handleCallback(Handler.java:587)
06-28 02:25:08.705: E/AndroidRuntime(729): at android.os.Handler.dispatchMessage(Handler.java:92)
06-28 02:25:08.705: E/AndroidRuntime(729): at android.os.Looper.loop(Looper.java:123)
06-28 02:25:08.705: E/AndroidRuntime(729): at android.app.ActivityThread.main(ActivityThread.java:4627)
06-28 02:25:08.705: E/AndroidRuntime(729): at java.lang.reflect.Method.invokeNative(Native Method)
06-28 02:25:08.705: E/AndroidRuntime(729): at java.lang.reflect.Method.invoke(Method.java:521)
06-28 02:25:08.705: E/AndroidRuntime(729): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
06-28 02:25:08.705: E/AndroidRuntime(729): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
06-28 02:25:08.705: E/AndroidRuntime(729): at dalvik.system.NativeStart.main(Native Method)
try using Application class:
public class MyApplication extends Application {
//Variable we want to share to All Activities in Application
private DropboxClient dropboxclient;
#Override
public void onCreate() {
super.onCreate();
}
//Getter Method
public DropboxClient getName() {
return dropboxclient;
}
//Setter Method
public void setName(DropboxClient dropboxclient) {
this.dropboxclient = dropboxclient;
}
}
In MyFirstActivity Activity:
private MyApplication app;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
app = (MyApplication)getApplication(); //Get Application
app.setName(dropboxclient);
Intent intent = new Intent();
intent.setClass(this, MySecondActivity.class);
startActivity(intent);
In MySecondActivity Activity:
private MyApplication app;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (MyApplication)getApplication(); //Get Application
DropboxClient dropboxclient=app.getName();//Access global value
do the following,
start the activity with startActivityForResult()
startActivityForResult(0, MyActivity.class);
before your started activity finished, in the started activity, create an intent, and put whatever data you want to pass back as extras in the intent. now call setResult(..., intent);
Intent resultIntent = new Intent();
resultIntent.putExtra("myKey", myVal);
setResult(0, resultIntent);
in your starting activity, implement onActivityResult(), and handle the result of the started activity. you will be passed an Intent, which is the intent where you added extras in the started activity.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    //TODO handle here. 
}
Extend Application class and declare and initialize your cross activity objects in that class and write getters for those objects.
now using following code in an activty, you can access those Objects.
getApplication().getMyObject().doSomeAction();
remember, you will have to modifiy your androidManifest.xml to tell android about your extended application class.
Solution:
Using StartActivityforResult there data moveback to Second Activity to First Activity
One Example there data move to second Activity to first Activity-
http://micropilot.tistory.com/1577

Categories