I'm making a simple application and want to open a new Activity when I click a button. I have looked at a few tutorials online to do so, but I keep getting errors in my code that I dont quite know how to get rid of.
My code:
public class MainActivity extends AppCompatActivity {
private static Button button_convert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onClick_Convert();
public void onClick_Convert() {
onClick_Convert = (button_convert) findViewById(R.id.button_convert);
onClick_Convert.setOnClickListener (
new View.onClickListener() {
public void onClick (View v) {
Intent intent = new Intent("com.example.jamesk93.bmi_app.SecondActivity");
startActivity(intent);
}
}
);
}
final Button button_calc = (Button) findViewById(R.id.button_calc);
final EditText field_weight = (EditText) findViewById(R.id.field_height);
final EditText field_height = (EditText) findViewById(R.id.field_height);
final TextView view_result = (TextView) findViewById(R.id.view_result);
final TextView view_msg = (TextView) findViewById(R.id.view_msg);
button_calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View V) {
double weight;
double height;
double bmi;
String msg = "";
weight = Double.parseDouble(field_weight.getText().toString());
height = Double.parseDouble(field_height.getText().toString());
if (field_height.getText().toString().equals("") || field_weight.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "No Valid Values", Toast.LENGTH_LONG);
} else {
bmi = height * height;
bmi = weight / bmi;
view_result.setText(String.valueOf(bmi));
if (bmi < 18.5) {
msg = "Underweight";
} else if (bmi > 18.5 && bmi < 25) {
msg = "Normal";
} else if (bmi > 25) {
msg = "Overweight";
}
view_msg.setText(msg);
}
}
});
}
}
Im pretty sure it is my use of brackets and indenting that is generating the errors. Ive tried to reposition them but it doesnt seem to be solving anything.
If I comment lines 21-33 out which is the code for the onclick intent, it runs fine. If you need to see any of my other files, just comment which ones and I'll upload them for you.
Your code should be like this:
private Button button_convert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_convert= (Button) findViewById(R.id.button_convert);
onClick_Convert();
}
public void onClick_Convert() {
button_convert.setOnClickListener (
new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
}
}
);
}
EDIT:
There are a few mistakes:
First:
You are trying to initialize "onClick Convert" but it was not declared, actually the name of your button is "button convert". And then you try to cast it with "button convert". You should cast your button with "(Button)"
Second:
You are trying to initialize your button inside the click event, you should initialized it before the event, because then your button will be null.
Third:
The correct syntax to start an activity is:
Intent intent = new Intent(YourActivity.class, NewActivity.class);
startActivity(intent);
Hope this help you, I recommend you to take a look to this link: http://developer.android.com/intl/es/training/basics/firstapp/starting-activity.html
Related
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
My code was running good, but just one times. I need repeating when ===> ok = (Button) findViewById(R.id.btnOk);
Is click.
This is the code
String questionNumber = "";
EditText answer;
Button ok;
TextView question;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
answer = (EditText) findViewById(R.id.answer);
ok = (Button) findViewById(R.id.btnOk);
question = (TextView) findViewById(R.id.TextViewQuestion);
Random random = new Random();
questionNumber = String.format("%04d",random.nextInt(10000));
question.setText(questionNumber);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (answer.getText().toString().equals(questionNumber)) {
Toast.makeText(getBaseContext(),"Input True", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Input Wrong", Toast.LENGTH_LONG).show();
}
}
});
}
}
Do this..
String questionNumber = "";
EditText answer;
Button ok;
TextView question;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
answer = (EditText) findViewById(R.id.answer);
ok = (Button) findViewById(R.id.btnOk);
question = (TextView) findViewById(R.id.TextViewQuestion);
getRandomQuestion();
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (answer.getText().toString().equals(questionNumber)) {
Toast.makeText(getBaseContext(),"Input True", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Input Wrong", Toast.LENGTH_LONG).show();
}
getRandomQuestion();
}
});
}
private void getRandomQuestion() {
Random random = new Random();
questionNumber = String.format("%04d",random.nextInt(10000));
question.setText(questionNumber);
}
Remember to put the getRandomQuestion() below the checker because if you put it above then I believe it will always show the Input Wrong toast unless the first random number will be the same as the second random number.
For example..
You generated a random question in onCreate and let's say it is 1..
Then you put 1 in your editText so you assume that it should show Input True, right? But if you put the getRandomQuestion above the checker.. what will happen is you will generate a random question again then it will be 2..
Then, in your checker.. your answer is 1 then the question is 2.. so it will not be equal.
here your solution
put this
Random random = new Random();
questionNumber = String.format("%04d",random.nextInt(10000));
question.setText(questionNumber);
in the button listner
EDIT:
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (answer.getText().toString().equals(questionNumber)) {
Toast.makeText(getBaseContext(),"Input True", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Input Wrong", Toast.LENGTH_LONG).show();
}
Random random = new Random();
questionNumber = String.format("%04d",random.nextInt(10000));
question.setText(questionNumber);
}
});
This is my code to display two values: Recommended insulin dose and administered insulin dose. The two value is passed to another activity.
I have used two intent to pass two values to another activity(NewActivity).
The problem is as two intents are used only one value is displayed. The output is displayed as:
Recommended insulin dosage:null, Administered insulin dosage:10 (correct value of the calculation).
If the startActivity(intent) is removed from the button.setOnClickListener the output is displayed as:
Recommended insulin dosage:23 (correct value), Administered insulin dosage:null.
One of the value is becoming null. How to get two values displayed?
I tried declaring the string as public also
MainActivity.java
public class MainActivity extends Activity implements View.OnClickListener {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
private Button button;
private Button button2;
private EditText editText;
private EditText editText2;
private EditText editText4;
public static String myid;
public static String insulin;
private Spinner dynamicSpinner;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent=getIntent();
String carbval=intent.getStringExtra("carbval");
final EditText editText2 = (EditText) findViewById(R.id.editText2);
editText2.setText(carbval);
dynamicSpinner = (Spinner) findViewById(R.id.dynamic_spinner);
editText = (EditText) findViewById(R.id.editText);
button2 = (Button) findViewById(R.id.button2);
button = (Button) findViewById(R.id.button);
editText4=(EditText) findViewById(R.id.editText4);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String carbohydrate = editText2.getText().toString().trim();
String dailydose = editText4.getText().toString().trim();
int cc = Integer.parseInt(carbohydrate);
int dd = Integer.parseInt(dailydose);
int goc = 450 / dd;
int ab = cc / goc;
myid = Integer.toString(ab);
Intent intent1=new Intent(MainActivity.this,NewActivity.class);
intent1.putExtra("ids",myid);
startActivity(intent1);
}
});
Spinner staticSpinner = (Spinner) findViewById(R.id.static_spinner);
// Create an ArrayAdapter using the string array and a default spinner
ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter
.createFromResource(this, R.array.brew_array,
android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
staticAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
staticSpinner.setAdapter(staticAdapter);
Spinner dynamicSpinner = (Spinner) findViewById(R.id.dynamic_spinner);
String[] items = new String[] { "---SELECT---", "LOW", "MODERATE", "HIGH" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
dynamicSpinner.setAdapter(adapter);
dynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Log.v("item", (String) parent.getItemAtPosition(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
private void getData() {
String bloodglucose = editText.getText().toString().trim();
if (bloodglucose.equals("")) {
Toast.makeText(this, "Please enter bloodglucose", Toast.LENGTH_LONG).show();
return;
}
String dosage =dynamicSpinner.getSelectedItem().toString().trim();
if (dosage.equals("")) {
Toast.makeText(this, "Please enter dosage", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Calculating insulin dosage...",false,false);
String url1 = "http://10.1.6.21/getData1.php?bloodglucose="+editText.getText().toString().trim()+"&dosage="+dynamicSpinner.getSelectedItem().toString().trim();
StringRequest stringRequest = new StringRequest(url1, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String insulin="";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Confignew.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
insulin = collegeData.getString(Confignew.KEY_INSULIN);
Intent intent1=new Intent(MainActivity.this,NewActivity.class);
intent1.putExtra("value",insulin);
startActivity(intent1);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
getData();
}
}
NewActivity.java
public class NewActivity extends AppCompatActivity {
private Button mBtGoBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
TextView tvmessage=(TextView) findViewById(R.id.tv_message);
tvmessage.setText("Recommended Insulin Dosage: "+getIntent().getExtras().getString("value"));
TextView tvmessage1=(TextView) findViewById(R.id.tv_message1);
tvmessage1.setText("Administered Insulin Dosage: "+getIntent().getExtras().getString("ids"));
mBtGoBack = (Button) findViewById(R.id.bt_go_back);
mBtGoBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
Looking at your code, it looks like you are re-creating the intent before starting an activity. Each of the intents you are creating only has one value passed through to NewActivity.java. You need to add both values to the same intent rather than re-creating it.
Here is your issue:
Intent intent1=new Intent(MainActivity.this,NewActivity.class);
intent1.putExtra("ids",myid);
Intent intent1=new Intent(MainActivity.this,NewActivity.class);
intent1.putExtra("value",insulin);
Rather than instantiating it twice, you should be creating the Intent only once and then adding extras to it as needed.
The two value is passed to another activity
You're only passing one value to the intent in every startActivity call, not two. That's why one is null and the other is not.
Here
Intent intent1=new Intent(MainActivity.this,NewActivity.class);
intent1.putExtra("value",insulin);
startActivity(intent1);
And here
Intent intent1=new Intent(MainActivity.this,NewActivity.class);
intent1.putExtra("ids",myid);
startActivity(intent1);
Just because you name it intent1 doesn't mean the data is shared.
You need to place both extras in the intent.
How about making a helper method, so you don't forget?
private void startNewActivity(String recommended, String administered) {
Intent i = new Intent(MainActivity.this,NewActivity.class);
i.putExtra("value",recommended);
i.putExtra("ids", administered);
startActivity(i);
}
Then use this to get both correct values.
startNewActivity("23", "10");
And by the way, this button event is never actually ran.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String carbohydrate = editText2.getText().toString().trim();
String dailydose = editText4.getText().toString().trim();
int cc = Integer.parseInt(carbohydrate);
int dd = Integer.parseInt(dailydose);
int goc = 450 / dd;
int ab = cc / goc;
myid = Integer.toString(ab);
// Replace this code with the method
/*
Intent intent1=new Intent(MainActivity.this,NewActivity.class);
intent1.putExtra("ids",myid);
startActivity(intent1);
*/
}
});
This one is... It overwrites the previous one.
button.setOnClickListener(this);
And does this
#Override
public void onClick(View v) {
getData();
}
One Intent can open a single Activity. What you are trying to do is sending value from two different Intents which you are re-creating inside onClicks.
You have to provide onClick using any one method. You have first set clickListener on Button using Anonymous Class and implemented the OnClickListener at the same time.
Remove onClickListener from the button, the part below
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String carbohydrate = editText2.getText().toString().trim();
String dailydose = editText4.getText().toString().trim();
int cc = Integer.parseInt(carbohydrate);
int dd = Integer.parseInt(dailydose);
int goc = 450 / dd;
int ab = cc / goc;
myid = Integer.toString(ab);
Intent intent1=new Intent(MainActivity.this,NewActivity.class);
intent1.putExtra("ids",myid);
startActivity(intent1);
}
});
Keep your overrdien onClick as it is.
#Override
public void onClick(View v) {
getData();
}
And now edit your getData() method to add the removed code
private void getData() {
String bloodglucose = editText.getText().toString().trim();
if (bloodglucose.equals("")) {
Toast.makeText(this, "Please enter bloodglucose", Toast.LENGTH_LONG).show();
return;
}
String dosage =dynamicSpinner.getSelectedItem().toString().trim();
if (dosage.equals("")) {
Toast.makeText(this, "Please enter dosage", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Calculating insulin dosage...",false,false);
String url1 = "http://10.1.6.21/getData1.php?bloodglucose="+editText.getText().toString().trim()+"&dosage="+dynamicSpinner.getSelectedItem().toString().trim();
StringRequest stringRequest = new StringRequest(url1, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
And finally showJSON
private void showJSON(String response){
String insulin="";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Confignew.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
//The code from button's onClickListener
String carbohydrate = editText2.getText().toString().trim();
String dailydose = editText4.getText().toString().trim();
int cc = Integer.parseInt(carbohydrate);
int dd = Integer.parseInt(dailydose);
int goc = 450 / dd;
int ab = cc / goc;
myid = Integer.toString(ab);
Intent intent1 = new Intent(MainActivity.this,NewActivity.class);
intent1.putExtra("ids",myid);
//startActivity(intent1); Put second value too before starting activity
insulin = collegeData.getString(Confignew.KEY_INSULIN);
intent1.putExtra("value",insulin);
startActivity(intent1);
} catch (JSONException e) {
e.printStackTrace();
`enter code here`}
}
#Rasiga could you please let me know why 2 OnCickListener is set like
`button.setOnClickListener(this)`
and
button.setOnClickListener(new OnCLickListner){.....}
You are setting 2 onCLickListener for same View
well i'm just testing the idea of shared preferences to save the user progress, but this simple code is not working, when i pass lev1 it should update preffile so that at next app start it should opens directly to lev2Activity, everything is ok even log cat is clean but nothing happens, i don't know whats wrong with my code, any help will be appreciated.
MainActivity.java
private Button b1;
public static final String levstate= "levstate";
private Context mycontext;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mycontext= this;
b1= (Button) findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
MainActivity.savelevstate(1, mycontext);
Intent i= new Intent(MainActivity.this, Lev1Activity.class);
startActivity(i);
}
});
}
public static void savelevstate(int state, Context mycontext)
{
SharedPreferences pref= mycontext.getSharedPreferences("preffile", MODE_APPEND);
Editor editor= pref.edit();
editor.putInt("levstate", state);
editor.commit();
}
public static int getlevstate(Context mycontext)
{
SharedPreferences pref= mycontext.getSharedPreferences("preffile", MODE_APPEND);
int state= pref.getInt("levstate", 1);
return state;
}
Lev1Activity.java
private EditText et1;
private Button b1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lev1);
et1= (EditText) findViewById(R.id.et1);
b1= (Button) findViewById(R.id.b1);
}
public void Next (View v)
{
String value= et1.getText().toString();
int finalvalue= Integer.parseInt(value);
if(finalvalue==22)
{
Intent i = new Intent (this, Lev2Activity.class);
startActivity(i);
MainActivity.savelevstate(2, this);
this.finish();
}
}
Your idea of using sharedPreferences is excellent. However, if you look at your MainActivity's onCreate(), you can see that you never check the last level state before starting the intent. The app runs, the user clicks on button "b1" and it immediately starts Lev1Activity. Assuming you want the correct level to start when the user presses that same button, you'd have to check for the current level state and then link that state to its appropriate level Activity.
For example (MainActivity.java):
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
Intent i;
switch(getlevstate(myContext)) {
case 1:
i = new Intent(myContext, Lev1Activity.class);
break;
case 2:
i = new Intent(myContext, Lev2Activity.class);
break;
case 3:
i = new Intent(myContext, Lev3Activity.class);
break;
case 4
i = new Intent(myContext, Lev4Activity.class);
break;
...
}
startActivity(i);
}
});
Using MODE_APPEND should work as well as using MODE_PRIVATE, however it is recommended to use the latter.
I would recommend to you to create a new class for working with SharedPreferences.
Here is a example for saving and retrieving data from shared preferences:
public class SharedPreferenceSettings {
private static final String PREFS_NAME = "MY_APP_SETTINGS";
private static final String PREFS_LANGUAGE = "LANGUAGE";
private static final String PREFS_CITY = "CITY";
private final SharedPreferences settings;
public SharedPreferenceSettings(Context context) {
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
}
public void setLanguage(String language) {
settings.edit().putString(PREFS_LANGUAGE, language).apply();
}
public String getlanguage() {
return settings.getString(PREFS_LANGUAGE, "english");
}
public void setCity(String city) {
settings.edit().putString(PREFS_CITY, city).apply();
}
public String getCity() {
return settings.getString(PREFS_CITY, "london");
}
}
For more info, check official Android documentation - link
You are only saving the states, but you aren't checking it anywhere in the code.
In MainActivity try this :
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
if(getlevstate(MainActivity.this)==2) {
Intent i= new Intent(MainActivity.this, Lev2Activity.class);
startActivity(i);
} else {
MainActivity.savelevstate(1, mycontext);
Intent i= new Intent(MainActivity.this, Lev1Activity.class);
startActivity(i);
}
}
});
Not sure this is the problem, but when I use Preferences I use Context.MODE_PRIVATE this is the only difference between my code and yours, maybe it will help!
Edit : I might be wrong, but I don't see anywhere the call to getlevstate. After setting this
et1= (EditText) findViewById(R.id.et1);
You shoud do somehing like this :
et1.setText(""+getlevstate(this))
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;
}
}