I am developing an app which has google in app purchase. There is a button buy now and after clicking the button I have to call inapp purchase but here is the problem I am facing, the buy now button is in an adapter class hence how can I do inapp purchase in an adapter class
here is my code
public void onClick(View v) {
switch (v.getId()) {
case R.id.loadmore_btn:
// call a url with ofset & limit with Thread
if (getbookItems.getContentName() == "LoadMore") {
booksItemsInfo.remove(booksItemsInfo.size() - 1);
}
if (UIAndDataLoader.offset < bookcategoryItem.getCount()) {
if (UIAndDataLoader.offset < DBTotalContentCount) {
UIAndDataLoader.offset = UIAndDataLoader.offset + 10;
UIAndDataLoader.loadFlag = 0;
myActivity.Tostart();
} else {
myActivity.URLConfig = MagURLConfig.bURL
+ MagURLConfig.uMAILIDNAME
+ _Settings.getString("setEmail-ID", null)
+ MagURLConfig.uPASSWORD
+ _Settings.getString("setPassword", null)
+ MagURLConfig.CATEGORYID
+ bookcategoryItem.getCatId() + MagURLConfig.OFFSET
+ DBTotalContentCount + MagURLConfig.LIMIT;
UIAndDataLoader.bookcountlimit = 1;
myActivity.toStartRefresh(true);
}
}
break;
case R.id.btn_buynow:
// System.out.println("this is buy btn------------->");
BookDataLoader.ActionButtonOnclick(btn_txt, action_btn,
getbookItems, "");
break;
case R.id.preview:
BookDataLoader.ActionButtonOnclick(btn_txt, action_btn,
getbookItems, "Preview");
break;
}
}
}
You can declare the adapter class in the same activity.thats why you can user mHelper object.
I done the same functionality in one of application for in puchase item.
like:-
holder.relative_layout_btn_buy.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
if(isOnline())
mHelper.launchPurchaseFlow(OnlineStoreList.this,"android.test.purchased",RC_REQUEST,mPurchaseFinishedListener, "");
else
{
NetworkAlert();
}
} catch (Exception e) {
// Toast.makeText(getApplicationContext(),"Please wait...Try after some time!! " ,1).show();
Log.e("Exception", "===>" + e.toString());
complain(e.getMessage());
}
}
});
I hope with will help.Thanks!!
Related
I am trying to display my text file on clicking continue button when dialog appears. This is how far i have done. When i click "Continue" button it isn't showing any text in dialog.
My text file is saved on desktop.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void OnLoad(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please read carefully!");
builder.setIcon(R.drawable.news);
builder.setCancelable(false);
builder.setPositiveButton("Yes", new OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
try {
FileInputStream fin =openFileInput("bloodline.txt");
InputStreamReader insr = new InputStreamReader(fin);
int i = 0;
String str = "";
while ((i = insr.read()) != -1) {
str = str + (char) i;
}
Toast.makeText(getBaseContext(), " " + str,
Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
System.out.println("File Not available " + e.getMessage());
Toast.makeText(getBaseContext(),
"File Not available " + e.getMessage(), Toast.LENGTH_SHORT)
.show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(getBaseContext(), "IO Exception " + e.getMessage(),
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
);
builder.setNegativeButton("Declined", new OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getBaseContext(), "You have declined",
Toast.LENGTH_SHORT).show();
}
});
}
}
Thanks in advance.
It would be better if you just go through some of these links that I'm listing below,then you'll have the basic idea of how to create dialog depending upon your needs.
Link 1: Which is a nice example from android.developer's site and recommended.
Link 2: Popular android tutorials from Vogella
Link 3: This link will be explaining you to create Custom Dialogs.
Link 4: Overview of creating dialog from android developers
Link 5: From AndroidHive
I hope this will help you a lot.
I have a spinner item.When I click on position 2. I want the following code to execute.
if (pos == 2) {
Log.e("TEST", "YOU CLICKED" + pos);
for (int i = 0; i < 2; i++) {
Log.e("TEST INSIDE FOR", "YOU CLICKED" + pos);
if (i % 2 == 0) {
// showFragOne();
showFragOne();
Log.e("TEST INSIDE FOR " + i, "YOU CLICKED" + pos);
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (i %2 == 1) {
// showFragTwo();
showFragTwo();
Log.e("TEST INSIDE FOR " + i, "YOU CLICKED" + pos);
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Toast.makeText(mCoreContext,"One Fragment added from feature app",Toast.LENGTH_LONG).show();
}
What i want this code to do is change the Frame layout in 20s. But only the second fragment I am getting at last. Here showFragTwo() function:-
private void showFragTwo() {
// TODO Auto-generated method stub
FragmentTransaction ft =
.getFragmentManager().beginTransaction();
if (fragtwo.isAdded()) {
if (fragtwo.isHidden())
ft.show(fragtwo);
else
ft.hide(fragtwo);
ft.commit();
} else {
ft.replace(com.example.coreapp.R.id.container, fragtwo,
"ADDFRAGTWO").commit();
ft.show(fragtwo);
}
}
Here showFragOne() function:-
private void showFragOne() {
// TODO Auto-generated method stub
FragmentTransaction ft =
.getFragmentManager().beginTransaction();
if (frag.isAdded()) {
if (frag.isHidden())
ft.show(frag);
else
ft.hide(frag);
ft.commit();
} else {
ft.replace(com.example.coreapp.R.id.container, frag, "ADDFRAG")
.commit();
ft.show(frag);
}
}
where i initialize frag and fragtwo at top to following to fragment class :-
frag = new AddFragmentOne();
fragtwo = new AddFragmentTwo();
I get the following as logcat o/p.
**02-28 04:56:34.250: E/TEST INSIDE FOR: YOU CLICKED2
02-28 04:56:34.290: E/TEST INSIDE FOR 0: YOU CLICKED2
02-28 04:56:54.350: E/TEST INSIDE FOR: YOU CLICKED2
02-28 04:56:54.350: E/TEST INSIDE FOR 1: YOU CLICKED2**
I am getting the logs message in o/p BUT WHY THE FRAGMENT IS NOT GETTING DISPLAYED?
ONLY THE SECOND FRAGMENT I AM GETTING
If i comment second if statemnt I AM GETTING FIRST FRAGMENT
Can anybody tell me where i am getting wrong?
This happens because you make the Thread sleep 20 seconds and its likely the Ui Thread.
You should replace this Thread.sleep() statement by a Timer that shows the appropriate fragment :
if(pos == 2) {
showFragOne();
new Timer().schedule(new TimerTask() {
#Override
public void run() {
showFragTwo();
}
}, 20000);
}
To complete the answer based on commentaries : I suggest you make one method
/** This method shows the fragment whose 'number' is {#code fragmentNumber}. */
public void showFrag(int fragmentNumber) {
Fragment f = fragments.get(fragmentNumber); // fragments can be a List for example
// Then use the code you already have to show fragment 'f'
}
Then, you can modify the preceding code like this :
if(pos == 2) {
final AtomicInteger count = new AtomicInteger(0); // Because use inside TimerTask requires a final variable
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if(count.get() < MAX_FRAG_INDEX)
showFrag(count.getAndIncrement);
else
cancel();
}
}, 0, 2000);
}
i am using in-app purchase for my quiz app to buy coins.And i have added 2 coins category 100 coins and 500 coins respectively.I have also added 2 SKU.My both coin purchase works well.While i purchase 100 coins and consume.100 coins gets added to app but when i purchase 500 coins once again 100 coins get added and not 500.I really need a helping hand as i am stuck with this for weeks.Here is the consume app purchase code
private void update() {
ArrayList<String> moreSkus = new ArrayList<String>();
moreSkus.add(SKU);
moreSkus.add(SKU_500);
buyHelper.queryInventoryAsync(true, moreSkus, new QueryInventoryFinishedListener() {
#Override
public void onQueryInventoryFinished(IabResult result, Inventory inv) {
if(result.isSuccess()) {
// SkuDetails details = inv.getSkuDetails(SKU);
//String price = details.getPrice();
//TextView tvPrice = (TextView)GameActivity.this.findViewById(R.id.textview_price);
// tvPrice.setText(price);
purchase = inv.getPurchase(SKU);
// purchase = inv.getPurchase(SKU_500);
purchase=inv.getPurchase(SKU_500);
if(purchase!=null) {
// buy100coins.setEnabled(false);
//coins_one_hundred.setVisibility(View.GONE);
// buy100coins.setVisibility(View.GONE);
buy100coins.setEnabled(false);
buy500coins.setEnabled(false);
//boughtcoins.setEnabled(true);
//boughtcoins.setVisibility(View.VISIBLE);
boughtcoins.setEnabled(true);
} else {
// buy100coins.setEnabled(true);
//coins_one_hundred.setVisibility(View.VISIBLE);
// buy100coins.setVisibility(View.VISIBLE);
buy100coins.setEnabled(true);
buy500coins.setEnabled(true);
//boughtcoins.setEnabled(false);
//boughtcoins.setVisibility(View.INVISIBLE);
boughtcoins.setEnabled(false);
}
Toast.makeText(GameActivity.this, "Successful got inventory!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(GameActivity.this, "Error getting inventory!", Toast.LENGTH_SHORT).show();
}
}
});
}
and button to consume
boughtcoins = (Button) buycoinsdialog.findViewById(R.id.bought_coins);
//boughtcoins.setVisibility(View.GONE);
// if button is clicked, close the custom dialog
boughtcoins.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Helper.playSound(getApplicationContext(), "click");
buyHelper.consumeAsync(purchase, new OnConsumeFinishedListener() {
#Override
public void onConsumeFinished(Purchase purchase, IabResult result) {
if(result.isSuccess()) {
Toast.makeText(GameActivity.this, "Coins consumed!", Toast.LENGTH_SHORT).show();
Helper.playSound(getApplicationContext(), "cash");
money += 100;
money_text.setText( "$" + money);
try {
// Small HACK: Give the system some time to realize the consume... without the sleep here,
// you have to press "Update" to see that the item can be bought again...
Thread.sleep(600);
update();
} catch(Exception e) {
// ignored
}
} else {
Toast.makeText(GameActivity.this, "Error consuming: "+result.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
buycoinsdialog.dismiss();
}
});
It looks like regardless of what the user selects your increasing the money/coin count by 100 as per this line:
money += 100;
Where are you handling the 500 coin purchase?
you have to do as follow
if(purchase.getSKU() == SKU_500){
money += 500;
}else if(purchase.getSKU() == SKU_100){
money += 100;
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener2
= new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result,
Purchase purchase)
{
if (result.isFailure()) {
// Handle error
return;
}else {
if (purchase.getSku().equals(ITEM_SKU1)) {
// do things
}else if(purchase.getSku().equals(ITEM_SKU2){}
}
}
};
check this it may help you
// on clicking your button call this method
if (mHelper!=null) mHelper.flagEndAsync();
mHelper.launchPurchaseFlow(this, ITEM_SKU, 10001,
mPurchaseFinishedListener, "");
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Please try after a few seconds"+e, Toast.LENGTH_SHORT).show();
implement listener as folloew:
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
= new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result,
Purchase purchase)
{
if (result.isFailure()) {
// Handle error
return;
}
else{
mHelper.consumeAsync(purchase, mConsumeFinishedListener);
}
}
};
// implement listener for "mConsumeFinishedListener" as follows:
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =
new IabHelper.OnConsumeFinishedListener()
{
public void onConsumeFinished(Purchase purchase,
IabResult result)
{
if (result.isSuccess())
{
if(purchase.getSKU().equals("android.test.purchase")){
}else if(purchase.getSKU().equals("android.test.cancel")){
}
}
}
};
I'm developing an app which will do multiple method in a single input. For example calculating square circumference and area, I give only one EditText and two button. But when I run the app, if I give an input and click the area button it won't do the calculation until I click the circumference button. And same goes if I change the input. Here is the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.square);
etSide = (EditText) findViewById(R.id.etSquare);
tvResult = (TextView) findViewById(R.id.tvSquare);
Button btnCir = (Button) findViewById(R.id.btnSqrCir);
btnCir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countCir();
}
});
Button btnArea = (Button) findViewById(R.id.btnSqrArea);
btnArea.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
countArea();
}
});
}
private void countArea() {
try {
side = etSide.getText().toString();
s = parseInt(side);
area = s * s;
tvResult.setText("Area = " + cir);
} catch (NumberFormatException ex){
Toast.makeText(getApplicationContext(), "Oops, you seem haven't enter the side length", Toast.LENGTH_LONG).show();
}
}
private void countCir() {
try {
side = etSide.getText().toString();
s = parseInt(side);
cir = 4 * s;
tvResult.setText("Circumference = " + area);
} catch (NumberFormatException ex){
Toast.makeText(getApplicationContext(), "Oops, you seem haven't enter the side length", Toast.LENGTH_LONG).show();
}
}
Any better idea? Really need help...
It looks like you have your variables backwards. For example:
private void countArea() {
try {
side = etSide.getText().toString();
s = parseInt(side);
area = s * s;
tvResult.setText("Area = " + cir); // <-- here cir doesn't have a value until you click the circumference button
} catch (NumberFormatException ex){
Toast.makeText(getApplicationContext(), "Oops, you seem haven't enter the side length", Toast.LENGTH_LONG).show();
}
}
So your TextView would display ""Area = ""
It looks to me like you want
tvResult.setText("Area = " + cir);
to be
tvResult.setText("Area = " + area);
Let me know if I'm not understanding you correctly
Note:
For your Toast you should use this or YourActivityName.this for Context instead of getApplicationContext()
One other suggestion I might make since your onClick()s only call a method, to make it simpler you could use one listener like this
public void onCreate(...)
{
...
btnCir.setOnClickListener(this);
btnArea.setOnClickListener(this);
...
}
public void onClick(View v)
{
switch(v.getId()) // get the id of the Button clicked
{
case (R.id.btnSqrArea): // call appropriate method
countArea();
break;
case (R.id.btnSqrCir):
countCir();
break;
}
}
You would just have to remember to add implements OnClickListener to your class definition. That's just a preference but worth mentioning.
I got a code from internet for inapp billing and I want to use that code in my application but I am getting an error that when I click the the buy button of my app it redirect me to the another layout of the code where I get an another Button and after that click my in-app billing starts.
I want that when I click my buy button then the in-app billing should start. without any another button clicks.
This is the code from where the the in-app billing start.
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSP = PreferenceManager.getDefaultSharedPreferences(this);
Log.i("BillingService", "Starting");
setContentView(R.layout.contact_market);
mContext = this;
mPurchaseButton = (Button) findViewById(R.id.main_purchase_yes);
mPurchaseButton.setOnClickListener(this);
mPreview = (TextView) findViewById(R.id.chakkde);
startService(new Intent(mContext, BillingService.class));
BillingHelper.setCompletedHandler(mTransactionHandler);
}
public Handler mTransactionHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
Log.i(TAG, "Transaction complete");
Log.i(TAG, "Transaction status: "
+ BillingHelper.latestPurchase.purchaseState);
Log.i(TAG, "Item purchased is: "
+ BillingHelper.latestPurchase.productId);
if (BillingHelper.latestPurchase.isPurchased()) {
showItem();
}
};
};
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.main_purchase_yes:
if (BillingHelper.isBillingSupported()) {
BillingHelper.requestPurchase(mContext,
"android.test.purchased");
} else {
Log.i(TAG, "Can't purchase on this device");
mPurchaseButton.setEnabled(false);
}
break;
default:
Log.i(TAG, "default. ID: " + v.getId());
break;
}
}
private void showItem() {
mPreview.setVisibility(View.VISIBLE);
SharedPreferences.Editor prefEditor = mSP.edit();
prefEditor.putBoolean(DroidSugarPreference.KEY_ENABLE,
true);
prefEditor.commit();
startActivity(new Intent(InAppMain.this, Setup.class));
InAppMain.this.finish();
}
#Override
protected void onPause() {
Log.i(TAG, "onPause())");
super.onPause();
}
#Override
protected void onDestroy() {
BillingHelper.stopService();
super.onDestroy();
}
}
this if from where I call the above class
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.gtask_button:
startActivity(new Intent(getActivity(), InAppMain.class));
default:
break;
}
but now i want that from case R.id.gtask_button: i should start the in-app billing activity that i was starting from R.id.main_purchase_yes.
thnx in advance...
From what i see, this is called when you click the button
BillingHelper.requestPurchase(mContext, "android.test.purchased");
So maybe thats where it changes your layout to something else...
Post the method so we can take a look.
EDIT:
Ok, here's the code
protected static void requestPurchase(Context activityContext, String itemId){
if (amIDead()) {
return;
}
Log.i(TAG, "requestPurchase()");
Bundle request = makeRequestBundle("REQUEST_PURCHASE");
request.putString("ITEM_ID", itemId);
try {
Bundle response = mService.sendBillingRequest(request);
//The RESPONSE_CODE key provides you with the status of the request
Integer responseCodeIndex = (Integer) response.get("RESPONSE_CODE");
//The PURCHASE_INTENT key provides you with a PendingIntent, which you can use to launch the checkout UI
PendingIntent pendingIntent = (PendingIntent) response.get("PURCHASE_INTENT");
//The REQUEST_ID key provides you with a unique request identifier for the request
Long requestIndentifier = (Long) response.get("REQUEST_ID");
Log.i(TAG, "current request is:" + requestIndentifier);
C.ResponseCode responseCode = C.ResponseCode.valueOf(responseCodeIndex);
Log.i(TAG, "REQUEST_PURCHASE Sync Response code: "+responseCode.toString());
startBuyPageActivity(pendingIntent, new Intent(), activityContext);
} catch (RemoteException e) {
Log.e(TAG, "Failed, internet error maybe", e);
Log.e(TAG, "Billing supported: "+isBillingSupported());
}
}
and we find the culprit -
startBuyPageActivity(pendingIntent, new Intent(), activityContext);