Using SharedPreferences to save users score - java

I have 2 activities. In the first one i choose a level. In the second i play the game.In the second activity I answer questions and everytime I answer correctly I add one value to my arraylist. When the game ends a user goes back to level select activity and there he can see his score. For example: Level1: you answered 17 questions correctly. How can I achieve that? I tried using sharedpreferences but had no luck. It always shows 0. Im guessing its because it gets the value at the start of the game, when the list is empty. How to show the values after the game has ended when the list is filled?
This is the game activity in witch I create a list, store values in it and answer questions.:
public class MainActivity extends Activity {
Button mYes;
Button mNo;
TextView mQuestion;
Button btnClosePopup;
TextView mPopupText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final int[] count = {0}; // Global array.
final int[] score = {0};
//final int[] intArray = new int[3];
mYes = (Button) findViewById(R.id.button2);
mPopupText = (TextView)findViewById(R.id.popupTekstas);
btnClosePopup = (Button)findViewById(R.id.btn_close_popup);
mNo = (Button) findViewById(R.id.button);
mQuestion = (TextView) findViewById(R.id.textView);
//Creating questions. (Question, boolean, answer).
final Question first = new Question("Do i understand this code?", true, "Only Jesus knows");
final Question second = new Question("Why dont i understand this code?", false, "Im not Jesus");
final Question third = new Question("Why I am not Jesus?", true, "2fat.");
//Creating Lists for questions and boolean values.
final ArrayList<Question> questions = new ArrayList<Question>();
final ArrayList<Boolean> type = new ArrayList<Boolean>();
final ArrayList<Integer> points = new ArrayList<Integer>();
SharedPreferences sharedPref = getSharedPreferences("level1", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("taskai", points.size());
editor.commit();
//mResult.setText("zdr");
//Adding questions to the question list
questions.add(first);
questions.add(second);
questions.add(third);
// Adding boleans to the boolean list
type.add(first.correctAnswer);
type.add(second.correctAnswer);
type.add(third.correctAnswer);
//Show the first question on Activity start.
mQuestion.setText(questions.get(0).question);
// Open PopUp Window on true button click.
mYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
initiatePopupWindow();
if(type.get(count[0])){
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("Correct!");
} else {
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("False!");
}
//Show the first answer on first button click.
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstas)).setText(questions.get((count[0]) % questions.size()).answer);
// When PopUp button closes open the next question with the if/else conditions.
btnClosePopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//if the question is true show next question/ else close app
if (type.get(count[0])) {
points.add(1); // if the answer is correct add +1 to the list.
score[0]++;
if(questions.size()-1 == count[0]) // if you count[0] is init to 0
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("WInner");
builder.setMessage("You won, play again?");
builder.setCancelable(false);
builder.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// just close dialog
dialog.cancel();
}
});
builder.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
// mResult.setText("" + points.size());
}
});
// Create dialog from builder
AlertDialog alert = builder.create();
// Show dialog
alert.show();
count[0]=0;
}
else if(questions.size()-1 < count[0])
try {
throw new Exception("Invalid ");
} catch (Exception e) {
e.printStackTrace();
}
else
count[0]++;
mQuestion.setText(questions.get(count[0]).question); // you dont need calculate the module anymore
pwindo.dismiss();
} else {
count[0]++;
mQuestion.setText(questions.get(count[0]).question); // you dont need calculate the module anymore
pwindo.dismiss();
}
}
});
}
});
mNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
initiatePopupWindow();
if(!type.get(count[0])){
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("Correct!");
} else {
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("False!");
}
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstas)).setText(questions.get((count[0]) % questions.size()).answer);
btnClosePopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!type.get(count[0])) {
points.add(1); // if the answer is correct add +1 to the list.
score[0]++;
if(questions.size()-1 == count[0]) // if you count[0] is init to 0
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("WInner")
.setMessage("You won, play again?")
.setCancelable(false)
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// just close dialog
dialog.cancel();
}
})
.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
//mResult.setText("" + points.size());
}
});
// Create dialog from builder
AlertDialog alert = builder.create();
// Show dialog
alert.show();
count[0]=0;
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("Klaida!");
}
else if(questions.size()-1 < count[0])
try {
throw new Exception("Invalid ");
} catch (Exception e) {
e.printStackTrace();
}
else
count[0]++;
mQuestion.setText(questions.get(count[0]).question); // you dont need calculate the module anymore
pwindo.dismiss();
} else {
count[0]++;
mQuestion.setText(questions.get(count[0]).question); // you dont need calculate the module anymore
pwindo.dismiss();
}
}
});
}
});
}
public PopupWindow pwindo;
public void initiatePopupWindow() {
try {
// We need to get the instance of the LayoutInflater
LayoutInflater inflater = (LayoutInflater) MainActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.popup,
(ViewGroup) findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 500, 570, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup);
btnClosePopup.setOnClickListener(cancel_button_click_listener);
} catch (Exception e) {
e.printStackTrace();
}
}
public View.OnClickListener cancel_button_click_listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
pwindo.dismiss();
}
};
In this activity I try to get the list values and show them:
public class LevelSelectActivity extends MainActivity {
Button mLevel1;
public TextView mResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level_select);
SharedPreferences sharedPref = getSharedPreferences("level1", Context.MODE_PRIVATE);
int result = sharedPref.getInt("taskai", 0);
mLevel1 = (Button)findViewById(R.id.level1);
mResult = (TextView)findViewById(R.id.Resultas);
// mResult.setText(players.size()-1 + "/" + 3);
mResult.setText("" + result);
mLevel1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent startGame = new Intent(LevelSelectActivity.this, MainActivity.class);
startActivity(startGame);
}
});
}

I don't know for sure what's happening in your code, but I do know preferences aren't the best way to pass data.
You are better off using a set results/ get results pattern.
The first activity uses
startActivityForResult(intent, LEVEL_REQUEST);
It will also create a function to read back the data after it is done. That'll look something like:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == LEVEL_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
}
}
}
The activity sending the results will do this to publish the results:
Intent resultsIntent=new Intent();
//Set data in the intent, note this intent is returned to the original function in `onActivityResult`
setResult(Activity.RESULT_OK,resultsIntent);
The second activity uses

Related

I want to count my every right and wrong answer submitted in my quiz app and want to display score in textview

This is the method I have created to check the condition
For the right answer, I am showing the png image and the same for the wrong answer
#SuppressLint("SetTextI18n")
private void checkAnswer(boolean userPressed) {
boolean answerProvided = mQuestionBank[mCurrentIndex].isQuestionTrueAnswer();
int messageStringId = 0;
if (answerProvided == userPressed) {
messageStringId = R.string.correct_toast;
mGreenTick.setImageResource(R.drawable.green_tick);
mGreenTick.setVisibility(View.VISIBLE);
}
else {
messageStringId = R.string.incorrect_toast;
mGreenTick.setImageResource(R.drawable.red_cross);
mGreenTick.setVisibility(View.VISIBLE);
}
// Toast.makeText(MainActivity.this, messageStringId, Toast.LENGTH_SHORT).show();
}
I have called the method checkAnswer() method in the true button click and false button click below.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Does nothing yet, but soon!
checkAnswer(true);
mTrueButton.setEnabled(false);
mFalseButton.setEnabled(false);
mMoreInfoButton.setVisibility(View.VISIBLE);
}
});
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Does nothing yet, but soon!
checkAnswer(false);
mFalseButton.setEnabled(false);
mTrueButton.setEnabled(false);
mMoreInfoButton.setVisibility(View.VISIBLE);
}
});
Now, i have used intent method in Score Button click and in the ScoreActivity.class i want to show the
store in textview.
please tell me how to count the true answer and wrong answer and store the score in the variable which i
can show in textview
Please help me.
mScoreButton = (Button)findViewById(R.id.score_button);
mScoreButton.setVisibility(View.INVISIBLE);
mScoreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ScoreActivity.class);
startActivity(intent);
finish();
}
});
private int trueCount = 0;
private int falseCount = 0;
#SuppressLint("SetTextI18n")
private void checkAnswer(boolean userPressed) {
boolean answerProvided = mQuestionBank[mCurrentIndex].isQuestionTrueAnswer();
int messageStringId = 0;
if (answerProvided == userPressed) {
trueCount++;
messageStringId = R.string.correct_toast;
mGreenTick.setImageResource(R.drawable.green_tick);
mGreenTick.setVisibility(View.VISIBLE);
}
else {
falseCount++;
messageStringId = R.string.incorrect_toast;
mGreenTick.setImageResource(R.drawable.red_cross);
mGreenTick.setVisibility(View.VISIBLE);
}
// Toast.makeText(MainActivity.this, messageStringId, Toast.LENGTH_SHORT).show();
}
...
//Displaying int textView
textView.setText(String.format("Right count: %d False count: %d", rightCount, falseCount));
mFinalMarks = (TextView)findViewById(R.id.final_marks);
mFinalMarks.setText("Final Score is: " + getIntent().getStringExtra("PLUS_MARKS") + "Marks out of 10 ");
getIntent().getStringExtra("PLUS_MARKS");
// it is showing null instead of score

Android returning NullPointerException when asking findViewById after app is paused

whenever I use the app switcher or the app gets paused in any other way then upon resuming it I will get a NullPointerException when trying to use findViewById in my fragment. The same happens when trying to use getActivity() or anything related to the Main activity. I've tried checking of the fragment is attached or not with isAdded() and it returns true but still gives the error. (Don't mind the way the code looks, I still need to clean it up)
All irrelevant classes and methods are not included (ex. Profanity class).
MainActivity onStart method (Launch activity)
#Override
public void onStart() {
super.onStart();
Profanity.downloadList();
if (AskForPermissions()) {
if (mAuth.getCurrentUser() != null) {
mAuth.getCurrentUser().reload().addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.MainFragment, new LoginFragment()).commit();
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.MainFragment, new HomeFragment()).commit();
}
});
} else {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.MainFragment, new LoginFragment()).commit();
}
} else {
onStart();
}
}
HomeFragment (The one that crashes, crash happens under Started() on the 4th line)
#SuppressWarnings("all")
#Override
public void onStart() {
super.onStart();
loadVariables();
final String UUID = ((MainActivity) getActivity()).mAuth.getCurrentUser().getUid();
User.UUID = UUID;
if (User.userName == null || User.userName.equals("")) {
Functions.loadUserData(UUID).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.getResult() == null) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose your username");
final EditText input = new EditText(getActivity());
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
final AlertDialog dialog = builder.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (input.getText() != null && !input.getText().toString().equals("") && !input.getText().toString().equals(" ")) {
if (input.getText().toString().toCharArray().length > 16) {
dialog.dismiss();
Functions.showBottomMessage(getView(), "Your username must be maximum 16 characters.");
dialog.show();
} else if (Profanity.contains(input.getText().toString())) {
dialog.dismiss();
Functions.showBottomMessage(getView(), "Please refrain from using restricted words in your username.");
input.setText("");
dialog.show();
} else {
User.userName = input.getText().toString();
dialog.dismiss();
FirebaseReferences.users.child(User.UUID).child("name").setValue(User.userName);
Functions.showBottomMessage(getView(), "Username saved.");
}
} else {
dialog.dismiss();
Functions.showBottomMessage(getView(), "Please enter a valid username.");
dialog.show();
}
}
});
Started();
} else {
HashMap temp = (HashMap) task.getResult();
if (temp.containsKey("name")) {
User.userName = temp.get("name").toString();
} else {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose your username");
final EditText input = new EditText(getActivity());
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
final AlertDialog dialog = builder.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (input.getText() != null && !input.getText().toString().equals("") && !input.getText().toString().equals(" ")) {
User.userName = input.getText().toString();
dialog.dismiss();
FirebaseReferences.users.child(UUID).child("name").setValue(input.getText().toString());
} else {
dialog.dismiss();
dialog.show();
}
}
});
}
if (temp.containsKey("place")) {
User.place = temp.get("place").toString();
}
if (temp.containsKey("ratedImages")) {
User.ratedImages = (ArrayList<String>) temp.get("ratedImages");
}
if (temp.containsKey("developer")) {
if (Boolean.valueOf(temp.get("developer").toString().toLowerCase()))
User.isDeveloper = true;
}
Started();
}
}
});
} else {
Started();
}
}
#SuppressWarnings("all")
private void Started() {
mainImageProgressBar.setVisibility(View.VISIBLE);
secondaryImageProgressBar.setVisibility(View.VISIBLE);
CacheHandler.update(getActivity(), imageView, secondImageView, true);
/*THIS IS THE FIRST CRASH POINT - */getView().findViewById(R.id.fabSendImage).setOnClickListener(getBtnSendImageOnClickListener());
getView().findViewById(R.id.btnReportImage).setOnClickListener(btnReportImageOnClick);
}
All view related code must be moved on to onCreateView(). So just place your code to onCreateView in case of fragment and onCreate in case of activity.
For more info just go through https://developer.android.com/guide/components/fragments.html
Crashing because of getView(). Because its not able get the view.
You need to pass the view which hold the view with id R.id.fabSendImage and try calling the view.findViewById(R.id.fabSendImage) to initialize.

OnclickListener not working on small screen sizes?

So I have some code that sets an onClickListener for a button that doesn't seem to work on devices with screen sizes less than 4 inches, but only for specific buttons. I'm not sure why, because it doesn't seem to be an effect OS Level version, but only screen size.
I have logging code in the onclick method that shows all the buttons registering and firing correctly except the new_game button. Any input on why this might be happening would be appreciated.
Code from OnCreate:
Button acknowledgements = (Button) findViewById(R.id.acknolwedgments_word_Game);
acknowledgements.setOnClickListener(this);
Button quit = (Button) findViewById(R.id.quit_word_game_button);
quit.setOnClickListener(this);
Button new_game = (Button) findViewById(R.id.word_game_new_Button);
Log.e("NEW GAME BUTTON", String.valueOf(new_game));
new_game.setOnClickListener(this);
Log.e("SET ONCLICK", "DONE");
OnClickListener:
public void onClick(View view) {
int id = view.getId();
Log.e("CLICKED BUTTON", String.valueOf(view));
if (id == R.id.quit_word_game_button){
Intent i = new Intent(this, Game.class);
startActivity(i);
}
else if (id == R.id.acknolwedgments_word_Game){
Intent i = new Intent(this, Acknowledgements.class);
startActivity(i);
}
else if (id == R.id.word_game_new_Button){
final AlertDialog alert = new AlertDialog.Builder(word_game_mainscreen.this).create();
final EditText edit = new EditText(getBaseContext());
edit.setHint("Username");
alert.setView(edit);
alert.setButton(DialogInterface.BUTTON_NEGATIVE, "CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
alert.dismiss();
}
});
alert.setButton(DialogInterface.BUTTON_POSITIVE, "PLAY!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final String opponent = String.valueOf(edit.getText());
new AsyncTask(){
#Override
protected Object doInBackground(Object[] objects) {
//Code to synchronize it to a server
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
Log.e("POST EXECUTE", (String)o);
//Creates intent to take you to the game
}
}.execute();
}
});
alert.show();
}
else if (id == R.id.togglesound){
ToggleButton music = (ToggleButton) findViewById(R.id.togglesound);
if (music.isChecked()){
Music.play(this, R.raw.wordgame);
}
else{
Music.stop(this);
}
}
}
Simple suggestion: swith case is far better than if-else and class_name.this is mostly friendly than getBaseContext().
For showing AlertDialog we have to first create the builder.Something like:
AlertDialog dialog;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setIcon(...).setTitle(...)
.setView(...)
.setPositiviButton(...)
.setNegativeButton(...);
//Now create the builder and assign to AlertDialog
dialog = builder.create();
dialog.show;

Code breaks at AlertDialog creation. I think I have Context wrong...?

i can't seem to figure out why my app/code is crashing in this section. Any help would be appreciated. I think the problem lies on the creation of an AlertDialog in the else if statement.
Basically, this method is called on first launch of the application and asks the user to choose between two options: OCPS and Other. When OCPS is chosen, a SharedPreference is set. When other is selected, an AlertDialog with text box should pop up, allowing the user to input their own local URL, which is then saved to the SharedPreference.
Full code is available here: https://github.com/danielblakes/progressbook/
code follows:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean firstrun = getSharedPreferences(
"com.danielblakes.progressbook", MODE_PRIVATE).getBoolean(
"firstrun", true);
if (firstrun) {
new AlertDialog.Builder(this).setTitle("First Run").show();
pickDistrict(this);
getSharedPreferences("com.danielblakes.progressbook", MODE_PRIVATE)
.edit().putBoolean("firstrun", false).commit();
}
else {
String saved_district = getSharedPreferences(
"com.danielblakes.progressbook", MODE_PRIVATE).getString(
"district", null);
startupWebView(saved_district);
}
}
public Dialog pickDistrict(final Context context) {
AlertDialog.Builder districtalert = new AlertDialog.Builder(context);
districtalert
.setTitle(R.string.choose_district)
.setItems(R.array.districts,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
if (i == 0) {
String district_site = "https://parentaccess.ocps.net/General/District.aspx?From=Global";
startupWebView(district_site);
getSharedPreferences(
"com.danielblakes.progressbook",
MODE_PRIVATE)
.edit()
.putString("district",
district_site).commit();
} else if (i == 1) {
AlertDialog.Builder customdistrict = new AlertDialog.Builder(context);
customdistrict
.setTitle(
R.string.custom_district_title)
.setMessage(
R.string.custom_district_message);
final EditText input = new EditText(
getParent());
customdistrict.setView(input);
customdistrict
.setPositiveButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
String custom_url = input
.getText()
.toString();
getSharedPreferences(
"com.danielblakes.progressbook",
MODE_PRIVATE)
.edit()
.putString(
"district",
custom_url)
.commit();
}
});
customdistrict
.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
return;
}
}).show();
}
}
}).show();
return districtalert.create();
}
}
Change
AlertDialog.Builder customdistrict = new AlertDialog.Builder(this);
to
AlertDialog.Builder customdistrict = new AlertDialog.Builder(context);
also,
final EditText input = new EditText(getParent());
needed to be changed to
final EditText input = new EditText(context);

I have text to speech that says the button text but all buttons speak the first button's text

I just completed the coding to have the text to speech button read the text on the button the user pressed.For some reason every button says the text on the first button instead of their own text. Obviously this is a problem because you don't want every button saying the same thing. It registers no errors in my LogCat so it works fine, just not the way I want it to. I don't have the java experience to find the source of the problem.
public class menu extends Activity implements TextToSpeech.OnInitListener,
OnClickListener {
TextToSpeech mTts;
Button speakButton, infoButton, voiceButton;
// TTS object
public TextToSpeech myTTS;
// status check code
public int MY_DATA_CHECK_CODE = 0;
#Override
protected void onCreate(Bundle aboutmenu) {
super.onCreate(aboutmenu);
setContentView(R.layout.mainx);
SpeakingAndroid speak = new SpeakingAndroid();
VoiceRecognition voiceinput = new VoiceRecognition();
// get a reference to the button element listed in the XML layout
speakButton = (Button) findViewById(R.id.btn_speak);
infoButton = (Button) findViewById(R.id.aboutbutton);
voiceButton = (Button) findViewById(R.id.voicebutton);
// listen for clicks
infoButton.setOnClickListener(this);
speakButton.setOnClickListener(this);
// check for TTS data
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
voiceButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
}
public void onClick1(View about) {
// get the text entered
infoButton = (Button) findViewById(R.id.aboutbutton);
String words = infoButton.getText().toString();
speakWords(words);
Intent infoIntent = new Intent("android.intent.action.INFOSCREEN");
startActivity(infoIntent);
}
// respond to button clicks
public void onClick(View v) {
// get the text entered
speakButton = (Button) findViewById(R.id.btn_speak);
String words = speakButton.getText().toString();
speakWords(words);
Intent voiceIntent = new Intent("android.intent.action.RECOGNITIONMENU");
startActivity(voiceIntent);
}
// speak the user text
public void speakWords(String speech) {
// speak straight away
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
// act on result of TTS data check
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// the user has the necessary data - create the TTS
myTTS = new TextToSpeech(this, this);
} else {
// no data - install it now
Intent installTTSIntent = new Intent();
installTTSIntent
.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
}
// setup TTS
public void onInit(int initStatus) {
// check for successful instantiation
if (initStatus == TextToSpeech.SUCCESS) {
if (myTTS.isLanguageAvailable(Locale.US) == TextToSpeech.LANG_AVAILABLE)
myTTS.setLanguage(Locale.US);
} else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...",
Toast.LENGTH_LONG).show();
}
}
}
Declare a text to speech attribute in your activity
private TextToSpeech mTTS;
Instantiate your Text to speech Object in your Activity
mTTS=new TextToSpeech(this,this);
Get a reference to your buttons listed in the XML layout
speakButton = (Button) findViewById(R.id.btn_speak);
infoButton = (Button) findViewById(R.id.btn_about);
voiceButton = (Button) findViewById(R.id.btn_voice);
Listen to ClickEvents for your Button, your activity must implement the View.OnClickListener interface
infoButton.setOnClickListener(this);
speakButton.setOnClickListener(this);
voiceButton.setOnClickListener(this);
Handle Click Events in th Overriden onClick() method:
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.btn_speak:
mTTS.speak(speakButton.getText().toString(), TextToSpeech.QUEUE_ADD, null);
break;
case R.id.btn_about:
mTTS.speak(infoButton.getText().toString(), TextToSpeech.QUEUE_ADD, null);
break;
case R.id.btn_voice:
mTTS.speak(voiceButton.getText().toString(), TextToSpeech.QUEUE_ADD, null);
break;
}
}

Categories