How to use Text to speech code with Text view only - java

I've tried to do the Text to Speech tutorials online but instead it gave me an out put of typing the words and clicking a button to speak the typed words.
What I really want for my output is that the app would just read the text showed on the app example, It will read the text "I am Happy" which the string is already declared as TextView.
Here is a picture of an example of what I want to do.
Link of picture here
When you press the speaker button it will just read the words above it.
Here is my java file which is still on typing the words and it gives out the speech:
package com.example.chadymaebarinan.emojiexpress;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.view.View;
import android.widget.EditText;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.content.Intent;
import android.widget.Toast;
import java.util.Locale;
public class Speech extends AppCompatActivity implements OnClickListener,OnInitListener {
private int MY_DATA_CHECK_CODE = 0;
private TextToSpeech myTTS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speech);
Button speakButton = (Button) findViewById(R.id.speak);
speakButton.setOnClickListener(this);
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
}
public void onClick(View v) {
//handle user clicks here
EditText enteredText = (EditText) findViewById(R.id.enter);
String words = enteredText.getText().toString();
speakWords(words);
}
private void speakWords(String speech) {
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
myTTS = new TextToSpeech(this, this);
} else {
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
}
public void onInit(int initStatus) {
if (initStatus == TextToSpeech.SUCCESS) {
if (myTTS.isLanguageAvailable(Locale.US) == TextToSpeech.LANG_AVAILABLE)
myTTS.setLanguage(Locale.US);
myTTS.setLanguage(Locale.US);
} else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...", Toast.LENGTH_LONG).show();
}
}
}
Thank you guys! :)

Create a textView in your xml with id say myword and remove the editText from xml
then instead of
public void onClick(View v) {
//handle user clicks here
EditText enteredText = (EditText) findViewById(R.id.enter);
String words = enteredText.getText().toString();
speakWords(words);
}
do
public void onClick(View v) {
//handle user clicks here
TextView myword = (TextView) findViewById(R.id.myword);
String words = myword.getText().toString();
speakWords(words);
}

here this code working properly for me:
implement in user click :
public void onClick(View v) {
//handle user clicks here
EditText enteredText = (EditText) findViewById(R.id.enter);
String words = enteredText.getText().toString();
if(words.length!=0){
StartSpeak(words);
}
}
Start a method before speak:
private void StartSpeak(final String data) {
TTS=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int initStatus) {
if (initStatus == TextToSpeech.SUCCESS) {
if(TTS.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE)
TTS.setLanguage(Locale.US);
TTS.setPitch(1.3f);
TTS.setSpeechRate(0.7f);
// start speak
speakWords(data);
}
else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(getApplicationContext(), "Sorry! Text To Speech failed...", Toast.LENGTH_LONG).show();
}
}
});
}
Start Text to Speech
private void speakWords(String speech) {
TTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}

Related

I am working on OCR reader application. below is my java code. My question is how to start another method if one is completed?

When the user captures the image, the device will automatically read aloud the text. for that i have implemented texttospeech method but when this activity stop i want to start another task. how will it can be done?
After reading the captured text, I want to implement another text-to-speech method how can i do this?
package com.example.software2.ocrhy;
import static android.Manifest.permission.CAMERA;
import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity2 extends AppCompatActivity {
private static final int REQUEST_SPEECH = 101;
private static final int REQ_CODE_SPEECH_INPUT = 100;
Button buttonCamera;
private Button button;
private TextView mVoiceInputTv;
private TextView textView;
private SurfaceView surfaceView;
private CameraSource cameraSource;
private TextRecognizer textRecognizer;
private static TextToSpeech textToSpeech;
private String stringResult = null;
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mVoiceInputTv = (TextView) findViewById(R.id.textView);
textView = (TextView) findViewById(R.id.textView);
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, PackageManager.PERMISSION_GRANTED);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.CANADA);
textToSpeech.setSpeechRate(1f);
Toast.makeText(MainActivity2.this, "tap on the screen and say yes for read and no for return to the main menu", Toast.LENGTH_SHORT).show();
textToSpeech.speak("tap on the screen and say yes for read and no for return to the main menu", TextToSpeech.QUEUE_ADD, null);
}
}
});
}
private void textRecognizer() {
Toast.makeText(MainActivity2.this, "Tap on the screen and listen ", Toast.LENGTH_SHORT).show();
textToSpeech.speak(" Tap on the screen take a picture of any text with your device and listen", TextToSpeech.QUEUE_FLUSH, null);
textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
.setRequestedPreviewSize(1280, 1024)
.setAutoFocusEnabled(true)
.build();
surfaceView = findViewById(R.id.surfaceView);
Context context = this;
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
}
private void capture() {
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
SparseArray<TextBlock> sparseArray = detections.getDetectedItems();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < sparseArray.size(); ++i) {
TextBlock textBlock = sparseArray.valueAt(i);
if (textBlock != null && textBlock.getValue() != null) {
stringBuilder.append(textBlock.getValue() + " ");
}
}
final String stringText = stringBuilder.toString();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
stringResult = stringText;
resultObtained();
}
});
}
});
}
private void resultObtained() {
setContentView(R.layout.activity_main2);
textView = findViewById(R.id.textView);
textView.setText(stringResult);
textToSpeech.speak(stringResult, TextToSpeech.QUEUE_FLUSH, null, null);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startVoiceInput();
}
});
}
private void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hello, How can I help you?");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mVoiceInputTv.setText(result.get(0));
}
if (mVoiceInputTv.getText().toString().contentEquals("time and date")) {
Intent intent = new Intent(getApplicationContext(), MainActivity4.class);
startActivity(intent);
}
if (mVoiceInputTv.getText().toString().contentEquals("battery")) {
Intent intent = new Intent(getApplicationContext(), MainActivity6.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().contentEquals("location")) {
Intent intent = new Intent(getApplicationContext(), MainActivity8.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().contentEquals("weather")) {
Intent intent = new Intent(getApplicationContext(), MainActivity5.class);
startActivity(intent);
mVoiceInputTv.setText(null);
} else {
textToSpeech.speak( "Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().contentEquals("calculator")) {
Intent intent = new Intent(getApplicationContext(), MainActivity3.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
else if(mVoiceInputTv.getText().toString().contentEquals("exit")) {
finish();
}
else {
textToSpeech.speak("Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().contentEquals("yes")) {
setContentView(R.layout.surface);
surfaceView = findViewById(R.id.surfaceView);
surfaceView.setOnClickListener((View v) -> {
capture();
});
textRecognizer();
mVoiceInputTv.setText(null);
} else if (mVoiceInputTv.getText().toString().contentEquals("no")) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
break;
}
}
}
public boolean onKeyDown(int keyCode, #Nullable KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
textToSpeech.speak("You are in main menu. just swipe right and say what you want", TextToSpeech.QUEUE_FLUSH, null);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
textToSpeech.speak("you are in main menu. just swipe right and say what you want", TextToSpeech.QUEUE_FLUSH, null);
}
},1000);
}
return true;
}
public void buttonStart(View view) {
startVoiceInput();
}
public void onPause() {
if (textToSpeech != null) {
textToSpeech.stop();
}
super.onPause();
}
}
just use the same mode on text to speech ADD and it will play when the first one is done, ADD = ADD, FLUSH = reset
textToSpeech.speak("this will play when first is done",
TextToSpeech.QUEUE_ADD, null);
You have to call startVoiceInput() again.
You are setting this call for an onClick() handler on a TextView already.

I can select an image from the device but it wont upload on and due to that, I am unable to create a user

For my app to register a user all it fills needs to be filled. However when I select an image when clicking on the image view; it doesn't come up, and after filling the other detail I can't create a new user due to the the imageview not being filled. I don't have no errors in my logcat.It only stopped creating a new user after implementing the Image part in the code.
package com.example.appdemo;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.IOException;
public class RegistrationActivity extends AppCompatActivity {
private EditText userName, userPassword, userEmail,userAge;
private Button regButton;
private TextView userLogin;
private ImageView userProfilePic;
private FirebaseAuth firebaseAuth;
String email, name, age, password;
private FirebaseStorage firebaseStorage;
private static int PICK_IMAGE = 123;
Uri imagePath;
private StorageReference storageReference;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == PICK_IMAGE && requestCode == RESULT_OK && data.getData() != null){
imagePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imagePath);
userProfilePic.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
setupUIViewas();
firebaseAuth = FirebaseAuth.getInstance();
firebaseStorage = FirebaseStorage.getInstance();
storageReference = firebaseStorage.getReference();
userProfilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");// for document //application/* audio/* mp3/*
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "select image"),PICK_IMAGE);
}
});
regButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(validate()){
//upload data to database
String user_email = userEmail.getText().toString().trim();
String user_password = userPassword.getText().toString().trim();
firebaseAuth.createUserWithEmailAndPassword(user_email,user_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//have to put the verification code here.
sendUserData();
// signs out user after registration and send you to login
firebaseAuth.signOut();
Toast.makeText(RegistrationActivity.this,"Registration successful",Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(RegistrationActivity.this,MainActivity.class));
}else{ Toast.makeText(RegistrationActivity.this,"Registration failed please try again",Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
userLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(RegistrationActivity.this,MainActivity.class));
}
});
}
private void setupUIViewas(){
userName = (EditText) findViewById(R.id.etUserName);
userPassword = (EditText) findViewById(R.id.etUserPassword);
userEmail = (EditText) findViewById(R.id.etUserEmail);
regButton = (Button) findViewById(R.id.btnRegister);
userLogin = (TextView) findViewById(R.id.tvUserLogin);
userAge = (EditText) findViewById(R.id.etAge);
userProfilePic = (ImageView) findViewById(R.id.ivProfile);
}
private Boolean validate(){
Boolean result = false;
name = userName.getText().toString();
password = userPassword.getText().toString();
email = userEmail.getText().toString();
age = userAge.getText().toString();
if(name.isEmpty()|| password.isEmpty()||email.isEmpty() || age.isEmpty() || imagePath == null){
Toast.makeText(this, "Please fill in all the details", Toast.LENGTH_SHORT).show();
}else {
result = true;
}
return result;
}
private void sendUserData(){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myref = firebaseDatabase.getReference(firebaseAuth.getUid());
StorageReference imageReference = storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic");//User Id/Images/profile_pic.jpg
UploadTask uploadTask = imageReference.putFile(imagePath);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegistrationActivity.this,"File upload failed!",Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(RegistrationActivity.this,"File upload successful!",Toast.LENGTH_SHORT).show();
}
});
UserProfile userProfile = new UserProfile(age,email,name);
myref.setValue(userProfile);
}
}
Check the condition you wrote in onActivityResult :)
The second requestCode should be resultCode.
Change:
(requestCode == PICK_IMAGE && requestCode == RESULT_OK &&
data.getData() != null)
To:
(requestCode == PICK_IMAGE && resultCode == RESULT_OK &&
data.getData() != null)

speech recognition intent not opening on button click

I am working on a simple assistant app intially by hardcoding what it replies. It has a button which on clicked shows up the voice recognizer intent. but it is not showing up now on button click. I have attached my code here please help me to find the mistake causing the error.
also please help me how to invoke the speech recognizer without tapping on the button, by just saying some specified word as in 'Ok google'.
MainActivity.java
package com.example.rv00485448.neha1;
import android.content.Intent;
import android.os.Build;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import java.util.ArrayList;
import java.util.Locale;
import static android.speech.RecognizerIntent.ACTION_RECOGNIZE_SPEECH;
public class MainActivity extends Activity{
private TextToSpeech tts;
private ArrayList<String> questions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.microphoneButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listen();
}
});
loadQuestions();
tts = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
}
speak("Hello");
} else {
Log.e("TTS", "Initilization Failed!");
}
}
});
}
private void loadQuestions(){
questions = new ArrayList<>();
questions.clear();
questions.add("hi how are you");
questions.add("I am good. how are you feeling today?");
questions.add("Do you have vitals readings?");
questions.add("you seem to have fever. Do you want me to book an appointment with doctor nandan ");
questions.add("I have booked an appointment with doctor nandan at 5 PM");
questions.add("Thank you too");
}
private void listen(){
Intent i = new Intent(ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say something");
// speak("I am listening to you");
// try {
// startActivityForResult(i, 100);
// } catch (ActivityNotFoundException a) {
// Toast.makeText(MainActivity.this, "Your device doesn't support Speech Recognition", Toast.LENGTH_SHORT).show();
// }
}
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
private void speak(String text){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
}else{
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 100){
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> res = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String inSpeech = res.get(0);
recognition(inSpeech);
}
}
}
private void recognition(String text){
switch (text)
{
case "hello":
{
speak(questions.get(0));
break;
}
case "fine how about you":
{
speak(questions.get(1));
break;
}
case "feeling dizzy":
{
speak(questions.get(2));
break;
}
case "yeah":
{
speak(questions.get(3));
break;
}
case "yes":
{
speak(questions.get(4));
break;
}
case "thank you":
{
speak(questions.get(5));
break;
}
}
}
}
you are not triggering that activity.
use startActivityForResult(i) inside listen method.
You need to add INTERNET permission in your manifest file

Data from sharedpreferences incorrect when validated on login.class

Login.class
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Login extends AppCompatActivity {
EditText Lname, Password;
TextView Regit;
Button Login, Cancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Lname = (EditText) findViewById(R.id.txtLname);
Password = (EditText) findViewById(R.id.txtPassword);
Login = (Button) findViewById(R.id.btnLogin);
Cancel = (Button) findViewById(R.id.btnCancel);
Regit = (TextView) findViewById(R.id.txtRegit);
Regit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Login.this, Registration.class);
startActivity(intent);
}
});
Cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Lname.setText("");
Password.setText("");
}
});
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
load();
}
});
}
public void run() {
Intent x = new Intent(Login.this, MainPage.class);
startActivity(x);
}
public void LoginSuccess() {
Toast.makeText(this, "Successfully Logged in!", Toast.LENGTH_SHORT).show();
run();
}
public void load(){
final SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = pref.edit();
String value=(pref.getString("Name", Lname.getText().toString()));
String value2=(pref.getString("Password", Password.getText().toString()));
if (value.equals(Lname) & value2.equals(Password)){
LoginSuccess();
} else{
Toast.makeText(this, "Last Name or Password Incorrect or Does not Exist!", Toast.LENGTH_SHORT).show();
}
}
}
Registration.class
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.regex.Pattern;
public class Registration extends AppCompatActivity {
EditText Lname, Fname, Mname, BDate, Email, Password;
String Lnamee, Fnamee, Mnamee, Bdatee, Emails, Passwords;
TextView Login;
Button Register, Cancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
Lname = (EditText) findViewById(R.id.txtFamilyName);
Fname = (EditText) findViewById(R.id.txtFirstName);
Mname = (EditText) findViewById(R.id.txtMiddleName);
BDate = (EditText) findViewById(R.id.txtBDay);
Email = (EditText) findViewById(R.id.txtEMail);
Password = (EditText) findViewById(R.id.txtPassword);
Register = (Button) findViewById(R.id.btnRegister);
Cancel = (Button) findViewById(R.id.btnCancel);
Login = (TextView) findViewById(R.id.txtLogin);
Login.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent(Registration.this, Login.class);
startActivity(intent);
}
});
Cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Lname.setText("");
Fname.setText("");
Mname.setText("");
BDate.setText("");
Email.setText("");
Password.setText("");
}
});
Register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
register();
}
});
}
public void register() {
initialize();
if (!validate()) {
Toast.makeText(this, "Sign-up has Failed", Toast.LENGTH_SHORT).show();
} else {
onSignUpSuccess();
}
}
public void onSignUpSuccess() {
save();
Toast.makeText(this, "Successfully Registered!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Registration.this, Login.class);
startActivity(intent);
}
public boolean validate() {
boolean valid = true;
if (Lnamee.isEmpty() || Pattern.compile("[a-zA-Z]*+").matcher(Lnamee).matches()) {
Lname.setError("Enter letters only!");
valid = false;
}
if (Mnamee.isEmpty() || Pattern.compile("[a-zA-Z]*+ ").matcher(Mnamee).matches()) {
Mname.setError("Enter letters only!");
valid = false;
}
if (Fnamee.isEmpty() || Pattern.compile("[a-zA-Z]*+").matcher(Fnamee).matches()) {
Fname.setError("Enter letters only!");
valid = false;
}
if (Emails.isEmpty() || Pattern.compile("[a-zA-Z0-9]" + "\\#" + "[a-zA-Z]" + "\\." + "[a-zA-Z]").matcher(Emails).matches()){
Email.setError("Enter valid e-mail address!");
valid = false;
}
if (Passwords.isEmpty() || Passwords.length() < 8){
Password.setError("Password must be 8 characters!");
valid = false;
}
return valid;
}
public void initialize(){
Lnamee = Lname.getText().toString().trim();
Mnamee = Mname.getText().toString().trim();
Fnamee = Fname.getText().toString().trim();
Emails = Email.getText().toString().trim();
Passwords = Password.getText().toString().trim();
}
public void save() {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = pref.edit();
String LastNameReg = Lname.getText().toString();
String PWReg = Password.getText().toString();
editor.putString("Name", LastNameReg);
editor.putString("Password", PWReg);
editor.commit();
}
}
The expected behavior of the program would be, from the registration: when the user enters the Family Name or Last Name(txtFamilyName) & Password(txtPassword) it will be stored in sharedpreferences, and it will be use as a data to be entered for user to login(Login.class) and enter MainPage().
During registration(Registration.class), when I entered my Family or Last Name & Password, and use it on the Login.class, it does not enter to MainPage even though the required fields are correct.
It occurs to me that you are comparing the value of an EditView object with the actual username / password strings. You also don't want to be using the Lname and Password values as "default" values. In this case, if there is no username / password saved it will always identify as logged in.
The changes made below should suffice.
public void load() {
final SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = pref.edit();
String value=(pref.getString("Name", ""));
String value2=(pref.getString("Password", ""));
if (value.equals(Lname.getText().toString()) & value2.equals(Password.getText().toString())){
LoginSuccess();
} else{
Toast.makeText(this, "Last Name or Password Incorrect or Does not Exist!", Toast.LENGTH_SHORT).show();
}
}

Skip the Activity only if account registeration is done

In my project user have to register and then proceed forward.After the restart of the app the login activity should start skipping the registration activity.But the problem arises when user restarts the app without registering,the login activity appears and not the register activity.So plz help me with this issue Thanks in Advance
package com.example.mobilefinder;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
public class SplashScreen extends Activity {
// Splash screen timer
private static int SPLASH_TIME_OUT = 4000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Context context = getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
if(!prefs.getBoolean("firstTime", false)) {
// run your one time code here
Intent i = new Intent(getApplicationContext(), NewAccount.class);
startActivity(i);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
boolean firstboot = getSharedPreferences("BOOT_PREF", MODE_PRIVATE).getBoolean("firstboot", true);
//
if (firstboot){
// // 1) Launch the authentication activity
Intent i = new Intent(getApplicationContext(), NewAccount.class);
startActivity(i);
// // 2) Then save the state
getSharedPreferences("BOOT_PREF", MODE_PRIVATE)
.edit()
.putBoolean("firstboot", false)
.commit();
}
else
{
Intent i = new Intent(getApplicationContext(), enterpass.class);
startActivity(i);
}
// Intent i =new Intent(getApplicationContext(), NewAccount.class);
// startActivity(i);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
}
}
NewAccount.java
package com.example.mobilefinder;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class NewAccount extends Activity implements OnClickListener {
EditText ed1, ed2, ed3, ed4;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.newaccount);
Button ok;
ok = (Button) findViewById(R.id.new_account_btn_ok);
ok.setOnClickListener(this);
ed1 = (EditText) findViewById(R.id.new_account_name);
ed2 = (EditText) findViewById(R.id.new_account_email);
ed3 = (EditText) findViewById(R.id.new_account_pass);
ed4 = (EditText) findViewById(R.id.new_account_repass);
}
public final static boolean isValidEmail(String email) {
{
return Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
}
#Override
public void onClick(View arg0) {
String s2 = ed2.getText().toString();
String s3 = ed3.getText().toString();
String s4 = ed4.getText().toString();
if (ed1.getText().toString().length() == 0
|| ed2.getText().toString().length() == 0
|| ed3.getText().toString().length() == 0
|| ed4.getText().toString().length() == 0) {
if (ed1.getText().toString().length() == 0) {
ed1.setError("field required");
} else if (ed2.getText().toString().length() == 0) {
ed2.setError("field required");
} else if (ed3.getText().toString().length() == 0) {
ed3.setError("field required");
} else if (ed4.getText().toString().length() == 0) {
ed2.setError("field required");
}
} else if (isValidEmail(s2) == false) {
Toast.makeText(getApplicationContext(), "Invalid Email",
Toast.LENGTH_SHORT).show();
} else if (ed3.getText().toString().length() < 6) {
Toast.makeText(getApplicationContext(), "Password too Short",
Toast.LENGTH_SHORT).show();
} else if (!s3.equals(s4)) {
Toast.makeText(getApplicationContext(), "Password Dont Match",
Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(),
"Account Created Successfully", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
}
}
Move this code inside NewAccount.class so firstboot will be set to false only when the user has authenticated.
// 2) Then save the state
getSharedPreferences("BOOT_PREF", MODE_PRIVATE)
.edit()
.putBoolean("firstboot", false)
.commit();
I've only rewieved it breefly but I'd put it here:
else {
Toast.makeText(getApplicationContext(),
"Account Created Successfully", Toast.LENGTH_SHORT).show();
// set firstboot to false here
getSharedPreferences("BOOT_PREF", MODE_PRIVATE)
.edit()
.putBoolean("firstboot", false)
.commit();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}

Categories

Resources