This is my small project, I can put name, address, and phone to SQLite and display it. And then I want to fill link image to the box and display an image in recyclerView. Please help!
Here's my app and code:
RecyclerView display, no img
And I want to fill the link image to this box... and img'll appear!
MainActivity:
public class MainActivity extends AppCompatActivity {
private StudentAdapter studentAdapter;
private ArrayList<Student> studentList;
private StudentDatabase studentDatabase;
private FloatingActionButton floatingActionButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
floatingActionButton = findViewById(R.id.floatingActionButton);
final RecyclerView recyclerView = findViewById(R.id.recycle);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
studentAdapter = new StudentAdapter();
studentDatabase = new StudentDatabase(this);
studentList = new ArrayList<>();
studentList = studentDatabase.getAll();
recyclerView.setAdapter(studentAdapter);
studentAdapter.setData(studentList);
Student student = new Student();
recyclerView.smoothScrollToPosition(studentList.size());
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, CreateStudent.class);
Student student = new Student();
intent.putExtra("data", student);
startActivityForResult(intent, 800);
}
});
studentAdapter.setOnClickEvent(new StudentAdapter.OnClickEvent() {
#Override
public void OnItemClick(int position) {
Student student = studentList.get(position);
Intent intent = new Intent(MainActivity.this, ModifyStudent.class);
intent.putExtra("data", student);
startActivityForResult(intent, 70);
}
#Override
public void OnDelete(int position) {
Student student = studentList.get(position);
studentDatabase.delete(student.getId());
studentList.remove(position);
studentList = studentDatabase.getAll();
studentAdapter.setData(studentList);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 70 && resultCode == RESULT_OK) {
Student student = (Student) data.getSerializableExtra("returnData");
studentDatabase.update(student);
studentList = studentDatabase.getAll();
studentAdapter.setData(studentList);
}
if (requestCode == 800 && resultCode == RESULT_OK) {
studentList = studentDatabase.getAll();
studentAdapter.setData(studentList);
}
}
}
Student.java:
public class Student implements Serializable {
private String img;
private int id;
private String name;
private String address;
private String phone;
public Student(String img, int id, String name, String address, String phone) {
this.img = img;
this.id = id;
this.name = name;
this.address = address;
this.phone = phone;
}
public Student(){
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public int 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 getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
CreateStudent.java:
public class CreateStudent extends AppCompatActivity {
private EditText createName, createAddress, creatPhone, createImage;
private StudentDatabase studentDatabase;
private Button btnCreate;
private Button btnCancle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_student2);
createName = findViewById(R.id.create_name);
createAddress = findViewById(R.id.create_address);
creatPhone = findViewById(R.id.create_phone);
btnCreate = findViewById(R.id.btn_create);
btnCancle = findViewById(R.id.btn_cancle);
createImage = findViewById(R.id.create_img);
final Student student = new Student();
if (student != null) {
createName.setText(student.getName());
createAddress.setText(student.getAddress());
creatPhone.setText(student.getPhone());
}
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String cname = createName.getText().toString();
String caddress = createAddress.getText().toString();
String cphone = creatPhone.getText().toString();
String cimage = createImage.getText().toString();
if (cname.trim().equals("") || caddress.trim().equals("") || cphone.trim().equals("")) {
btnCreate.setEnabled(false);
} else {
student.setName(cname);
student.setAddress(caddress);
student.setPhone(cphone);
student.setImg(cimage);
studentDatabase = new StudentDatabase(CreateStudent.this);
studentDatabase.addStudent(student);
Intent intent = new Intent();
intent.putExtra("createData", student);
setResult(RESULT_OK, intent);
finish();
}
}
});
btnCancle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
StudentDatabase.java:
public class StudentDatabase extends SQLiteOpenHelper {
public StudentDatabase(#Nullable Context context) {
super(context, "STUDENT_DATABASE", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE STUDENT(ID INTEGER PRIMARY KEY, NAME TEXT, ADDRESS TEXT, PHONE INTEGER)";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS STUDENT");
onCreate(db);
}
public void addStudent(Student student) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("NAME", student.getName());
cv.put("ADDRESS", student.getAddress());
cv.put("PHONE", student.getPhone());
db.insert("STUDENT", null, cv);
db.close();
}
public void delete(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete("STUDENT", " ID = " + id, null);
db.close();
}
public ArrayList<Student> getAll() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM STUDENT";
Cursor cursor = db.rawQuery(query, null);
ArrayList<Student> studentList = new ArrayList<>();
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String address = cursor.getString(2);
String phone = cursor.getString(3);
Student student = new Student();
student.setName(name);
student.setId(id);
student.setAddress(address);
student.setPhone(phone);
studentList.add(student);
} while (cursor.moveToNext());
}
db.close();
return studentList;
}
public void update(Student student) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("NAME", student.getName());
cv.put("ADDRESS", student.getAddress());
cv.put("PHONE", student.getPhone());
db.update("STUDENT", cv, "ID = " + student.getId(), null);
}
}
StudentAdapter.java:
public class StudentAdapter<extend> extends RecyclerView.Adapter<StudentAdapter.MyViewHolder> {
private ArrayList<Student> studentList;
private OnClickEvent onClickEvent;
public void setOnClickEvent(OnClickEvent onClickEvent) {
this.onClickEvent = onClickEvent;
}
public StudentAdapter() {
}
public void setData(ArrayList<Student> listData) {
if (studentList == null) {
studentList = new ArrayList<>();
}
studentList.clear();
studentList.addAll(listData);
notifyDataSetChanged();
}
#NonNull
#Override
public StudentAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycle, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull StudentAdapter.MyViewHolder holder, final int position) {
Student student = studentList.get(position);
Glide.with(holder.imageView.getContext()).load(studentList.get(position).getImg()).into(holder.imageView);
holder.name.setText(student.getName());
holder.address.setText(student.getAddress());
holder.phone.setText(student.getPhone());
holder.btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onClickEvent != null) {
onClickEvent.OnDelete(position);
}
}
});
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onClickEvent != null) {
onClickEvent.OnItemClick(position);
}
}
});
}
#Override
public int getItemCount() {
return studentList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView name, address, phone;
private Button btn_delete, btn_edit;
private ImageView imageView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.img);
name = itemView.findViewById(R.id.name);
address = itemView.findViewById(R.id.address);
phone = itemView.findViewById(R.id.phone);
btn_delete = itemView.findViewById(R.id.btn_delete);
btn_edit = itemView.findViewById(R.id.btn_edit);
}
}
public interface OnClickEvent {
void OnItemClick(int position);
void OnDelete(int position);
}
}
Though you have correctly defined your recyclerView with Glide library to show the picture but you are not storing(saving) picture information in your database.
public void addStudent(Student student) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("NAME", student.getName());
cv.put("ADDRESS", student.getAddress());
cv.put("PHONE", student.getPhone());
db.insert("STUDENT", null, cv);
db.close();
}
you should have something like
cv.put("PICTURE", student.getImg());
you should also do the same for your public void update(Student student) method for storing(saving) user picture. And also with your public void addStudent(Student student) method definition. And also you should retrieve your picture information inside your `
public ArrayList<Student> getAll() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM STUDENT";
Cursor cursor = db.rawQuery(query, null);
ArrayList<Student> studentList = new ArrayList<>();
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String address = cursor.getString(2);
String phone = cursor.getString(3);
Student student = new Student();
student.setName(name);
student.setId(id);
student.setAddress(address);
student.setPhone(phone);
studentList.add(student);
} while (cursor.moveToNext());
}
db.close();
return studentList;
}
something like this:
String picture = cursor.getString(4);
student.setImg(picture);
The picture information should be the path of the picture location which might be a URL or a file location in your phone's disk.
...............
updates:
String query = "CREATE TABLE STUDENT(ID INTEGER PRIMARY KEY, NAME TEXT, ADDRESS TEXT, PHONE INTEGER, PICTURE TEXT)";
Related
Update
I found the issue within my program, the values are actually being saved as seen within the database inspector
The activity for adding the values never displays the current values which is what I thought they should, from this activity I can only enter new values and save
I have a user object which is already created in a separate activity via recyclerview, I want to then click into each recycler view created and update the users data within that but my update user method is not updating or storing any data at all when I enter the new data in the fields.
I know this is due to my app not being able to identify which user I'm actually trying to update but I'm unsure how to assign the id to my user object and then search for the clicked on user's id within my updateUser method in the UserDetails activity?
See below my user object created within User entity
#Entity
public class User {
#PrimaryKey(autoGenerate = true)
public int uid = 0;
#ColumnInfo(name = "Username")
public String UserName;
#ColumnInfo(name = "Field1")
public String Value1;
#ColumnInfo(name = "Field2")
public String Value2;
#ColumnInfo(name = "Field3")
public String Value3;
#ColumnInfo(name = "Field4")
public String Value4;
#ColumnInfo(name = "Field5")
public String Value5;
#ColumnInfo(name = "Field6")
public String Value6;
#ColumnInfo(name = "Field7")
public String Value7;
#ColumnInfo(name = "Field8")
public String Value8;
#ColumnInfo(name = "Field9")
public String Value9;
#ColumnInfo(name = "Field10")
public String Value10;
public User() { this("", "", "", "", "", "", "", "", "", "", ""); }
public User(String UserName, String value1, String value2, String value3, String value4, String value5, String value6, String value7, String value8, String value9, String value10 ) {
setUserName(UserName);
setValue1(Value1);
setValue1(Value2);
setValue1(Value3);
setValue1(Value4);
setValue1(Value5);
setValue1(Value6);
setValue1(Value7);
setValue1(Value8);
setValue1(Value9);
setValue1(Value10);
}
public int getId() {
return uid;
}
public void setId(int id) {
this.uid = id;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
// Field 1 value
public String getValue1() {
return Value1;
}
public void setValue1(String value1) {
Value1 = value1;
}
// Field 2 value
public String getValue2() {
return Value2;
}
public void setValue2(String value2) {
Value2 = value2;
}
// Field 3 value
public String getValue3() {
return Value3;
}
public void setValue3(String value3) {
Value3 = value3;
}
// Field 4 value
public String getValue4() {
return Value4;
}
public void setValue4(String value4) {
Value4 = value4;
}
// Field 5 value
public String getValue5() {
return Value5;
}
public void setValue5(String value5) {
Value5 = value5;
}
// Field 6 value
public String getValue6() {
return Value6;
}
public void setValue6(String value6) {
Value6 = value6;
}
// Field 7 value
public String getValue7() {
return Value7;
}
public void setValue7(String value7) {
Value7 = value7;
}
// Field 8 value
public String getValue8() {
return Value8;
}
public void setValue8(String value8) {
Value8 = value8;
}
// Field 9 value
public String getValue9() {
return Value9;
}
public void setValue9(String value9) {
Value9 = value9;
}
// Field 10 value
public String getValue10() {
return Value10;
}
public void setValue10(String value10) {
Value10 = value10;
}
}
See below my UserDao with my methods for inserting and updating a user
#Dao
public interface UserDao {
#Query("SELECT * FROM User")
List<User> getAllUsers();
#Query("SELECT * FROM User WHERE uid =:userID")
User getUser(int userID);
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insertUser(User users);
#Query("UPDATE User SET Field1 =:Value1, Field2 =:Value2, Field3 =:Value3, Field4 =:Value4, Field5 =:Value5, Field6 =:Value6, " +
"Field7 =:Value7, Field8 =:Value8, Field6 =:Value9, Field6 =:Value9, Field10 =:Value10 WHERE uid = uid ")
void updateUser(String Value1, String Value2, String Value3, String Value4, String Value5, String Value6, String Value7,
String Value8, String Value9, String Value10);
#Update
void updateUser(User...users);
#Delete
void delete(User user);
}
See below my addnewuseractivity where a user is initially created
public class AddNewUserActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_user);
final EditText firstNameInput = findViewById(R.id.firstNameInput);
/* final EditText txtField1Value = findViewById(R.id.txtField1Value);
final EditText txtField2Value = findViewById(R.id.txtField2Value);
final EditText txtField3Value = findViewById(R.id.txtField3Value);
final EditText txtField4Value = findViewById(R.id.txtField4Value);
final EditText txtField5Value = findViewById(R.id.txtField5Value);
final EditText txtField6Value = findViewById(R.id.txtField6Value);
final EditText txtField7Value = findViewById(R.id.txtField7Value);
final EditText txtField8Value = findViewById(R.id.txtField8Value);
final EditText txtField9Value = findViewById(R.id.txtField9Value);
final EditText txtField10Value = findViewById(R.id.txtField10Value);
*/
Button saveButton = findViewById(R.id.saveButton);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveNewUser(firstNameInput.getText().toString()); /*, txtField1Value.getText().toString(), txtField2Value.getText().toString(),
txtField3Value.getText().toString(), txtField4Value.getText().toString(), txtField5Value.getText().toString(),
txtField6Value.getText().toString(), txtField7Value.getText().toString(), txtField8Value.getText().toString(),
txtField9Value.getText().toString(), txtField10Value.getText().toString());*/
}
});
}
public void saveNewUser(String firstName) {
AppDatabase db = AppDatabase.getDbInstance(this.getApplicationContext());
User user = new User();
user.UserName = firstName;
/*user.Value1 = value1;
user.Value2 = value2;
user.Value3 = value3;
user.Value4 = value4;
user.Value5 = value5;
user.Value6 = value6;
user.Value7 = value7;
user.Value8 = value8;
user.Value9 = value9;
user.Value10 = value10;*/
db.userDao().insertUser(user);
finish();
}
}
See below my userdetails activity where the created user's data is supposed to be updated on press
public class UserDetails extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_details);
final EditText txtField1Value = findViewById(R.id.txtField1Value);
final EditText txtField2Value = findViewById(R.id.txtField2Value);
final EditText txtField3Value = findViewById(R.id.txtField3Value);
final EditText txtField4Value = findViewById(R.id.txtField4Value);
final EditText txtField5Value = findViewById(R.id.txtField5Value);
final EditText txtField6Value = findViewById(R.id.txtField6Value);
final EditText txtField7Value = findViewById(R.id.txtField7Value);
final EditText txtField8Value = findViewById(R.id.txtField8Value);
final EditText txtField9Value = findViewById(R.id.txtField9Value);
final EditText txtField10Value = findViewById(R.id.txtField10Value);
Intent detailIntent = getIntent();
if (detailIntent != null) {
final int userId = detailIntent.getIntExtra("userId", -1);
if (userId != -1) {
Button saveButton = findViewById(R.id.saveButton2);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateUser(userId, txtField1Value.getText().toString(), txtField2Value.getText().toString(),
txtField3Value.getText().toString(), txtField4Value.getText().toString(), txtField5Value.getText().toString(),
txtField6Value.getText().toString(), txtField7Value.getText().toString(), txtField8Value.getText().toString(),
txtField9Value.getText().toString(), txtField10Value.getText().toString());
}
});
}
}
}
/* public User getUser(int userID)
{
return AppDatabase.getDbInstance(this.getApplicationContext()).userDao().getUser(userID);
}*/
public void updateUser( int userId, String value1, String value2, String value3, String value4, String value5, String value6, String value7,
String value8, String value9, String value10) {
AppDatabase db = AppDatabase.getDbInstance(this.getApplicationContext());
User user = db.userDao().getUser(userId);
user.Value1 = value1;
user.Value2 = value2;
user.Value3 = value3;
user.Value4 = value4;
user.Value5 = value5;
user.Value6 = value6;
user.Value7 = value7;
user.Value8 = value8;
user.Value9 = value9;
user.Value10 = value10;
db.userDao().updateUser(user);
finish();
}
}
See below my UserListAdapter and MainActivity for reference
public class UserListAdapter extends RecyclerView.Adapter<UserListAdapter.MyViewHolder> {
private Context context;
private List<User> userList;
private ItemClickListener clickListener;
public UserListAdapter(Context context) {
this.context = context;
}
public void setUserList(List<User> userList) {
this.userList = userList;
notifyDataSetChanged();
}
#NonNull
#Override
public UserListAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recycler_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UserListAdapter.MyViewHolder holder, #SuppressLint("RecyclerView") final int position) {
final User user = userList.get(position);
holder.tvFirstName.setText(this.userList.get(position).UserName);
/* holder.tvValue1.setText(this.userList.get(position).Value1);
holder.tvValue2.setText(this.userList.get(position).Value2);
holder.tvValue3.setText(this.userList.get(position).Value3);
holder.tvValue4.setText(this.userList.get(position).Value4);
holder.tvValue5.setText(this.userList.get(position).Value5);
holder.tvValue6.setText(this.userList.get(position).Value6);
holder.tvValue7.setText(this.userList.get(position).Value7);
holder.tvValue8.setText(this.userList.get(position).Value8);
holder.tvValue9.setText(this.userList.get(position).Value9);
holder.tvValue10.setText(this.userList.get(position).Value10);*/
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context , UserDetails.class);
context.startActivity(intent);
}
});
holder.deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AppDatabase.getDbInstance(context).userDao().delete(user);
userList.remove(user);
notifyItemRemoved(position);
}
});
}
#Override
public int getItemCount() {
return this.userList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView tvFirstName;
/* TextView tvValue1;
TextView tvValue2;
TextView tvValue3;
TextView tvValue4;
TextView tvValue5;
TextView tvValue6;
TextView tvValue7;
TextView tvValue8;
TextView tvValue9;
TextView tvValue10;*/
Button deleteBtn;
public MyViewHolder(View view) {
super(view);
tvFirstName = view.findViewById(R.id.tvFirstName);
/* tvValue1 = view.findViewById(R.id.tvField1Value);
tvValue2 = view.findViewById(R.id.tvField2Value);
tvValue3 = view.findViewById(R.id.tvField3Value);
tvValue4 = view.findViewById(R.id.tvField4Value);
tvValue5 = view.findViewById(R.id.tvField5Value);
tvValue6 = view.findViewById(R.id.tvField6Value);
tvValue7 = view.findViewById(R.id.tvField7Value);
tvValue8 = view.findViewById(R.id.tvField8Value);
tvValue9 = view.findViewById(R.id.tvField9Value);
tvValue10 = view.findViewById(R.id.tvField10Value);*/
deleteBtn = view.findViewById(R.id.deleteBtn);
}
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView userName;
public ViewHolder(View itemView) {
super(itemView);
userName = (TextView) itemView.findViewById(R.id.tvFirstName);
itemView.setTag(itemView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
}
}
}
public class MainActivity extends AppCompatActivity implements ItemClickListener{
private UserListAdapter userListAdapter;
private List<User> users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addNewUserButton = findViewById(R.id.addNewUserButton);
addNewUserButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(new Intent(MainActivity.this, AddNewUserActivity.class), 100);
}
});
initRecyclerView();
loadUserList();
}
private void initRecyclerView() {
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
recyclerView.addItemDecoration(dividerItemDecoration);
userListAdapter = new UserListAdapter(this);
recyclerView.setAdapter(userListAdapter);
}
private void loadUserList() {
AppDatabase db = AppDatabase.getDbInstance(this.getApplicationContext());
List<User> userList =db.userDao().getAllUsers();
userListAdapter.setUserList(userList);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == 100) {
loadUserList();
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onClick(View view, int position) {
final User user = users.get(position);
}
}
When creating the User, Room auto-generates the primary key for you - uid.
When trying to update the User, it is you, who need to provide the uid.
public void updateUser(int usertID, String value1...value10) {
AppDatabase db = AppDatabase.getDbInstance(this.getApplicationContext());
User user = new User();
user.uid = userUID // <------------
user.Value1 = value1;
...
user.Value10 = value10;
db.userDao().updateUser(user);
finish();
}
I think you are missing passing the user ID to the detail activity as well.
UserListAdapter
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context , UserDetails.class);
intent.putExtra("userId", user.uid)
context.startActivity(intent);
}
});
UserDetails activity
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_details);
final EditText txtField1Value = findViewById(R.id.txtField1Value);
...
final EditText txtField10Value = findViewById(R.id.txtField10Value);
Intent detailIntent = getIntent();
if (detailIntent != null) {
int userId = detailIntent.getIntExtra("userId", -1);
if (userId != -1) {
Button saveButton = findViewById(R.id.saveButton2);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateUser(
userId
txtField1Value.getText().toString(),
...
txtField10Value.getText().toString());
}
});
}
}
}
I have a populate view holder recyclerview
and I want to order it by child, it is synced with my firebase as shown in the code.
mDatabase.orderByKey().orderByChild("Timestamp").limitToLast(100);
it doesnt work
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monitorar_morador);
LinearLayoutManager manager = new LinearLayoutManager(this);
String bairro = "test";
String cidade = "test";
mDatabase = FirebaseDatabase.getInstance().getReference().child(cidade).child(bairro).child("Relatorio");
//Query chatQuery = mDatabase.orderByChild("last_time_stamp"). limitToLast(20);
mDatabase.keepSynced(true);
//mDatabase.orderByChild("Timestamp").limitToLast(100);
//mDatabase.orderByKey().orderByChild("Timestamp").limitToLast(100);
mBlogList=(RecyclerView)findViewById(R.id.myrecycleview);
mBlogList.setHasFixedSize(true);
mBlogList.setLayoutManager(manager);
manager.setReverseLayout(false);
mBlogList.scrollToPosition(0);
// manager.setReverseLayout(true);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
#Override
protected void onStart() {
super.onStart();
final FirebaseRecyclerAdapter<Blog,BlogViewHolder>firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>
(Blog.class,R.layout.blog_row,BlogViewHolder.class,mDatabase) {
// int n =0;
#Override
protected void populateViewHolder(BlogViewHolder viewHolder, Blog model,int position) {
if (model.getNome() == null){
}else{
viewHolder.setNome(model.getNome());
}
if (model.getMensagem() == null){
}else{
viewHolder.setMensagem(model.getMensagem());
}
if (model.getRua() == null){
}else{
viewHolder.setRua(model.getRua());
}
if (model.getNumero() == null){
}else{
viewHolder.setNumero(model.getNumero());
}
if (model.getImage() == null){
}else{
viewHolder.setImage(getApplicationContext(),model.getImage());
}
if(model.getLon() == null){
// String is empty or null
}else {
viewHolder.setLon(Double.toString(model.getLon()));
// n = 1;
}
if(model.getLat() == null){
// String is empty or null
}else {
viewHolder.setLat(Double.toString(model.getLat()));
//n++;
}
if(model.getTimestamp() == null){
// String is empty or null
}else {
viewHolder.setTimestamp(model.getTimestamp());
}
if(model.getLat() == null || model.getLon() == null){
viewHolder.setgps("GPS NÂO LOCALIZADO");
// n = 0;
}else {
viewHolder.setgps(getAddress(model.getLon(), model.getLat()));
}
// n =0;
}
};
readData();
mBlogList.setAdapter(firebaseRecyclerAdapter);
// mBlogList.scrollToPosition(firebaseRecyclerAdapter.getItemCount() - 1);
}
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.mensagem);
post_title.setText(title);
}
public void setRua(String ruat) {
TextView rua = (TextView) mView.findViewById(R.id.rua);
rua.setText(ruat);
}
public void setNome(String nomet) {
TextView nome = (TextView) mView.findViewById(R.id.nome);
nome.setText(nomet);
}
public void setgps(String gpst) {
TextView gps = (TextView) mView.findViewById(R.id.gps);
gps.setText(gpst);
}
String Late;
String Lone;
public void setLon(String Lont) {
Lone = Lont;
TextView lon = (TextView) mView.findViewById(R.id.lon);
if (TextUtils.isEmpty(Lont)) {
// String is empty or null
} else {
lon.setText(Lont);
}
}
public void setTimestamp(Long cal) {
TextView data = (TextView) mView.findViewById(R.id.dataehora);
// Calendar cale = Calendar.getInstance();
// cale.setTimeInMillis(cal);
SimpleDateFormat fmt = new SimpleDateFormat("dd MM yyyy hh:mm aa", Locale.getDefault());
String date = fmt.format(cal);
data.setText(date);
}
public void setLat(String Latt){
Late = Latt;
TextView lat = (TextView)mView.findViewById(R.id.lat);
if(TextUtils.isEmpty(Late)){
// String is empty or null
}else {
lat.setText(Latt);
}
}
public void setNumero(String numerot){
TextView numero = (TextView)mView.findViewById(R.id.numero);
numero.setText(numerot);
}
public void setMensagem(String mensagemt){
TextView mensagem = (TextView)mView.findViewById(R.id.mensagem);
mensagem.setText(mensagemt);
}
public void setImage(Context ctx, String image){
ImageView post_Image=(ImageView)mView.findViewById((R.id.post_image) );
Picasso.with(ctx).load(image).into(post_Image);
}
}
public String getAddress(Double Late,Double Lone) {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(Lone, Late, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
return address;
} catch (IOException e) {
e.printStackTrace();
}
return "GPS NAO LOCALIZADO";
}
private void readData(){
mDatabase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Query lastQuery = mDatabase.child("Relatorio").orderByChild("Timestamp").limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String message = dataSnapshot.child("nome").getValue(String.class);
String title = String.format("O morador: %s", message);
builder.setContentTitle("Morador Solicitou Serviço");
builder.setContentText(title);
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Handle possible errors.
}
});
mBlogList.scrollToPosition(0);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentText("Por favor vigilante, verifique.");
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// notificationManager.notify(1, builder.build());
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
I want to be able to order my populate view holder in the correct order as timestamp
I am trying to send an ID as an int and get it from an intent in another activity but it returns zero.
This is the intent in the first activity:
public class Main_page extends AppCompatActivity {
ListView PatientList;
Button BTaddPatient;
DBpatients db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
PatientList = findViewById(R.id.PateintList);
BTaddPatient = findViewById(R.id.ADDpateint);
db = new DBpatients(this);
BTaddPatient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main_page.this, Add_patient_Activity.class);
startActivity(intent);
}
});
PatientList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Patient selected_patient = (Patient) parent.getItemAtPosition(position);
Intent intent = new Intent(getApplicationContext(), Update_patient.class);
intent.putExtra("ID", selected_patient.getId());
intent.putExtra("name", selected_patient.getName());
intent.putExtra("diagnose", selected_patient.getDiagnose());
startActivity(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
ArrayList<Patient> patients = db.getAllPatients();
PatientAdapter patientAdapter = new PatientAdapter(this, R.layout.item_pateint, patients);
PatientList.setAdapter(patientAdapter);
}
}
And trying to get the ID in the other activity:
public class Update_patient extends AppCompatActivity {
DBpatients db;
EditText editName, editDiagnose;
Button UpdateBTN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_patient);
final int id = getIntent().getExtras().getInt("ID");
db = new DBpatients(this);
editName = findViewById(R.id.EDname);
editDiagnose = findViewById(R.id.EDdiagnose);
UpdateBTN = findViewById(R.id.BTupdate);
Patient patient = db.getPatientByID2(id);
editDiagnose.setText(patient.getDiagnose());
editName.setText(patient.getName());
UpdateBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = editName.getText().toString();
String diagnose = editDiagnose.getText().toString();
Patient newPatient = new Patient( id, name, diagnose);
db.UpdatePatient(newPatient);
Toast.makeText(Update_patient.this, "successfuly UPDATED", Toast.LENGTH_SHORT).show();
}
});
}
This is Patient class :
public class Patient {
private String name;
private int id;
private String diagnose;
public Patient(String name, String diagnose) {
this.name = name;
this.diagnose = diagnose;
}
public Patient(int id, String name, String diagnose) {
this.name = name;
this.diagnose = diagnose;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDiagnose() {
return diagnose;
}
public void setDiagnose(String diagnose) {
this.diagnose = diagnose;
}
}
The app crashes, and, by using the debugger, it shows that ID = 0 when receiving it.
Please help.
You just have to send extras while calling your intent.
Like this:
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("Variable name", "Value you want to pass");
startActivity(intent);
Now on the OnCreate method of your SecondActivity you can fetch the extras like this.
If the value you sent was in int:
int value = getIntent().getIntExtra("Variable name which you sent as an extra", defaultValue(you can give it anything));
Example:
int value = getIntent().getIntExtra("ID", 0);
This is the event object that I want to inflate with RecyclerView:
public class Event {
private String mName;
private String mId;
private String mDate;
private String mPlace;
private User mUser;
private Category mCat;
private String mDescription;
public void setmEventCat(Map<String, Category> mEventCat) {
this.mEventCat = mEventCat;
}
public Map<String, Category> getmEventCat() {
return mEventCat;
}
private Map<String,Category> mEventCat;
public String getmDescription() {
return mDescription;
}
public void setDescription(String mDescription) {
this.mDescription = mDescription;
}
public Category getCat() {
return mCat;
}
public void setCat(Category mCat) {
this.mCat = mCat;
}
public String getDate() {
return mDate;
}
public String getPlace() {
return mPlace;
}
private ArrayList<User> mList;
public Event() {
}
public String getName() {
return mName;
}
public void setName(String mName) {
this.mName = mName;
}
public void setDate(String mDate) {
this.mDate = mDate;
}
public void setPlace(String mPlace) {
this.mPlace = mPlace;
}
public String getId() {
return mId;
}
public void setId(String mId) {
this.mId = mId;
}
}
The nested Category object:
public class Category implements Serializable{
private String mCatName;
private String mCatID;
public Category() {
}
public Category(String mCatName) {
this.mCatName = mCatName;
}
public String getCatName() {
return mCatName;
}
public String getCatID() {
return mCatID;
}
public void setCatName(String mCatName) {
this.mCatName = mCatName;
}
public void setCatID(String mCatID) {
this.mCatID = mCatID;
}
}
How I retrieve the data from firebase:
mDataBase = FirebaseDatabase.getInstance().getReference("Event");
mEvents = new ArrayList<Event>();
mEvent=new Event();
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
mDataBase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null && dataSnapshot.getValue() != null) {
try {
for (DataSnapshot eventSnapshot : dataSnapshot.getChildren()) {
Event event = eventSnapshot.getValue(Event.class);
String id = eventSnapshot.getKey();
mEvents.add(event);
mRecyclerView.scrollToPosition(mEvents.size() - 1);
mAdapter.notifyItemInserted(mEvents.size() - 1);
}
}
catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mAdapter = new EventAdapter(mContext, mEvents);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
My EventAdapter:
#Override
public void onBindViewHolder(EventAdapter.ViewHolder holder, int position) {
mEvent = mEvents.get(position);
holder.mEventName.setText(mEvent.getName());
//Every time I tried to add this line to set category name
//the NullPointerException error occurs
holder.mEventCategory.setText(mEvent.getCat().getCatName());
holder.mEventDate.setText(mEvent.getDate());
}
The ViewHolder Class:
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView mEventName, mEventDate,mEventCategory;
public ViewHolder(View itemView) {
super(itemView);
mEventName = itemView.findViewById(R.id.eventName_tv);
mEventDate = itemView.findViewById(R.id.date_tv);
mEventCategory = itemView.findViewById(R.id.categoryTv);
}
}
#Override
public EventAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_event, parent, false);
return new ViewHolder(view);
}
The problem is the Event is displayed as I expected, but I cannot get the category inside the event and bind it to my widget by simply calling the getCat(). I know this may caused by asynchronous Firebase API. How can I set up the TextView with the nested category object.
This is my FINAL piece of my application, any hints would be a great help.
Thanks in advance!
I figure out the question that may be useful for other people. Before adding the event object to the list, I retrieve the nested object by key and assign it to category object. Finally, linking it with event...
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null && dataSnapshot.getValue() != null) {
try {
for (DataSnapshot eventSnapshot : dataSnapshot.getChildren()) {
Event event = eventSnapshot.getValue(Event.class);
String id = eventSnapshot.getKey();
mCategory = eventSnapshot.child(id).getValue(Category.class);
event.setCat(mCategory);
mEvents.add(event);
mRecyclerView.scrollToPosition(mEvents.size() - 1);
mAdapter.notifyItemInserted(mEvents.size() - 1);
}
}
catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
}
Then binding the desired data with widget by calling the pojo getter method (nothing's changed here).
#Override
public void onBindViewHolder(EventAdapter.ViewHolder holder, int position) {
mEvent = mEvents.get(position);
holder.mEventName.setText(mEvent.getName());
holder.mEventCategory.setText(mEvent.getCat().getCatName());
holder.mEventDate.setText(mEvent.getDate());
}
I'm trying to retrieve values from the database to display on views but im getting this crash right here
FATAL EXCEPTION: main
Process: com.example.ahmad.carrental, PID: 15975
com.google.firebase.database.DatabaseException: Failed to convert a value of type java.lang.String to long
at com.google.android.gms.internal.zzear.zzb(Unknown Source)
at com.google.android.gms.internal.zzear.zza(Unknown Source)
at com.google.android.gms.internal.zzear.zzb(Unknown Source)
at com.google.android.gms.internal.zzeas.zze(Unknown Source)
at com.google.android.gms.internal.zzear.zzb(Unknown Source)
at com.google.android.gms.internal.zzear.zza(Unknown Source)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
at com.example.ahmad.carrental.Utilities.FirebaseUtilities.getCarData(FirebaseUtilities.java:178)
at com.example.ahmad.carrental.CarPost.CreatePostActivity$1$1.onDataChange(CreatePostActivity.java:100)
at com.google.android.gms.internal.zzduz.zza(Unknown Source)
at com.google.android.gms.internal.zzdwu.zzbvb(Unknown Source)
at com.google.android.gms.internal.zzdxa.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6605)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:999)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:889)
The classes are as follows
Car Model
public class Car {
private String brand;
private String id;
private int price;
private String model;
private long distance;
private String status;
private String picture;
private String location;
private String description;
public Car() {
}
public Car(String brand, String id, int price, String model, long distance, String status, String picture, String location, String description) {
this.brand = brand;
this.id = id;
this.price = price;
this.model = model;
this.distance = distance;
this.status = status;
this.picture = picture;
this.location = location;
this.description = description;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public long getDistance() {
return distance;
}
public void setDistance(long distance) {
this.distance = distance;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
User Model
public class User {
private String email;
private String id;
private String name;
private int phonenumber;
public User(String email, String id, String name,int phonenumber) {
this.email = email;
this.id = id;
this.name = name;
this.phonenumber = phonenumber;
}
public User(){
}
public int getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(int phonenumber) {
this.phonenumber = phonenumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
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;
}
}
Database Querying Function
public Car getCarData(DataSnapshot dataSnapshot) {
Log.i(TAG,"getCardData: Getting car data from database");
Car data = new Car();
for(DataSnapshot ds :dataSnapshot.getChildren()){
if(ds.getKey().equals(context.getString(R.string.dbname_car_post))){
try{
data.setId(ds.child(userID).getValue(Car.class).getId());
data.setBrand(ds.child(userID).getValue(Car.class).getBrand());
data.setDescription(ds.child(userID).getValue(Car.class).getDescription());
data.setModel(ds.child(userID).getValue(Car.class).getModel());
data.setDistance(ds.child(userID).getValue(Car.class).getDistance());
data.setPicture(ds.child(userID).getValue(Car.class).getPicture());
data.setStatus(ds.child(userID).getValue(Car.class).getStatus());
data.setLocation(ds.child(userID).getValue(Car.class).getLocation());
data.setPrice(ds.child(userID).getValue(Car.class).getPrice());
}catch (NullPointerException e){
Log.d(TAG, "getCarData: NullPointerException : " + e.getMessage());
}
}
}
return data;
}
Activity that im retrieving the data from
CreateCarPost Activity
public class CreatePostActivity extends AppCompatActivity implements CreatePostView,AdapterView.OnItemSelectedListener{
//Activity Tag
private static final String TAG ="CreateCarPost";
//Spinners
Spinner statusSpinner;
Spinner brandSpinner;
//Adapter of spinners
ArrayAdapter mArrayAdapter;
ArrayAdapter mArrayAdapter2;
//views
private TextView tvDistance;
private EditText etDistance;
private AutoCompleteTextView etCarLocation;
private CircleImageView civPicture;
private EditText etPrice;
private EditText etDescription;
private EditText etModel;
private ImageView checkButton;
//Strings
private String carLoactionStr;
private String carBrandStr;
private String carStatusStr;
//layout containg the views
private LinearLayout layoutContainer;
//To adjust dynamic views margins
LinearLayout.LayoutParams layoutParamsTv,layoutParamsEt;
//Firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mDatabaseReference;
private ValueEventListener singleValueEventListener;
private FirebaseUtilities mFirebaseUtilities;
Context mContext;
CreatePostPresenter createPostPresenter;
private Car car;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_post);
initialization();
setupFirebaseAuth();
setUpLocationSpinner();
//Assigning Car object with its data from database.
io.reactivex.Observable.create(new ObservableOnSubscribe() {
#Override
public void subscribe(ObservableEmitter emitter) throws Exception {
singleValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
car = mFirebaseUtilities.getCarData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "CANCELLED.");
}
};
mDatabaseReference.addValueEventListener(singleValueEventListener);
}
}).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe();
checkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createPostPresenter.onSaveChanges(car);
}
});
}
//initalizing everything necessary here
public void initialization(){
mContext = getApplicationContext();
createPostPresenter = new CreatePostPresenter(this,this);
//Adapter set up for spinners
mArrayAdapter2 = ArrayAdapter.createFromResource(this,R.array.car_brands,android.R.layout.simple_spinner_item);
mArrayAdapter = ArrayAdapter.createFromResource(this,R.array.car_status_array,android.R.layout.simple_spinner_item);
//Status spinner set up
statusSpinner = findViewById(R.id.createPostCarStatusSpinner_ID);
statusSpinner.setAdapter(mArrayAdapter);
statusSpinner.setOnItemSelectedListener(this);
//Brand spinner set up
brandSpinner = findViewById(R.id.createPostCarBrandSpinner_ID);
brandSpinner.setAdapter(mArrayAdapter2);
brandSpinner.setOnItemSelectedListener(this);
layoutContainer = findViewById(R.id.createPostLinearLayout_ID);
tvDistance = new TextView(this);
tvDistance.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
tvDistance.setText("Distance Travelled");
etDistance = new EditText(this);
etDistance.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//margin settings editText
layoutParamsEt = (LinearLayout.LayoutParams)etDistance.getLayoutParams();
layoutParamsEt.setMargins(0,10,0,0);
etDistance.setLayoutParams(layoutParamsEt);
//margin settings textView
layoutParamsTv = (LinearLayout.LayoutParams)tvDistance.getLayoutParams();
layoutParamsTv.setMargins(0,10,0,0);
tvDistance.setLayoutParams(layoutParamsTv);
etCarLocation = findViewById(R.id.createPostCarLocation_ID);
etDescription = findViewById(R.id.createPostCarDes_ID);
etPrice = findViewById(R.id.createPostCarPrice_ID);
etModel = findViewById(R.id.createPostCarModel_ID);
checkButton = findViewById(R.id.check_ID);
mFirebaseUtilities = new FirebaseUtilities(this);
}
private void setUpLocationSpinner() {
ArrayAdapter<String> listOfCities = new ArrayAdapter<>(getBaseContext(),
android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.TR_cities));
//--- to ensure user is restricted to selections from drop-down menu
etCarLocation.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
carLoactionStr = etCarLocation.getAdapter().getItem(position).toString();
}
});
etCarLocation.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
for (int i = 0; i < etCarLocation.getAdapter().getCount(); i++) {
if (etCarLocation.getText().toString().equals(etCarLocation.getAdapter().getItem(i))) {
carLoactionStr = etCarLocation.getAdapter().getItem(i).toString();
} else
carLoactionStr = null;
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
//start autocomplete after 1 letter
etCarLocation.setThreshold(1);
etCarLocation.performCompletion();
etCarLocation.setAdapter(listOfCities);
}
/**
* Listener for car status spinner
* #param parent
* #param view
* #param position
* #param id
*/
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Spinner spinner = (Spinner)parent;
if(spinner.getId() == R.id.createPostCarStatusSpinner_ID){
TextView textView = (TextView) view;
carStatusStr = textView.getText().toString();
addDynamicViews(position);
}
else if(spinner.getId() == R.id.createPostCarBrandSpinner_ID){
TextView textView = (TextView) view;
carBrandStr = textView.getText().toString();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
/**
* Dynamic views creation done by handling user spinner selection for first hand or second hand car status.
*#param position: position of selected value from spinner
*/
public void addDynamicViews(int position){
if(position == 1){
layoutContainer.addView(tvDistance);
layoutContainer.addView(etDistance);
}
else if(position == 0){
mFirebaseUtilities.removeNodeDynamically();
layoutContainer.removeView(tvDistance);
layoutContainer.removeView(etDistance);
}
}
#Override
public void setBrand(String brand) {
}
#Override
public void setPrice(int price) {
}
#Override
public void setLocation(String location) {
}
#Override
public void setDescription(String description) {
}
#Override
public void setModel(String model) {
}
#Override
public void setDistance(long distance) {
}
#Override
public void setStatus(String status) {
}
#Override
public void setPicture(String picture) {
}
#Override
public String getBrand() {
return carBrandStr;
}
#Override
public String getDescription() {
return etDescription.getText().toString();
}
#Override
public String getLocation() {
return carLoactionStr;
}
#Override
public String getModel() {
return etModel.getText().toString();
}
#Override
public String getStatus() {
return carStatusStr;
}
#Override
public String getPicture() {
return null;
}
#Override
public int getPrice() {
String priceViewTemp = etPrice.getText().toString();
if (priceViewTemp.equals("")) {
return 0;
} else {
return Integer.valueOf(etPrice.getText().toString());
}
}
#Override
public long getDistance() {
String distanceViewTemp = etDistance.getText().toString();
if (distanceViewTemp.equals("")) {
return 0;
} else {
return Integer.valueOf(etDistance.getText().toString());
}
}
/*************************************** Firebase *******************************************/
private void setupFirebaseAuth() {
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference();
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
//User is signed in
Log.d(TAG, "onAuthStateChanged: user signed in : " + user.getUid());
} else {
//User is signed out
Log.d(TAG, "onAuthStateChanged: user signed out");
}
}
};
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onPause() {
super.onPause();
if (singleValueEventListener != null) {
mDatabaseReference.removeEventListener(singleValueEventListener);
}
}
#Override
public void onResume(){
super.onResume();
mDatabaseReference.addListenerForSingleValueEvent(singleValueEventListener);
}
}
Firebase Structure
Firebase Structure
Haven't read if much, but i first noticed something here.
for(DataSnapshot ds :dataSnapshot.getChildren()){
if(ds.getKey().equals(context.getString(R.string.dbname_car_post))){
try{ }
The key you're trying to retrieve is an Object. So i would propose we convert it string first, sample down here.
for(DataSnapshot ds :dataSnapshot.getChildren()){
Object myKey=ds.getKey;
if(myKey.toString().equals(context.getString(R.string.dbname_car_post))){
try{ }
}}
Let me know what happens next!