In app-billing takes money but wont give product - android

When i call the purchase screen i can buy the in app product and everything works ok but when the user leave the app and returns to view the product it keeps asking them to buy again,
I need to know how i can make this so when the user purchases the app the store screen doesnt come up anymore and they can access the product, the app is designed so that when the user buys the app they gain access to a new activity with features built in
if anyone could help, I would be most grateful
I used this tutorial which was very helpful in getting me started:[TUT] Simple InApp Billing / Payment By blundell
Here is my code
package com.IrishSign.app;
import java.util.Locale;
import com.IrishSign.app.BillingHelper;
import com.IrishSign.app.R;
import com.IrishSign.app.BillingService;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class IrishSignAppActivity extends Activity implements OnClickListener {
private static final String TAG = "BillingService";
private Context mContext;
private ImageView purchaseableItem;
private Button purchaseButton;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Log.i("BillingService", "Starting");
setContentView(R.layout.main);
mContext = this;
Button A = (Button) findViewById(R.id.alphabet);
Button purchaseableItem = (Button) findViewById(R.id.topics);
Button Intro = (Button) findViewById(R.id.intro);
Button G = (Button) findViewById(R.id.about);
purchaseableItem.setOnClickListener(this);
startService(new Intent(mContext, BillingService.class));
BillingHelper.setCompletedHandler(mTransactionHandler);
A.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent1 = new Intent("com.IrishSign.app.alpha");
startActivity(intent1);
}
});
Intro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent("com.IrishSign.app.Intro");
startActivity(intent1);
}
});
G.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog alertDialog = new AlertDialog.Builder(
IrishSignAppActivity.this).setCancelable(false)
.create(); // Reads Update
alertDialog.setTitle("Welcome");
alertDialog.setMessage("-----");//
alertDialog.setButton("Continue",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int arg1) {
Intent intent5 = new Intent(
IrishSignAppActivity.this,
IrishSignAppActivity.class);
}
});
alertDialog.show(); // <-- Shows dialog on screen.
}
});
}
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()) {
Intent intent = new Intent("com.IrishSign.app.Topics");
startActivity(intent);
}
};
};
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.topics:
if (BillingHelper.isBillingSupported()) {
BillingHelper.requestPurchase(mContext,
"com.blundell.item.passport");
// android.test.purchased or android.test.canceled or
// android.test.refunded or com.blundell.item.passport
} else {
Log.i(TAG, "Can't purchase on this device");
purchaseButton.setEnabled(false); // XXX press button before
// service started will
// disable when it shouldnt
}
break;
default:
// nada
Log.i(TAG, "default. ID: " + v.getId());
break;
}
}
#Override
protected void onPause() {
Log.i(TAG, "onPause())");
super.onPause();
}
#Override
protected void onDestroy() {
BillingHelper.stopService();
super.onDestroy();
}
}

You can check when the application starts by using restoreTransactions. If you have used Managed Products or Subscriptions then only you will get all the details of the user.
For Unmanaged product there is no detail maintained by google.
So call this in your main activity
mBillingService = new BillingService();
mBillingService.setContext(this);
mBillingService.restoreTransactions();
Once you call this in ResponseHandler class there is one method purchaseResponse
purchaseResponse(final Context context,
final PurchaseState purchaseState, final String productId,
final String orderId, final long purchaseTime,
final String developerPayload, final String purchaseToken) {
}
which will return all the details.
You can check purchaseState then after
if (purchaseState == PurchaseState.PURCHASED) {
} else if (purchaseState == PurchaseState.REFUNDED) {
} else if (purchaseState == PurchaseState.CANCELED) {
}

Related

Google Reward Video ads works with test ad unit id , but not with live adunit id

I have a strange problem implementing Google Reward Video. In test mode (with google ad-id) works perfect first time, but not loading video in the second time. In production (with my ids) not loading video at all. Here is my code:
import android.content.DialogInterface;
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import eu.healthydev.quizhero.Common.Common;
import eu.healthydev.quizhero.Model.Question;
import eu.healthydev.quizhero.Model.QuestionScore;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.reward.RewardItem;
import com.google.android.gms.ads.reward.RewardedVideoAd;
import com.google.android.gms.ads.reward.RewardedVideoAdListener;
public class DoneActivity extends AppCompatActivity implements RewardedVideoAdListener{
Button btnTryAgain, exit_game;
TextView txtResultScore, getTxtResultQuestion;
ProgressBar progressBar;
FirebaseDatabase database;
DatabaseReference question_score;
//VideoAd Award
private static final String AD_UNIT_ID = "ca-app-pub-5883754622051955/6179215953";
private static final String APP_ID = "ca-app-pub-5883754622051955~8837168889";
private int coinCount;
private TextView coinCountText;
private RewardedVideoAd rewardedVideoAd;
private Button showVideoButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_done);
// Initialize the Mobile Ads SDK.
MobileAds.initialize(this, APP_ID);
rewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
rewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
database = FirebaseDatabase.getInstance();
question_score = database.getReference("Question_Score");
txtResultScore = (TextView)findViewById(R.id.txtTotalScore);
getTxtResultQuestion =(TextView)findViewById(R.id.txtTotalQuestion);
progressBar = (ProgressBar)findViewById(R.id.doneProgressBar);
// Create the "retry" button, which tries to show an interstitial between game plays.
btnTryAgain = (Button)findViewById(R.id.btnTryAgain);
exit_game = (Button) findViewById(R.id.exit_game);
btnTryAgain.setVisibility(View.INVISIBLE);
btnTryAgain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(DoneActivity.this, HomeActivity.class);
startActivity(intent);
finish();
}
});
// Create the "show" button, which shows a rewarded video if one is loaded.
showVideoButton = findViewById(R.id.show_video_button);
showVideoButton.setVisibility(View.VISIBLE);
showVideoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showRewardedVideo();
}
});
exit_game.setVisibility(View.VISIBLE);
exit_game.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
// Display current coin count to user.
coinCountText = findViewById(R.id.coin_count_text);
coinCount = 0;
coinCountText.setText("Coins: " + coinCount);
//Get data from bundle and set view
Bundle extra = getIntent().getExtras();
if(extra != null)
{
int score = extra.getInt("SCORE");
int totalQuestion = extra.getInt("TOTAL");
int correctAnswer = extra.getInt("CORRECT");
txtResultScore.setText(String.format("SCORE : %d", score));
getTxtResultQuestion.setText(String.format("PASSED : %d /%d", correctAnswer,totalQuestion));
progressBar.setMax(totalQuestion);
progressBar.setProgress(correctAnswer);
//Upload points to Database
question_score.child(String.format("%s_%s", Common.currentUser.getUserName(),
Common.categoryID))
.setValue(new QuestionScore(String.format("%s_%s", Common.currentUser.getUserName(),
Common.categoryID),
Common.currentUser.getUserName(),
String.valueOf(score),
Common.categoryID,
Common.categoryName));
}
}
private void loadRewardedVideoAd() {
if (!rewardedVideoAd.isLoaded()) {
rewardedVideoAd.loadAd(AD_UNIT_ID, new AdRequest.Builder().build());
}
}
private void addCoins(int coins) {
coinCount += coins;
coinCountText.setText("Coins: " + coinCount);
}
private void showRewardedVideo() {
showVideoButton.setVisibility(View.INVISIBLE);
exit_game.setVisibility(View.INVISIBLE);
if (rewardedVideoAd.isLoaded()) {
rewardedVideoAd.show();
}
}
#Override
public void onRewardedVideoAdLeftApplication() {
Toast.makeText(this, "onRewardedVideoAdLeftApplication", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdClosed() {
Toast.makeText(this, "onRewardedVideoAdClosed", Toast.LENGTH_SHORT).show();
// Preload the next video ad.
loadRewardedVideoAd();
btnTryAgain.setVisibility(View.INVISIBLE);
showVideoButton.setVisibility(View.VISIBLE);
exit_game.setVisibility(View.VISIBLE);
}
#Override
public void onRewardedVideoAdFailedToLoad(int errorCode) {
Toast.makeText(this, "Ad Video Failed to Load", Toast.LENGTH_SHORT).show();
showVideoButton.setVisibility(View.VISIBLE);
exit_game.setVisibility(View.VISIBLE);
}
#Override
public void onRewardedVideoAdLoaded() {
Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewarded(RewardItem reward) {
Toast.makeText(this,
String.format(" You ve got one free try!", reward.getType(),
reward.getAmount()),
Toast.LENGTH_SHORT).show();
btnTryAgain.setVisibility(View.VISIBLE);
showVideoButton.setVisibility(View.INVISIBLE);
exit_game.setVisibility(View.INVISIBLE);
addCoins(1);
Intent intent = new Intent(DoneActivity.this, HomeActivity.class);
startActivity(intent);
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finishAffinity();
System.exit(0);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
I double checked my ids and are correct. Probably my code too as it works ane time exactly as it has to do. I will appriciate any help or idea.
From: https://developers.google.com/admob/android/rewarded-video
#Override
public void onRewardedVideoAdClosed() {
// Load the next rewarded video ad.
loadRewardedVideoAd();
}
We need to re-load once the first one is closed.
My app is working fine due to same. Hope that helps.

Android code does not update user account

I am working on an android code and trying to update the user information. I am able to retrieve the information but have not been able to update. Not sure what I am doing wrong.
In the if-else statement, it does not hit the If statement, goes directly to the error(else statement.
here is the code
package com.example.autrui;
import com.parse.GetCallback;
import com.parse.ParseACL;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import com.parse.SendCallback;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class EditPP extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.editpp);
final Button confirmChangeEditPP = (Button) findViewById(R.id.bconfirmChangeEditPP);
final EditText fullName = (EditText) findViewById(R.id.etFullName);
final EditText email = (EditText) findViewById(R.id.etEmail);
//final ParseUser currentUser = new ParseUser();
final ParseUser currentUser = ParseUser.getCurrentUser();
System.out.println(currentUser);
String objectId = currentUser.getObjectId();
System.out.println(objectId);
String fName = currentUser.getString("fullName");
fullName.setText(fName);
email.setText(currentUser.getString("email"));
ParseQuery<ParseObject> userQuery = ParseQuery.getQuery("User");
userQuery.getInBackground((String)objectId, new GetCallback<ParseObject>(){
public void done(final ParseObject object, ParseException e) {
if (e == null) {
confirmChangeEditPP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ParseACL acl = new ParseACL();
acl.setPublicReadAccess(true);
acl.setPublicWriteAccess(true);
currentUser.setACL(acl);
object.put("fullName", fullName.getText().toString());
object.put("email", email.getText().toString());
object.saveInBackground();
}
});
} else {
Log.e("error","error");
}
}
});
}
#Override
public void onBackPressed() {
finish();
// Go to settings
/*
* if(MainActivity.s.isEmpty()) return; else { View v =
* MainActivity.s.pop(); Class c = MainActivity.s2.pop(); Intent intent
* = new Intent(v.getContext(), c); startActivityForResult(intent, 0); }
*/
}
private void showUserDetailsActivity() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
I got the answer. the error was regarding the ACL and yes we did not need the query. I wrote the whole code again and made it simpler.

How to disable Ads while changing to landscape mode in android app?

I need to permanently disable the Ads while changing to landscape mode in android app.Below I listed the codes:
PlayerActivity.java:
package com.grace.view;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.InterstitialAd;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;
import com.grace.view.ads.Ads;
public class PlayerActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener, AdListener{
// create string variables
String YOUTUBE_APIKEY;
String ID;
private InterstitialAd interstitial;
private static final String LOG_TAG = "LayarTancep";
// create object of view
YouTubePlayerView youTubePlayerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
// connect view object and view id on xml
youTubePlayerView = (YouTubePlayerView)findViewById(R.id.youtubeplayerview);
// create the interstitial
interstitial = new InterstitialAd(this, getString(R.string.admob_id));
// load interstitialAd
Ads.loadInterstitialAd(interstitial);
// set Ad Listener to use the callbacks below
interstitial.setAdListener(this);
// get YOUTUBE APIKEY
YOUTUBE_APIKEY = getString(R.string.youtube_apikey);
// get video id from previous page
Intent i = getIntent();
ID = i.getStringExtra("id");
}
#Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {
if(result == YouTubeInitializationResult.DEVELOPER_KEY_INVALID)
Toast.makeText(this, "Initialization Fail- key invalid", Toast.LENGTH_SHORT).show();
else if(result == YouTubeInitializationResult.NETWORK_ERROR)
Toast.makeText(this, getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
else if(result == YouTubeInitializationResult.SERVICE_INVALID)
updateYoutubeDialog(
getString(R.string.update_youtube_app),
getString(R.string.update));
else if(result == YouTubeInitializationResult.SERVICE_MISSING)
updateYoutubeDialog(
getString(R.string.no_youtube_app),
getString(R.string.install));
}
void updateYoutubeDialog(String message, String button){
//if Youtube app is not available show alert dialog
Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message);
builder.setCancelable(true);
builder.setPositiveButton(button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.youtube"));
startActivity(intent);
//Finish the activity so they can't circumvent the check
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
player.loadVideo(ID);
}
}
#Override
public void onDismissScreen(Ad arg0) {
// TODO Auto-generated method stub
Log.d(LOG_TAG, "onDismissScreen");
// display youtube player
youTubePlayerView.initialize(YOUTUBE_APIKEY, this);
}
#Override
public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
// TODO Auto-generated method stub
String message = "onFailedToReceiveAd (" + arg1 + ")";
Log.d(LOG_TAG, message);
// display youtube player
youTubePlayerView.initialize(YOUTUBE_APIKEY, this);
}
#Override
public void onLeaveApplication(Ad arg0) {
// TODO Auto-generated method stub
Log.d(LOG_TAG, "onLeaveApplication");
}
#Override
public void onPresentScreen(Ad arg0) {
// TODO Auto-generated method stub
Log.d(LOG_TAG, "onPresentScreen");
}
#Override
public void onReceiveAd(Ad ad) {
// TODO Auto-generated method stub
Log.d("OK", "Received ad");
if (ad == interstitial) {
interstitial.show();
}
}
}
if I click any one of the particular video,the ads would be
occurred.After I cancel the ads,the video will be playing.
I need to disable the ads permanently.Is there any way to solve
it.Thank You.
When you want to change the orientation configuration you need to find the same activity created again for orientation changes, here you will realize Android Life Cycle.
So this one will help you
http://www.devahead.com/blog/2012/01/preserving-the-state-of-an-android-webview-on-screen-orientation-change/link

onActivityResult Is not responding when choosing from a list

Hi Guys I am new with android programming and Java. I am trying to make a travel app. My issue is that how do I pass data from the selected item from the list to the editText filed. This is out I have done so far.. Pls. be kind I am newbee
The activity class that uses the ListActivity
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class SelectStationActivity extends ListActivity {
String stations[] = { "Acton Main Line","Ealing","Great Western","Albany Park"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter <String> adapter =new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, stations);
setListAdapter(adapter);
}
protected void OnListItemClick(ListView l, View v, int position, long id) {
String values = stations[(int) id];
Intent result = new Intent().putExtra("SELECTED_STATION_NAME", values);
setResult(RESULT_OK, result);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.select_station, menu);
return true;
}
The main class
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class TravelActivity extends Activity {
// The request code for the selectChkInBt
protected static final int SelectChkin_REQUEST_CODE = 1;
// The request code for the selectChkOutBt
protected static final int SelectChkout_REQUEST_CODE = 2;
private String checkinStation;
private String checkoutStation;
private Button checkinButton, checkoutButton, selectChkInButton, selectChkOutButton;
private EditText checkinEditText, checkoutEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_travel);
checkinButton = (Button) findViewById(R.id.btCkIn);
checkoutButton = (Button) findViewById(R.id.BtChkOut);
selectChkInButton = (Button) findViewById(R.id.btselectChkIn);
selectChkOutButton = (Button) findViewById(R.id.btselectChkOut);
checkinEditText = (EditText) findViewById(R.id.EditTxtChkIn);
checkoutEditText = (EditText) findViewById(R.id.EditTxtChkOut);
checkinButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkinEditText.getText().toString().equals("")) {
Toast.makeText(TravelActivity.this,
"Enter Check-in Station", Toast.LENGTH_LONG).show();
} else {
checkinStation = checkinEditText.getText().toString();
// Enable the check-out EditText and Button
checkinEditText.setEnabled(false);
checkinEditText.setTextColor(Color.CYAN);
checkinButton.setEnabled(false);
// Disable the check-in- EdiText AND Button
checkoutEditText.setEnabled(true);
checkoutButton.setEnabled(true);
checkoutEditText.requestFocus();
}
}
});
checkoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkoutEditText.getText().toString().equals("")) {
Toast.makeText(TravelActivity.this,
"Enter Check-Out station", Toast.LENGTH_LONG)
.show();
} else {
checkoutStation = checkoutEditText.getText().toString();
// Clear edit Text
checkoutEditText.setText("");
// Enable the check-in EditText and Button
checkoutEditText.setEnabled(false);
checkoutButton.setEnabled(false);
/*
* Disable the check-out EditText and Button, to allow the
* eternal cycle of checking in and out to commence once again */
checkinEditText.setText("");
checkinEditText.setEnabled(true);
checkinButton.setEnabled(true);
checkinEditText.requestFocus();
Toast.makeText(getApplicationContext(),
"Travel information added!", Toast.LENGTH_SHORT)
.show();
}
}
});
I could implement a inner class for the two select buttons but i have diffculties to do it.Pls. provide some help how I could implement it thanks.
selectChkInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TravelActivity.this,
SelectStationActivity.class);
startActivityForResult(intent, SelectChkin_REQUEST_CODE);
}
});
selectChkOutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TravelActivity.this,SelectStationActivity.class);
startActivityForResult(intent, SelectChkout_REQUEST_CODE);
}
});
}
The onActivityResult is not responding here
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode== RESULT_OK){
if (requestCode == 1) {
checkinEditText.setText(data.getStringExtra("SELECTED_STATION_NAME"));
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(Menu.NONE, Menu.FIRST, Menu.NONE, "Recipt");
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
public boolean OnMenuItemSelected(int featureId, MenuItem item) {
String Recipt = "Recipt" + item.getItemId() + "\nCheck-in: "
+ checkinStation + "\nCheck-Out: " + checkoutStation;
Toast.makeText(getApplicationContext(), Recipt, Toast.LENGTH_LONG)
.show();
return true;
}
protected void OnSaveInstanceState(Bundle outState) {
outState.putString("lAST_CHECKIN", checkinStation);
outState.putString("lAST_CHECKOUT", checkoutStation);
}
protected void onRestoreInstance(Bundle savedInstanceState) {
checkinStation = savedInstanceState.getString(checkinStation);
checkoutStation = savedInstanceState.getString(checkoutStation);
}
}
You Should use this
checkinEditText.setText(data.getStringExtra("SELECTED_STATION_NAME"));
as
checkinEditText.setText(data.getStringExtra("SELECTED_STATION_NAME").toString());

My text to speech doesn't want to talk back to me

I am still having problems with my TextToSpeech android, I entered the button twice once for the implemented Speech like exlipse asked me too and one for the implemented OnClickListener, Even if I take out the bottom action for the button it doesn't want to play, Why? idk it just doesn't want to say what is in my EditText Field I have no clue why it doesn't want to and I have asked around many times but I haven't goten an answer that worked.
package com.write.it;
import java.util.HashMap;
import java.util.StringTokenizer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Speech extends Activity implements OnInitListener, OnUtteranceCompletedListener, OnClickListener {
private EditText words = null;
private Button speakBtn = null;
private static final int REQ_TTS_STATUS_CHECK = 0;
private static final String TAG = "TTS Demo";
private TextToSpeech mTts;
private int uttCount = 0;
private HashMap<String, String> params = new HashMap<String, String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
words = (EditText)findViewById(R.id.wordsToSpeak);
speakBtn = (Button)findViewById(R.id.speak);
// Check to be sure that TTS exists and is okay to use
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, REQ_TTS_STATUS_CHECK);
}
public void doSpeak(View view) {
StringTokenizer st = new StringTokenizer(words.getText().toString(),",.");
while (st.hasMoreTokens()) {
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,
String.valueOf(uttCount++));
mTts.speak(st.nextToken(), TextToSpeech.QUEUE_ADD, params);
}
speakBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.speak:
doSpeak(v);
break;
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQ_TTS_STATUS_CHECK) {
switch (resultCode) {
case TextToSpeech.Engine.CHECK_VOICE_DATA_PASS:
// TTS is up and running
mTts = new TextToSpeech(this, this);
Log.v(TAG, "Pico is installed okay");
break;
case TextToSpeech.Engine.CHECK_VOICE_DATA_BAD_DATA:
case TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_DATA:
case TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_VOLUME:
// missing data, install it
Log.v(TAG, "Need language stuff: " + resultCode);
Intent installIntent = new Intent();
installIntent.setAction(
TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
break;
case TextToSpeech.Engine.CHECK_VOICE_DATA_FAIL:
default:
Log.e(TAG, "Got a failure. TTS not available");
}
}
else {
// Got something else
}
}
public void onInit(int status) {
// Now that the TTS engine is ready, we enable the button
if( status == TextToSpeech.SUCCESS) {
mTts.setOnUtteranceCompletedListener(this);
speakBtn.setEnabled(true);
}
}
#Override
public void onPause()
{
super.onPause();
// if we're losing focus, stop talking
if( mTts != null)
mTts.stop();
}
#Override
public void onDestroy()
{
super.onDestroy();
mTts.shutdown();
}
public void onUtteranceCompleted(String uttId) {
Log.v(TAG, "Got completed message for uttId: " + uttId);
Integer.parseInt(uttId);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.speak:
doSpeak(v);
break;
}
}
}
Did you try speaking the text with just one method call? Like this
mTts.speak(aString, TextToSpeech.QUEUE_ADD, null);
It works fine for me. The initialization I use is the same as yours. The only remaining difference is this (which should not be necessary to get the TTS to work!):
this.speaker.setSpeechRate(0.9f);
this.speaker.setPitch(0.9f);

Categories

Resources