I have a button in an activity, i would like when a user click a button it makes him pay a fee to access it. with my code the button isn't clickable at all, when I take off this line " upper.setEnabled(true); " the button is clickable but the billing isnt starting.
this is my code :
public class Main extends Activity {
private Vibrator myVib;
static final String ITEM_SKU = "android.test.purchased";
IabHelper mHelper;
private static final String TAG = "com.dave.where.inappbilling";
private Button upper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myVib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
String base64EncodedPublicKey = "<My License key>";
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
Log.d(TAG, "In-app Billing setup failed: " + result);
} else {
Log.d(TAG, "In-app Billing is set up OK");
}
}
});
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result,
Purchase purchase) {
if (result.isFailure()) {
// Handle error
return;
} else if (purchase.getSku().equals(ITEM_SKU)) {
consumeItem();
upper.setEnabled(false);
}
}
};
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase, IabResult result) {
if (result.isSuccess()) {
upper.setEnabled(true);
} else {
// handle error
}
}
};
upper = (Button) findViewById(R.id.upper);
upper.setEnabled(false);
upper.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),
Exerciseupper.class);
startActivity(intent);
}
});
}
public void consumeItem() {
mHelper.queryInventoryAsync(mReceivedInventoryListener);
}
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
if (result.isFailure()) {
// Handle failure
} else {
// mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),
// mConsumeFinishedListener);
}
}
};
public void upperClicked(View view) {
upper.setEnabled(true);
}
public void buyClick(View view) {
// mHelper.launchPurchaseFlow(this, ITEM_SKU, 10001,
// mPurchaseFinishedListener, "mypurchasetoken");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mHelper != null)
mHelper.dispose();
mHelper = null;
}
}
upper.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),
Exerciseupper.class);
startActivity(intent);
}
});
change this to:
upper.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),
Exerciseupper.class);
startActivity(intent);
}
});
Related
I am using the ZXING QR Code Reader. It is working fine. Detecting codes etc but it does not shows any detection progress(Like red line) while it is scanning the QR Code. Here is Screenshot
And my ScanActivity is,
ScanCode.Java
public class ScanCode extends Activity implements OnClickListener {
Button btnScan;
TextView scanResult;
String text;
Bitmap bmp;
ImageView ivPic;
#Override
public void onCreate(Bundle icicle) {
// TODO Auto-generated method stub
super.onCreate(icicle);
setContentView(R.layout.scan_code);
initViews();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.btnScanCode) {
Intent intent = new Intent(
"com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 1);
}
}
private void initViews() {
scanResult = (TextView) findViewById(R.id.scanResult);
ivPic = (ImageView) findViewById(R.id.capturedImg);
btnScan = (Button) findViewById(R.id.btnScanCode);
btnScan.setOnClickListener(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1)
if (resultCode == Activity.RESULT_OK) {
String contents = data.getStringExtra("SCAN_RESULT");
String format = data.getStringExtra("SCAN_RESULT_FORMAT");
Toast.makeText(getApplicationContext(), contents,
Toast.LENGTH_SHORT).show();
scanResult.setText(contents);
}// if result_ok
}// onActivityResult
}
I know this answer is bit late but I've just used Zxing barcode/QR-Code scanner recently in my app, if anyone has issue implementing it just follow the steps below (Using Android Studio Official IDE for android).
First add dependencies in app --> build.gradle file
dependencies {
compile 'com.journeyapps:zxing-android-embedded:3.2.0#aar'
compile 'com.google.zxing:core:3.2.1'
}
Activity Usage:
public class MainActivity extends AppCompatActivity {
Button btnScan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnScan = (Button) findViewById(R.id.btnScan);
btnScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanBarcode();
}
});
}
private void scanBarcode()
{
new IntentIntegrator(this).initiateScan();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Log.d("MainActivity", "Cancelled scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Log.d("MainActivity", "Scanned");
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
}
}
}
If you want to use custom callback and BarCodeView. Zxing provide this functionality simply make layout file
<com.journeyapps.barcodescanner.CompoundBarcodeView
android:id="#+id/barcode_scanner"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.journeyapps.barcodescanner.CompoundBarcodeView>
<TextView
android:id="#+id/tvScanResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scan Results will be shown here"
android:textColor="#android:color/white"
android:textStyle="bold"/>
In Activity use the following code
public class MainActivity extends AppCompatActivity
{
CompoundBarcodeView barcodeView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
barcodeView = (CompoundBarcodeView) findViewById(R.id.barcode_scanner);
barcodeView.decodeContinuous(callback);
barcodeView.setStatusText("");
}
#Override
protected void onResume()
{
super.onResume();
barcodeView.resume();
isScanned = false;
}
#Override
protected void onPause()
{
super.onPause();
barcodeView.pause();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
return barcodeView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
}
private BarcodeCallback callback = new BarcodeCallback()
{
#Override
public void barcodeResult(BarcodeResult result)
{
if (result.getText() != null)
{
barcodeView.setStatusText(result.getText());
tvscanResult.setText("Data found: " + result.getText());
}
//you can also Add preview of scanned barcode
//ImageView imageView = (ImageView) findViewById(R.id.barcodePreview);
//imageView.setImageBitmap(result.getBitmapWithResultPoints(Color.YELLOW));
}
#Override
public void possibleResultPoints(List<ResultPoint> resultPoints)
{
System.out.println("Possible Result points = " + resultPoints);
}
};
}
Source zxing-android-embedded. Hope someone get help from this solution
I am writing a log in fragment that hosts Facebook and Google+ sign in. The fragment is a parent fragment for three fragments with user content that are called with view pager after successful log in. I am storing email and service name in shared preferences upon retrieval from Google or Facebook, and then if successful the view pager is displayed with user fragments. Facebook log in works fine but when I start Google+ sign in it does not get to the onConnected callback method. When I switch to other tabs and return to log in fragment it is somehow triggered and I get user fragments. How can i trigger the onConnected method upon pressing the Google+ sign in button?
to ensure the onActivityResult is called i added this in main activity
MainActivity.java
#Override
protected void onActivityResult(int arg0, int arg1, Intent arg2) {
// TODO Auto-generated method stub
super.onActivityResult(arg0, arg1, arg2);
LoginFragment lf = (LoginFragment)getSupportFragmentManager().findFragmentByTag("Login");
if (lf != null) {
lf.onActivityResult(arg0, arg1, arg2);
}
}
LoginFragment.java
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
// Session class instance
mSession = new SessionManager(getActivity());
setupGoogleplus();
loginButton = (SignInButton) getActivity().findViewById(R.id.sign_in_button);
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!mPlusClient.isConnected()) {
if (mConnectionResult == null) {
mConnectionProgressDialog.show();
} else {
try {
mConnectionResult.startResolutionForResult(getActivity(), REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
// Try connecting again.
mConnectionResult = null;
mPlusClient.connect();
}
}
}
}
});
setupViewPager();
if (mSession.isLoggedIn()) {
onLoged();
}
}
private void setupViewPager() {
mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getChildFragmentManager());
mViewPager = (ViewPager) getActivity().findViewById(R.id.pager);
}
private void setupGoogleplus() {
// google+ part
mPlusClient = new PlusClient.Builder(getSherlockActivity(), new ConnectionCallbacks() {
#Override
public void onConnected(Bundle connectionHint) {
String accountName = mPlusClient.getAccountName();
// new
// DownloadImageTask(userPicture).execute(mPlusClient.getCurrentPerson().getImage().getUrl());
// Toast.makeText(getActivity(), accountName + " is connected.",
// Toast.LENGTH_LONG).show();
mConnectionProgressDialog.dismiss();
mSession.createLoginSession(mPlusClient.getCurrentPerson().getName().getGivenName().toString(), mPlusClient.getAccountName(), "Google+");
}
#Override
public void onDisconnected() {
Log.d(TAG, "disconnected");
}
}, new OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
if (mConnectionProgressDialog.isShowing()) {
// The user clicked the sign-in button already. Start to
// resolve
// connection errors. Wait until onConnected() to dismiss
// the
// connection dialog.
if (result.hasResolution()) {
try {
result.startResolutionForResult(getActivity(), REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
}
// Save the result and resolve the connection failure upon a
// user click.
mConnectionResult = result;
}
}).setActions("http://schemas.google.com/AddActivity", "http://schemas.google.com/BuyActivity").build();
mConnectionProgressDialog = new ProgressDialog(getActivity());
mConnectionProgressDialog.setMessage("Signing in...");
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
// Request user data and show the results
Request.newMeRequest(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
// TODO Auto-generated method stub
if (user != null) {
// Display the parsed user info
// Set the id for the ProfilePictureView
// view that in turn displays the profile picture.
// profilePictureView.setProfileId(user.getId());
// Set the Textview's text to the user's name.
mSession.createLoginSession(user.getName(), user.getProperty("email").toString(), "Facebook");
onLoged();
}
}
}).executeAsync();
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
#Override
public void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == REQUEST_CODE_RESOLVE_ERR) {
mConnectionResult = null;
mPlusClient.connect();
} else {
uiHelper.onActivityResult(requestCode, responseCode, intent);
}
super.onActivityResult(requestCode, responseCode, intent);
}
private static class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new FirstFragment();
case 1:
return new SecondFragment();
case 2:
return new ThirdFragment();
}
return null;
}
#Override
public int getCount() {
return NUMBER_OF_PAGES;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "1";
case 1:
return "2";
case 2:
return "3";
}
return null;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.login_fragment, container, false);
authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("email"));
return view;
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
#Override
public void onStart() {
mPlusClient.connect();
super.onStart();
}
#Override
public void onStop() {
super.onStop();
mPlusClient.disconnect();
}
public void googleLogout() {
if (mPlusClient.isConnected()) {
mPlusClient.clearDefaultAccount();
mPlusClient.disconnect();
mPlusClient.connect();
mSession.logoutUser();
}
}
public void onLoged() {
mViewPager.setAdapter(mMyFragmentPagerAdapter);
mViewPager.setVisibility(View.VISIBLE);
authButton.setVisibility(View.INVISIBLE);
loginButton.setVisibility(View.INVISIBLE);
}
public void onNotLoged() {
mViewPager.setAdapter(null);
mViewPager.setVisibility(View.INVISIBLE);
authButton.setVisibility(View.VISIBLE);
loginButton.setVisibility(View.VISIBLE);
}}
In onConnected method I call mySession object creation (shared preferences) to store the data and onLoged to display user fragments. Why do I have to switch tabs a few times for onConnected to be called?
Because the resolution for the connection failure was started with startIntentSenderForResult and the code REQUEST_CODE_RESOLVE_ERR, you need to capture the result inside Activity.onActivityResult.
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == RESULT_OK) {
mConnectionResult = null;
mPlusClient.connect();
}
}
So in your case you should call mPlusClient.connect(); in LoginFragment onActivityResult after all needed checks.
I need to show my facebook friends in listview..
my code is here..
when i launch it in emulator it stop working..
pls help me...
I need to show my facebook friends in listview..
my code is here..
when i launch it in emulator it stop working..
pls help me...
i refer code is [1]: http://pastebin.com/5fCRxtL
public class LoginActivity extends Activity{
private static final String[] PERMISSIONS = new String[] {"publish_stream","publish_checkins", "read_stream", "offline_access"};
public static final String APP_ID = "**************";
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
private ProgressDialog mProgress;
private Handler mHandler = new Handler();
private ProgressDialog mSpinner;
private Handler mRunOnUi = new Handler();
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
public static ArrayList<String> friends ;
String _error;
// private FriendsArrayAdapter friendsArrayAdapter;
// SharedPreferences.Editor editor;
TextView tv;
Button loginButton;
private UiLifecycleHelper uiHelper;
private ContextWrapper uiActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setContentView(R.layout.login);
friends= new ArrayList<String>();
tv=(TextView)LoginActivity.this.findViewById(R.id.textview1);
loginButton=(Button)findViewById(R.id.button_login);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (! facebook.isSessionValid()) {
facebook.authorize(LoginActivity.this, PERMISSIONS, new LoginDialogListener());
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("FB Demo App", "onActivityResult(): " + requestCode);
facebook.authorizeCallback(requestCode, resultCode, data);
}
private class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
saveCredentials(facebook);
getAlbumsData task = new getAlbumsData();
task.execute();
mHandler.post(new Runnable() {
public void run() {
//--- Intent i = new Intent(LoginActivity.this,FrndActivity.class);
//--- i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//--- startActivity(i);
}
});
mAsyncRunner.request("me/friends", new FriendsRequestListener());
}
private void saveCredentials(Facebook facebook) {
// TODO Auto-generated method stub
}
public void onFacebookError(FacebookError error) {
showToast("Authentication with Facebook failed!");
}
public void onError(DialogError error) {
showToast("Authentication with Facebook failed!");
}
public void onCancel() {
showToast("Authentication with Facebook cancelled!");
}
}
public void showToast(String string) {
// TODO Auto-generated method stub
}
public class getAlbumsData {
public void execute() {
// TODO Auto-generated method stub
}
}
private class FriendsRequestListener implements RequestListener {
String friendData;
//Method runs when request is complete
public void onComplete(String response, Object state) {
Log.v("", "FriendListRequestONComplete");
//Create a copy of the response so i can be read in the run() method.
friendData = response;
Log.v("friendData--", ""+friendData);
//Create method to run on UI thread
LoginActivity.this.runOnUiThread(new Runnable() {
public void run() {
try {
//Parse JSON Data
JSONObject json;
json = Util.parseJson(friendData);
//Get the JSONArry from our response JSONObject
JSONArray friendArray = json.getJSONArray("data");
Log.v("friendArray--", ""+friendArray);
for(int i = 0; i< friendArray.length(); i++)
{
JSONObject frnd_obj = friendArray.getJSONObject(i);
friends.add(frnd_obj.getString("name")+"~~~"+frnd_obj.getString("id"));
}
Intent ide = new Intent(LoginActivity.this,FrndActivity.class);
ide.putStringArrayListExtra("friends", friends);
// ide.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(ide);
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,android.R.id.text1, friends_list);
// lv.setAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
}
Please pay attention...the AsyncFacebookRunner is deprecated,as it's shown on the Facebook documentation.
https://developers.facebook.com/docs/reference/android/current/AsyncFacebookRunner/
I have implemented Inapp Billing in my app. For that i have used buttons. when i click button it goes to the purchase activity and it purchases the product. once it purchases the product the button will be invisible. and the other button will be visible which will allow the user to open the product. It is all happening perfectly.But when i reopen the app again the button for purchase is visible . i do not want the button to be visible once it is purchased. how to make the button invisible once it is used for successful purchase.
StartUpActivity.java
public class StartUpActivity extends PurchaseActivity implements OnIabSetupFinishedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("App started");
}
#Override
public void onIabSetupFinished(IabResult result) {
if (result.isSuccess()) {
Log.d("In-app Billing set up" + result);
dealWithIabSetupSuccess();
} else {
Log.d("Problem setting up In-app Billing: " + result);
dealWithIabSetupFailure();
}
}
#Override
protected void dealWithIabSetupSuccess() {
navigate().toMainActivity();
finish();
}
#Override
protected void dealWithIabSetupFailure() {
popBurntToast("Sorry In App Billing isn't available on your device");
}
}
MainActivity.java
public class MainActivity extends BlundellActivity implements MainMenu {
public Button topicsbutton;
public Button mediabutton;
public Button purchasetopicsbutton;
public Button purchasemediabutton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
topicsbutton = (Button) findViewById(R.id.button1a);
mediabutton = (Button) findViewById(R.id.button2a);
purchasetopicsbutton = (Button) findViewById(R.id.button1);
purchasemediabutton = (Button) findViewById(R.id.button2);
}
#Override
public void onTopicsPurchaseItemClick(View v) {
navigate().toPurchaseTopicsActivityForResult();
}
#Override
public void onMediaPurchaseItemClick(View v) {
navigate().toPurchaseMediaActivityForResult();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Navigator.REQUEST_TOPICS_PURCHASE == requestCode) {
if (RESULT_OK == resultCode) {
dealWithSuccessfulTopicsPurchase();
} else {
dealWithFailedTopicsPurchase();
}
} else if (Navigator.REQUEST_MEDIA_PURCHASE == requestCode) {
if (RESULT_OK == resultCode) {
dealWithSuccessfulMediaPurchase();
} else {
dealWithFailedMediaPurchase();
}
}
}
public void dealWithSuccessfulTopicsPurchase() {
Log.d("Topics purchased");
popToast("Topics purchased");
topicsbutton.setVisibility(View.VISIBLE);
purchasetopicsbutton.setVisibility(View.INVISIBLE);
}
private void dealWithSuccessfulMediaPurchase() {
Log.d("Media purchased");
popToast("Media purchased");
mediabutton.setVisibility(View.VISIBLE);
purchasemediabutton.setVisibility(View.INVISIBLE);
}
private void dealWithFailedTopicsPurchase() {
Log.d("Topics purchase failed");
popToast("Failed to purchase Topics");
}
private void dealWithFailedMediaPurchase() {
Log.d("Media purchase failed");
popToast("Failed to purchase Media");
}
public void TopicsOpen(View v) {
navigate().toTopicsopen();
}
public void MediaOpen(View v) {
navigate().toMediaopen();
}
}
PurchaseActivity.java
public abstract class PurchaseActivity extends BlundellActivity implements OnIabSetupFinishedListener, OnIabPurchaseFinishedListener {
private IabHelper billingHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_purchase);
setResult(RESULT_CANCELED);
billingHelper = new IabHelper(this, AppProperties.BASE_64_KEY);
billingHelper.startSetup(this);
}
#Override
public void onIabSetupFinished(IabResult result) {
if (result.isSuccess()) {
Log.d("In-app Billing set up" + result);
dealWithIabSetupSuccess();
} else {
Log.d("Problem setting up In-app Billing: " + result);
dealWithIabSetupFailure();
}
}
protected abstract void dealWithIabSetupSuccess();
protected abstract void dealWithIabSetupFailure();
protected void purchaseItem(String sku) {
billingHelper.launchPurchaseFlow(this, sku, 123, this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
billingHelper.handleActivityResult(requestCode, resultCode, data);
}
#Override
public void onIabPurchaseFinished(IabResult result, Purchase info) {
if (result.isFailure()) {
dealWithPurchaseFailed(result);
} else if (Items.SKU1.equals(info.getSku())) {
dealWithTopicsPurchaseSuccess(result, info);
}
else if (Items.SKU2.equals(info.getSku())) {
dealWithMediaPurchaseSuccess(result, info);
}
finish();
}
protected void dealWithPurchaseFailed(IabResult result) {
Log.d("Error purchasing: " + result);
}
protected void dealWithTopicsPurchaseSuccess(IabResult result, Purchase info) {
Log.d("Item purchased: " + result);
}
protected void dealWithMediaPurchaseSuccess(IabResult result, Purchase info) {
Log.d("Item purchased: " + result);
billingHelper.consumeAsync(info, null);
}
#Override
protected void onDestroy() {
disposeBillingHelper();
super.onDestroy();
}
private void disposeBillingHelper() {
if (billingHelper != null) {
billingHelper.dispose();
}
billingHelper = null;
}
}
If you are using the API version 3 you can call getPurchases() method at the onCreate().
This method returns the current un-consumed products owned by the user.
That means if your product is un-consumable, i.e, user will only buy it once then you will have your necessary info right here.
Can't explain how to do it better than in official documentation. Take a look at the Querying for Purchased Items topic to have a code example.
Basically you will receive a list of ownedSkus (owned product ID's) and all you have to do is a loop over this list and make your buttons invisible/ visible.
Let me know if this what you was looking for :)
I have implemented login with facebook in my project.
The code is below:
public class login extends Activity{
ImageView fbtn;
private SharedPreferences mPrefs;
static Facebook facebook = new Facebook("271089732997803");
String access_token;
long expires;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.yf_login1);
mPrefs = getPreferences(MODE_PRIVATE);
access_token = mPrefs.getString("access_token", null);
expires = mPrefs.getLong("access_expires", 0);
fbtn = (ImageView)findViewById(R.id.fbtn);
fbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(access_token != null) {
facebook.setAccessToken(access_token);
Log.v("access_token", access_token);
}
if(expires != 0) {
facebook.setAccessExpires(expires);
Log.i("expires", ""+expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(login.this,new String[] {}, new DialogListener() {
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}
else{
startActivity(new Intent(login.this,ChooseTeam.class));
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
#Override
public void onResume() {
super.onResume();
facebook.extendAccessTokenIfNeeded(this, null);
}
Now my question is when i click on the the fb button it will load the progress bar and after 30-40 second it returns the same page.
The most important thing is when i run the same project in my another pc it will run perfectly, opens the dialog of login for the facebook and got the value in my preferences. But in my case i cannot even get the preferences made in my data.
What will be the problem in my emulator?? I am using eclipse galilio and sdk20.
I got the solution actually my antivirus is blocked the internet for the emulator. So i have uninstalled the antivirus and run the app and it works.
Thank you all for helping me out.
Try this....
and use this Permission for Share in Facebook..
private String[] mPermissions={"publish_stream"};
mFb.authorize(SettingActivity.this, mPermissions,new com.fbintegration.Facebook.DialogListener()
{
public void onFacebookError(FacebookError e)
{
}
public void onError(DialogError e)
{
}
public void onComplete(Bundle values)
{
SessionStore.save(mFb, getApplicationContext());
}
public void onCancel()
{
// TODO Auto-generated method stub
}
});
and this is Facebook Connector Class....
public class FacebookConnector
{
private Facebook facebook = null;
private Context context;
private String[] permissions;
private Handler mHandler;
private Activity activity;
//private SessionListener mSessionListener = new SessionListener();;
public FacebookConnector(String appId,Activity activity,Context context,String[] permissions)
{
this.facebook = new Facebook(appId);
SessionStore.restore(facebook, context);
this.context=context;
this.permissions=permissions;
this.mHandler = new Handler();
this.activity=activity;
}
public void login()
{
if (!facebook.isSessionValid())
{
facebook.authorize(this.activity, this.permissions,new LoginDialogListener());
}
}
/*public void logout()
{
SessionEvents.onLogoutBegin();
AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(this.facebook);
asyncRunner.logout(this.context, new LogoutRequestListener());
}*/
public void postMessageOnWall(String msg)
{
if (facebook.isSessionValid())
{
Bundle parameters = new Bundle();
parameters.putString("message", msg);
try
{
//JSONObject response=Util.parseJson(facebook.request("me/feed", parameters,"POST"));
String response = facebook.request("me/feed", parameters,"POST");
System.out.println(response);
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
}
}
private final class LoginDialogListener implements DialogListener
{
public void onComplete(Bundle values)
{
SessionEvents.onLoginSuccess();
}
public void onFacebookError(FacebookError error)
{
SessionEvents.onLoginError(error.getMessage());
}
public void onError(DialogError error)
{
SessionEvents.onLoginError(error.getMessage());
}
public void onCancel()
{
SessionEvents.onLoginError("Action Canceled");
}
}
private class SessionListener implements AuthListener, LogoutListener
{
public void onAuthSucceed()
{
SessionStore.save(facebook, context);
}
public void onAuthFail(String error) {
}
public void onLogoutBegin() {
}
public void onLogoutFinish() {
SessionStore.clear(context);
}
}
public Facebook getFacebook()
{
return this.facebook;
}
}