Failed to get request token method POST must have a request body - java

I'm trying to implement twitter login in my android app.
I've followed the instructions ( https://dev.twitter.com/twitter-kit/android/twitter-login ).
Everything is working fine if I have the twitter app installed but if I don't when I tap on the login button I get the exception below.
It shoulw open a webview asking to login instead.
Any hint?
06-02 11:22:23.531 24124-24124/it.quepasa W/dalvikvm: VFY: unable to resolve virtual method 39779: Lretrofit/client/OkClient;.openConnection (Lretrofit/client/Request;)Ljava/net/HttpURLConnection;
06-02 11:22:23.611 24124-24124/it.quepasa E/Twitter﹕ Failed to get request token
com.twitter.sdk.android.core.TwitterApiException: method POST must have a request body.
at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:400)
at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220)
at retrofit.RestAdapter$RestHandler$2.obtainResponse(RestAdapter.java:278)
at retrofit.CallbackRunnable.run(CallbackRunnable.java:42)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at retrofit.Platform$Android$2$1.run(Platform.java:142)
at java.lang.Thread.run(Thread.java:838)
06-02 11:22:23.686 24124-24124/it.quepasa E/Twitter﹕ Authorization completed with an error
com.twitter.sdk.android.core.TwitterAuthException: Failed to get request token
at com.twitter.sdk.android.core.identity.OAuthController$1.failure(OAuthController.java:78)
at com.twitter.sdk.android.core.internal.oauth.OAuth1aService$1.failure(OAuth1aService.java:198)
at com.twitter.sdk.android.core.Callback.failure(Callback.java:28)
at retrofit.CallbackRunnable$2.run(CallbackRunnable.java:53)
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:5370)
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)
Here there is my code:
AndroidManifest.xml:
<meta-data
android:name="io.fabric.ApiKey"
android:value="XXXXXXXX" />
MainActivity.java:
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Twitter(authConfig), new Crashlytics()); //I've tried without crashlytics, same problem. Crashlytics works..
LoginActivity.java:
loginButton = (TwitterLoginButton) findViewById(R.id.twitter_login_buttons);
loginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
Log.d(TAG, "Success");
}
#Override
public void failure(TwitterException exception) {
Log.d(TAG, "Failure");
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
loginButton.onActivityResult(requestCode, resultCode, data);
}

I've found a solution:
it is a breaking change in okhttp 2.4, reverting to 2.3 solved my problem.
See:
https://github.com/square/okhttp/issues/751
https://github.com/square/retrofit/issues/854

Related

Google Sign in Error 12500 SHA1 double checked GoogleSignInAccount account = completedTask.getResult(ApiException.class);

I am getting this error after selecting a google account. OnActivityResult is called, but after evaluating the result this error is thrown. The cause is not a wrong SHA1, I am using the same key for release and debug. The app is not from Google Play. I am not using firebase. The google signin sample works with the same key.
com.google.android.gms.common.api.ApiException: 12500:
Stacktrace:
W/System.err: com.google.android.gms.common.api.ApiException: 12500:
W/System.err: at com.google.android.gms.common.internal.ApiExceptionUtil.fromStatus(Unknown Source)
W/System.err: at com.google.android.gms.auth.api.signin.GoogleSignIn.getSignedInAccountFromIntent(Unknown Source)
W/System.err: at de.org.limindo.limindo2.fragLogin.onActivityResult(fragLogin.java:412)
W/System.err: at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:151)
W/System.err: at de.org.limindo.limindo2.MainActivity.onActivityResult(MainActivity.java:788)
W/System.err: at android.app.Activity.dispatchActivityResult(Activity.java:5456)
W/System.err: at android.app.ActivityThread.deliverResults(ActivityThread.java:3549)
W/System.err: at android.app.ActivityThread.handleSendResult(ActivityThread.java:3596)
W/System.err: at android.app.ActivityThread.access$1300(ActivityThread.java:151)
W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1369)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:110)
W/System.err: at android.os.Looper.loop(Looper.java:193)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5299)
W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
W/System.err: at dalvik.system.NativeStart.main(Native Method)
The code is:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(fragLogin.this._main, gso);
mSignInGoogle0.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view)
{
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
// Signed in successfully, show authenticated UI.
if (account != null)
{
mPasswordView.setVisibility(View.GONE);
mPasswordView.setVisibility(View.GONE);
}
updateUI(account);
} catch (ApiException e) {
e.printStackTrace();
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
lib.ShowMessage(getContext(), getString(R.string.googleloginnotsuccessfull) + "\n" + getString(R.string.ErrorCode) + GoogleSignInStatusCodes.getStatusCodeString(e.getStatusCode()) + ":" + e.getStatusCode(), getString(R.string.Error));
updateUI(null);
}
}
In case this helps anybody: I was in this situation, except that it worked initially then stopped working later. I finally realized that it was because I switched laptops.
The solution is the package name: The package name of the manifest is de.org.limindo.limindo2 but the package of the apk is de.org.limindo2 ..... It seems that gradle shortens package names, if they contain double entries….

FATAL EXCEPTION: main on Android App

I'm getting this fatal exception: main error. It is only when I click on the 'Pick A Place' button on my app.
The logcat report when clicking on the 'Pick A Place' button is below:
04-13 13:52:19.418 10737-10737/cct.mad.lab E/AndroidRuntime: FATAL EXCEPTION: main
Process: cct.mad.lab, PID: 10737
java.lang.NoSuchMethodError: cct.mad.lab.SettingsActivity.checkSelfPermission
at cct.mad.lab.SettingsActivity.calculateCurrentCoordinates(SettingsActivity.java:679)
at cct.mad.lab.SettingsActivity.onPrepareDialog(SettingsActivity.java:581)
at android.app.Activity.onPrepareDialog(Activity.java:3061)
at android.app.Activity.showDialog(Activity.java:3124)
at android.app.Activity.showDialog(Activity.java:3075)
at cct.mad.lab.SettingsActivity$8.onClick(SettingsActivity.java:374)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
The logcat points to a 'NoSuchMethodError' when checking for 'self permission' to do with the method 'calculateCurrentCooridnates'. This method is below:
#TargetApi(Build.VERSION_CODES.M)
private void calculateCurrentCoordinates() {
float lat = 0, lon = 0;
try {
LocationManager locMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
Location recentLoc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
lat = (float) recentLoc.getLatitude();
lon = (float) recentLoc.getLongitude();
} catch (Exception e) {
Log.e(DEBUG_TAG, "Location failed", e);
}
mFavPlaceCoords = new GPSCoords(lat, lon);
}
The ToDo was automatically generated when Android Studio automatically added the '#TargetAPI' bit. With this in mind I added the following to the manifest and as I got no more errors I thought this would be enough:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
However, the app just crashes.
Any help greatly appreciated.
Thanks
Extending AppCompatActivity will solve the issue.
Do like this
public class SettingsActivity extends AppCompatActivity {

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

Error: Class not found when unmarshalling: com.facebook.login.Login Client Request

I am getting this error when hitting the "Login With Facebook" (Simple login button).
I have Google, and read other topics here - but I can not see any thing matching my issue.
I am adding Login.java class below.
public class Login extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_login);
CallbackManager callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("public_profile", "email", "user_friends");
// Other app specific specialization
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.i("Login", "Logged in: ");
Intent i = new Intent(Login.this, MainActivity.class);
startActivity(i);
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
Log.i("Error" , "Error");
}
});
}
}
StackTrace:
05-28 20:07:27.550 872-1363/? E/Parcel﹕ Class not found when unmarshalling: com.facebook.login.LoginClient$Request
java.lang.ClassNotFoundException: com.facebook.login.LoginClient$Request
at java.lang.Class.classForName(Native Method)
at java.lang.Class.forName(Class.java:308)
at java.lang.Class.forName(Class.java:272)
at android.os.Parcel.readParcelableCreator(Parcel.java:2275)
at android.os.Parcel.readParcelable(Parcel.java:2239)
at android.os.Parcel.readValue(Parcel.java:2146)
at android.os.Parcel.readArrayMapInternal(Parcel.java:2479)
at android.os.BaseBundle.unparcel(BaseBundle.java:221)
at android.os.BaseBundle.getString(BaseBundle.java:918)
at android.content.Intent.getStringExtra(Intent.java:5378)
at com.android.server.am.ActivityStackSupervisor.startActivityLocked(ActivityStackSupervisor.java:1768)
at com.android.server.am.ActivityStackSupervisor.startActivityMayWait(ActivityStackSupervisor.java:1313)
at com.android.server.am.ActivityManagerService.startActivityAsUser(ActivityManagerService.java:4522)
at com.android.server.am.ActivityManagerService.startActivity(ActivityManagerService.java:4368)
at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:140)
at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:2964)
at android.os.Binder.execTransact(Binder.java:446)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.facebook.login.LoginClient$Request" on path: DexPathList[[directory "."],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
            at java.lang.Class.classForName(Native Method)
            at java.lang.Class.forName(Class.java:308)
            at java.lang.Class.forName(Class.java:272)
            at android.os.Parcel.readParcelableCreator(Parcel.java:2275)
            at android.os.Parcel.readParcelable(Parcel.java:2239)
            at android.os.Parcel.readValue(Parcel.java:2146)
            at android.os.Parcel.readArrayMapInternal(Parcel.java:2479)
            at android.os.BaseBundle.unparcel(BaseBundle.java:221)
            at android.os.BaseBundle.getString(BaseBundle.java:918)
            at android.content.Intent.getStringExtra(Intent.java:5378)
            at com.android.server.am.ActivityStackSupervisor.startActivityLocked(ActivityStackSupervisor.j
Java:1768)      at com.android.server.am.ActivityStackSupervisor.startActivityMayWait(ActivityStackSupervisor.java:1313)
at com.android.server.am.ActivityManagerService.startActivityAsUser(ActivityManagerService.java:4522)
            at com.android.server.am.ActivityManagerService.startActivity(ActivityManagerService.java:4368)
            at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:140)
            at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:2964)
            at android.os.Binder.execTransact(Binder.java:446)
Suppressed: java.lang.ClassNotFoundException: com.facebook.login.LoginClient$Request
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 18 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
Check your android:noHistory flag on the activity.
See link
https://developers.facebook.com/bugs/1621984714705591/
look for post by Andreas Bergenwall
This can happen when the user has the native Facebook App installed.
You can suppress the attempt to open it by initializing the LoginManager's LoginBehaviour:
// Don't allow the Facebook App to open.
LoginManager.getInstance().setLoginBehavior(LoginBehavior.WEB_VIEW_ONLY);
I too had this issue. Mine however was a login call made within the FBActivity.OnResume method for callbacks to login after accepting fb perms.
I simply moved the request into the profile tracker in the onCreate method
ProfileTracker profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
Profile.fetchProfileForCurrentAccessToken();
if(currentProfile != null) {
String fbUserId = currentProfile.getId();
profileUrl = currentProfile.getProfilePictureUri(200, 200).toString();
Log.d("FB profile", "got new/updated profile from thread " + fbUserId);
// jump if logged in already
GetFacebookProfileAndJump(currentProfile);
}
}
};
Also ensure your OnCreate super is as follows
FacebookSdk.sdkInitialize(getApplicationContext());
mCallbackmanager = CallbackManager.Factory.create();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fbauth_);
...
You should add this to your acctivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
but if your using parse SDK add this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ParseFacebookUtils.onActivityResult(requestCode, resultCode, data);
}
I had the same problem, and solved by putting the facebook_app_id to strings.xml instead of a constant:
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
In my case i forgot to add application package name and class name on the developer page of facebook. After i added this information then it worked.
I have struggled with this problem and I fixed with multidex enabled
add this in your build file
multiDexEnabled true
also this code in your activity
#Override
protected void attachBaseContext(Context context) {
super.attachBaseContext(context);
MultiDex.install(this);
}
after adding this in your build gradle dependencies
compile 'com.android.support:multidex:1.0.1'
Actually this is happend. Because of the onActivityResult method has not implemented in side your Activity and also you must call
callbackManager.onActivityResult(requestCode, resultCode, data);
method inside this method. I am sure 100% your problem resolved.

Throws NullPointerException while retrieving data from SharedPreferences

First of all, sorry for my bad English !
I have an Activity ( say MainActivity.java ) and a class ( say AsynkTaskClass.java ).
AsynkTaskClass.java contains an AsynkTask. I am calling this AsynkTask from MainActivity.java.
Before calling this AsynkTask, I am saving some data using SharedPreferences.
From the onPostExecute function of AsynkTask, I am calling a normal function ( say displaySharedData() )which defined in MainActivity.java. There I am trying to retrieve the data I stored using SharedPreferences. Then It shows a NullPointerException. But I can access the Shared data from anywhere other than this displaySharedData() function.
This is the Log Output:
W/dalvikvm(3896): threadid=1: thread exiting with uncaught exception
E/AndroidRuntime(3896): FATAL EXCEPTION: main
E/AndroidRuntime(3896): java.lang.NullPointerExceptionE/AndroidRuntime(3896): at com.samApp.project.samApp.ui.MainActivity.displaySharedData(MainActivity.java:52)
E/AndroidRuntime(3896): at com.samApp.project.samApp.s3.AsynkTaskClass$UploadImage.onPostExecute(AsynkTaskClass.java:264)
E/AndroidRuntime(3896): at com.samApp.project.samApp.s3.AsynkTaskClass$UploadImage.onPostExecute(AsynkTaskClass.java:1)
E/AndroidRuntime(3896): at android.os.AsyncTask.finish(AsyncTask.java:417)
E/AndroidRuntime(3896): at android.os.AsyncTask.access$300(AsyncTask.java:127)
E/AndroidRuntime(3896): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
E/AndroidRuntime(3896): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(3896): at android.os.Looper.loop(Looper.java:130)
E/AndroidRuntime(3896): at android.app.ActivityThread.main(ActivityThread.java:3683)
E/AndroidRuntime(3896): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(3896): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime(3896): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
E/AndroidRuntime(3896): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
E/AndroidRuntime(3896): at dalvik.system.NativeStart.main(Native Method)
MainActivity.java
public class MainActivity extends Activity implements TextView.OnEditorActionListener {
public SharedPreferences myData;
public String mySharedData="com.samApp.project.samApp.ui";
public SharedPreferences.Editor editor;
protected void onCreate(Bundle savedBundle) {
super.onCreate(savedBundle);
myData = PreferenceManager.getDefaultSharedPreferences(this);
editor = myData.edit();
editor.commit();
attachfileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, PHOTO_SELECTED);
}
});
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case PHOTO_SELECTED:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
Log.d("URIsssss", String.valueOf(selectedImage));
AsynkTaskClass obj = new AsynkTaskClass ();
AsynkTaskClass.s3context=this;
obj.new UploadImage().execute(selectedImage);
}
}
}
}
protected void onResume() {
super.onResume();
editor.putString("name", "MeSSi");
editor.commit();
}
public void displaySharedData()
{
Log.d("SharedData",myData.getString("name","")); // line No : 52
}
}
AsynkTaskClass.java
public class AsynkTaskClass {
MainActivity mainActvtyObj = new MainActivity();
public static Context s3context;
protected void onPostExecute(S3TaskResult result) {
if(dialog != null)
dialog.dismiss();
if (result.getErrorMessage() != null) {
displayErrorAlert(
AsynkTaskClass.s3context.getString(R.string.upload_failure_title),
result.getErrorMessage());
}
mainActvtyObj.displaySharedData();
}
}
So, Any Help ??
MainActivity mainActvtyObj = new MainActivity();
Never instantiate activity classes with new.
For example, their lifecycle callbacks such as onCreate() are not run. You init your myData in onCreate() and it remains null in this activity instance.
Instead, pass a reference to your activity object to the async task as a parameter.
Finally I got a working solution.
I don't know whether It is perfect! But it works well..
I replaced the displaySharedData() calling statement i.e. mainActvtyObj.displaySharedData(); to the following :
((MainActivity) s3context).displaySharedData();
Now It Works Great !!

Categories