How do I solve IabHelper Error - java

I have an error on 264 and 163 of two file but in editor it's look fine
line 264 :
if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
line 163 :
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
I can't find why my activity unable to start
Logcat:
1266-1266/com.exercise.AndroidHTML E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exercise.AndroidHTML/com.company.clipboard.AndroidHTMLActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.company.clipboard.util.IabHelper.startSetup(IabHelper.java:264)
at com.company.clipboard.AndroidHTMLActivity.onCreate(AndroidHTMLActivity.java:163)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at android.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
This is the whole block of payment that contain line 163:
//=====================================================
String base64EncodedPublicKey = "MIHNMA0GCSqGSIb3DQEBAQUAA4G7ADCBtwKBrwDtUWVdLt6clZldCQGZxcyyWeeBp8vF/6qm7qCKuQPdXg6HB71hVu8lmcEO0VcyS2xpzXt03iW7LhKXRtDsxi5H9wHLESfY9SQUc0ugPD+n5nE+I6zCiB/RB2WscvZFa3JCiYRbmsvez+DwaQSHfq6CNUawl0fbz4NfJntZHKYHanm6PtjquO9JSj+Pa9PV38C3o5Y3ALCvPMCAwEAAQ==";
mHelper = new IabHelper(this, base64EncodedPublicKey);
mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
Log.d(TAG, "Query inventory finished.");
if (result.isFailure()) {
Log.d(TAG, "Failed to query inventory: " + result);
return;
}
else {
Log.d(TAG, "Query inventory was successful.");
// does the user have the premium upgrade?
mIsPremium = inventory.hasPurchase(SKU_PREMIUM);
if (mIsPremium){
MasrafSeke(inventory.getPurchase(SKU_PREMIUM));
}
// update UI accordingly
Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));
}
Log.d(TAG, "Initial inventory query finished; enabling main UI.");
}
};
mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
Log.d(TAG, "Error purchasing: " + result);
return;
}
else if (purchase.getSku().equals(SKU_PREMIUM)) {
// give user access to premium content and update the UI
Toast.makeText(AndroidHTMLActivity.this,"خرید موفق",Toast.LENGTH_SHORT).show();
MasrafSeke(purchase);
}
}
};
Log.d(TAG, "Starting setup.");
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
Log.d(TAG, "Setup finished.");
if (!result.isSuccess()) {
// Oh noes, there was a problem.
Log.d(TAG, "Problem setting up In-app Billing: " + result);
}
// Hooray, IAB is fully set up!
mHelper.queryInventoryAsync(mGotInventoryListener);
}
});

Seems an issue of IabHelper. The method queryIntentServices returns a null, instead an empty list.
Try to update the code from this:
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
// service available to handle that Intent
mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
else {
// no service available to handle that Intent
if (listener != null) {
listener.onIabSetupFinished(
new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
"Billing service unavailable on device."));
}
}
to this:
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
List<ResolveInfo> intentServices = mContext.getPackageManager().queryIntentServices(serviceIntent, 0);
if (intentServices != null && intentServices.isEmpty() == false) {
// service available to handle that Intent
mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
else {
// no service available to handle that Intent
if (listener != null) {
listener.onIabSetupFinished(
new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
"Billing service unavailable on device."));
}
}

Related

runOnUiThread: Cant touch the View, Exception

I know this has been posted multiple times now, but nothing seemed to fix my problem. I create a Loading Dialog on the UI thread, then start another thread which is doing some networking stuff and via interface, the class gets a callback, when networking is done. The problem is, after its done, i cant remove the loading dialog, even with "runOnUIThread". Here is the code:
public void onClickLoginButton (View view) {
if (!((EditText)findViewById(R.id.textNickname)).getText().toString().isEmpty() &&
!((EditText)findViewById(R.id.textPassword)).getText().toString().isEmpty()) {
loggingIn = new ProgressDialog(this);
loggingIn.setTitle("Login");
loggingIn.setMessage("Wait while logging in...");
loggingIn.show();
final LoginInterface callbackInterface = this;
new Thread(new Runnable() {
public void run() {
Networking net = new Networking();
net.Login(((EditText) findViewById(R.id.textNickname)).getText().toString(), ((EditText) findViewById(R.id.textPassword)).getText().toString(), callbackInterface);
}
}).start();
}
}
And this is the function that gets called by the networking stuff, after its done:
#Override
public void LoginCallback(final boolean loginSuccess, final boolean isActivated) {
loggingIn.hide();
loggingIn = null;
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
if (loginSuccess && isActivated) {
loggingIn.hide();
loggingIn = null;
finish();
} else if (loginSuccess == false) {
Toast.makeText(context, "Login failed! User/Password wrong", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Login failed! Account not activated", Toast.LENGTH_SHORT).show();
}
}
});
}
And this is the stack trace:
04-17 17:06:11.313 13018-13121/com.assigame.nidhoegger.assigame E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-1422
Process: com.assigame.nidhoegger.assigame, PID: 13018
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6122)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:850)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.setFlags(View.java:8908)
at android.view.View.setVisibility(View.java:6036)
at android.app.Dialog.hide(Dialog.java:299)
at com.assigame.nidhoegger.assigame.Login.LoginCallback(Login.java:72)
at com.assigame.nidhoegger.assigame.Networking.Login(Networking.java:134)
at com.assigame.nidhoegger.assigame.Login$1.run(Login.java:64)
at java.lang.Thread.run(Thread.java:841)
04-17 17:06:11.719 13018-13018/com.assigame.nidhoegger.assigame E/WindowManager﹕ android.view.WindowLeaked: Activity com.assigame.nidhoegger.assigame.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42284588 G.E..... R......D 0,0-684,324} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:366)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at com.assigame.nidhoegger.assigame.Login.onClickLoginButton(Login.java:56)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3818)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
You are calling the loggingIn.hide() method twice, and the first time not on the UI thread. Change your code to this:
#Override
public void LoginCallback(final boolean loginSuccess, final boolean isActivated) {
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
if (loginSuccess && isActivated) {
loggingIn.hide();
loggingIn = null;
finish();
} else if (loginSuccess == false) {
Toast.makeText(context, "Login failed! User/Password wrong", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Login failed! Account not activated", Toast.LENGTH_SHORT).show();
}
}
});
}

NullPointerException error. I cannot seem to spot the issue

Logcat error message.
I receive this error when I attempt to register an account on the application, the app crashes momentarily and returns to the login page.
02-14 13:11:19.857 31983-31983/example.com.androidim E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: example.com.androidim, PID: 31983
java.lang.NullPointerException
at example.com.androidim.SignUp$2$1$1.run(SignUp.java:126)
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:5103)
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:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606
at dalvik.system.NativeStart.main(Native Method)
The following is line 111-142 in the SignUp activity.
if (passwordText.getText().toString().equals(passwordAgainText.getText().toString())){
if (usernameText.length() >= 5 && passwordText.length() >= 5) {
Thread thread = new Thread(){
String result = new String();
#Override
public void run() {
result = imService.signUpUser(usernameText.getText().toString(),
passwordText.getText().toString(),
eMailText.getText().toString());
handler.post(new Runnable(){
public void run() {
if (result.equals(SERVER_RES_RES_SIGN_UP_SUCCESFULL)) {
Toast.makeText(getApplicationContext(),R.string.signup_successfull, Toast.LENGTH_LONG).show();
showDialog(SIGN_UP_SUCCESSFULL);
}
else if (result.equals(SERVER_RES_SIGN_UP_USERNAME_CRASHED)){
Toast.makeText(getApplicationContext(),R.string.signup_username_crashed, Toast.LENGTH_LONG).show();
showDialog(SIGN_UP_USERNAME_CRASHED);
}
else //if (result.equals(SERVER_RES_SIGN_UP_FAILED))
{
Toast.makeText(getApplicationContext(),R.string.signup_failed, Toast.LENGTH_LONG).show();
showDialog(SIGN_UP_FAILED);
}
}
});
}
When calling equals on your result variable, result is null. You have to do a null-check before calling equals.
public void run() {
if(result != null){
if (result.equals(SERVER_RES_RES_SIGN_UP_SUCCESFULL)) {
Toast.makeText(getApplicationContext(),R.string.signup_successfull, Toast.LENGTH_LONG).show();
showDialog(SIGN_UP_SUCCESSFULL);
}
else if (result.equals(SERVER_RES_SIGN_UP_USERNAME_CRASHED)){
Toast.makeText(getApplicationContext(),R.string.signup_username_crashed, Toast.LENGTH_LONG).show();
showDialog(SIGN_UP_USERNAME_CRASHED);
}
else //if (result.equals(SERVER_RES_SIGN_UP_FAILED))
{
Toast.makeText(getApplicationContext(),R.string.signup_failed, Toast.LENGTH_LONG).show();
showDialog(SIGN_UP_FAILED);
}else{
//result == null
}
}
}

Unable to start receiver NullPointerException

I have a BroadcastReceiver that receives an SMS and then is supposed to immediately send a reply SMS if the text has certain characters. Now it receives and sends the SMSs but it soon forces close giving something like: Unable to start receiver... NullPointerException... ActivityThread.handleReciever (paraphrasing) in the LogCat...what might be the issue? Here's my code, you're looking for the ELSE IF statement(that's the part that I'm currently testing):
public class Service extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.getAction()
.equals("android.provider.Telephony.SMS_RECEIVED")) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String msgFrom;
if (bundle != null) {
try {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
String verificationCode = "717345221";
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
msgFrom = msgs[i].getOriginatingAddress();
String encodeHash = Uri.encode("#");
msgFrom = "0" + msgFrom.substring(4) + encodeHash;
String msgBody = msgs[i].getMessageBody();
if (msgBody.startsWith(verificationCode)) {
this.abortBroadcast();
msgBody = msgBody.substring(verificationCode
.length());
try {
String dial = msgBody + "*" + msgFrom;
Intent call = new Intent(Intent.ACTION_CALL,
Uri.parse("tel:" + dial));
call.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(call);
} catch (Exception e) {
e.toString();
}
} else if (msgBody.contains("TEST123")) {
Toast.makeText(context,
"TEST123 text recieved",
Toast.LENGTH_LONG).show();
String transactionCode = null;
if (msgBody.length() > 9) {
transactionCode = msgBody.substring(0, 9);
}
String attachCode = "776f76wfuh";
String number = msgs[i].getOriginatingAddress();
String message = attachCode + transactionCode;
try {
SmsManager sms = SmsManager.getDefault();
PendingIntent pi = PendingIntent.getBroadcast(
context, 0, new Intent(context,
Service.class), 0);
sms.sendTextMessage(number, null, message, pi,
null);
Toast.makeText(context,
"Text sent with attach code",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO: handle exception
Log.d("Exception caught", e.getMessage());
}
}
}
} catch (Exception e) {
Log.d("Exception caught", e.getMessage());
}
}
}
}
}
Here's the LogCat:
10-31 20:42:05.269: E/AndroidRuntime(15080): FATAL EXCEPTION: main
10-31 20:42:05.269: E/AndroidRuntime(15080): java.lang.RuntimeException: Unable to start receiver com.adbionicpaymentsystem.Service: java.lang.NullPointerException
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.app.ActivityThread.handleReceiver(ActivityThread.java:1805)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.app.ActivityThread.access$2400(ActivityThread.java:117)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:981)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.os.Handler.dispatchMessage(Handler.java:99)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.os.Looper.loop(Looper.java:130)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.app.ActivityThread.main(ActivityThread.java:3683)
10-31 20:42:05.269: E/AndroidRuntime(15080): at java.lang.reflect.Method.invokeNative(Native Method)
10-31 20:42:05.269: E/AndroidRuntime(15080): at java.lang.reflect.Method.invoke(Method.java:507)
10-31 20:42:05.269: E/AndroidRuntime(15080): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875)
10-31 20:42:05.269: E/AndroidRuntime(15080): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
10-31 20:42:05.269: E/AndroidRuntime(15080): at dalvik.system.NativeStart.main(Native Method)
10-31 20:42:05.269: E/AndroidRuntime(15080): Caused by: java.lang.NullPointerException
10-31 20:42:05.269: E/AndroidRuntime(15080): at com.adbionicpaymentsystem.Service.onReceive(Service.java:21)
10-31 20:42:05.269: E/AndroidRuntime(15080): at android.app.ActivityThread.handleReceiver(ActivityThread.java:1794)
10-31 20:42:05.269: E/AndroidRuntime(15080): ... 10 more
be sure to have the permission in your manifest
<uses-permission android:name="android.permission.SEND_SMS"/>
and note that sendTextMessage
This method was deprecated in API level 4.
Use android.telephony.SmsManager.
Problem was I had another service running on the test device that seemingly interferes with this service

Android NPE with Admob Interstitial Ads

I've update my app adding Google Admob Interstital ads, they works perfect on my device and emulator, I don't get any error, I've tried everything to make the app crash but didn't happen.
This is the error shown on Google Play Developers Console:
java.lang.RuntimeException: Unable to pause activity {com.myapp.android/com.google.ads.AdActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:2859)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:2815)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:2793)
at android.app.ActivityThread.access$800(ActivityThread.java:138)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1224)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:4787)
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:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.myapp.android.f.a(Unknown Source)
at com.google.ads.b.w.q(Unknown Source)
at com.google.ads.AdActivity.h(Unknown Source)
at com.google.ads.AdActivity.onPause(Unknown Source)
at android.app.Activity.performPause(Activity.java:5106)
at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1225)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:2846)
... 12 more
The users says that the crash happens when they close the ad, this is my onDismissScreen method:
#Override
public void onDismissScreen(Ad ad) {
showInterstitial = false;
launchChapter(getSherlockActivity().getApplicationContext());
}
private void launchChapter(Context c) {
boolean extPlayer = Settings.getSettingPlayer(c);
boolean extCheck = Settings.extCheck(c);
boolean saveView = Settings.getSettingChapterView(c);
if (saveView == true) {
String vid = cid.replace(getString(R.string.chapter) + " ", "");
Settings.setChapterView(c, pid + "_" + vid, true);
}
if (extPlayer && extCheck)
new GetSources().initExternal(getString(R.string.url) + url, c);
else {
Intent intent = new Intent(c, Player.class);
intent.putExtra("ID", cid);
intent.putExtra("URL", url);
intent.putExtra("TITLE", title);
intent.putExtra("SCREEN", screen);
startActivity(intent);
}
}
Notice that 'com.myapp.android.f' is a fragment.

Twitter: After giving username and password the app gets crash

In my android application the data has to be shared using twitter so had followed this link http://androidcodeexamples.blogspot.in/2011/12/how-to-integrate-twitter-in-android.html, everything works fine, but after giving username and password, getting force close option.
here's the logcat output
01-17 17:07:54.118: E/AndroidRuntime(383): FATAL EXCEPTION: main
01-17 17:07:54.118: E/AndroidRuntime(383): java.lang.NullPointerException
01-17 17:07:54.118: E/AndroidRuntime(383): com.twitter.android.TwitterApp$1.handleMessage(TwitterApp.java:237)
01-17 17:07:54.118: E/AndroidRuntime(383): at android.os.Handler.dispatchMessage(Handler.java:99)
01-17 17:07:54.118: E/AndroidRuntime(383): at android.os.Looper.loop(Looper.java:123)
01-17 17:07:54.118: E/AndroidRuntime(383): at android.app.ActivityThread.main(ActivityThread.java:3683)
01-17 17:07:54.118: E/AndroidRuntime(383): at java.lang.reflect.Method.invokeNative(Native Method)
01-17 17:07:54.118: E/AndroidRuntime(383): at java.lang.reflect.Method.invoke(Method.java:507)
01-17 17:07:54.118: E/AndroidRuntime(383): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-17 17:07:54.118: E/AndroidRuntime(383): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-17 17:07:54.118: E/AndroidRuntime(383): at dalvik.system.NativeStart.main(Native Method)
this is the code in mainactivity
public class Singlemenuitem extends Activity {
private TwitterApp mTwitter;
private static final String CONSUMER_KEY = "6JyIkj71ZqG4wk3YF0Y4hw";
private static final String CONSUMER_SECRET = "sJl9aRVqlEt7nxlKvpMVK6tLULz5FSQ2KUOW0yie4";
private enum FROM {
TWITTER_POST, TWITTER_LOGIN
};
private enum MESSAGE {
SUCCESS, DUPLICATE, FAILED, CANCELLED
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
mTwitter = new TwitterApp(this, CONSUMER_KEY, CONSUMER_SECRET);
//share twitter
final ImageView twitter = (ImageView) findViewById(R.id.twitter);
twitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
mTwitter.resetAccessToken();
if (mTwitter.hasAccessToken() == true) {
try {
mTwitter.updateStatus(String.valueOf(Html
.fromHtml(TwitterApp.MESSAGE)));
// File f = new File("/mnt/sdcard/android.jpg");
// mTwitter.uploadPic(f, String.valueOf(Html
// .fromHtml(TwitterApp.MESSAGE)));
postAsToast(FROM.TWITTER_POST, MESSAGE.SUCCESS);
} catch (Exception e) {
if (e.getMessage().toString().contains("duplicate")) {
postAsToast(FROM.TWITTER_POST, MESSAGE.DUPLICATE);
}
e.printStackTrace();
}
mTwitter.resetAccessToken();
} else {
mTwitter.authorize();
}
}
private void postAsToast(FROM twitterPost, MESSAGE success) {
switch (twitterPost) {
case TWITTER_LOGIN:
switch (success) {
case SUCCESS:
Toast.makeText(Singlemenuitem.this, "Login Successful", Toast.LENGTH_LONG)
.show();
break;
case FAILED:
Toast.makeText(Singlemenuitem.this, "Login Failed", Toast.LENGTH_LONG).show();
default:
break;
}
break;
case TWITTER_POST:
switch (success) {
case SUCCESS:
Toast.makeText(Singlemenuitem.this, "Posted Successfully", Toast.LENGTH_LONG)
.show();
break;
case FAILED:
Toast.makeText(Singlemenuitem.this, "Posting Failed", Toast.LENGTH_LONG)
.show();
break;
case DUPLICATE:
Toast.makeText(Singlemenuitem.this,
"Posting Failed because of duplicate message...",
Toast.LENGTH_LONG).show();
default:
break;
}
break;
}
TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
public void onError(String value) {
postAsToast(FROM.TWITTER_LOGIN, MESSAGE.FAILED);
Log.e("TWITTER", value);
mTwitter.resetAccessToken();
}
public void onComplete(String value) {
try {
mTwitter.updateStatus(TwitterApp.MESSAGE);
postAsToast(FROM.TWITTER_POST, MESSAGE.SUCCESS);
} catch (Exception e) {
if (e.getMessage().toString().contains("duplicate")) {
postAsToast(FROM.TWITTER_POST, MESSAGE.DUPLICATE);
}
e.printStackTrace();
}
mTwitter.resetAccessToken();
}

Categories