Android TextToSpeech doesn't work - android

I would like to use TTS in my application. First of all I'm trying to run some examples, but every time TTS doesn't work on my device. In example I have the code:
MainActivity:
package com.example.tts;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener {
private TextToSpeech textToSpeech;
private Button button;
private EditText inputText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
inputText = (EditText) findViewById(R.id.inputText);
textToSpeech = new TextToSpeech(this, this);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
convertTextToSpeech();
}
});
convertTextToSpeech();
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("error", "This Language is not supported");
} else {
convertTextToSpeech();
}
} else {
Log.e("error", "Initilization Failed!");
}
}
#Override
public void onDestroy() {
textToSpeech.shutdown();
super.onDestroy();
}
private void convertTextToSpeech() {
//String text = "test";
String text = inputText.getText().toString();
if (null == text || "".equals(text)) {
text = "Please give some input.";
}
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TextToSpeechActivity" >
<EditText
android:id="#+id/inputText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="42dp"
android:layout_marginTop="28dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/inputText"
android:layout_below="#+id/inputText"
android:layout_marginTop="14dp"
android:text="Speak" />
</RelativeLayout>
After typing the word and clicking button application says nothing.
Does anyone have an idea how to solve it? Thanks in advance.

Related

change the text in another activity

I have a button in Activity A, which changes the text in it when clicked. There is an Activity B in which I need the TextView to become visible and its text to be the same as the text in the button on the Activity A. Please help.
Activity A
package com.example.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.annotation.Nullable;
public class SmActivity extends Activity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sm);
Button btn_apple = (Button) findViewById(R.id.button_apple);
Button btn_cherry = (Button) findViewById(R.id.button_cherry);
Button btn_orange = (Button) findViewById(R.id.button_orange);
Button btn_waterLemon = (Button) findViewById(R.id.button_waterlemon);
View.OnClickListener appleListener = new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
if (!action) {
action = true;
btn_apple.setText("1");
}
else {
int i = Integer.parseInt(btn_apple.getText().toString());
btn_apple.setText(String.valueOf(i + 1));
i = i;
}
}
};
View.OnClickListener cherryListener = new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
if (!action) {
action = true;
btn_cherry.setText("1");
}
else {
int j = Integer.parseInt(btn_cherry.getText().toString());
btn_cherry.setText(String.valueOf(j + 1));
j = j;
}
}
};
View.OnClickListener orangeListener = new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
if (!action) {
action = true;
btn_orange.setText("1");
}
else {
int k = Integer.parseInt(btn_orange.getText().toString());
btn_orange.setText(String.valueOf(k + 1));
k = k;
}
}
};
View.OnClickListener waterListener = new View.OnClickListener() {
boolean action = false;
#Override
public void onClick(View v) {
if (!action) {
action = true;
btn_waterLemon.setText("1");
} else {
int q = Integer.parseInt(btn_waterLemon.getText().toString());
btn_waterLemon.setText(String.valueOf(q + 1));
q = q;
}
}
};
btn_apple.setOnClickListener(appleListener);
btn_cherry.setOnClickListener(cherryListener);
btn_orange.setOnClickListener(orangeListener);
btn_waterLemon.setOnClickListener(waterListener);
}
public void OnClickBsk(View view){
Intent intent = new Intent(SmActivity.this, BasketActivity.class);
startActivity(intent);
}
public void OnClickProfile(View view){
Intent intent = new Intent(SmActivity.this, ProfileActivity.class);
startActivity(intent);
}
}
Do this In Activity A when you click button to go to next Activity B
btn.setOnClickListener(v -> {
Intent i = new Intent(AActivity.this,BActivity.class);
// This below line sends Key- btnText and Value- Apple
i.putExtra("btnText","Apple");
startActivity(i);
});
In BActivity do this to button
// Here you receives data from activity a with the help of Key- btnText
btn.setText(getIntent().getStringExtra("btnText"));
This is a simple way to do this.
I Have Solved the answer for you,
Minor Explanations is in the comments in code.
Use this code as a concept and apply changes to yours based on your requirement.
XML of Activity A:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ActivityA">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text Before Button Click"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:id="#+id/text_to_change"
android:textSize="20sp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_to_change"
android:id="#+id/change_text_btn"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="20dp"
android:text="Change Text and Start Activity B"
/>
</RelativeLayout>
Java of Activity A
package com.example.text_to_speech;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
public class ActivityA extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity);
TextView textView;
Button button;
textView=findViewById(R.id.text_to_change);
button=findViewById(R.id.change_text_btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newtext="New Text From Activity A";
textView.setText(newtext);
Intent intent=new Intent(ActivityA.this,ActivityB.class);
intent.putExtra("Change", newtext);//this string will be
//accessed by activityB
startActivity(intent);
}
});
}
}
XML of Activity B:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ActivityB">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Waiting for New Text"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:id="#+id/new_textview"
android:textSize="20sp"
android:visibility="gone"
/>
</RelativeLayout>
Java of Activity B:
package com.example.text_to_speech;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class ActivityB extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
TextView textView;
textView=findViewById(R.id.new_textview);
// Below if block is looking for an intent, if it gets it and
// there is content in the extras with key "Change",
// it will make the textview in xml visible and update its string
// based on value set by Activity A
if(savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if (extras == null) {
Toast.makeText(ActivityB.this, "Can't Get the Intent", Toast.LENGTH_LONG).show();
} else {
String get_String = extras.getString("Change");
textView.setVisibility(View.VISIBLE);// be default i have set the visibility to gone in xml
//here it will get visible and then filled with the string sent by the intent in activity A
textView.setText(get_String);
}
}
}
}

Can't open activity, screen flickers after splash screen

I am a newbie in Android programming. I have a splash screen after which I am trying to open an activity but after the splash screen my screen keeps flickering and the activity doesn't open. show anything. My code is as follows:
Splashscreen.java
public class splashscreen extends AppCompatActivity
{
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen);
imageView =(ImageView)findViewById(R.id.imageView);
Animation animation= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.slideinright);
imageView.setAnimation(animation);
animation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
finish();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
}
Loginpage.java
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class LoginActivity2 extends AppCompatActivity implements View.OnClickListener {
private Button loginbuttonRegister;
private EditText logineditTextEmail;
private EditText logineditTextPassword;
private TextView textViewLogin;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
private LoginButton loginButton;
private CallbackManager callbackManager;
private Profile profile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login2);
progressDialog = new ProgressDialog(this);
firebaseAuth = FirebaseAuth.getInstance();
if( firebaseAuth.getCurrentUser() != null){
//display navigation activity
finish();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
loginbuttonRegister = (Button) findViewById(R.id.loginbuttonRegister);
logineditTextEmail = (EditText) findViewById(R.id.logineditTextEmail);
logineditTextPassword = (EditText) findViewById(R.id.logineditTextPassword);
textViewLogin =(TextView) findViewById(R.id.textViewLogin);
loginbuttonRegister.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
loginbuttonRegister = (Button) findViewById(R.id.loginbuttonRegister);
if(v == loginbuttonRegister)
{
userLogin();
}
}
});
textViewLogin.setOnClickListener(this);
//Initializing Facebook Sdk.
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
//intialize callback manager
callbackManager = CallbackManager.Factory.create();
//initializing facebook login button
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
loginButton = (LoginButton)findViewById(R.id.login_button);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
ProfileTracker profileTracker;
#Override
public void onSuccess(LoginResult loginResult) {
Toast.makeText(LoginActivity2.this,"Succesfully Logged In",Toast.LENGTH_SHORT).show();
profile = Profile.getCurrentProfile();
//check profile is fetched or not, if not then wait for sometime
// to load your profile using profile tracker
if(profile == null){
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile, Profile profile1) {
if(profile1 != null){
startActivity(new Intent(LoginActivity2.this,MainActivity.class));
}
}
};
}else{
startActivity(new Intent(LoginActivity2.this,MainActivity.class));
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
});
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode,resultCode,data);
}
private void userLogin(){
String email = logineditTextEmail.getText().toString().trim();
String password = logineditTextPassword.getText().toString().trim();
if(TextUtils.isEmpty(email)){
//mail empty
Toast.makeText(this, "Please enter email!", Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this, "Please enter Password!", Toast.LENGTH_SHORT).show();
return;
}
//if valid then shows progressbar
progressDialog.setMessage("Loggin in...!");
progressDialog.show();
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{ progressDialog.dismiss();
//start anvigation activity
finish();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
else {progressDialog.dismiss();
Toast.makeText(LoginActivity2.this, "Failed to login! Try again.", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onClick(View view) {
if(view == textViewLogin)
{finish();
startActivity(new Intent(this,Registeruser.class));
}
}
}
Loginactivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_login2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.dell.Swing.LoginActivity2"
tools:showIn="#layout/activity_login2"
android:background="#drawable/probeach">
<LinearLayout
android:id="#+id/registerlayout"
android:orientation="vertical"
android:layout_centerVertical="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_margin="10dp"
android:hint="Enter your E-mail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:id="#+id/logineditTextEmail"
/>
<EditText
android:layout_margin="10dp"
android:hint="Enter your Password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:id="#+id/logineditTextPassword" />
<Button
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/loginbuttonRegister"
android:text="Log In"
style="#style/Widget.AppCompat.Button.Colored"
android:background="#android:color/holo_red_dark"
android:elevation="0dp" />
<TextView
android:textAlignment="center"
android:text="Not Registered? Sign up Here"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textViewLogin" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginBottom="66dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:weightSum="1">
<TextView
android:id="#+id/orview"
android:text="Or"
android:gravity="center"
android:textAppearance="#style/TextAppearance.AppCompat.Button"
android:layout_width="match_parent"
android:layout_weight="0.63"
android:layout_height="40dp" />
<com.facebook.login.widget.LoginButton
android:layout_margin="10dp"
android:id="#+id/login_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_below="#+id/orview"
/>
</LinearLayout>
Please check your background image resolution,
android:background="#drawable/probeach"

Android text to speech not working on mobile

i am having problem in text to speech. have this code in java class
package com.techblogon.loginexample;
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;
public class listenActivity extends Activity implements OnClickListener, OnInitListener {
private TextToSpeech tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.categories);
tts = new TextToSpeech(this, this);
findViewById(R.id.button1).setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (tts!=null) {
String text = ((EditText)findViewById(R.id.editText1)).getText().toString();
if (text!=null) {
if (!tts.isSpeaking()) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
}
#Override
public void onInit(int code) {
if (code==TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.getDefault());
} else {
tts = null;
Toast.makeText(this, "Failed to initialize TTS engine.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onDestroy() {
if (tts!=null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}
and xml file has this code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".listenActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TTS Demonstration" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:text="Say It" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="77dp"
android:ems="10"
android:text="Hello world!" />
</RelativeLayout>
but issue is when i click button no sound heard on my mobile. does i need any permission for that
any help
Many thanks

How to keep state of RadioButton in Android?

Hi I'm trying to develop an application which runs for every interval time, lets say for every 1 minute it will display some Toast message.
But problem is I'm using RadioButton functionality is perfect but when I tap on one radio button it will be green, but when I close and re-open the activity I'll get as none of the radio buttons selected.
Here is my MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_one_min:
if (checked)
{
//some code
}
break;
case R.id.radio_ten_min:
if (checked)
{
//some code
}
break;
case R.id.radio_disable:
if (checked)
{
//some code
}
break;
}
}
}
and here is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/radio">
<RadioButton android:id="#+id/radio_disable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Disable"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_one_min"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1 minute"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_ten_min"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10 minute"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
Please help me to solve this riddle.
Thanks in advance...
This code is useful for store the ratingbar state, when we start new activity, you will see the previous rating state..
package com.example.ratingbar;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class RatingbarMainActivity extends Activity {
RatingBar ratingbarClick;
Button sub_btn;
TextView textRatingView , textRatingViewSave;
Boolean val = true;
float ans = (float) 0.0;
//--------------------------------------------------------------------------------------------
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ratingbar_main);
ratingbarClick = (RatingBar) findViewById(R.id.ratingBar1);
ratingbarClick.setOnRatingBarChangeListener(rateObj);
SharedPreferences sharePref = PreferenceManager.getDefaultSharedPreferences
(RatingbarMainActivity.this);
ans = sharePref.getFloat("Get_Rating", 0.0f);
System.out.println("--------------------------------------ans = " + ans);
if(val) {
ratingbarClick.setRating(ans);
}
else {
ratingbarClick.setRating(ans);
}
textRatingView = (TextView) findViewById(R.id.ratingView);
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
RatingBar.OnRatingBarChangeListener rateObj = new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating,boolean fromUser) {
//textRatingView.setText(String.valueOf(rating));
ans = ratingbarClick.getRating();
SharedPreferences sharePref = PreferenceManager.getDefaultSharedPreferences
(RatingbarMainActivity.this);
SharedPreferences.Editor edit = sharePref.edit();
edit.putFloat("Get_Rating", ans);
edit.commit();
val = false;
}
};
//--------------------------------------------------------------------------------------------
}
---------------------------------------------------------------------------------------------------
activity_ratingbar_main.xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ratingBar1"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="23dp"
android:text="Select Your Rating Bar Here"
tools:context=".RatingbarMainActivity" />
<RatingBar
android:id="#+id/ratingBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="21dp"
android:layout_marginTop="63dp" />
<TextView
android:id="#+id/ratingView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/ratingBar1"
android:text="TextView" />
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Click To Save Rating In TextBox" />
</RelativeLayout>
it is the simplest way to do so,no need of sharedpreference at all.you will get confused while using it.keep the things simple like this
public class MainActivity extends Activity {
Public static int flag=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(flag==1)
radio_one_min.setChecked(true);
else if(flag==2)
radio_ten_min.setCheckek(true);
else if(flag==3)
radio_disable.setCheckek(true);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_one_min:
if (checked)
{
flag =1;
//some code
}
break;
case R.id.radio_ten_min:
if (checked)
{
flag=2 ;
//some code
}
break;
case R.id.radio_disable:
if (checked)
{
flag=3;
//some code
}
break;
}
}
}
[EDITED]
I found developer.android.com/training/basics/activity-lifecycle/recreating.html document first, so my first guess was using Bundles and on Save/Resume Instace State methods. However this does not seem to work well. Here's my final attempt at a working solution (using SharedPreferences class, as suggested by some users):
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
public class MainActivity extends Activity {
final String PREFERENCES = "prefs";
final String RADIO_BUTTON = "prefsval";
SharedPreferences sp;
Editor e;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = this.getSharedPreferences(PREFERENCES, MODE_PRIVATE);
e = sp.edit();
}
#Override
protected void onResume() {
super.onResume();
if (sp != null) {
if (sp.getInt(RADIO_BUTTON, 0) != 0) {
RadioButton rb;
rb = (RadioButton) findViewById(sp.getInt(RADIO_BUTTON, 0));
rb.setChecked(true);
}
}
}
public void onRadioButtonClicked(View view) {
e.putInt(RADIO_BUTTON, view.getId());
e.apply();
}
}

Button duplication in android when setting new text

I am working with the android support library, to be able to use fragments from Froyo, and the Sherlock extension, to show an ActionBar.
I have a fragment which shows three textViews and a button, and I want to be able to change the button text dinamically, depending on the content of the Intent. The problem is that when I call button.setText(String text), a second button appears. However, I've called button.getId() when clicking on each of them, and the Id is the same. I don't have a clue of why this is happening, so I'd appreciate some help.
The app is run on a Samsung Galaxy S, with Android 2.3.3. I can't upload a screen capture because I don't have enough reputation yet :(
This is the code:
FRAGMENT
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.actionbarsherlock.app.SherlockFragment;
import com.parse.ParseUser;
import com.tiempoderodar.egdf.EGDF_App;
import com.tiempoderodar.egdf.R;
import com.tiempoderodar.egdf.security.Constants;
/**
* #author Daniel Leal López
*
*/
public class ChapterDetailsFragment extends SherlockFragment{
private Button b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("ChapterDetailsFragment", "Created");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ParseUser user = EGDF_App.getUser();
b = (Button) getSherlockActivity().findViewById(R.id.buttonWatchChapter);
if (user != null){
String chapterNumber = "";
Bundle extras = getSherlockActivity().getIntent().getExtras();
String s = extras.getString(Constants.CHAPTER_NUMBER_PARSE);
if((s != null)&&(!s.equals(""))){
// tvNumber.setText(s);
chapterNumber = "Chapter_" + s;
Log.i("Properties", s);
}
String seen = user.getString(chapterNumber);
if((seen != null)&&(!seen.equals(""))&&(seen.equals(Constants.USER_CHAPTER_SEEN))){
b.setText("Second text: "+getString(R.string.watch_chapter_button_text));
Log.i("BUTTON CHANGED", "Text changed to watch");
}
else if((seen != null)&&(!seen.equals(""))&&(seen.equals(Constants.USER_CHAPTER_NOT_SEEN))){
b.setText("Second text: " + getString(R.string.buy_chapter_button_text));
Log.i("BUTTON CHANGED", "Text changed to buy");
}else{
Log.w("DEV ERROR", "Chapter text not obtained");
}
}else{
Log.w("DEV ERROR", "ParseUser is null in EGDF_App!!!");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.chapter_details, container, false);
return view;
}
public void setText(String item) {
getSherlockActivity().getSupportActionBar().setTitle(item);
}
public void setButtonText(String text){
b.setText(text);
}
}
Activity
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class ChapterDetailsActivity extends SherlockFragmentActivity {
private Bundle extras;
MediaPlayer mMediaPlayer;
private String chapterNumber;
private boolean isChapterSeen;
// private int duration;
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.Theme_Sherlock_Light_DarkActionBar);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapter_details);
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
ChapterDetailsFragment details = new ChapterDetailsFragment();
details.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(
android.R.id.content, details).commit();
}
}
public void watchChapter(View view){
Log.i("Button", "Watch chapter button PRESSED");
Button b = (Button) view;
Log.d("BUTTON PARENT VIEW", b.getParent().getClass().getName());
Log.d("BUTTON ID", String.valueOf(b.getId()));
String loadChapter = getString(R.string.load_chapter_button_text);
String watchChapter = getString(R.string.watch_chapter_button_text);
String buyChapter = getString(R.string.buy_chapter_button_text);
}
#Override
protected void onPause() {
Log.i("Activity lifecycle", "On pause called");
super.onPause();
}
#Override
protected void onStop() {
Log.i("Activity lifecycle", "On stop called");
super.onStop();
}
#Override
protected void onDestroy() {
Log.i("Activity lifecycle", "On destroy called");
super.onDestroy();
EGDF_App.releaseMediaPlayer();
}
#Override
protected void onResume() {
Log.i("Activity lifecycle", "On resume called");
super.onResume();
}
#Override
protected void onStart() {
Log.i("Activity lifecycle", "On start called");
super.onStart();
}
}
Activity layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/chapterDetailsFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.tiempoderodar.egdf.content.ChapterDetailsFragment" />
</LinearLayout>
Fragment Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textViewChapterNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30dip" />
<TextView
android:id="#+id/textViewChapterSeason"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30dip" />
<TextView
android:id="#+id/textViewChapterSinopsis"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30dip" />
<TextView
android:id="#+id/textViewChapterCredits"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30dip" />
<Button
android:id="#+id/buttonWatchChapter"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/watch_chapter_button_text"
android:layout_gravity="center"
android:onClick="watchChapter"/>
</LinearLayout>
Thanks!
I think I might have found the problem. I was calling
b = (Button) getSherlockActivity().findViewById(R.id.button);
but it should be
b = (Button) getView().findViewById(R.id.button);
With that change it works correctly

Categories

Resources