Android Studio Text to Speech - java

I wrote a program which converts a given text into speech.
My code works perfectly on the emulator, but I couldn't achieve the same result on my device.
Can you help me, showing me where is my problem?
MainActivity.java
import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Locale;
public class MainActivity extends ActionBarActivity {
TextToSpeech ttsobject;
int result;
EditText et;
String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et= (EditText)findViewById(R.id.editText);
ttsobject = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
result = ttsobject.setLanguage(Locale.ENGLISH);
} else {
Toast.makeText(getApplicationContext(), "Feature Not Support Your Device ", Toast.LENGTH_SHORT).show();
}
}
});
}
public void doSomething(View v){
switch (v.getId()){
case R.id.bspeak:
if(result==TextToSpeech.LANG_NOT_SUPPORTED || result==TextToSpeech.LANG_MISSING_DATA){
Toast.makeText(getApplicationContext(), "NO SUPPORT FOR LANGUAGE ", Toast.LENGTH_SHORT);
}
else{
text = et.getText().toString();
ttsobject.speak(text,TextToSpeech.QUEUE_FLUSH,null);
}
break;
case R.id.bstopspeaking:
if(ttsobject!=null){
ttsobject.stop();
}
break;
}
}
#Override
protected void onDestroy(){
super.onDestroy();
if(ttsobject!=null){
ttsobject.stop();
ttsobject.shutdown();
}
}
}
activity_main.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Speak"
android:id="#+id/bspeak"
android:layout_centerVertical="true"
android:layout_alignStart="#+id/bstopspeaking"
android:onClick="doSomething"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP"
android:id="#+id/bstopspeaking"
android:layout_below="#+id/bspeak"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:onClick="doSomething"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_above="#+id/bspeak"
android:layout_centerHorizontal="true"
android:layout_marginBottom="62dp" />

Related

How to zoom out a bitmap image?

I'm capturing an image using a biometric reader.
Connecting the reader to the tablet and capturing the image works fine, but the image looks like this:
The image is cropped. It looks like it's magnified when the biometric capture takes place.
this is my code:
package mobfeel.com.br.exfingerprintreaderuareu4500;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import asia.kanopi.fingerscan.Status;
public class MainActivity extends AppCompatActivity {
private ImageView ivFingerprint;
private Button btScan;
private static final int SCAN_FINGERPRINT = 1234;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
btScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ScanActivity.class);
startActivityForResult(intent, SCAN_FINGERPRINT);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case SCAN_FINGERPRINT:
if (resultCode == RESULT_OK) {
int status = data.getIntExtra("status", Status.ERROR);
if (status == Status.SUCCESS) {
toast("Fingerprint OK!");
byte[] img = data.getByteArrayExtra("img");
Bitmap bm = BitmapFactory.decodeByteArray(img, 0, img.length);
ivFingerprint.setImageBitmap(bm);
return;
}
toast(data.getStringExtra("errorMessage"));
}
break;
}
}
private void toast(String msg){
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();
}
private void init(){
ivFingerprint = findViewById(R.id.ma_iv_fingerprint);
btScan = findViewById(R.id.ma_bt_scan);
}
}
And this is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".MainActivity">
<ImageView
android:id="#+id/ma_iv_fingerprint"
android:layout_width="221dp"
android:layout_height="206dp"
android:layout_gravity="center"
android:layout_marginBottom="460dp"
android:adjustViewBounds="true"
android:scaleType="fitXY"
app:layout_constraintBottom_toTopOf="#+id/ma_bt_scan"
app:srcCompat="#mipmap/ic_launcher"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="8dp" />
<Button
android:id="#+id/ma_bt_scan"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="Scan"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>
I also have the ScanActivity.java class
package mobfeel.com.br.exfingerprintreaderuareu4500;
import android.content.Intent;
import android.os.Looper;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import asia.kanopi.fingerscan.Fingerprint;
import asia.kanopi.fingerscan.Status;
public class ScanActivity extends AppCompatActivity {
private TextView tvStatus;
private Fingerprint fingerprint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
init();
}
#Override
protected void onStart() {
fingerprint.scan(ScanActivity.this, printHandler, updateHandler);
super.onStart();
}
#Override
protected void onStop() {
fingerprint.turnOffReader();
super.onStop();
}
Handler updateHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
int status = msg.getData().getInt("status");
switch (status) {
case Status.INITIALISED:
tvStatus.setText("Setting up reader");
break;
case Status.SCANNER_POWERED_ON:
tvStatus.setText("Reader powered on");
break;
case Status.READY_TO_SCAN:
tvStatus.setText("Ready to scan finger");
break;
case Status.FINGER_DETECTED:
tvStatus.setText("Finger detected");
break;
case Status.RECEIVING_IMAGE:
tvStatus.setText("Receiving image");
break;
case Status.FINGER_LIFTED:
tvStatus.setText("Finger has been lifted off reader");
break;
case Status.SCANNER_POWERED_OFF:
tvStatus.setText("Reader is off");
break;
case Status.SUCCESS:
tvStatus.setText("Fingerprint successfully captured");
break;
case Status.ERROR:
tvStatus.setText("Error");
toast(msg.getData().getString("errorMessage"));
break;
default:
tvStatus.setText(String.valueOf(status));
toast(msg.getData().getString("errorMessage"));
break;
}
}
};
Handler printHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
byte[] image;
String errorMessage = "";
int status = msg.getData().getInt("status");
Intent intent = new Intent();
intent.putExtra("status", status);
if (status == Status.SUCCESS) {
intent.putExtra("img", msg.getData().getByteArray("img"));
} else {
intent.putExtra("errorMessage", msg.getData().getString("errorMessage"));
}
setResult(RESULT_OK, intent);
finish();
}
};
private void toast(String msg){
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();
}
private void init() {
tvStatus = findViewById(R.id.sa_tv_status);
fingerprint = new Fingerprint();
}
}
activity_scan.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".ScanActivity">
<TextView
android:id="#+id/sa_tv_status"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
What feature can I use to zoom out?
I appreciate if anyone can help me analyze this!

How to get Hint and Text of a button In android studio

I am using this code to get the id of the button which is clicked and then use the id to get the text and hint of the same button
I don't know why but maybe this code this crashing the app after I use getID() method.
I am using Relative Layout.
The Java code
package com.example.firstapp;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity{
public AlertDialog.Builder dialogBuilder;
public AlertDialog dialog;
public EditText Name,Password;
public Button Save,Cancel,temp,ok,x;
public String file_location = "Passwords.txt";
public String name_x,pass_y;
public LinearLayout mylayout = null;
public RelativeLayout rl = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void View_Password(Button x){
ok = (Button) findViewById(R.id.button6);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
};
public void NewPassword(){
dialogBuilder = new AlertDialog.Builder(this);
final View NewPassSaveView = getLayoutInflater().inflate(R.layout.newpasspopup, null);
Name = (EditText) NewPassSaveView.findViewById(R.id.editTextTextPersonName);
Password = (EditText) NewPassSaveView.findViewById(R.id.editTextTextPersonName2);
Save = (Button) NewPassSaveView.findViewById(R.id.button4);
Cancel = (Button) NewPassSaveView.findViewById(R.id.button);
dialogBuilder.setView(NewPassSaveView);
dialog = dialogBuilder.create();
dialog.show();
Save.setOnClickListener(new View.OnClickListener() {
#SuppressLint("ResourceType")
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(Name.getText().toString())) {
Name.setError("This Field is compulsory");
return;
} else if (TextUtils.isEmpty(Password.getText().toString())) {
Password.setError("This Field is compulsory");
return;
}
rl = (RelativeLayout) findViewById(R.id.layout2);
Toast.makeText(getApplicationContext(), "Password Saving...", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Password Saved", Toast.LENGTH_SHORT).show();
Button temp = new Button(MainActivity.this);
temp.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
));
rl.addView(temp);
temp.setText(Name.getText().toString());
temp.setHint(Password.getText().toString());
temp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int btn_id = v.getId();
btn2string(btn_id);
}
});
dialog.dismiss();
}
});
Cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
}
public void AddNew(View view) {
NewPassword();
}
public void btn2string(int x){
Button btn = findViewById(x);
name_x = btn.getText().toString();
pass_y = btn.getHint().toString();
See_Password(name_x,pass_y);
}
public void See_Password(String name,String pass){
Toast.makeText(getApplicationContext(), "Name: "+name+"\n"+"Password: "+pass, Toast.LENGTH_SHORT).show();
}
}
//The XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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/heading"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/textView4"
android:layout_width="319dp"
android:layout_height="50dp"
android:text="Password Manager"
android:textSize="34sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.051" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="28dp"
android:layout_marginRight="28dp"
android:onClick="AddNew"
android:text="Add new"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView4"
app:layout_constraintVertical_bias="0.973" />
<RelativeLayout
android:id="#+id/layout2"
android:layout_width="366dp"
android:layout_height="541dp"
android:layout_marginTop="28dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.488"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView4"
app:layout_constraintVertical_bias="0.0"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Please tell if there is any other way to do this or tell the mistakes in the above code so that I can get the hint and text of that button which is clicked...
Thank You.
Inside,
NewPassword()
method just change the following code.
public void NewPassword(){
......
save.setOnClickListener(...){
........
temp.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
int btn_id = v.getId(); // remove this line.
btn2String(temp); //directly pass temp i.e. Button you created.
}
});
dialog.dismiss();
}
});
..........
}
And, pass Button type as a parameter in btn2String() method. as below:
public void btn2String(Button x){
Button btn = findViewById(x); // remove this line of code.
name_x = x.getText().toString();
pass_y = x.getHint().toString();
See_Password(name_x, pass_y);
}

Why the status of text to speech is error rather than successful implementation?

I am trying to make a simple Text to Speech application but it is throwing an error and thus, as a result, the toast is appearing when the button is clicked instead of getting TextToSpeech.SUCCESS as the int status.
Here is the code I used:
package com.example.notifyme;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
EditText txt;
Button b;
String s;
TextToSpeech tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = findViewById(R.id.input);
b = findViewById(R.id.button);
}
public void notify(View view) {//for creating tts activity
tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
s = txt.getText().toString();
if (status == TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.ENGLISH);
tts.setSpeechRate(1.0f);
tts.speak(s, TextToSpeech.QUEUE_FLUSH, null, null);
Toast.makeText(getApplicationContext(),"Here it is",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Something unexpected happened", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onPause();
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">
<EditText
android:id="#+id/input"
android:layout_width="330dp"
android:layout_height="72dp"
android:layout_marginTop="156dp"
android:ems="10"
android:hint="#string/add_your_text_here"
android:gravity="start|top"
android:layout_marginBottom="50dp"
android:inputType="textMultiLine"
app:layout_constraintBottom_toTopOf="#+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.493"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="114dp"
android:layout_height="55dp"
android:backgroundTint="#4CAF50"
android:text="#string/speak"
android:textAllCaps="true"
android:onClick="notify"
android:textFontWeight="40"
app:layout_constraintTop_toBottomOf="#+id/input"
android:layout_marginTop="30dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="266dp" />
</androidx.constraintlayout.widget.ConstraintLayout/>
Kindly let me know what is the mistake.

Am I missing something in my Forget Password function?

For my Android app, I have a "forget password" button. In my MainActivity.java, the code works fine to click on "Forget Password?" and transfers the user into a new java activity called ForgetPassword.java (I followed a tutorial online by Mazn). I then proceed to type in my email (that is already registered) and click "Submit" to submit my email that I forgot my password to. This only proceeds to bring me back to MainActivity.java, however, I do not believe I call it anywhere in my Password.java function.
This is my Password.java function:
package com.example.myapplication;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.widget.ProgressBar;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
public class ForgotPassword extends AppCompatActivity {
private EditText emailEt;
private Button resetBtn;
private ProgressBar progressbar;
FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forgot_password);
progressbar = findViewById(R.id.progressBar4);
auth = FirebaseAuth.getInstance();
emailEt = findViewById(R.id.etEmail);
resetBtn = findViewById(R.id.btnReset);
resetBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = emailEt.getText().toString().trim();
progressbar.setVisibility(View.VISIBLE);
auth.sendPasswordResetEmail(email).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
Toast.makeText(getApplicationContext(), "Check your email to reset your password.", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Try again. Something went wrong!", Toast.LENGTH_LONG).show();
}
}
});
}
});
}
}
activity_forgot_password.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".ForgotPassword">
<TextView
android:id="#+id/tvPetWatch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="28dp"
android:fontFamily="sans-serif-black"
android:gravity="center_horizontal"
android:text="PetWatch"
android:textAlignment="center"
android:textSize="60sp"
android:textStyle="bold"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tvDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="The app that watches your pet!"
android:textStyle="italic"
android:textSize="18sp"
android:textAlignment="center"
app:layout_constraintBottom_toTopOf="#+id/etEmail"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tvPetWatch"
app:layout_constraintVertical_bias="0.0"
android:gravity="center_horizontal" />
<EditText
android:id="#+id/etEmailAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="124dp"
android:ems="10"
android:hint="Enter email"
android:inputType="textEmailAddress"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tvDescription"
app:layout_constraintVertical_bias="0.028" />
<Button
android:id="#+id/btnReset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="Reset Password"
android:textSize="24sp"
app:backgroundTint="#3F51B5"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/etEmailAddress"
app:layout_constraintVertical_bias="0.044" />
<ProgressBar
android:id="#+id/progressBar4"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:visibility="invisible"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tvDescription"
app:layout_constraintVertical_bias="0.316" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is my MainActivity.java function:
package com.example.myapplication;
import androidx.annotation.NonNull;
import androidx.appcompat.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.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;
import android.util.Log;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MainActivity extends AppCompatActivity {
private EditText eEmail;
private EditText ePassword;
private Button eLogin;
private TextView register;
private ProgressBar progressBar;
private TextView forgotPassword;
boolean isValid = false;
private int counter = 3;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Bind them to the XML layout
// findViewById attaches the particular value to the particular XML element
eEmail = findViewById(R.id.etEmail);
ePassword = findViewById(R.id.etPassword);
eLogin = findViewById(R.id.btnLogin);
register = findViewById(R.id.tvRegister);
FirebaseApp.initializeApp(MainActivity.this);
mAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressBar);
forgotPassword = findViewById(R.id.tvForgotPassword);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.tvRegister:
startActivity(new Intent(MainActivity.this, RegisterUser.class));
break;
default:
throw new IllegalStateException("Unexpected value: " + v.getId());
}
}
});
eLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.btnLogin:
{
userLogin();
break;
}
}
}
});
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.tvForgotPassword:
startActivity(new Intent(MainActivity.this, ForgotPassword.class));
break;
default:
throw new IllegalStateException("Unexpected value: " + v.getId());
}
}
});
}
private void userLogin() {
String email = eEmail.getText().toString().trim();
String password = ePassword.getText().toString().trim();
if (email.isEmpty())
{
eEmail.setError("Email is required!");
eEmail.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches())
{
eEmail.setError("Please enter a valid email address!");
eEmail.requestFocus();
return;
}
if (password.isEmpty())
{
ePassword.setError("Email is required!");
ePassword.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
// direct to user profile
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user.isEmailVerified())
{
startActivity(new Intent(MainActivity.this, ProfileActivity.class));
Toast.makeText(getApplicationContext(), "Login credentials was successful!", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
else
{
user.sendEmailVerification();
Toast.makeText(getApplicationContext(), "Please check your email to verify your account.", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
else
{
Toast.makeText(getApplicationContext(), "Failed to login! Recheck your credentials.", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">
<EditText
android:id="#+id/etEmail"
android:layout_width="380dp"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:ems="10"
android:hint="Enter email address"
android:inputType="textEmailAddress"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.314" />
<Button
android:id="#+id/btnLogin"
android:layout_width="380dp"
android:layout_height="70dp"
android:layout_marginTop="24dp"
android:textStyle="bold"
android:ems="10"
android:text="Login"
android:textSize="24sp"
app:backgroundTint="#3F51B5"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/etPassword"
app:layout_constraintVertical_bias="0.097" />
<EditText
android:id="#+id/etPassword"
android:layout_width="380dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter password"
android:inputType="textPassword"
android:textSize="24sp"
android:layout_marginTop="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/etEmail"
app:layout_constraintVertical_bias="0.058" />
<TextView
android:id="#+id/tvPetWatch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="28dp"
android:fontFamily="sans-serif-black"
android:gravity="center_horizontal"
android:text="PetWatch"
android:textAlignment="center"
android:textSize="60sp"
android:textStyle="bold"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tvDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="The app that watches your pet!"
android:textStyle="italic"
android:textSize="18sp"
android:textAlignment="center"
app:layout_constraintBottom_toTopOf="#+id/etEmail"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tvPetWatch"
app:layout_constraintVertical_bias="0.0"
android:gravity="center_horizontal" />
<TextView
android:id="#+id/tvForgotPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Forgot Password?"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.056"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnLogin"
app:layout_constraintVertical_bias="0.096" />
<TextView
android:id="#+id/tvRegister"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New User? Register Here!"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.94"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnLogin"
app:layout_constraintVertical_bias="0.095" />
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Your emailEt is in MainActivity, so calling findViewByID(R.id.etEmail) in ForgotPassword Activity is returning null reference.
When I clicked reset button, it seems to moving MainActivity, but in fact, the App crashes.
My local log:
2020-11-12 15:44:38.964 7425-7425/xyz.dps0340.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: xyz.dps0340.myapplication, PID: 7425
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at xyz.dps0340.myapplication.ForgotPassword$1.onClick(ForgotPassword.java:43)
at android.view.View.performClick(View.java:7448)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
You must use etEmailAddress view in ForgotPassword activity.
Code:
Xml files are same.
MainActivity.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.content.Intent;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity {
private EditText eEmail;
private EditText ePassword;
private Button eLogin;
private TextView register;
private ProgressBar progressBar;
private TextView forgotPassword;
boolean isValid = false;
private int counter = 3;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Bind them to the XML layout
// findViewById attaches the particular value to the particular XML element
eEmail = findViewById(R.id.etEmail);
ePassword = findViewById(R.id.etPassword);
eLogin = findViewById(R.id.btnLogin);
register = findViewById(R.id.tvRegister);
FirebaseApp.initializeApp(getApplicationContext());
mAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressBar);
forgotPassword = findViewById(R.id.tvForgotPassword);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.tvRegister:
startActivity(new Intent(MainActivity.this, RegisterUser.class));
break;
default:
throw new IllegalStateException("Unexpected value: " + v.getId());
}
}
});
eLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.btnLogin:
{
userLogin();
break;
}
}
}
});
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.tvForgotPassword:
Intent forgotPasswordIntent = new Intent(MainActivity.this, ForgotPassword.class);
startActivity(forgotPasswordIntent);
break;
default:
throw new IllegalStateException("Unexpected value: " + v.getId());
}
}
});
}
private void userLogin() {
String email = eEmail.getText().toString().trim();
String password = ePassword.getText().toString().trim();
if (email.isEmpty())
{
eEmail.setError("Email is required!");
eEmail.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches())
{
eEmail.setError("Please enter a valid email address!");
eEmail.requestFocus();
return;
}
if (password.isEmpty())
{
ePassword.setError("Email is required!");
ePassword.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
// direct to user profile
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user.isEmailVerified())
{
startActivity(new Intent(MainActivity.this, ProfileActivity.class));
Toast.makeText(getApplicationContext(), "Login credentials was successful!", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
else
{
user.sendEmailVerification();
Toast.makeText(getApplicationContext(), "Please check your email to verify your account.", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
else
{
Toast.makeText(getApplicationContext(), "Failed to login! Recheck your credentials.", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
}
ForgotPassword.java
package com.example.myapplication;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.widget.ProgressBar;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
public class ForgotPassword extends AppCompatActivity {
private Button resetBtn;
private ProgressBar progressbar;
private EditText emailAddress;
FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forgot_password);
Intent intent = getIntent();
emailAddress = findViewById(R.id.etEmailAddress);
progressbar = findViewById(R.id.progressBar4);
auth = FirebaseAuth.getInstance();
resetBtn = findViewById(R.id.btnReset);
resetBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = emailAddress.getText().toString();
if(email.equals("")) {
Toast.makeText(getApplicationContext(), "Your Email is wrong.", Toast.LENGTH_LONG).show();
return;
}
progressbar.setVisibility(View.VISIBLE);
auth.sendPasswordResetEmail(email).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
Toast.makeText(getApplicationContext(), "Check your email to reset your password.", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Try again. Something went wrong!", Toast.LENGTH_LONG).show();
}
progressbar.setVisibility(View.INVISIBLE);
}
});
}
});
}
}

App seems like launching more than once in landscape mode after splash screen?

I have a splash screen and after that my main activity starts. This works fine in portrait mode but if in case i tilt my phone in landscape mode, the main activity can be seen launching more than once after splash screen.
I tried using android:launchMode="singleInstance" but in that case i am not able to attach files in feedback alert-box.
Following is my code:
MainActivity.java
package com.example.android.tel;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
TextView toolbar_title_mainActivity, main_textView, disclaimer_txtView;
CardView SearchDept, SearchName, disclaimer, feedback;
ImageView back;
ArrayList<Uri> arrayUri = new ArrayList<Uri>();
ArrayAdapter<Uri> myFileListAdapter;
ListView listViewFiles;
Dialog alertDialog;
final int RQS_LOADIMAGE = 0;
final int RQS_SENDEMAIL = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_main);
} else {
setContentView(R.layout.activity_main);
}
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar_main_activity);
toolbar_title_mainActivity = (TextView) findViewById(R.id.toolbar_title);
main_textView = (TextView) findViewById(R.id.main_textView);
main_textView.setPaintFlags(main_textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
setSupportActionBar(mActionBarToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar_title_mainActivity.setText("Hry. Govt. Telephone Directory");
back = (ImageView) findViewById(R.id.back);
back.setVisibility(View.INVISIBLE);
disclaimer = (CardView) findViewById(R.id.disclaimer);
feedback = (CardView) findViewById(R.id.feedback);
SearchDept = (CardView) findViewById(R.id.cardView1_mainActivity);
SearchName = (CardView) findViewById(R.id.cardView2_mainActivity);
SearchDept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, CardViewActivity.class);
startActivity(i);
}
});
SearchName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent j = new Intent(MainActivity.this, ByNameListActivity.class);
startActivity(j);
}
});
disclaimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog alertDialog = new Dialog(MainActivity.this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.disclaimer);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
alertDialog.show();
}
});
feedback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog = new Dialog(MainActivity.this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.feedback);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
alertDialog.setCanceledOnTouchOutside(true);
ImageView send_btn=(ImageView)alertDialog.findViewById(R.id.send);
ImageView attach_btn=(ImageView)alertDialog.findViewById(R.id.attachment);
final TextView to_email_add=(TextView)alertDialog.findViewById(R.id.email_address);
to_email_add.setText("tel#gmail.com");
final EditText email_subject=(EditText)alertDialog.findViewById(R.id.email_subject);
final EditText email_text=(EditText)alertDialog.findViewById(R.id.email_text);
final EditText mobile_no=(EditText)alertDialog.findViewById(R.id.mobile_text);
email_subject.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
email_text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
myFileListAdapter = new ArrayAdapter<Uri>(
MainActivity.this,
android.R.layout.simple_list_item_1,
arrayUri);
listViewFiles = (ListView)alertDialog.findViewById(R.id.filelist);
listViewFiles.setAdapter(myFileListAdapter);
listViewFiles.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
myFileListAdapter.remove(arrayUri.get(position));
myFileListAdapter.notifyDataSetChanged();
Toast.makeText(view.getContext(), "You unattached one item", Toast.LENGTH_LONG).show();
return false;
}
});
attach_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_LOADIMAGE);
}
});
send_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email_add=to_email_add.getText().toString();
String email_sub=email_subject.getText().toString();
String email_txt=email_text.getText().toString();
String emailAddressList[] = {email_add};
String mobileNo=mobile_no.getText().toString();
String info=email_txt+"\n\nPhone Number :"+mobileNo;
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_EMAIL, emailAddressList);
intent.putExtra(Intent.EXTRA_SUBJECT, email_sub);
intent.putExtra(Intent.EXTRA_TEXT,info);
if(arrayUri.isEmpty()&& isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email without photo attached
intent.setAction(Intent.ACTION_SEND);
intent.setType("plain/text");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}else if(arrayUri.size() == 1 && isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email with ONE photo attached
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, arrayUri.get(0));
intent.setType("image/*");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}else if(arrayUri.size()>1&& isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email with MULTI photo attached
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, arrayUri);
intent.setType("image/*");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}
else {
Toast.makeText(v.getContext(), "Phone number is not valid", Toast.LENGTH_LONG).show();
}
startActivity(Intent.createChooser(intent, "Please provide valid details"));
}
});
alertDialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
switch(requestCode){
case RQS_LOADIMAGE:
Uri imageUri = data.getData();
arrayUri.add(imageUri);
myFileListAdapter.notifyDataSetChanged();
break;
case RQS_SENDEMAIL:
break;
}
}
}
public static boolean isValidPhone(String phone)
{
String expression = "^([0-9\\+]|\\(\\d{1,3}\\))[0-9\\-\\. ]{3,15}$";
CharSequence inputString = phone;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputString);
if (matcher.matches())
{
return true;
}
else{
return false;
}
}
public void hideKeyboard(View view) {
InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation;
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
// or = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}else {
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
// Add code if needed
// listViewFiles.setAdapter(myFileListAdapter);
// myFileListAdapter.notifyDataSetChanged();
setRequestedOrientation(orientation);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:weightSum="14"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
tools:context="com.example.android.tel.MainActivity">
<include
android:id="#+id/tool_bar_main_activity"
layout="#layout/toolbar">
</include>
<TextView
android:id="#+id/main_textView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:layout_marginTop="10dp"
android:text="How would you like to search?"
android:textStyle="bold"
android:textSize="14sp"
android:textColor="#1A237E"
android:gravity="center_horizontal"/>
<RelativeLayout
android:id="#+id/searchby_btns"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="4"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:gravity="center_vertical">
<android.support.v7.widget.CardView
android:id="#+id/cardView1_mainActivity"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
card_view:cardCornerRadius="4dp"
android:layout_marginTop="10dp"
card_view:cardBackgroundColor="#e97c1d">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search By Department.."
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="18sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/cardView2_mainActivity"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_below="#id/cardView1_mainActivity"
card_view:cardCornerRadius="4dp"
android:layout_marginTop="20dp"
card_view:cardBackgroundColor="#e97c1d">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search By Name.."
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="18sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight="8.5">
<ImageView
android:id="#+id/map_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/hry_map"
android:elevation="4dp"
android:layout_gravity="center"/>
</RelativeLayout>
<RelativeLayout
android:layout_below="#id/map_image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:paddingRight="16dp"
android:paddingLeft="16dp"
android:layout_marginTop="2dp"
android:gravity="center_horizontal"
android:layout_alignParentBottom="true">
<android.support.v7.widget.CardView
android:id="#+id/disclaimer"
android:layout_width="150dp"
android:layout_height="30dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
android:layout_marginRight="8dp"
card_view:cardBackgroundColor="#424242">
<TextView
android:layout_width="150dp"
android:layout_height="30dp"
android:text="Disclaimer"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/feedback"
android:layout_toRightOf="#id/disclaimer"
android:layout_width="150dp"
android:layout_height="30dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
card_view:cardBackgroundColor="#424242">
<TextView
android:layout_width="150dp"
android:layout_height="30dp"
android:text="Feedback"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
</android.support.v7.widget.CardView>
</RelativeLayout>
</LinearLayout>
SplashScreenActivity.java
package com.example.android.telephonedirectory;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ProgressBar;
import com.felipecsl.gifimageview.library.GifImageView;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
public class SplashScreenActivity extends AppCompatActivity {
// private GifImageView gifimageview;
private ProgressBar progressBarSplashScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_splash_screen);
} else {
setContentView(R.layout.activity_splash_screen);
}
// gifimageview=(GifImageView)findViewById(R.id.gifSplashscreenImage);
progressBarSplashScreen=(ProgressBar)findViewById(R.id.progressbarSplashscreen);
progressBarSplashScreen.setVisibility(progressBarSplashScreen.VISIBLE);
//set GifImageView Resource
/*try {
InputStream inputStream=getAssets().open("splash_Screen.png");
byte[] bytes= IOUtils.toByteArray(inputStream);
gifimageview.setBytes(bytes);
gifimageview.startAnimation();
}catch (IOException ex){
}*/
//Wait for 4 seconds and start activity main
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
SplashScreenActivity.this.startActivity(new Intent(SplashScreenActivity.this,MainActivity.class));
SplashScreenActivity.this.finish();
}
},2000);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation;
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
// or = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}else {
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
// Add code if needed
// listViewFiles.setAdapter(myFileListAdapter);
// myFileListAdapter.notifyDataSetChanged();
setRequestedOrientation(orientation);
}
}
Dont use android:launchMode="singleInstance"
Launch mode you should use "singleTask" for this .
Because singleInstance creates separate task stack for Activity and do not check activity in current Task Stack.
while "singleTask" check each time if an Activity exist in Task Stack it can not create new one.

Categories

Resources