I never understood how SQL Database works. So I searched a little and found this library. I'm still trying it.
I want to display the data into a RecyclerView using a RecyclerAdapter. I have always worked with it and I know how to do it but only using Cloud Firestore. So my question is: how to display the data in that database library that I have found into the RecyclerView?
I have written the adapter code and created the model class. I still need the part where the data are displayed.
This is how to read all data:
Cursor res = easyDB.getAllData();
while (res.moveToNext()) {
int anIntegerVariable = res.getInt(columnIndex);
String aStringVariable = res.getString(columnIndex);
}
User.java
public class User {
String id, name, password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(String id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public User() {
}
}
UsersRecyclerAdapater.java
public class UsersRecyclerAdapater extends RecyclerView.Adapter<UsersRecyclerAdapater.ViewHolder> {
public List<User> userList;
public Context context;
public UsersRecyclerAdapater(Context context, List<User> userList) {
this.userList = userList;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_list_item, parent, false);
context = parent.getContext();
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
holder.setIsRecyclable(false);
String id = userList.get(position).getId();
String name = userList.get(position).getName();
String password = userList.get(position).getPassword();
holder.setIdView(id);
holder.setName(name);
holder.setPasswordView(password);
}
#Override
public int getItemCount() {
return userList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView idView;
private TextView nameView;
private TextView passwordView;
public View view;
public ViewHolder(#NonNull View itemView) {
super(itemView);
view = itemView;
}
public void setIdView(String id) {
idView = view.findViewById(R.id.user_id);
idView.setText(id);
}
public void setName(String name) {
nameView = view.findViewById(R.id.user_name);
nameView.setText(name);
}
public void setPasswordView(String password) {
passwordView = view.findViewById(R.id.user_password);
passwordView.setText(password);
}
}
}
MainActivity.java
easyDB = EasyDB.init(this, DATABASE_NAME)
.setTableName(TABLE_NAME)
.addColumn(new Column(NAME_COLUMN, "TEXT"))
.addColumn(new Column(PASSWORD_COLUMN, "TEXT"))
.doneTableColumn();
mainAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = mainName.getText().toString();
String password = mainPassword.getText().toString();
boolean done = easyDB.addData(1, name)
.addData(2, password)
.doneDataAdding();
if (done) {
Toast.makeText(MainActivity.this, "User added successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "User not added", Toast.LENGTH_SHORT).show();
}
}
});
mainRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
Cursor cursor = easyDB.getAllData();
while (cursor.moveToNext()) {
String name = cursor.getString(1);
String password = cursor.getString(2);
Toast.makeText(MainActivity.this, name + "\n" + password, Toast.LENGTH_SHORT).show();
}
*/
startActivity(new Intent(MainActivity.this, UsersActivity.class));
}
});
Any help please?
You have to prepare the user list from the DB cursor and use it to RecyclerView. Check below:
List<User> userList = new ArrayList<>();
EasyDB easyDB = EasyDB.init(this, DATABASE_NAME).setTableName(TABLE_NAME);
Cursor res = easyDB.getAllData();
if(res != null && res.getCount() > 0) {
res.moveToFirst();
do {
int id = res.getInt(0);
String name = res.getString(1);
String pass = res.getString(2);
userList.add(new User(id, name, pass));
} while (res.moveToNext());
}
res.close();
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
UsersRecyclerAdapater adapter = new UsersRecyclerAdapater(this, userList);
recyclerView.setAdapter(adapter);
You will have to iterate through the cursor and create a List out of it and your RecyclerView will take that list as input.
List<User> userList = new ArrayList<>();
if (cursor.moveToFirst()) {
do {
int anIntegerVariable = cursor.getInt(columnIndex);
String aStringVariable = cursor.getString(columnIndex);
User user = new User();
user.setId(anIntegerVariable();
user.setName(aStringVariable);
userList.add(user);
} while (cursor.moveToNext());
}
cursor.close();
You should have a look at Room which is the recommended database library for android applications. https://developer.android.com/training/data-storage/room
Related
public class Memo extends AppCompatActivity {
DBHandler dbh;
Notes items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memo);
getSupportActionBar().hide();
try{
dbh = new DBHandler(this);
}
catch (Exception ex){
ex.printStackTrace();
}
display();
}
public void display( ){ //method to display all items in the database
List<Notes> books_list = dbh.getNotes(); ////here i get the list fromm the database
///// i used a custom adapter because i needed it
final myAdapter adapter = new myAdapter(this, books_list); ///creating adapter from
myadapter to link it with the list
ListView _note_ = findViewById(R.id.list_txt);
_note_.setAdapter(adapter);
_note_.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
items = (Notes) adapter.getItem(position);
String Note_content = items.getNote();
String title = items.getTitle();
String Date = items.getDate();
Intent i = new Intent(getApplicationContext() ,Note_content.class);
i.putExtra("Note ", Note_content);
i.putExtra("title", title);
i.putExtra("Date", Date);
startActivity(i);
}
});
i have a problem when I try to to get data( only Note) from this activity to another activity, other values(Date and Title) are working, I tried to use toString method in Notes class but it gives null for note
public class Note_content extends AppCompatActivity {
Notes item;
TextView txt_note ,txt_date , txt_title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_content);
txt_title = findViewById(R.id.txt_ntitle);
txt_note = findViewById(R.id.txt_Nnote);
txt_date = findViewById(R.id.txt_Ndate);
Intent i = getIntent();
String note = i.getStringExtra("Note");
String title = i.getStringExtra("title");
String date = i.getStringExtra("Date");
item = new Notes(title,note,date);
txt_note.setText(item.getNote());
//txt_note.setText(note)
txt_date.setText(date);
txt_title.setText(title);
}
this is the second activit, it is not giving any errors but null instead of the note
and this Notes class
public class Notes {
private int id;
private String title;
private String note ;
private String date;
public Notes() {
}
public Notes(String title, String note, String date) {
this.title = title;
this.note = note;
this.date = date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
#Override
public String toString() {
return this.note+"\n"+title+"\n"+date;
}
}
i.putExtra("Note ", Note_content);
In the above code line, "Note " has an extra space at the end.
I am trying to get data from my database to show on a listview. The problem I am having is it seems the getters are not working properly. When I test what they are returning, it comes back null.
Any insight would be appreciated as I am lost here. Thanks in advance.
Here is where I initialise the class:
public ArrayList<GameStats> getAllData() {
ArrayList<GameStats> arrayList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM savedGamesTable", null);
while(cursor.moveToNext()){
int id = cursor.getInt(0);
String lName = cursor.getString(1);
int lScore = cursor.getInt(2);
String rName = cursor.getString(3);
int rScore = cursor.getInt(4);
String notes = cursor.getString(5);
GameStats gameStats = new GameStats(id, lName, lScore, rName, rScore, notes);
arrayList.add(gameStats);
}
return arrayList;
}
Here is where I am trying to use the getters:
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.activity_saved_games, null);
TextView lName = convertView.findViewById(R.id.lName);
TextView lScore = convertView.findViewById(R.id.lScore);
TextView rName = convertView.findViewById(R.id.rName);
TextView rScore = convertView.findViewById(R.id.rScore);
TextView notes = convertView.findViewById(R.id.notes);
GameStats gameStats = arrayList.get(position);
testVar = gameStats.getlName();
Log.d("MyAdaptor","gameStats = " + var);
lName.setText(gameStats.getlName());
lScore.setText(String.valueOf(gameStats.getlScore()));
rName.setText(gameStats.getrName());
rScore.setText(String.valueOf(gameStats.getrScore()));
notes.setText(gameStats.getNotes());
return convertView;
}
Here is the model class:
public class GameStats {
int id, lScore, rScore;
String lName, rName, notes;
public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getlScore() {
return lScore;
}
public void setlScore(int lScore) {
this.lScore = lScore;
}
public int getrScore() {
return rScore;
}
public void setrScore(int rScore) {
this.rScore = rScore;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public String getrName() {
return rName;
}
public void setrName(String rName) {
this.rName = rName;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
}
and here is where I am calling the methods:
public class SavedGameScreen extends AppCompatActivity {
ListView lv1;
ArrayList<GameStats> arrayList;
MyAdaptor myAdaptor;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved_game_screen);
lv1 = findViewById(R.id.lv1);
databaseHelper = new DatabaseHelper(this);
arrayList = new ArrayList<>();
loadData();
}
private void loadData() {
arrayList = databaseHelper.getAllData();
myAdaptor = new MyAdaptor(this, arrayList);
lv1.setAdapter(myAdaptor);
myAdaptor.notifyDataSetChanged();
}
}
Please change the constructor as below and see if that works,
public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {
this.id = id;
this.lName = IName;
this.lScore = IScore;
this.rName = rName;
this.rScore = rScore;
this.notes = notes;
}
In your model class initialize the variables using constrtuctor. I guess that is the problem. Since you are not initializing the model class properties, it the getters will return "null" or any garbage value
You are passing the values to the model constructor but you are not assigning it to the model variables. You need to change the code as below,
public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {
this.id = id;
this.lName = IName;
this.lScore = IScore;
this.rName = rName;
this.rScore = rScore;
this.notes = notes;
}
Else initialise each variable through setter() method.
I want to know that, How can I use the Url to set the background of a particular view.
Something like this:
TextView someview;
someview.setbackground(url).
Suppose I am getting that URL from Firebase Database through a getter method in my model class.
Can someone help me clearly understand this...
Actually I am trying to load user status from Firebase node that I have created.
Below is the whole code and explanation:
The problem is in adapter class, and I commented there please check...
The Node I want to achieve from firebase:
Model class for that node:
package com.example.sociapp;
public class Status {
String backgrounduri, date, fullname, profileimage, e, time, uid, userstatus;
long textcolor, textsize;
public Status ( )
{
}
public Status(String backgrounduri, String date, String fullname, String profileimage, long textcolor, long textsize, String time, String uid, String userstatus)
{
this.backgrounduri = backgrounduri;
this.date = date;
this.fullname = fullname;
this.profileimage = profileimage;
this.textcolor = textcolor;
this.textsize = textsize;
this.time = time;
this.uid = uid;
this.userstatus = userstatus;
}
public String getBackgrounduri() {
return backgrounduri;
}
public void setBackgrounduri(String backgrounduri) {
this.backgrounduri = backgrounduri;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getProfileimage() {
return profileimage;
}
public void setProfileimage(String profileimage) {
this.profileimage = profileimage;
}
public long getTextcolor() {
return textcolor;
}
public void setTextcolor(long textcolor) {
this.textcolor = textcolor;
}
public long getTextsize() {
return textsize;
}
public void setTextsize(long textsize) {
this.textsize = textsize;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getUserstatus() {
return userstatus;
}
public void setUserstatus(String userstatus) {
this.userstatus = userstatus;
}
}
Below is the adapter class:
public class StatusAdapter extends RecyclerView.Adapter<StatusAdapter.viewHolder> {
java.util.List<String> statuskeyList;
List<Status> SList;
Context context;
DatabaseReference ClickstatusRef;
FirebaseAuth mAuth;
public StatusAdapter(List<String> statuskeyList, List<Status> SList, Context context)
{
this.statuskeyList = statuskeyList;
this.SList = SList;
this.context = context;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.all_user_status_layout, parent, false);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull viewHolder holder, int position) {
Status status = SList.get(position);
String statusKey = statuskeyList.get(position);
mAuth = FirebaseAuth.getInstance();
final String CurrentUserId = mAuth.getCurrentUser().getUid();
Picasso.get().load(status.getProfileimage()).placeholder(R.drawable.profile).into(holder.Profileimage);
holder.FullName.setText(status.getFullname());
holder.Date.setText(status.getDate());
holder.Time.setText(status.getTime());
holder.UserStatus.setText(status.getUserstatus());
ClickstatusRef = FirebaseDatabase.getInstance().getReference().child("Status").child(statusKey);
/* String name = status.getBackgrounduri();
int id = context.getResources().getIdentifier(name, "drawable", context.getPackageName());
Drawable drawable = context.getResources().getDrawable(id);*/
try {
int status_background = Integer.parseInt(status.getBackgrounduri());
holder.UserStatus.setBackgroundResource(status_background);
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
//I tried all the code for setting background commented and not commented but no use
//The problem is here, and here I am setting background Url that I am getting from firebase. I tried all the code you can see in here commented and none commented
// holder.UserStatus.setBackground(context.getResources().getDrawable(context.getResources().getIdentifier("SociApp", "getBackground",context.getPackageName())));
int status_color = (int) status.getTextcolor();
holder.UserStatus.setTextColor(status_color);
int Text_Size = (int) status.getTextsize()/ 3 ;
holder.UserStatus.setTextSize(Text_Size);
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
ClickstatusRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
String statusUserId = dataSnapshot.child("uid").getValue().toString();
if (statusUserId.equals(CurrentUserId))
{
View mview = LayoutInflater.from(context).inflate(R.layout.dialog_layout, null);
TextView Message = mview.findViewById(R.id.dialog_text);
Button OkBtn = mview.findViewById(R.id.dialog_btn);
AlertDialog.Builder mbuilder = new AlertDialog.Builder(context, R.style.mydialog);
mbuilder.setView(mview);
String message = "Do you want to delete your status!";
Message.setText(message);
OkBtn.setText("Do it");
OkBtn.setWidth(100);
final Dialog dialog = mbuilder.create();
dialog.show();
OkBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ClickstatusRef.removeValue();
dialog.dismiss();
SendUserToLoadstatusActivity();
}
});
}
else
{
Toast.makeText(context, "You just long clicked the status", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return true;
}
});
}
private void SendUserToLoadstatusActivity()
{
Intent MainIntent = new Intent(context, LoadStatusActivity.class);
MainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(MainIntent);
}
#Override
public int getItemCount()
{
return SList.size();
}
public class viewHolder extends RecyclerView.ViewHolder{
private CircleImageView Profileimage;
private TextView FullName;
private TextView Date,Time;
private TextView UserStatus;
public viewHolder(#NonNull View itemView)
{
super(itemView);
Profileimage = itemView.findViewById(R.id.status_profile_image);
FullName = itemView.findViewById(R.id.status_user_name);
Date = itemView.findViewById(R.id.status_date);
Time = itemView.findViewById(R.id.status_time);
UserStatus = itemView.findViewById(R.id.all_user_status);
}
}
}
Below I am passing data to arraylists from LoadStatusActivity:
public class LoadStatusActivity extends AppCompatActivity {
private Toolbar mtoolbar;
private TextView UserStatusButton;
private RecyclerView StatusList;
private ProgressBar ProgressCircular;
private DatabaseReference StatusRef;
private FirebaseAuth mAuth;
private List<Status> mUserStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_load_status);
mtoolbar = findViewById(R.id.status_page_toolbar);
setSupportActionBar(mtoolbar);
mAuth = FirebaseAuth.getInstance();
StatusList = (RecyclerView) findViewById(R.id.all_users_status_list);
ProgressCircular = (ProgressBar) findViewById(R.id.status_progress_circular);
StatusRef = FirebaseDatabase.getInstance().getReference().child("Status");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Status");
UserStatusButton = findViewById(R.id.status_post_btn);
mUserStatus = new ArrayList();
final List<String> Keys = new ArrayList<>();
StatusList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
StatusList.setLayoutManager(linearLayoutManager);
UserStatusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SendUserToStatusPostActivity( );
}
});
Query sortStatusInDescendantOrder = StatusRef.orderByChild("counter");
sortStatusInDescendantOrder.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUserStatus.clear();
if (dataSnapshot.exists()) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Keys.add(dataSnapshot1.getKey());
Status status = dataSnapshot1.getValue(Status.class);
mUserStatus.add(status);
}
StatusAdapter statusAdapter = new StatusAdapter( Keys, mUserStatus, LoadStatusActivity.this);
StatusList.setAdapter(statusAdapter);
ProgressCircular.setVisibility(View.INVISIBLE);
} else {
Toast.makeText(LoadStatusActivity.this, "There is no post Exists! " + DatabaseError.PERMISSION_DENIED, Toast.LENGTH_SHORT).show();
ProgressCircular.setVisibility(View.INVISIBLE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToStatusPostActivity() {
Intent StatusPostIntent = new Intent(LoadStatusActivity.this, StatusPostActivity.class);
startActivity(StatusPostIntent);
}
}
The Output I am getting:
but I want text with background not only text.and that background url is saved in backgrounduri as shown in first picture at the top. how to load it.
You have to download the Bitmap from the given URL and set this Bitmap as the background Drawable of your TextView.
To download the Bitmap you have to add internet permission to your AndroidManifest.xml.
You can download your Bitmap from the given url like this:
try {
// create url from string
URL url = new URL(imageUrl);
// connect to url
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
// download image
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
# return myBitmap or do something else
} catch (IOException e) {
e.printStackTrace();
return null;
}
To set this Bitmap as background of your TextView you have to convert it to a Drawable first by using:
// create drawable from bitmap
Drawable dr = new BitmapDrawable(myBitmap);
myTextView.setBackground(dr);
I found the answer from above link in comment.
For my problem I solved it by adding the below code in my adapter class at the place I commented above:
Code peace I needed:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url = new URL(status.backgrounduri);
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
Drawable dr = new BitmapDrawable(image);
holder.UserStatus.setBackgroundDrawable(dr);
} catch(IOException e) {
System.out.println(e);
}
int status_color = (int) status.getTextcolor();
holder.UserStatus.setTextColor(status_color);
int Text_Size = (int) status.getTextsize()/ 3 ;
holder.UserStatus.setTextSize(Text_Size);
We can do this by downloading the URL in String formate then convert it into Bitmap and then Convert that bitmap into drawable formate and set as background through the use of setbackground(the drawable);
Firebase Database LinkI am trying to save data to firebase using this code.
Everything works fine. I was saving the data creating new children uder users>uid. but now when i try to save the data by creating an object and passing that object in setvalue, the app crashes. Please help.
public class RegComplete extends AppCompatActivity {
private EditText Name, Surname, Address, Tel, DateOfBirth,Username;
private String _name, _surname, _address, _Tel, _DateOfBirth,_UserName, email;
public String uid = "";
FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference mdatabase;
private DatabaseReference fdatabase;
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser objuser = auth.getCurrentUser();
List<String> lstSports = new ArrayList<String>();
List<String> lstSteden = new ArrayList<String>();
String strSport1,strSport2,strSport3;
public String strCity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reg_complete);
fdatabase = database.getReference();
fdatabase.child("Steden").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot DS:dataSnapshot.getChildren()) {
String CityName = DS.child("CityName").getValue(String.class);
City stad = new City(CityName);
lstSteden.add(stad.CityName);
}
final Spinner CitySpin = (Spinner) findViewById(R.id.CitySpin);
ArrayAdapter<String> CityAdapter = new ArrayAdapter<String>(RegComplete.this, android.R.layout.simple_spinner_item, lstSteden);
CityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
CitySpin.setAdapter(CityAdapter);
CitySpin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
strCity = CitySpin.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
fdatabase.child("SPORTS").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds :dataSnapshot.getChildren()) {
String sportName = ds.child("SportName").getValue(String.class);
Sport objsport = new Sport(sportName);
lstSports.add(objsport.SportName);
}
final Spinner Sports1 = (Spinner) findViewById(R.id.SportSpinner1);
ArrayAdapter<String> SportAdapter = new ArrayAdapter<String>(RegComplete.this, android.R.layout.simple_spinner_item, lstSports);
SportAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Sports1.setAdapter(SportAdapter);
Sports1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
strSport1 = Sports1.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
final Spinner Sports2 = (Spinner) findViewById(R.id.SportSpinner2);
Sports2.setAdapter(SportAdapter);
Sports2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
strSport2 = Sports2.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
final Spinner Sports3 = (Spinner) findViewById(R.id.SportSpinner3);
Sports3.setAdapter(SportAdapter);
Sports3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
strSport3 = Sports3.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Name = findViewById(R.id.NameeditText);
_name = Name.getText().toString();
Surname = findViewById(R.id.SurnameEditText);
_surname = Surname.getText().toString();
Address = findViewById(R.id.AdressEditText);
_address = Address.getText().toString();
Tel = findViewById(R.id.TelEditText);
_Tel = Tel.getText().toString();
DateOfBirth = findViewById(R.id.DOBEditText);
_DateOfBirth = DateOfBirth.getText().toString();
Username = findViewById(R.id.UserIDEditText);
_UserName = Username.getText().toString();
email = FirebaseAuth.getInstance().getCurrentUser().getEmail().toString();
}
public void btnSave_Click(View V){
User usinfo = new User(email,_UserName,_name,_surname,_address,strCity,_Tel,_DateOfBirth,strSport1,strSport2,strSport3,uid);
mdatabase = FirebaseDatabase.getInstance().getReference("USERS");
uid = objuser.getUid();
mdatabase.child(uid).setValue(usinfo);
Intent i = new Intent(RegComplete.this, LoginActivity.class);
Toast.makeText(RegComplete.this ,"Registration Complete" ,Toast.LENGTH_SHORT).show();
startActivity(i);
}
}
The code for USER.class
public class User {
public String Email;
public String UserName;
public String Name;
public String SurName;
public String StreetAdress;
public String City;
public String Tel;
public String DOB;
public String Sport1;
public String Sport2;
public String Sport3;
public String UserId;
public User(){
// Default constructor required by Firebase
}
public User(String email, String userName, String name, String surName, String streetAdress, String city, String tel, String DOB, String sport1, String sport2, String sport3, String userId) {
Email = email;
UserName = userName;
Name = name;
SurName = surName;
StreetAdress = streetAdress;
City = city;
Tel = tel;
this.DOB = DOB;
Sport1 = sport1;
Sport2 = sport2;
Sport3 = sport3;
UserId = userId;
}
public String getEmail() {
return Email;
}
public String getUserName() {
return UserName;
}
public String getName() {
return Name;
}
public String getSurName() {
return SurName;
}
public String getStreetAdress() {
return StreetAdress;
}
public String getCity() {
return City;
}
public String getTel() {
return Tel;
}
public String getDOB() {
return DOB;
}
public String getSport1() {
return Sport1;
}
public String getSport2() {
return Sport2;
}
public String getSport3() {
return Sport3;
}
public String getUserId() {
return UserId;
}
}
And i am also trying to retrieve UserName for the user with which i am signed in in another activity.
using this code.
mdatabase.child("USERS").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
userinf = ds.child(uid).getValue(User.class);
};
txtUserNaam.setText(userinf.UserName);
}
Where
DatabaseReference mdatabase = FirebaseDatabase.getInstance().getReference();
Please help
Firebase is getting confused between this field:
public String City;
And this getter:
public String getCity() {
return City;
}
The field defines a property City, while the getter defines a property city. As you can see the case is different between the two, which leads to the error message.
The easiest fix is to mark all your fields as private:
private String City;
This keeps Firebase from considering them while reading/writing users.
I'm working on an android project, where I want to get all the columns for a row (specific condition) and split them into TextViews.
I have a ListView with items:
StartPage Layout
When I click on one of the items from the listview it will navigate to another layout and pass the listview item as string:
public void Select()
{
final ListView listView = (ListView) findViewById(R.id.ListViewMovie);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
final String details = listView.getAdapter().getItem(position).toString();
Intent i = new Intent(getApplicationContext(), MovieDetailsActivity.class);
i.putExtra("key", details);
startActivity(i);
}
});
}
This is the other layout that it navigates to:
MovieDetails Layout
Other than that I have a MovieRepository:
public class MoviesRepository
{
private SQLiteDatabase db;
private MyDBHelper myDBHelper;
Movie movie;
private String [] MovieAllColumns ={Movie.COlUMN_ID,
Movie.COlUMN_NAME};
private String [] MovieColumns ={Movie.COlUMN_ID,
Movie.COlUMN_NAME,
Movie.COlUMN_GENRE,
Movie.COlUMN_YEAR};
public MoviesRepository(Context context)
{
myDBHelper = new MyDBHelper(context);
}
public void open() throws SQLException
{
//Open connection to write data
db = myDBHelper.getWritableDatabase();
}
public void close()
{
//Close connection to database
db.close();
}
private Movie cursorToMovie (Cursor cursor)
{
Movie movie = new Movie();
movie.setId(cursor.getInt(0));
movie.setName(cursor.getString(1));
return movie;
}
public List<Movie> getAllMovies()
{
open();
List<Movie> movieList = new ArrayList<>();
Cursor cursor = db.query(Movie.TABLE_NAME, MovieAllColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast())
{
Movie movie = cursorToMovie(cursor);
movieList.add(movie);
cursor.moveToNext();
}
cursor.close();
close();
return movieList;
}
public void Create(Movie movie)
{
open();
//helps you insert values to the table
ContentValues values = new ContentValues();
//Put method - first column; what column do you want to be storing this ind. Second; what is the value you want to put ind
values.put(Movie.COlUMN_NAME, movie.getName());
values.put(Movie.COlUMN_GENRE, movie.getGenre());
values.put(Movie.COlUMN_YEAR, movie.getYear());
db.insert(Movie.TABLE_NAME, null, values);
close();
}
public void Delete(Movie movie)
{
open();
//Deletes Movie by id
db.delete(Movie.TABLE_NAME, Movie.COlUMN_ID + " = " + movie.getId(), null);
db.close();
}
}
A DBHelper
And a Movie Model:
public class Movie
{
// property to help us handle the data
private int id;
private String name;
private String genre;
private int year;
//Getters and Setters of the properties
public long getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getGenre()
{
return genre;
}
public void setGenre(String genre)
{
this.genre = genre;
}
public int getYear()
{
return year;
}
public void setYear(int year)
{
this.year = year;
}
public String toString()
{
return name;
}
//----------Start--------- Here we have defined the table contents (basically a blueprint of the table Movie) -------------------------------------
public static final String TABLE_NAME = "movie";
public static final String COlUMN_ID = "id";
public static final String COlUMN_NAME = "make";
public static final String COlUMN_GENRE = "model";
public static final String COlUMN_YEAR = "year";
//----------------------END----------------------------------------------------------------------------------------------------------------//
}
Hope you guys can help me figure it out
You can pass entire object to an Activity and retrieve it there.
Calling Activity:
final Movie details = listView.getAdapter().getItem(position);
Intent i = new Intent(getApplicationContext(), MovieDetailsActivity.class);
i.putExtra("key", details);
Called Activity (here it is MovieDetailsActivity):
Intent intent = getIntent();
Movie details = (Movie)(intent.getExtras().getSerializable("key"));
Note that you'll have to make your class Movie Serializable.
public class Movie implements Serializable
You should keep list of data(Movies in your case) in your adapter. And then pass not title, but id of object to another activity to be able to query this object from database by id.