I am making an application for Android where it displays your exact coordinates via GPS in a text view when you open the app. You then press a button, and an SMS is sent to a preset number with your coordinates. I have everything working, but the SMS body. I can't figure out how to take the textview with your coordinates and have it send in the SMS body. Any help would be awesome!
MAIN JAVA PAGE
package com.example.test;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
#SuppressWarnings("deprecation")
public class MainActivity extends Activity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1000, this);
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
String messageToSend = "R.id.textview1";
String number = "8143664050";
SmsManager.getDefault().sendTextMessage(number, null, messageToSend, null,null);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "SMS failed!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
}
#Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}
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"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/textview1"
android:layout_marginRight="16dp"
android:layout_marginTop="22dp"
android:onClick="gotoActivity"
android:text="Button" />
</RelativeLayout>
Try to change this:
String messageToSend = "R.id.textview1";
to this
TextView tv = (TextView) findViewById(R.id.textview1);
String messageToSend = tv.getText().toString();
Related
Hello eveyone i hope you are all doing good. I have a little problem and I couldn't find the solution. I have a translation app and after the user input his phrase by a record, the translation message doesn't appear. So I hope that someone could help me.
Here is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity">
<EditText
android:id="#+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Tap Mic to Speak"
android:padding="20dp"
android:textColor="#000000"
android:textSize="20sp" />
<Button
android:id="#+id/idBtnTranslateLanguage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/TransledText"
android:layout_centerInParent="true"
android:text="Translate language" />
<ImageButton
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edittext"
android:layout_centerHorizontal="true"
android:layout_marginTop="128dp"
android:background="#color/white"
android:padding="40dp"
android:src="#drawable/ic_baseline_mic_24" />
<TextView
android:id="#+id/TransledText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/edittext"
android:layout_centerHorizontal="true"
android:layout_margin="20dp"
android:gravity="center_horizontal"
android:text="Translated language"
android:textAlignment="center"
android:textSize="20sp"
tools:ignore="UnknownId" />
</RelativeLayout>
And my main code:
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions;
import com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateLanguage;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslator;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslatorOptions;
public class MainActivity extends AppCompatActivity {
private static final int CodeSpeechInput =100;
private TextView EditText;
private ImageButton SpeakButton;
private TextView TransledText;
FirebaseTranslator englishFrenshTranslator;
private Button translateLanguageBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseTranslatorOptions options =
new FirebaseTranslatorOptions.Builder()
.setSourceLanguage(FirebaseTranslateLanguage.EN)
.setTargetLanguage(FirebaseTranslateLanguage.FR)
.build();
englishFrenshTranslator = FirebaseNaturalLanguage.getInstance().getTranslator(options);
EditText = (TextView) findViewById(R.id.edittext);
SpeakButton = (ImageButton) findViewById(R.id.button);
TransledText = (TextView) findViewById(R.id.TransledText);
translateLanguageBtn = findViewById(R.id.idBtnTranslateLanguage);
translateLanguageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String string = EditText.getText().toString();
downloadModal(string);
}
private void downloadModal(String input) {
FirebaseModelDownloadConditions conditions = new FirebaseModelDownloadConditions.Builder().requireWifi().build();
englishFrenshTranslator.downloadModelIfNeeded(conditions).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// this method is called when modal is downloaded successfully.
Toast.makeText(MainActivity.this, "Please wait language modal is being downloaded.", Toast.LENGTH_SHORT).show();
// calling method to translate our entered text.
translateLanguage(input);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Fail to download modal", Toast.LENGTH_SHORT).show();
}
});
}
private void translateLanguage(String input) {
englishFrenshTranslator.translate(input).addOnSuccessListener(new OnSuccessListener<String>() {
#Override
public void onSuccess(String result) {
TransledText.setText(input);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Fail to translate", Toast.LENGTH_SHORT).show();
}
});
}
});
SpeakButton.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());
try {
startActivityForResult(intent, CodeSpeechInput);
} catch (ActivityNotFoundException a) {
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CodeSpeechInput : {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
EditText.setText(result.get(0));
}
break;
}
}
}
}
I also use firebase if that could help you.
So my problem, let's say we are in SignInFragment (To navigate in SignInFragment, the launcher is the MainActivity inside that it will open the HomeFragment then inside of HomeFragment there is code if there is no user signed in it will navigate to SignInFragment) then in SignInFragment there is a TextView "Do not have account yet? Register here." So whenever I press that nothings happen. Hope you understand.
I will add the other Fragments to easily understand the flow of my App.
Here are the codes for: MainActivity
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HomeActivity fragment = new HomeActivity();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, fragment, fragment.getTag());
ft.commit();
}
Here are the codes for: HomeActivity
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class HomeActivity extends Fragment {
private static final String TAG = "HomeActivity";
TextView mWelcome;
Button btnSignout;
//Firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home_activity, container, false);
mWelcome = view.findViewById(R.id.welcome);
btnSignout = view.findViewById(R.id.btnSignOut);
setupFirebaseAuth();
//Firebase
mAuth = FirebaseAuth.getInstance();
btnSignout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, new SignOutFragment());
ft.commit();
}
});
return view;
}
/*
-------------------------------Firebase--------------------------------
*/
/*
check if the user is logged in
*/
private void checkCurrentUser(FirebaseUser user){
Log.d(TAG, "checkCurrentUser: checking if user is logged in.");
if (user == null){
SignInFragment fragment = new SignInFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.remove(HomeActivity.this);
ft.replace(R.id.container, fragment);
ft.commit();
}
}
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
//checking if the user is logged in or not remove
// checkCurrentUser(user);
if (user != null){
//User is signed in
Log.d(TAG, "onAuthStateChanged: signed_in: " + user.getUid());
}else {
// User is signed out
Log.d(TAG, "onAuthStateChanged: signed_out");
}
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
checkCurrentUser(mAuth.getCurrentUser());
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
Here are the codes for: SignInFragment
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
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;
import com.google.firebase.auth.FirebaseUser;
public class SignInFragment extends Fragment {
private static final String TAG = "SignInFragment";
private TextView mEmail, mPassword, mHeading, mToRegister, mFckyou;
private EditText eEmail, ePassword;
private Button btnSignin;
private ProgressBar mProgressBar;
//Firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.signin_fragment, container, false);
//TextView
mEmail = view.findViewById(R.id.tvEmail);
mPassword = view.findViewById(R.id.tvPassword);
mHeading = view.findViewById(R.id.heading);
mToRegister = view.findViewById(R.id.tvToRegister);
mFckyou = view.findViewById(R.id.fckyou);
//EditText
mEmail = view.findViewById(R.id.etEmail);
ePassword = view.findViewById(R.id.etPassword);
//Button
btnSignin = view.findViewById(R.id.btnSignin);
//ProgressBar
mProgressBar = view.findViewById(R.id.progressBar);
//Progress Bar and Text view = GONE
mProgressBar.setVisibility(View.GONE);
mFckyou.setVisibility(View.GONE);
navigateToReigster();
setupFirebaseAuth();
signInUser();
return view;
}
public void navigateToReigster(){
mToRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegisterFragment fragment = new RegisterFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, fragment, fragment.getTag());
ft.commit();
}
});
}
private boolean isStringNull(String string){
if (string.equals("")){
return true;
}
return false;
}
/*
---------------------------------Firebase-----------------------------------
*/
private void signInUser(){
// Button = to sign in the user.
btnSignin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = eEmail.getText().toString();
String password = ePassword.getText().toString();
if (isStringNull(email) && isStringNull(password)){
Toast.makeText(getActivity(), "You must field out all the fields.", Toast.LENGTH_SHORT).show();
}else {
//Progress Bar and TextView be visible
mProgressBar.setVisibility(View.VISIBLE);
mFckyou.setVisibility(View.VISIBLE);
//To sign in users
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(getActivity(), "Sign in Successful!", Toast.LENGTH_SHORT).show();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, new HomeActivity());
ft.commit();
}else {
//Progress bar and Text View will be GONE. So the users can try again.
mProgressBar.setVisibility(View.GONE);
mFckyou.setVisibility(View.GONE);
Toast.makeText(getActivity(), "Could not sign in. Please try again.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
Here are my codes for: RegisterFragment
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
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;
import com.google.firebase.auth.FirebaseUser;
public class RegisterFragment extends Fragment {
private static final String TAG = "RegisterFragment";
private TextView mEmail, mPassword, mHeading, mToSignin, mFckyou;
private EditText eEmail, ePassword;
private Button btnRegister;
private ProgressBar mProgressBar;
//Firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private String userID;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.register_fragment, container, false);
//TextView
mEmail = view.findViewById(R.id.tvEmail);
mPassword = view.findViewById(R.id.tvPassword);
mHeading = view.findViewById(R.id.heading);
mToSignin = view.findViewById(R.id.tvToSignin);
mFckyou = view.findViewById(R.id.fckyou);
//EditText
mEmail = view.findViewById(R.id.etEmail);
ePassword = view.findViewById(R.id.etPassword);
//Button
btnRegister = view.findViewById(R.id.btnRegister);
//ProgressBar
mProgressBar = view.findViewById(R.id.progressBar);
//Progress Bar and Text View = GONE
mProgressBar.setVisibility(View.GONE);
mFckyou.setVisibility(View.GONE);
navigateToSignIn();
registerNewUser();
setupFirebaseAuth();
return view;
}
public void navigateToSignIn(){
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, new SignInFragment());
ft.commit();
}
private boolean isStringNull(String string){
if (string.equals("")){
return true;
}
return false;
}
/*
To check if the user is creating a same email.
*/
public void checkUserId(){
if (mAuth.getCurrentUser() != null){
userID = mAuth.getCurrentUser().getUid();
}
}
/*
---------------------------------Firebase-----------------------------------
*/
public void registerNewUser(){
// To register new user
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = eEmail.getText().toString();
String password = ePassword.getText().toString();
if (isStringNull(email) && isStringNull(password)){
Toast.makeText(getContext(), "You must field out all the fields.", Toast.LENGTH_SHORT).show();
}else {
//Progress Bar and TextView be visible
mProgressBar.setVisibility(View.VISIBLE);
mFckyou.setVisibility(View.VISIBLE);
//To create/register new user
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
//user is succesfully registered and logged in
checkUserId(); //Checking if the user is create same email
Log.d(TAG, "onComplete: AuthstateChange: " + userID);
Toast.makeText(getActivity(), "Registered Successfully", Toast.LENGTH_SHORT).show();
//AFter Registering account it will navigate to the Login Fragment
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.container, new SignInFragment());
fr.commit();
}else {
//If can't register the Progresss bar and Text view will be gone, so users can sign in again.
//Progress Bar and Text View = GONE. So users can try again.
mProgressBar.setVisibility(View.GONE);
mFckyou.setVisibility(View.GONE);
Toast.makeText(getActivity(), "Please check your internet. Or maybe you registered same email.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
Here are my codes for: register_fragment.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/heading"
android:text="Register"
android:textColor="#000"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:textSize="50sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvEmail"
android:text="Email"
android:layout_below="#+id/heading"
android:layout_marginLeft="10dp"
android:layout_marginTop="100dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/etEmail"
android:textColor="#000"
android:hint="Type your email here..."
android:layout_below="#+id/tvEmail"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvPassword"
android:text="Password"
android:layout_below="#+id/etEmail"
android:layout_marginTop="20dp"
android:layout_marginLeft="10dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/etPassword"
android:inputType="textPassword"
android:layout_below="#+id/tvPassword"
android:hint="Type your password here..."
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnRegister"
android:text="Register"
android:layout_below="#+id/etPassword"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvToSignin"
android:text="Already have an account? Sign in here."
android:textColor="#color/colorPrimary"
android:textSize="10sp"
android:layout_below="#+id/btnRegister"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_below="#+id/tvEmail"
android:layout_marginTop="35dp"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fckyou"
android:text="That's bad"
android:textColor="#color/colorAccent"
android:textStyle="bold"
android:layout_below="#+id/progressBar"
android:layout_centerHorizontal="true"/>
Here are my codes for: signin_fragment.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/heading"
android:text="Sign In"
android:textColor="#000"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:textSize="50sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvEmail"
android:text="Email"
android:layout_below="#+id/heading"
android:layout_marginLeft="10dp"
android:layout_marginTop="100dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/etEmail"
android:textColor="#000"
android:hint="Type your email here..."
android:layout_below="#+id/tvEmail"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvPassword"
android:text="Password"
android:layout_below="#+id/etEmail"
android:layout_marginTop="20dp"
android:layout_marginLeft="10dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/etPassword"
android:inputType="textPassword"
android:layout_below="#+id/tvPassword"
android:hint="Type your password here..."
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnSignin"
android:text="Sign in"
android:layout_below="#+id/etPassword"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvToRegister"
android:text="Do not have a account yet? Register here."
android:textColor="#color/colorPrimary"
android:textSize="10sp"
android:layout_below="#+id/btnSignin"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_below="#+id/tvEmail"
android:layout_marginTop="35dp"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fckyou"
android:text="Fuck you..."
android:textColor="#color/colorAccent"
android:textStyle="bold"
android:layout_below="#+id/progressBar"
android:layout_centerHorizontal="true"/>
//Home Activity
//implemet View.OnClickListener , it is working
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
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;
import com.google.firebase.auth.FirebaseUser;
public class SignInFragment extends Fragment implements View.OnClickListener {
private static final String TAG = "SignInFragment";
private TextView mEmail, mPassword, mHeading, mToRegister, mFckyou;
private EditText eEmail, ePassword;
private Button btnSignin;
private ProgressBar mProgressBar;
//Firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.signin_fragment, container, false);
//TextView
mEmail = view.findViewById(R.id.tvEmail);
mPassword = view.findViewById(R.id.tvPassword);
mHeading = view.findViewById(R.id.heading);
mToRegister = view.findViewById(R.id.tvToRegister);
mFckyou = view.findViewById(R.id.fckyou);
//EditText
mEmail = view.findViewById(R.id.etEmail);
ePassword = view.findViewById(R.id.etPassword);
//Button
btnSignin = view.findViewById(R.id.btnSignin);
//ProgressBar
mProgressBar = view.findViewById(R.id.progressBar);
//Progress Bar and Text view = GONE
mProgressBar.setVisibility(View.GONE);
mFckyou.setVisibility(View.GONE);
mToRegister.setOnClickListener(this);
setupFirebaseAuth();
signInUser();
return view;
}
public void navigateToReigster(){
Fragment fragment = new RegisterFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment).commit();
});
}
#Override
public void onClick(View vv) {
if (vv == mToRegister) {
navigateToReigster();
}
}
private boolean isStringNull(String string){
if (string.equals("")){
return true;
}
return false;
}
/*
---------------------------------Firebase-----------------------------------
*/
private void signInUser(){
// Button = to sign in the user.
btnSignin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = eEmail.getText().toString();
String password = ePassword.getText().toString();
if (isStringNull(email) && isStringNull(password)){
Toast.makeText(getActivity(), "You must field out all the fields.", Toast.LENGTH_SHORT).show();
}else {
//Progress Bar and TextView be visible
mProgressBar.setVisibility(View.VISIBLE);
mFckyou.setVisibility(View.VISIBLE);
//To sign in users
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(getActivity(), "Sign in Successful!", Toast.LENGTH_SHORT).show();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, new HomeActivity());
ft.commit();
}else {
//Progress bar and Text View will be GONE. So the users can try again.
mProgressBar.setVisibility(View.GONE);
mFckyou.setVisibility(View.GONE);
Toast.makeText(getActivity(), "Could not sign in. Please try again.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
I think the problem is with getFragmentManager(),
when using fragments from v4.app.Fragment you need to use getSupportFragmentManager()
Update:
I just realized you are starting new fragment from a fragment. Though this is not a good practice and you should always let your parent activity make fragment transactions.You can learn more here and here
But for now you can get a reference to getSupportFragmentManager() like this:
mToRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegisterFragment fragment = new RegisterFragment();
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, fragment, fragment.getTag());
ft.commit();
}
});
Did you set your TextView to be clickable
With this code i want to create custom TextToSpeech files with the text written in the Textedit.
The User can write something in the TextEdit and the TextToSpeech converts this into speech and then I want to create this speech as a audiofile, which I can share.
But now I dont know where my error is and I don't know further.
Could you please help me :)
import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import java.io.File;
import java.util.HashMap;
import java.util.Locale;
import static de.fresenborg.aufeinwort4.R.id.editText;
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener, View.OnClickListener {
private TextToSpeech tts;
private static String fileLocation;
private static String text;
public TextToSpeechFile(String fLocation, String txt) {
fileLocation = fLocation;
text = txt;
}
#Override
public void onClick(View view) {
final EditText wassoll = (EditText) findViewById(editText);
tts.speak(wassoll.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
ImageButton Sharebutton = (ImageButton) findViewById(R.id.Sharebutton);
Sharebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
public static void createFile(){
TextToSpeech tts;
HashMap<String, String> myHashRender = new HashMap();
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, text);
tts.synthesizeToFile(text, myHashRender, fileLocation);
final int utteranceId = 1;
File destinationFile = new File(getCacheDir(), utteranceId + ".wav");
int utteranceId++;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.synthesizeToFile(TextToSpeech.ACTION_TTS_QUEUE_PROCESSING_COMPLETED, null, destinationFile, utteranceId);
} else {
Bundle params = new Bundle();
params.putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utteranceId);
tts.synthesizeToFile(TextToSpeech.ACTION_TTS_QUEUE_PROCESSING_COMPLETED, params, destinationFile.getPath());)
tts.setOnUtteranceCompletedListener(new TextToSpeech.OnUtteranceCompletedListener() {
#Override
public void onUtteranceCompleted(String s) {
if (s.equals(utteranceId)) {
}
}
});
}
}
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
}
#Override
public void onInit(int arg0) {
tts.setLanguage(Locale.GERMAN);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
}
This is my XML:
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/my_toolbar"
android:ems="10"
android:hint="Was soll ich sagen?"
android:inputType="textMultiLine"
android:lines="8"
android:minLines="1"
android:text="#string/wassoll" />
<ImageButton
android:id="#+id/Sharebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/button"
android:layout_toEndOf="#+id/button"
android:layout_toRightOf="#+id/button"
android:background="#null"
app:srcCompat="#drawable/share" />
<Button
android:id="#+id/button"
android:layout_width="130dp"
android:layout_height="50dp"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp"
android:text="#string/button_sag_es" />
Can anyone please help me resolve this error?
What I'm trying to do is to get current location using google play services and display city name in edit text inside a fragment.
MainActivity.java
package com.example.mylocationwiki;
import java.util.List;
import java.util.Locale;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.app.Activity;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements ConnectionCallbacks,
OnConnectionFailedListener {
private static final String TAG = MainActivity.class.getSimpleName();
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private boolean mRequestingLocationUpdates = false;
private LocationRequest mLocationRequest;
String cityname="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkPlayServices()) {
buildGoogleApiClient();
}
try {
getLocation();
}
catch (Exception e) {
e.printStackTrace();
}
if(cityname!=null)Log.d("pathanor thik agey ", cityname);
new FragmentA(cityname);
}
private void getLocation() throws Exception{
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
Geocoder gc=new Geocoder(this,Locale.getDefault());
List<Address> addresses=gc.getFromLocation(latitude, longitude, 1);
cityname=addresses.get(0).getLocality();
if(cityname!=null)Log.d("calculate holo ", cityname );
new FragmentA(cityname);
} else{
}
return;
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(getApplicationContext(),
"This device is not supported.", Toast.LENGTH_LONG)
.show();
finish();
}
return false;
}
return true;
}
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
#Override
protected void onResume() {
super.onResume();
checkPlayServices();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
try {
getLocation();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
}
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"
android:background="#00BBFF"
android:gravity="center"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.mylocationwiki.MainActivity" >
<fragment
android:id="#+id/fragment1"
android:name="com.example.mylocationwiki.FragmentA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" /></RelativeLayout>
FragmentA.java
package com.example.mylocationwiki;
import android.app.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 android.widget.EditText;
public class FragmentA extends Fragment implements View.OnClickListener{
String cityname="";
Button button;
EditText field;
FragmentA(String cityname){
cityname=this.cityname;
if(cityname!=null)Log.d("received ", cityname);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_a, container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
button=(Button) getActivity().findViewById(R.id.button1);
field=(EditText)getActivity().findViewById(R.id.editText1);
field.setText(cityname);
}
#Override
public void onClick(View v) {
//
}
}
fragment_a.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFBB00" >
<EditText
android:id="#+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="20dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:layout_marginTop="37dp"
android:text="Button" />
</RelativeLayout>
What I have tried so far:
Read this this link :
similar question on SO and made the following changes in my project:
1) Included the following imports:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
2) Made sure that MainActivity extends FragmentActivity
3) Decared getActivity() method inside onActivityCreated() method as nicely suggested here
4) Even the following part is included in my manifest as suggested Here
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
Still I fail to resolve the issue. Any more insights please?
Thanks!
I guess the reason is that you don't have a default constructor in your Fragment class. You overloaded the constructor, but Fragment needs an empty one.
Empty Constructor for Extended Fragment
If you need to receive arguments in your fragment, do it using a Bundle:
public static YourFragment getInstance(String argument)
{
YourFragment fragment = new YourFragment();
Bundle bundle = new Bundle();
bundle.putString("argument", argument);
fragment.setArguments(bundle);
return fragment;
}
And from activity:
YourFragment fragment = YourFragment.getInstance(argument);
getFragmentManager().beginTransaction().add(R.id.container, fragment, "fragmentTag").commit();
R.id.container has to be an id of your RelativeLayout (remove <fragment/> from it).
If you still want to use a <fragment/> in xml, then here is a suggestion, how to pass an argument there: If I declare a fragment in an XML layout, how do I pass it a Bundle?
Hey Guys this may a silly question but I am a bit confused . So I need a help and I am new to android . Here Is my code that I have that I have tried
Main.java
package com.example.bluetooth;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 1;
private Button onBtn;
private Button offBtn;
private Button listBtn;
private Button findBtn;
private TextView text;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
onBtn = (Button) findViewById(R.id.turnOn);
offBtn = (Button) findViewById(R.id.turnOff);
listBtn = (Button) findViewById(R.id.paired);
findBtn = (Button) findViewById(R.id.search);
myListView = (ListView) findViewById(R.id.list1);
BTArrayAdapter = new ArrayAdapter<String>(this,R.layout.simple_list_item_1);
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null){
onBtn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(), "Bluetooth is not supported on your device.", Toast.LENGTH_SHORT).show();
}else{
text = (TextView) findViewById(R.id.text);
onBtn = (Button) findViewById(R.id.turnOn);
onBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button) findViewById(R.id.turnOff);
offBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
listBtn = (Button) findViewById(R.id.paired);
listBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button) findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView) findViewById(R.id.list1);
BTArrayAdapter = new ArrayAdapter<String>(this,R.layout.activity_main);
}
}
public void on(View view) {
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(), "Bluetooth turned on",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
public void onActivityResult(int requestCode,int resultCode, Intent data ){
if(requestCode == REQUEST_ENABLE_BT){
if(myBluetoothAdapter.isEnabled()){
text.setText("Status : Connected");
}else{
text.setText("Status : Disconnected");
}
}
}
public void list(View view){
pairedDevices = myBluetoothAdapter.getBondedDevices();
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
Toast.makeText(getApplicationContext(),"Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
myBluetoothAdapter.cancelDiscovery();
}else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
public void off(View v) {
// TODO Auto-generated method stub
myBluetoothAdapter.disable();
text.setText("Bluetooth is disconnected");
Toast.makeText(getApplicationContext(), "Bluetooth is disconnected", Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I am getting an error with simple_list_item_1. I don't know to resolve this problem .So kindly help me out with this.
And this is my xml 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Status"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="30dp" >
<Button
android:id="#+id/turnOn"
android:text="#string/on"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/turnOff"
android:text="#string/off"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="80dp" >
<Button
android:id="#+id/paired"
android:text="#string/paired"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/search"
android:text="#string/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ListView
android:id="#+id/list1"
android:layout_height="200dp"
android:layout_width="fill_parent">
</ListView>
</LinearLayout>
</RelativeLayout>
Thanks in advance.
Since that is an Android resource and not one you created, append the android prefix to it like so
BTArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);