In my app my user is entering the category and that category is stored in the FirebseDB. After storing the value in the DB the user can view the inserted value in the Spinner.
At this point all works fine.
I want user to enter only unique value .so , if user wants to enter the value which is already there he should get a Toast.
Following is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.lenovo.baicactivitytest.MainActivity">
<Spinner
android:id="#+id/sp"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<Button
android:id="#+id/add_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="70dp"
android:text="Add" />
</RelativeLayout>
Following is my inputdialogue.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
android:orientation="vertical"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="50dp">
<android.support.design.widget.TextInputLayout
android:id="#+id/nameLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/nameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:hint= "Name" />
</android.support.design.widget.TextInputLayout>
<Button android:id="#+id/saveBtn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save"
android:clickable="true"
android:background="#color/colorAccent"
android:layout_marginTop="40dp"
android:textColor="#android:color/white"/>
</LinearLayout>
</LinearLayout>
Spacecraft.java
package com.example.lenovo.baicactivitytest;
/**
* Created by LENOVO on 29-12-2017.
*/
public class Spacecraft {
String name;
public Spacecraft() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
FirebaseHelper
package com.example.lenovo.baicactivitytest;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseException;
import com.google.firebase.database.DatabaseReference;
import java.util.ArrayList;
/**
* Created by LENOVO on 29-12-2017.
*/
public class FirebaseHelper {
DatabaseReference db;
Boolean saved = null;
public FirebaseHelper(DatabaseReference db) {
this.db = db;
}
//SAVE
public Boolean save(Spacecraft spacecraft)
{
if(spacecraft==null)
{
saved=false;
}else
{
try
{
db.child("Spacecraft").push().setValue(spacecraft);
saved=true;
}catch (DatabaseException e)
{
e.printStackTrace();
saved=false;
}
}
return saved;
}
//READ
public ArrayList<String> retrieve()
{
final ArrayList<String> spacecrafts=new ArrayList<>();
db.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot,spacecrafts);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot,spacecrafts);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return spacecrafts;
}
private void fetchData(DataSnapshot snapshot,ArrayList<String> spacecrafts)
{
spacecrafts.clear();
for (DataSnapshot ds:snapshot.getChildren())
{
String name=ds.getValue(Spacecraft.class).getName();
spacecrafts.add(name);
}
}
}
MainActivity.java
package com.example.lenovo.baicactivitytest;
import android.app.Dialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity extends AppCompatActivity {
DatabaseReference db;
FirebaseHelper helper;
private Button madd_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner sp =(Spinner) findViewById(R.id.sp);
//SETUP FB
db= FirebaseDatabase.getInstance().getReference();
helper = new FirebaseHelper(db);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,helper.retrieve());
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
madd_btn = (Button) findViewById(R.id.add_btn);
madd_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
displayInputDialog();
}
});
}
//DISPLAY INPUT DILAOG
private void displayInputDialog()
{
Dialog d=new Dialog(this);
d.setTitle("Firebase database");
d.setContentView(R.layout.inputdialog);
final EditText nameTxt= (EditText) d.findViewById(R.id.nameEditText);
Button saveBtn = (Button) d.findViewById(R.id.saveBtn);
//SAVE
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//GET DATA
String name=nameTxt.getText().toString();
//set data
Spacecraft s = new Spacecraft();
s.setName(name);
//SAVE
if(name != null && name.length()>0)
{
if(helper.save(s))
{
nameTxt.setText("");
}
}else
{
Toast.makeText(MainActivity.this, "Name Cannot Be Empty", Toast.LENGTH_SHORT).show();
}
}
});
d.show();
}
}
Can do this:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Category");
ref.orderByChild("categoryname").equalTo(name).addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot){
if(dataSnapshot.exist()) {
Toast.makeText(MainActivity.this, "Name already exists", Toast.LENGTH_SHORT).show();
}
}
Can do the above, it will search in the Category node in the db, and if it exists then it will give you the Toast message.
Related
It is kind of a chatting feature in an application where users with different ids send msg and it is stored in the database in realtime.
I have stored the data into the realtime database but when i try to retrive and display it is not displayed.I am not sure if the data is getting retrived in the first place.
I have tried storing the data through the application and it is being stored in the firebase database.
Layout:
<?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=".chatroom">
<Button
android:id="#+id/send_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="9dp"
android:layout_marginLeft="9dp"
android:layout_marginEnd="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="8dp"
android:text="SEND"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/text_send" />
<EditText
android:id="#+id/text_send"
android:layout_width="286dp"
android:layout_height="49dp"
android:layout_marginEnd="9dp"
android:layout_marginRight="9dp"
android:layout_marginBottom="8dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/send_button"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/msgview"
android:layout_width="390dp"
android:layout_height="699dp"
android:layout_marginEnd="3dp"
android:layout_marginRight="3dp"
android:text="look here"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Code:
package com.example.sdl;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.Iterator;
public class chatroom extends AppCompatActivity {
FirebaseDatabase database=FirebaseDatabase.getInstance();
Button send_button;
EditText text_send;
TextView msgview;
String ctext_send,cmsgview;
String sdomain,ssubdomain,sprofession,sbranch,srollno,spass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatroom);
SharedPreferences sp = getApplication().getSharedPreferences("user", Context.MODE_PRIVATE);
sdomain=sp.getString("domain"," xyz");
ssubdomain=sp.getString("subdomain","xyz ");
sprofession=sp.getString("profession"," xyz");
sbranch=sp.getString("branch","xyz ");
srollno=sp.getString("rollno","xyz ");
spass=sp.getString("pass"," xyz");
send_button =(Button) findViewById(R.id.send_button);
send_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openchat();
}
});
msgview=(TextView) findViewById(R.id.msgview);
text_send=(EditText) findViewById(R.id.text_send);
DatabaseReference ref = database.getReference().child(sdomain).child(ssubdomain).child(sbranch).child("chat");
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, String s) {
append_chat_conv(dataSnapshot);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, String s) {
append_chat_conv(dataSnapshot);
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private String chatmsg;
private void append_chat_conv(DataSnapshot dataSnapshot){
Iterator i=dataSnapshot.getChildren().iterator();
while (i.hasNext()){
chatmsg= (String) ((DataSnapshot)i.next()).getValue();
msgview.append(chatmsg);
}
}
public void openchat(){
ctext_send=text_send.getText().toString();
Task<Void> ref=database.getReference().child(sdomain).child(ssubdomain).child(sprofession).child(sbranch).child("chat").push().child(srollno).setValue(ctext_send);
}
}
I have 5 different TextView's on a page and I want to make them swipe-able so that when I swipe them all to the left it will display the same information but with different values (E.g. Name = Ben, but when swiped left Name = Tim), is this possible? If so how would I go about doing it? The information for the TextView's are pulled from a Firebase database but can be changed to static values if needs be.
This is what I have so far:
CalendarActivity:
package com.example.adamf.authtest;
import android.content.Intent;
import android.renderscript.Allocation;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import org.w3c.dom.Text;
import android.text.util.Linkify;
import java.util.GregorianCalendar;
public class CalendarActivity extends AppCompatActivity implements View.OnClickListener {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mUserRef = mRootRef.child(uid).child("2018-04-23").child("Jane Jenkins");
DatabaseReference mNameRef = mUserRef.child("Name");
DatabaseReference mAddressRef = mUserRef.child("Address");
DatabaseReference mPostCodeRef = mUserRef.child("PostCode");
DatabaseReference mMobileRef = mUserRef.child("Mobile");
DatabaseReference mTimeRef = mUserRef.child("Time");
private DatabaseReference mDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private Button InformationBtn = null;
TextView mName;
TextView mAddress;
TextView mPostCode;
TextView mMobile;
TextView mTime;
#Override
protected void onDestroy() {
super.onDestroy();
mAuth.signOut();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.buttonSignOut) {
startActivity(new Intent(CalendarActivity.this, LoginActivity.class));
FirebaseAuth.getInstance().signOut();
Toast.makeText(CalendarActivity.this, "Sign out successful", Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
Toast.makeText(getApplicationContext(), "Please use the Sign Out button above", Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar_v2);
mName = findViewById(R.id.textViewName);
mAddress = findViewById(R.id.textViewAddress);
mPostCode = findViewById(R.id.textViewPostcode);
mMobile = findViewById(R.id.textViewMobile);
mTime = findViewById(R.id.textViewTime);
InformationBtn = findViewById(R.id.buttonInformation);
InformationBtn.setOnClickListener(this);
mAuth = FirebaseAuth.getInstance();
Linkify.addLinks(mMobile, Linkify.PHONE_NUMBERS);
Linkify.addLinks(mAddress, Linkify.MAP_ADDRESSES);
InformationBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(CalendarActivity.this, ClientInfo.class));
}
});
CalendarView view = new CalendarView(this);
view.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
public GregorianCalendar calendar;
#Override
public void onSelectedDayChange(CalendarView calendarView, int year, int month, int day) {
this.calendar = new GregorianCalendar(year, month, day);
}
});
}
protected void onStart() {
super.onStart();
mNameRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
mName.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mAddressRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
mAddress.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mPostCodeRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
mPostCode.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mMobileRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
mMobile.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mTimeRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
mTime.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onClick(View v) {
}
}
activity_calendar_v2.xml (layout file):
<?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"
xmlns:tools="http://schemas.android.com/tools">
<CalendarView
android:id="#+id/calendar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:minWidth="400dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textName"
android:layout_below="#+id/calendar"
android:text="Name of patient:"
android:layout_marginTop="20dp"
android:layout_marginStart="30dp"
android:textSize="14dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textViewName"
android:layout_toEndOf="#+id/textName"
android:layout_alignBottom="#+id/textName"
android:text=" "
android:textSize="12dp"
android:layout_marginStart="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textAddress"
android:layout_below="#+id/textName"
android:text="Patients address:"
android:layout_marginTop="10dp"
android:layout_marginStart="30dp"
android:autoLink="map"
android:textSize="14dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textViewAddress"
android:text=" "
android:textSize="12dp"
android:layout_alignStart="#+id/textViewName"
android:layout_alignBottom="#+id/textAddress"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textPostcode"
android:layout_below="#+id/textAddress"
android:text="Postcode:"
android:layout_marginTop="10dp"
android:layout_marginStart="30dp"
android:textSize="14dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textViewPostcode"
android:text=" "
android:textSize="12dp"
android:layout_alignStart="#+id/textViewName"
android:layout_alignBottom="#+id/textPostcode"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textMobile"
android:layout_below="#+id/textPostcode"
android:text="Mobile number:"
android:layout_marginTop="10dp"
android:layout_marginStart="30dp"
android:autoLink="phone"
android:linksClickable="true"
android:textSize="14dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textViewMobile"
android:text=" "
android:textSize="12dp"
android:layout_alignStart="#+id/textViewName"
android:layout_alignBottom="#+id/textMobile"
android:autoLink="phone"
android:linksClickable="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textTime"
android:layout_below="#+id/textMobile"
android:text="Appointment time:"
android:layout_marginTop="10dp"
android:layout_marginStart="30dp"
android:textSize="14dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textViewTime"
android:text=" "
android:textSize="12dp"
android:layout_alignStart="#+id/textViewName"
android:layout_alignBottom="#+id/textTime"/>
<Button
android:id="#+id/buttonInformation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textTime"
android:text="View Patient Information"
android:textSize="12dp"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Will I also have to put all the TextView's inside of something to group them all together?
Thanks
I am attempting to make a simple app for personal and maybe a few coworkers to use. I am having trouble successfully reading and writing into a Firebase Database.
Some of this code is ripped so there may be mistakes I am looking over without realizing.
I am fairly positive this is something silly and stupid easy to fix, but I just can't see it and have had no success with searching.
The way I am thinking of putting the information into the database is in this fashion.
possible layout?
If there is a better way to lay this out, I'm all ears lol. Hope someone can point me in the right direction. All the files have the proper top lines or 2, and sometimes missing the bottom brace. My computer is being super derpy and deleting some lines for some reason when I am trying to copy/paste.
Rundown of what I am trying to accomplish.
App that will show/store NSNs, name, and description of items
User can enter all of this information themselves to be entered into the database or can search a database for the information. Search part is coming next after I get the easier part down.
information is presented in a CardView form, eventually to be made clickable for more information. information on card will be NSN, name, description, and eventually a picture.
All information is either from user input or directly into the database.
MainActivity.java
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.milapps.jd.militemnsnfinder.ShowItemInfo;
import java.io.IOException;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
//Button Variables
private Button btnChoose, btnUpload, btnSubmit, btnReturn;
private final int PICK_IMAGE_REQUEST = 71;
private Uri filePath;
//Firebase storage
FirebaseStorage storage;
StorageReference storageReference;
// Declaring String variable ( In which we are storing firebase server URL
).
public static final String Firebase_Server_URL = "https://mil-item-nsn-
finder.firebaseio.com/";
// Declaring String variables to store name & phone number get from .
String nsnHolder, nameHolder, descHolder;
//Declaring firebase database
Firebase firebase;
DatabaseReference databaseReference;
// Root Database Name for Firebase Database.
public static final String Database_Path = "Military NSN Database";
//Declaring EditTexts
EditText NameEditText, NSNEditText, DescEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSubmit = (Button)findViewById(R.id.btnSubmit_iv);
btnReturn = (Button)findViewById(R.id.btnReturn_iv);
btnChoose = (Button)findViewById(R.id.btnChoose_iv);
btnUpload = (Button)findViewById(R.id.btnUpload_iv);
NameEditText = (EditText)findViewById(R.id.itemNameIV);
NSNEditText = (EditText)findViewById(R.id.itemNSN_iv);
DescEditText = (EditText)findViewById(R.id.itemDesc_iv);
Firebase.setAndroidContext(MainActivity.this);
firebase = new Firebase(Firebase_Server_URL);
databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);
//Firebase init
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseImage();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadImage();
}
});
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ItemInfo itemInfo = new ItemInfo();
GetDataFromEditText();
// Adding item name into class function object.
itemInfo.setItemName(nameHolder);
// Adding item NSN into class function object.
itemInfo.setItemNSN(nsnHolder);
//Adding item desc into class function object
itemInfo.setItemDesc(descHolder);
// Getting the ID from firebase database.
String ItemIDFromServer = databaseReference.push().getKey();
// Adding the both name and number values using student details
class object using ID.
databaseReference.child(ItemIDFromServer).setValue(itemInfo);
// Showing Toast message after successfully data submit.
Toast.makeText(MainActivity.this,"Successfully Added",
Toast.LENGTH_LONG).show();
}
});
btnReturn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
ShowItemInfo.class);
startActivity(intent);
}
});
}
private void uploadImage(){
if(filePath != null){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/"+
UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot
taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Uploaded",
Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Failed"
+e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new
OnProgressListener<UploadTask.TaskSnapshot>(){
#Override
public void onProgress(UploadTask.TaskSnapshot
taskSnapshot){
double progress = (100.0
*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded " +
(int)progress+"%");
}
});
}
}
private void chooseImage(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select
Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data!= null && data.getData() != null)
{
filePath = data.getData();
try{
Bitmap bitmap =
MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
}
catch (IOException e){
e.printStackTrace();
}
}
}
public void GetDataFromEditText(){
nameHolder = NameEditText.getText().toString().trim();
descHolder = DescEditText.getText().toString().trim();
nsnHolder = NSNEditText.getText().toString().trim();
}
ItemInfo.java
package com.milapps.jd.militemnsnfinder;
public class ItemInfo {
private String itemName;
private String itemNSN;
private String itemDesc;
public ItemInfo() {
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemNSN() {
return itemNSN;
}
public void setItemNSN(String itemNSN) {
this.itemNSN = itemNSN;
}
public String getItemDesc() {
return itemDesc;
}
public void setItemDesc(String itemDesc) {
this.itemDesc = itemDesc;
}
}
RecyclerViewAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class RecyclerViewAdapter extends
RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<ItemInfo> MainImageUploadInfoList;
public RecyclerViewAdapter(Context context, List<ItemInfo> TempList) {
this.MainImageUploadInfoList = TempList;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =
LayoutInflater.from(parent.getContext()).inflate(
R.layout.recyclerview_items, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ItemInfo itemInfo = MainImageUploadInfoList.get(position);
holder.itemName_iv.setText(itemInfo.getItemName());
holder.itemNSN_iv.setText(itemInfo.getItemNSN());
holder.itemDesc_iv.setText(itemInfo.getItemDesc());
}
#Override
public int getItemCount() {
return MainImageUploadInfoList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView itemName_iv;
public TextView itemNSN_iv;
public TextView itemDesc_iv;
public ViewHolder(View itemView) {
super(itemView);
itemName_iv = (TextView)
itemView.findViewById(R.id.itemName_iv);
itemDesc_iv = (TextView)
itemView.findViewById(R.id.itemDesc_iv);
itemNSN_iv = (TextView) itemView.findViewById(R.id.itemNSN_iv);
}
}
}
ShowItemInfo.java
package com.milapps.jd.militemnsnfinder;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class ShowItemInfo extends AppCompatActivity {
DatabaseReference databaseReference;
ProgressDialog progressDialog;
List<ItemInfo> list = new ArrayList<>();
RecyclerView recyclerView;
RecyclerView.Adapter adapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_items_list);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new
LinearLayoutManager(ShowItemInfo.this));
progressDialog = new ProgressDialog(ShowItemInfo.this);
progressDialog.setMessage("Loading Data from Firebase Database");
progressDialog.show();
databaseReference =
FirebaseDatabase.getInstance().getReference(MainActivity.Database_Path);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
ItemInfo itemInfo =
dataSnapshot.getValue(ItemInfo.class);
list.add(itemInfo);
}
adapter = new RecyclerViewAdapter(ShowItemInfo.this, list);
recyclerView.setAdapter(adapter);
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.milapps.jd.militemnsnfinder.MainActivity"
android:layout_margin="10dp">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Enter New Item"
android:textSize="20dp"
android:textAlignment="center"
android:textColor="#000"
android:id="#+id/textView" />
<EditText
android:id="#+id/itemNameIV"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/textView"
android:layout_marginTop="15dp"
android:gravity="center"
android:hint="Enter Item Name(Stock)" />
<EditText
android:id="#+id/itemNSN_iv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/itemNameIV"
android:gravity="center"
android:hint="Enter Item NSN" />
<EditText
android:id="#+id/itemDesc_iv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/itemNSN_iv"
android:gravity="center"
android:hint="Enter Item Description" />
<Button
android:id="#+id/btnChoose_iv"
android:layout_width="175dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/btnUpload_iv"
android:layout_alignBottom="#+id/btnUpload_iv"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:text="Choose" />
<Button
android:id="#+id/btnUpload_iv"
android:layout_width="175dp"
android:layout_height="wrap_content"
android:layout_below="#+id/itemDesc_iv"
android:layout_marginTop="53dp"
android:layout_toEndOf="#+id/btnChoose_iv"
android:layout_toRightOf="#+id/btnChoose_iv"
android:text="Upload" />
<Button
android:id="#+id/btnSubmit_iv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/btnChoose_iv"
android:layout_marginTop="32dp"
android:text="Submit" />
<Button
android:id="#+id/btnReturn_iv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/btnSubmit_iv"
android:layout_marginTop="18dp"
android:text="Return" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/btnChoose_iv"
android:layout_centerHorizontal="true"
android:ems="10"
android:gravity="center"
android:inputType="textPersonName"
android:text="Upload Picture(Optional)" />
</RelativeLayout>
content_show_student_details.xml
<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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.milapps.jd.militemnsnfinder.ShowItemInfo"
tools:showIn="#layout/show_items_list">
</android.support.constraint.ConstraintLayout>
recyclerview_items.xml
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardview1"
android:layout_width="match_parent"
android:layout_height="75dp"
android:layout_margin="8dp"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:orientation="vertical">
<TextView
android:id="#+id/itemName_iv"
android:layout_width="233dp"
android:layout_height="25dp"
android:text="something" />
<TextView
android:id="#+id/itemNSN_iv"
android:layout_width="233dp"
android:layout_height="25dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:text="something" />
<TextView
android:id="#+id/itemDesc_iv"
android:layout_width="232dp"
android:layout_height="25dp"
android:layout_alignEnd="#+id/itemName_iv"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/itemName_iv"
android:text="something" />
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
card_view:srcCompat="#mipmap/ic_launcher" />
</RelativeLayout>
</android.support.v7.widget.CardView>
show_items_list.xml
<android.support.constraint.ConstraintLayout
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="com.milapps.jd.militemnsnfinder.ShowItemInfo">
<android.support.v7.widget.RecyclerView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/recyclerView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>
First, in your POJO make sure the name of the constants are equal to the ones in your firebase database, first in your firebase database you have item Name and in your pojo itemName , you should put in your firebase either item_Name or itemName , if you put item_Name refactor the name in your pojo but keep the same names in the pojo and the firebase
Second, your reference must be like this .child("items").child("item_NSN").... , or .child("items/item_NSN")..... but please do not use blank spaces in names inside firebase
Last, please update your firebase rules if they are not able to write and read for everyone without sign in first
go to your realtime database and find rules, inside you should have this
// These rules require authentication
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
if you want to each one read and write data without authentication just change that rules to this
// These rules do not require authentication
// These rules give anyone, even people who are not users of your app,
// read and write access to your database
{
"rules": {
".read": true,
".write": true
}
}
So my brain is no longer fried. So when trying to enter information via the submit button, I "think" I fixed my reference but I'm not 100%. Still a little confused from it.
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String itemNSN;
ItemInfo itemInfo = new ItemInfo();
GetDataFromEditText();
// Adding item name into class function object.
itemInfo.setItemName(nameHolder);
// Adding item NSN into class function object.
itemInfo.setItemNSN(nsnHolder);
itemNSN = nsnHolder;
//Adding item desc into class function object
itemInfo.setItemDesc(descHolder);
// Getting the ID from firebase database.
String ItemIDFromServer = databaseReference.push().getKey();
// Adding the both name and number values using student details
class object using ID.
databaseReference.child("items").setValue(itemNSN);
databaseReference.child("items/itemNSN").setValue(itemInfo);
// Showing Toast message after successfully data submit.
Toast.makeText(MainActivity.this,"Successfully Added",
Toast.LENGTH_LONG).show();
}
});
Then to pull all the information via the return button, I am unsure of what is supposed to be but I haven't changed it at all. I have the cardview layout I would like for it. but this is my btnReturn clickListener.
btnReturn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
ShowItemInfo.class);
startActivity(intent);
}
});
I'm trying to read a list form a fire base in a recycle viewer, but it's not showing it to me.
this addfood.java - it's the class which i will show the blog flow in it:
package com.example.median1.sora;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.MenuView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.firebase.client.Firebase;
import com.firebase.client.core.Context;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
import org.w3c.dom.Text;
public class addfood extends AppCompatActivity {
private RecyclerView mBlogList;
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addfood);
mDatabase=FirebaseDatabase.getInstance().getReference("Blog");
mBlogList=(RecyclerView)findViewById(R.id.blog_list);
mBlogList.setHasFixedSize(true);
mBlogList.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Blog1,BlogViewHolder> firebaseRecyclerAdapter1=new FirebaseRecyclerAdapter<Blog1, BlogViewHolder>(
Blog1.class,
R.layout.blog_row,
BlogViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(BlogViewHolder viewHolder, Blog1 model, int position) {
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
}
};
mBlogList.setAdapter(firebaseRecyclerAdapter1);
}
public static class BlogViewHolder extends RecyclerView.ViewHolder{
View mView;
public BlogViewHolder(View itemView) {
super(itemView);
mView=itemView;
}
public void setTitle(String title){
TextView post_title=(TextView)mView.findViewById(R.id.post_title1);
post_title.setText(title);
}
public void setDesc(String desc){
TextView post_desc=(TextView)mView.findViewById(R.id.post_desc1);
post_desc.setText(desc);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.action_add){
Intent u=new Intent(addfood.this,potedfood.class);
startActivity(u);
}
return super.onOptionsItemSelected(item);
}
}
this is blog1.java this is the:
package com.example.median1.sora;
/**
* Created by median1 on 9/23/2017.
*/
public class Blog1 {
private String title;
private String desc;
private String image;
public Blog1(){
}
public Blog1(String title, String desc, String image) {
this.title = title;
this.desc = desc;
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
addfood.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="com.example.median1.sora.addfood">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/blog_list"></android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>
blog_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/post_image1"
android:src="#mipmap/add_btn"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/post_title1"
android:hint="name"
android:padding="10dp"
android:textSize="16dp"
android:textStyle="bold"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/post_desc1"
android:hint="price"
android:padding="10dp"
android:textSize="16dp"
android:textStyle="bold"/>
</LinearLayout>
</LinearLayout>
i had this same issue but then i saw this solution it turns out the adapter needs to start listening and it has to be made global
To solve this, first make your adapter variable global:
private FirebaseRecyclerAdapter<UserInformation, EmployeeViewHolder> adapter;
Then you need to add the following lines of code in your onStart() and onStop() methods:
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
if(adapter != null) {
adapter.stopListening();
}
}
Because the adapter uses a listener to check for database changes, in order to make it work, you need to start listening first. And when you close the application, you need to stop listening.
I am a newbie in Android programming. I have a splash screen after which I am trying to open an activity but after the splash screen my screen keeps flickering and the activity doesn't open. show anything. My code is as follows:
Splashscreen.java
public class splashscreen extends AppCompatActivity
{
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen);
imageView =(ImageView)findViewById(R.id.imageView);
Animation animation= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.slideinright);
imageView.setAnimation(animation);
animation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
finish();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
}
Loginpage.java
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class LoginActivity2 extends AppCompatActivity implements View.OnClickListener {
private Button loginbuttonRegister;
private EditText logineditTextEmail;
private EditText logineditTextPassword;
private TextView textViewLogin;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
private LoginButton loginButton;
private CallbackManager callbackManager;
private Profile profile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login2);
progressDialog = new ProgressDialog(this);
firebaseAuth = FirebaseAuth.getInstance();
if( firebaseAuth.getCurrentUser() != null){
//display navigation activity
finish();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
loginbuttonRegister = (Button) findViewById(R.id.loginbuttonRegister);
logineditTextEmail = (EditText) findViewById(R.id.logineditTextEmail);
logineditTextPassword = (EditText) findViewById(R.id.logineditTextPassword);
textViewLogin =(TextView) findViewById(R.id.textViewLogin);
loginbuttonRegister.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
loginbuttonRegister = (Button) findViewById(R.id.loginbuttonRegister);
if(v == loginbuttonRegister)
{
userLogin();
}
}
});
textViewLogin.setOnClickListener(this);
//Initializing Facebook Sdk.
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
//intialize callback manager
callbackManager = CallbackManager.Factory.create();
//initializing facebook login button
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
loginButton = (LoginButton)findViewById(R.id.login_button);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
ProfileTracker profileTracker;
#Override
public void onSuccess(LoginResult loginResult) {
Toast.makeText(LoginActivity2.this,"Succesfully Logged In",Toast.LENGTH_SHORT).show();
profile = Profile.getCurrentProfile();
//check profile is fetched or not, if not then wait for sometime
// to load your profile using profile tracker
if(profile == null){
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile, Profile profile1) {
if(profile1 != null){
startActivity(new Intent(LoginActivity2.this,MainActivity.class));
}
}
};
}else{
startActivity(new Intent(LoginActivity2.this,MainActivity.class));
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
});
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode,resultCode,data);
}
private void userLogin(){
String email = logineditTextEmail.getText().toString().trim();
String password = logineditTextPassword.getText().toString().trim();
if(TextUtils.isEmpty(email)){
//mail empty
Toast.makeText(this, "Please enter email!", Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this, "Please enter Password!", Toast.LENGTH_SHORT).show();
return;
}
//if valid then shows progressbar
progressDialog.setMessage("Loggin in...!");
progressDialog.show();
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{ progressDialog.dismiss();
//start anvigation activity
finish();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
else {progressDialog.dismiss();
Toast.makeText(LoginActivity2.this, "Failed to login! Try again.", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onClick(View view) {
if(view == textViewLogin)
{finish();
startActivity(new Intent(this,Registeruser.class));
}
}
}
Loginactivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_login2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.dell.Swing.LoginActivity2"
tools:showIn="#layout/activity_login2"
android:background="#drawable/probeach">
<LinearLayout
android:id="#+id/registerlayout"
android:orientation="vertical"
android:layout_centerVertical="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_margin="10dp"
android:hint="Enter your E-mail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:id="#+id/logineditTextEmail"
/>
<EditText
android:layout_margin="10dp"
android:hint="Enter your Password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:id="#+id/logineditTextPassword" />
<Button
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/loginbuttonRegister"
android:text="Log In"
style="#style/Widget.AppCompat.Button.Colored"
android:background="#android:color/holo_red_dark"
android:elevation="0dp" />
<TextView
android:textAlignment="center"
android:text="Not Registered? Sign up Here"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textViewLogin" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginBottom="66dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:weightSum="1">
<TextView
android:id="#+id/orview"
android:text="Or"
android:gravity="center"
android:textAppearance="#style/TextAppearance.AppCompat.Button"
android:layout_width="match_parent"
android:layout_weight="0.63"
android:layout_height="40dp" />
<com.facebook.login.widget.LoginButton
android:layout_margin="10dp"
android:id="#+id/login_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_below="#+id/orview"
/>
</LinearLayout>
Please check your background image resolution,
android:background="#drawable/probeach"