public class MainActivity extends AppCompatActivity {
MaterialEditText edtNewUser, edtNewPassword, edtNewEmail; //pentru Sign up
MaterialEditText edtUser, edtPassword, edtEmail; //pentru Sign in
Button btnSignUp, btnSignIn;
FirebaseDatabase database;
DatabaseReference users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Firebase
database = FirebaseDatabase.getInstance();
users = database.getReference("Users");
edtUser = (MaterialEditText)findViewById(R.id.edtUser);
edtPassword = (MaterialEditText)findViewById(R.id.edtPassword);
btnSignIn = (Button)findViewById(R.id.btn_sign_in);
btnSignUp = (Button)findViewById(R.id.btn_sign_up);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showSignUpDialog();
}
});
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn(edtUser.getText().toString(), edtPassword.getText().toString());
}
});
}
private void signIn(final String user, final String pwd) {
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(user).exists()){
if(!user.isEmpty()){
User login = dataSnapshot.child(user).getValue(User.class);
if(login.getPassword().equals(pwd))
Toast.makeText(MainActivity.this, "Login ok!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Parola incorecta!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "Va rog introduceti username!", Toast.LENGTH_SHORT).show();
}
}
else
Toast.makeText(MainActivity.this, "Username-ul nu exista!", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showSignUpDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Sign up");
alertDialog.setMessage("Introduceti informatiile necesare");
LayoutInflater inflater = this.getLayoutInflater();
View sign_up_layout = inflater.inflate(R.layout.sign_up_layout,null);
edtNewUser = (MaterialEditText)sign_up_layout.findViewById(R.id.edtNewUserName);
edtNewEmail = (MaterialEditText)sign_up_layout.findViewById(R.id.edtNewEmail);
edtNewPassword = (MaterialEditText)sign_up_layout.findViewById(R.id.edtNewPassword);
alertDialog.setView(sign_up_layout);
alertDialog.setIcon(R.drawable.ic_account_circle_black_24dp);
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final User user = new User(edtNewUser.getText().toString(),
edtNewPassword.getText().toString(),
edtNewEmail.getText().toString());
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(user.getUserName()).exists())
Toast.makeText(MainActivity.this, "User-ul exista deja!",Toast.LENGTH_SHORT).show();
else{
users.child(user.getUserName()).setValue(user);
Toast.makeText(MainActivity.this, "Inregistrat cu success!",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
dialogInterface.dismiss();
}
});
alertDialog.show();
}
}
XML file
<?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"
android:background="#color/colorPrimary"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" >
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/info_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:cardElevation="4dp"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edtNewUserName"
android:hint="Username"
android:textColorHint="#color/colorPrimary"
android:textColor="#color/colorPrimary"
android:textSize="24sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:met_baseColor="#color/colorPrimary"
app:met_floatingLabel="highlight"
app:met_primaryColor="#color/colorPrimary"
app:met_singleLineEllipsis="true"
/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edtNewPassword"
android:hint="Password"
android:textColorHint="#color/colorPrimary"
android:textColor="#color/colorPrimary"
android:textSize="24sp"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:met_baseColor="#color/colorPrimary"
app:met_floatingLabel="highlight"
app:met_primaryColor="#color/colorPrimary"
app:met_singleLineEllipsis="true"
/>
</LinearLayout>
</android.support.v7.widget.CardView>
<LinearLayout
android:layout_below="#id/info_login"
android:orientation="horizontal"
android:weightSum="2"
android:layout_margin="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#id/btn_sign_up"
android:text="Sign up"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<Button
android:id="#id/btn_sign_in"
android:text="Sign in"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
Please help me! I've tried anything I knew but nothing works
The program I work in is ANDROID STUDIO. I need to solve this to finish my app.
signIn(edtUser.getText().toString(), edtPassword.getText().toString());
This is the line that gives me ERROR. If I comment this line the app works properly but I need it for the rest of the app.
Your edtUser MaterialEditText and edtPassword are not present in your xml file, you have to change the ids in xml file to match the Activity ids, or remplace
edtUser = (MaterialEditText)findViewById(R.id.edtUser);
edtPassword = (MaterialEditText)findViewById(R.id.edtPassword);
by :
edtUser = (MaterialEditText)findViewById(R.id.edtNewUserName);
edtPassword = (MaterialEditText)findViewById(R.id.edtNewPassword);
Related
I make a chat app using a video tutorial, but this tutorial does not show how to make messages from different people appear on different sides. The sender and receiver see all messages on the left. Could you please give some advices on this? Thanks in advance.
Now it looks like this
Main code
public class MainActivity extends AppCompatActivity {
private static int SIGN_IN_CODE=1;
private RelativeLayout activity_main;
private FirebaseListAdapter<Message> adapter;
private FloatingActionButton sendBtn;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==SIGN_IN_CODE) {
if(requestCode == RESULT_OK) {
Snackbar.make(activity_main, "You are authorized", Snackbar.LENGTH_LONG).show();
displayAllMessages();
} else {
Snackbar.make(activity_main, "You are not authorized", Snackbar.LENGTH_LONG).show();
finish();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity_main=findViewById(R.id.activity_main);
sendBtn = findViewById(R.id.btnSend);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText textField = findViewById(R.id.messageField);
if(textField.getText().toString().equals(""))
return;
FirebaseDatabase.getInstance().getReference().push().setValue(
new Message(
FirebaseAuth.getInstance().getCurrentUser().getEmail(),
textField.getText().toString()));
textField.setText("");
}
});
//Пользователь ещё не авторизован
if (FirebaseAuth.getInstance().getCurrentUser()==null)
startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_CODE);
//Пользователь авторизован
else {
Snackbar.make(activity_main, "You are authorized", Snackbar.LENGTH_LONG).show();
displayAllMessages();
}
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
private void displayAllMessages() {
ListView listOfMessages = findViewById(R.id.list_of_messages);
FirebaseListOptions<Message> options =
new FirebaseListOptions.Builder<Message>()
.setQuery(FirebaseDatabase.getInstance().getReference(), Message.class)
.setLayout(R.layout.list_item)
.build();
adapter = new FirebaseListAdapter<Message>(options){
#Override
protected void populateView(View v, Message model, int position) {
TextView mess_user, mess_time;
BubbleTextView mess_text;
mess_user = v.findViewById(R.id.message_user);
mess_time = v.findViewById(R.id.message_time);
mess_text = v.findViewById(R.id.message_text);
mess_user.setText(model.getUserName());
mess_text.setText(model.getTextMessage());
mess_time.setText(DateFormat.format("dd-MM-yyyy HH:mm:ss", model.getMessageTime()));
}
};
listOfMessages.setAdapter(adapter);
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
Message Class
public class Message {
private String UserName;
private String TextMessage;
private long MessageTime;
public Message() {}
public Message (String UserName, String TextMessage){
this.UserName = UserName;
this.TextMessage = TextMessage;
this.MessageTime = new Date().getTime();
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public String getTextMessage() {
return TextMessage;
}
public void setTextMessage(String textMessage) {
TextMessage = textMessage;
}
public long getMessageTime() {
return MessageTime;
}
public void setMessageTime(long messageTime) {
MessageTime = messageTime;
}
}
Main XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="#+id/activity_main">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:src="#drawable/ic_send_button"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
app:fabSize="normal">
</com.google.android.material.floatingactionbutton.FloatingActionButton>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/text_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#id/btnSend"
>
<EditText
android:id="#+id/messageField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint=" Message..."
/>
</com.google.android.material.textfield.TextInputLayout>
<ListView
android:id="#+id/list_of_messages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/text_layout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:divider="#android:color/transparent"
android:dividerHeight="12dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll">
</ListView>
</RelativeLayout>
XML for the message bubbles
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/message_user"
android:textStyle="normal|bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:id="#+id/message_time"
/>
<com.github.library.bubbleview.BubbleTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:id="#+id/message_text"
android:layout_marginTop="9dp"
android:layout_below="#id/message_user"
android:textSize="18sp"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#fff"
android:padding="10dp"
app:angle="10dp"
app:arrowWidth="8dp"
app:arrowHeight="10dp"
app:arrowPosition="10dp"
app:bubbleColor="#03dac5"
/>
</RelativeLayout>
Try adding layout_gravity attribute in your BubbleTextView when you need this like this:
android:layout_gravity="right"
Every user will have a unique email - Let say here in the example - d#mail.ru is your email. You need to add user logic to dynamically check to decide whether you want a bubble test layout to be LEFT or RIGHT.
Update the message bubble layout.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/message_user"
android:textStyle="normal|bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:id="#+id/message_time"
/>
<com.github.library.bubbleview.BubbleTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:id="#+id/message_text"
android:layout_marginTop="9dp"
android:layout_below="#id/message_user"
android:textSize="18sp"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#fff"
android:padding="10dp"
app:angle="10dp"
app:arrowWidth="8dp"
app:arrowHeight="10dp"
app:arrowPosition="10dp"
app:bubbleColor="#03dac5"
/>
</RelativeLayout>
Adapter code:- you can update as you need either LEFT or RIGHT.
adapter = new FirebaseListAdapter<Message>(options){
#Override
protected void populateView(View v, Message model, int position) {
TextView mess_user, mess_time;
BubbleTextView mess_text;
RelativeLayout Layout = v.findViewById(R.id.parentlayout);
mess_user = v.findViewById(R.id.message_user);
mess_time = v.findViewById(R.id.message_time);
mess_text = v.findViewById(R.id.message_text);
mess_user.setText(model.getUserName());
mess_text.setText(model.getTextMessage());
mess_time.setText(DateFormat.format("dd-MM-yyyy HH:mm:ss", model.getMessageTime()));
if(!model.getUserName().equals("d#mail.ru")) {
mess_text.setGravity(Gravity.LEFT)
} else {
mess_text.setGravity(Gravity.RIGHT)
}
}
};
Check this link as a reference - https://github.com/rpadma/Trip-Planner/blob/master/app/src/main/java/com/etuloser/padma/rohit/homework09a/ChatAdapter.java
Chat.java :
My app only shows the last message typed and shows in the ChatWindow. My firebase Database gets the messages but i am unable to show the same to the user in my app. I want to show at least 5-10 previous messages to the user.
public class Chat extends AppCompatActivity {
private DatabaseReference Database;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
final UserLocalStore localStore = new UserLocalStore(Chat.this);
Database = FirebaseDatabase.getInstance().getReference("Messages");
final TextView Chat_Window=(TextView)findViewById(R.id.chat_window);
Database.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #androidx.annotation.Nullable String s) {
Log.e("DatasnapShot",dataSnapshot.getKey().toString());
Chat_Window.setText(dataSnapshot.getValue().toString());
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #androidx.annotation.Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #androidx.annotation.Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Button SendMessage = (Button)findViewById(R.id.send);
SendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String messageText = Chat_Window.getText().toString();
Database.push().setValue((localStore.getUserData().get(0).toString()));
Database.push().setValue(ChatType.getText().toString());
Chat_Window.append(ChatType.getText().toString());
ChatType.setText("");
}
});
Button Signout = (Button)findViewById(R.id.signout);
{
Signout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
UserLocalStore localStore=new UserLocalStore(Chat.this);
localStore.LogOut();
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(Chat.this,MainActivity.class);
startActivity(intent);
}
});
}
}
}
My activity_chat.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/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/chat_type"
android:layout_width="260dp"
android:layout_height="44dp"
android:layout_marginBottom="2dp"
android:ems="10"
android:hint="Enter message to send..."
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/send"
android:layout_width="122dp"
android:layout_height="47dp"
android:layout_marginStart="29dp"
android:text="Send"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toEndOf="#+id/chat_type" />
<TextView
android:id="#+id/chat_window"
android:layout_width="406dp"
android:layout_height="566dp"
android:layout_marginTop="24dp"
android:layout_marginBottom="8dp"
android:gravity="bottom"
android:hint="Chat message wil appear here..."
android:padding="5dp"
app:layout_constraintBottom_toTopOf="#+id/chat_type"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/signout" />
<Button
android:id="#+id/signout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="324dp"
android:text="Sign Out"
app:layout_constraintBottom_toTopOf="#+id/chat_window"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#id/chat_window" />
</androidx.constraintlayout.widget.ConstraintLayout>
A screentshot of the VirtualMobile:
https://imgur.com/a/XUWgom7
Firebase Database structure:
Chat_Window.setText("");
Add this line after you initialize Chat_Window.
Chat_Window.setText(dataSnapshot.getValue().toString());
Change this line to -
Chat_Window.append("\n" + dataSnapshot.getValue().toString());
I am having troubles setting the two buttons on the lower part of the alert what I am trying to do is get a similar look to the IOS look of the buttons.
here is my current code:
public void openInstructions() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final AlertDialog dialog = builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
setNewDateOnView();
dialog.cancel();
}
}).setPositiveButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).create();
TextView myMsg = new TextView(getActivity());
myMsg.setText("ExampleText ");
myMsg.setTextSize(15);
myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
dialog.setView(myMsg);
dialog.setTitle("Confirm Date of Purchase");
dialog.setOnShowListener( new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface arg0) {
Button negativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
negativeButton.setTextColor(0xFFFF0000);
Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
positiveButton.setTextColor(0xFF0000FF);
}
});
dialog.show();
}
Example of how it looks right now:
How I wanted it to look:
To design Dialog like ios , we can create custom dialog using custom layout like this :
dialog_custom.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:orientation="vertical"
app:layout_constraintHeight_max="wrap">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#drawable/custom_bg">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_below="#+id/title"
android:gravity="center"
android:text="Confirm Date of Purchase"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="17sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/back_ll"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/rebooking_single_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:textAlignment="center"
android:text="#string/dummuy"
android:textColor="#android:color/black"
android:textSize="17sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/back_ll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/end_time_recycle"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#8F8F8F" />
<LinearLayout
android:id="#+id/rebooking_back_button_ll"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:gravity="center">
<TextView
android:id="#+id/ok_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".49"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="Ok"
android:textAlignment="center"
android:textColor="#FF6363"
android:textSize="17sp"
android:textStyle="bold" />
<View
android:layout_width="0dp"
android:layout_weight=".01"
android:layout_height="match_parent"
android:layout_below="#+id/end_time_recycle"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#8F8F8F" />
<TextView
android:id="#+id/cancel_btn"
android:layout_width="0dp"
android:layout_weight=".5"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:textAlignment="center"
android:paddingRight="10dp"
android:text="Cancle"
android:textColor="#7BC5FF"
android:textSize="17sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Main_Activity
final Dialog dialog=new Dialog(FirstActivity.this);
dialog.setCancelable(false);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog_custom);
TextView cancel_btn=dialog.findViewById(R.id.cancel_btn);
cancel_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
dialog.dismiss();
}
});
TextView ok_btn=dialog.findViewById(R.id.ok_btn);
ok_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
dialog.dismiss();
}
});
dialog.show();
Well, as a start, google recommends you use the Android Design Guidelines when creating Android apps, really you should be sticking to those as that's what your users will be used to (not Apple's).
Also there's no reason to be assigning the dialog a TextView if all you're doing is showing text, the AlertDialog provides this functionality with setMessage.
If that hasn't convinced you to stick to the normal design rules, the only other option would be creating a Custom View and assign it to the AlertDialog with setView(similar to how you're doing it with the TextView).
Here's a tutorial on creating a Custom View
You can create a custom view such as the one sent and inflate it
Example:
AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity());
View mView=getActivity().getLayoutInflater().inflate(R.layout.custom_layout, null);
mBuilder.setView(mView);
Button close = (Button) mView.findViewById(R.id.close);
Button OK = (Button) mView.findViewById(R.id.ok);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//close the dialog
hideDialog1();
}
});
OK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
dialog = mBuilder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.show();
Use .setNeutralButton that make place left most
TextView textview;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button =(Button)findViewById(R.id.button1);
textview = (TextView)findViewById(R.id.textView1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AlertDialog.Builder(MainActivity.this).setIcon(R.drawable.ic_launcher_background)
.setTitle("Alert Dialog Box Title")
.setMessage("Are you sure( Alert Dialog Message )")
.setPositiveButton("YES", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(MainActivity.this, "You Clicked on Yes", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(MainActivity.this, "You Clicked on Cancel", Toast.LENGTH_SHORT).show();
}
})
.setNeutralButton("NO", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(MainActivity.this, "You Clicked on NO", Toast.LENGTH_SHORT).show();
}
})
.show();
}
});
}
===============================================
It is allowing me to login through Gmail and its showing display picture, my name etc. but its not working with other random people's id.
I've added more owners on developer.google.com and its also allowing them but not me.
public class MainActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener{
private LinearLayout Prof_Section;
private Button SignOut;
private SignInButton SignIn;
private TextView Name,Email;
private ImageView Prof_Pic;
private GoogleApiClient googleApiClient;
private static final int REQ_CODE=9001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Prof_Section = (LinearLayout)findViewById(R.id.Prof_Section);
SignOut = (Button)findViewById(R.id.bn_logout);
SignIn = (SignInButton)findViewById(R.id.bn_login);
Name=(TextView)findViewById(R.id.name);
Email=(TextView)findViewById(R.id.email);
Prof_Pic=(ImageView) findViewById(R.id.prof_pic);
SignIn.setOnClickListener(this);
SignOut.setOnClickListener(this);
Prof_Section.setVisibility(View.GONE);
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
googleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this,this).addApi(Auth.GOOGLE_SIGN_IN_API,signInOptions).build();
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.bn_login:
signIn();
break;
case R.id.bn_logout:
signOut();
break;
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
private void signIn()
{
Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(intent,REQ_CODE);
}
private void signOut()
{
Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
updateUI(false);
}
});
}
private void handleResult(GoogleSignInResult result)
{if(result.isSuccess())
{
GoogleSignInAccount account = result.getSignInAccount();
String name = account.getDisplayName();
String email = account.getEmail();
String img_url = account.getPhotoUrl().toString();
Name.setText(name);
Email.setText(email);
// Glide.with(this).load(img_url).into(Prof_Pic);
// Glide.with(this)
// .load(img_url)
// // .override(300, 200)
// .into(Prof_Pic);
// Glide.with(this).load(img_url).into(Prof_pic);
updateUI(true);
}
else
{updateUI(false);}
}
private void updateUI(boolean isLogin){
if(isLogin){
Prof_Section.setVisibility(View.VISIBLE);
SignIn.setVisibility((View.GONE));
}
else
{
Prof_Section.setVisibility(View.GONE);
SignIn.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent data)
{
super.onActivityResult(requestCode,resultCode,data);
if(requestCode==REQ_CODE)
{
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleResult(result);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="wrap_content"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/Prof_Section"
android:layout_width="match_parent"
android:layout_height="176dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/prof_pic"
android:layout_width="113dp"
android:layout_height="match_parent"
android:src="#drawable/myalpha"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="37dp"
android:layout_marginTop="20dp"
android:gravity="center"
android:text="Name display here"
android:textSize="18dp"
android:textStyle="bold" />
<TextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Email display here"
android:textSize="12dp"
android:textStyle="bold" />
<Button
android:id="#+id/bn_logout"
android:layout_width="match_parent"
android:layout_height="61dp"
android:text="Logout Google Account" />
</LinearLayout>
</LinearLayout>
<com.google.android.gms.common.SignInButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:layout_marginRight="50dp"
android:layout_marginLeft="50dp"
android:id="#+id/bn_login"
>
</com.google.android.gms.common.SignInButton>
</LinearLayout>
Its logging me and showing me my details but not others people details.
I want that if they try to login, they also get there details
SignInButton Signin = findViewById(R.id.);
findViewById(R.id.bn_login).setOnClickListener(this);
findViewById(R.id.bn_login).setVisibility(View.GONE);
I am new to Android Programming. I successfully integrated the Google sign-in and successful in Passing data to another Activity. But When I am going back to the activity through the navigation drawer where I passed the data it sowing empty screen. I Want to Save user Profile in that Activity. I want to save user details by clicking the save button permanently in the app to show as a user profile. Please help me in solving this Problem. Thanks, in Advance for the Solution.
Here are my java files and XML files.
activity_main3.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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/activity_main3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Main3Activity">
<LinearLayout
android:id="#+id/prof_section"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/prof_pic"
android:layout_width="90dp"
android:layout_height="125dp"
android:src="#drawable/profilep" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="28dp"
android:layout_marginTop="20dp"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Disply Name Here"
android:textSize="18dp"
android:textStyle="bold" />
<TextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Disply Email Here"
android:textSize="18dp"
android:textStyle="bold" />
<Button
android:id="#+id/butn_logout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Logout"
/>
</LinearLayout>
</LinearLayout>
<com.google.android.gms.common.SignInButton
android:id="#+id/butn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginTop="60dp" >
</com.google.android.gms.common.SignInButton>
activity_detail.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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=".Detail">
<ImageView
android:id="#+id/dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<Button
android:id="#+id/button_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SAVE" />
Detail.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
dp = (ImageView) findViewById(R.id.dp);
name = (TextView) findViewById(R.id.name);
email = (TextView) findViewById(R.id.email);
Intent i = getIntent();
final String i_name, i_email, i_url;
i_name = i.getStringExtra("p_name");
i_email = i.getStringExtra("p_email");
i_url = i.getStringExtra("p_url");
name.setText(i_name);
email.setText(i_email);
new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(i_url);
InputStream is = url.openConnection().getInputStream();
final Bitmap bmp = BitmapFactory.decodeStream(is);
runOnUiThread(new Runnable() {
#Override
public void run() {
dp.setImageBitmap(bmp);
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
Main3Activity.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
preferenceConfig = new SharedPreferenceConfig(getApplicationContext());
if (preferenceConfig.readLoginStatus()) {
startActivity(new Intent(this, Main2Activity.class));
finish();
}
Prof_Section = (LinearLayout) findViewById(R.id.prof_section);
SignOut = (Button) findViewById(R.id.butn_logout);
SignIn = (SignInButton) findViewById(R.id.butn_login);
Name = (TextView) findViewById(R.id.name);
Email = (TextView) findViewById(R.id.email);
Prof_Pic = (ImageView) findViewById(R.id.prof_pic);
SignIn.setOnClickListener(this);
SignOut.setOnClickListener(this);
Prof_Section.setVisibility(View.GONE);
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().requestProfile().build();
googleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, signInOptions).build();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.butn_login:
signIn();
break;
case R.id.butn_logout:
signOut();
break;
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
private void signIn() {
Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(intent, REQ_CODE);
}
private void signOut() {
Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
updateUI(false);
}
});
}
private void updateUI(boolean isLogin) {
if (isLogin) {
Prof_Section.setVisibility(View.VISIBLE);
SignIn.setVisibility(View.GONE);
} else {
Prof_Section.setVisibility(View.GONE);
SignIn.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE) {
GoogleSignInResult googleSignInResult = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
GoogleSignInAccount account = googleSignInResult.getSignInAccount();
String name = account.getDisplayName();
String email = account.getEmail();
String img_url = account.getPhotoUrl().toString();
Name.setText(name);
Email.setText(email);
Glide.with(this).load(img_url).into(Prof_Pic);
updateUI(true);
preferenceConfig.writeLoginStatus(true);
try {
Intent sendData = new Intent(Main3Activity.this, Detail.class);
name = account.getDisplayName();
email = account.getEmail();
img_url = account.getPhotoUrl().toString();
sendData.putExtra("p_name", name);
sendData.putExtra("p_email", email);
sendData.putExtra("p_url", img_url);
startActivity(sendData);
} catch (Exception e) {
Toast.makeText(Main3Activity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(Main3Activity.this, "Login Failed", Toast.LENGTH_SHORT).show();
}
}
Use shared preferences for your purpose. You can read more about it here.
An example is provided here sharedPreferences