排序后在RecyclerView中编辑数据条目,在Android Studio更改屏幕后编辑不同的条目



我是Android Studio的初学者,我正在尝试创建一个学生跟踪器应用程序,该应用程序可以与Firebase实时数据库和Firebase云存储进行通信。目的是跟踪学生条目,允许我编辑条目,并对条目进行排序。

在对学生项目(存储在ArrayList中(进行排序(按字母顺序(后,它会用排序后的条目重新填充RecyclerView,这非常有效。但是,如果在对视图进行排序并保存编辑后编辑条目,则视图将不再按字母顺序排列,最终编辑不同的条目。如果能为解决这个问题提供任何帮助,我将不胜感激。

以下是它的一些图像:

查看学生屏幕

查看配置文件屏幕

以下是此过程所需的所有代码:

ViewStudents.java

package com.example.studenttracker;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

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.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class ViewStudents extends AppCompatActivity {

RecyclerView recyclerView;
Button addStudent;

private DatabaseReference myRef;
public ArrayList<Students> students;
public ArrayList<Students> unorderedStudents;
private RecyclerAdapter recyclerAdapter;
ImageButton homeButton;
private SharedPreferences sharedPreferences;
private EditText mEditTextAge;
private EditText mEditTextAssignment;
public static Students student;
private Button order;
private final String checkIfOrderedClick = "orderedCheck";
private int orderCounter;
public static int realPos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_students);
recyclerView = findViewById(R.id.recyclerView);
homeButton=findViewById(R.id.homeButton);
addStudent = findViewById(R.id.addStudentButton);
sharedPreferences = getSharedPreferences(checkIfOrderedClick,Context.MODE_PRIVATE);
mEditTextAge = findViewById(R.id.EditTextAge);
order = findViewById(R.id.orderStudents);
mEditTextAssignment = findViewById(R.id.EditTextAssignment);
order.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
orderStudents();
}
});
homeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(ViewStudents.this, MainMenu.class));
}
});
addStudent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(ViewStudents.this, AddStudent.class));
}
});
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
recyclerView.setHasFixedSize(true);

myRef = FirebaseDatabase.getInstance().getReference();
students = new ArrayList<>();
unorderedStudents = new ArrayList<>();
ClearAll();
GetDataFromFirebase();
//        LoadInt();
if (orderCounter ==1) {
orderStudents();
}

}
private void GetDataFromFirebase() {
Query query = myRef.child("student");
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
ClearAll();
for(DataSnapshot snapshot: dataSnapshot.getChildren()) {
Students student = new Students();
if (snapshot.child("url").getValue() == null) {
student.setImageUrl(snapshot.child("imageUrl").getValue().toString());
}
else {
student.setImageUrl(snapshot.child("url").getValue().toString());
}
student.setName(snapshot.child("name").getValue().toString());
if (snapshot.child("age").getValue().toString()!=null ) {
student.setAge(snapshot.child("age").getValue().toString());
}
if (snapshot.child("Daily Grade").getValue().toString()!=null) {
student.setGrade(snapshot.child("Daily Grade").getValue().toString());
}
if (snapshot.child("assignment").getValue().toString()!=null) {
student.setAssignment(snapshot.child("assignment").getValue().toString());
}

students.add(student);
unorderedStudents.add(student);
}
recyclerAdapter = new RecyclerAdapter(getApplicationContext(), students);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.setOnItemClickListener(new RecyclerAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position) {
student = students.get(position);
realPos = position;
Intent viewProf = new Intent(ViewStudents.this, ViewProfile.class);
startActivity(viewProf);
}
});
recyclerAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void ClearAll() {
if (unorderedStudents != null) {
unorderedStudents.clear();
}
unorderedStudents = new ArrayList<>();
if (students != null) {
students.clear();
if(recyclerAdapter != null) {
recyclerAdapter.notifyDataSetChanged();
}
}
students = new ArrayList<>();
}
public void orderStudents() {
orderCounter = 1;
SaveInt();
Collections.sort( students, new Comparator<Students>() {
@Override
public int compare( Students o1, Students o2 ) {
return o1.name.compareTo( o2.name );
}
});
recyclerAdapter.notifyDataSetChanged();
}
private void SaveInt() {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(checkIfOrderedClick, orderCounter);
editor.clear().commit();
}
private void LoadInt() {
orderCounter = sharedPreferences.getInt(checkIfOrderedClick, 0);
}
}

ViewProfile.java

package com.example.studenttracker;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

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.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class ViewStudents extends AppCompatActivity {


RecyclerView recyclerView;
Button addStudent;


private DatabaseReference myRef;

public ArrayList<Students> students;
public ArrayList<Students> unorderedStudents;
private RecyclerAdapter recyclerAdapter;
ImageButton homeButton;
private SharedPreferences sharedPreferences;
private EditText mEditTextAge;
private EditText mEditTextAssignment;
public static Students student;
private Button order;
private final String checkIfOrderedClick = "orderedCheck";
private int orderCounter;
public static int realPos;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_students);

recyclerView = findViewById(R.id.recyclerView);
homeButton=findViewById(R.id.homeButton);
addStudent = findViewById(R.id.addStudentButton);
sharedPreferences = getSharedPreferences(checkIfOrderedClick,Context.MODE_PRIVATE);
mEditTextAge = findViewById(R.id.EditTextAge);
order = findViewById(R.id.orderStudents);
mEditTextAssignment = findViewById(R.id.EditTextAssignment);

order.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
orderStudents();
}
});
homeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(ViewStudents.this, MainMenu.class));
}
});
addStudent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(ViewStudents.this, AddStudent.class));
}
});

recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
recyclerView.setHasFixedSize(true);


myRef = FirebaseDatabase.getInstance().getReference();

students = new ArrayList<>();
unorderedStudents = new ArrayList<>();

ClearAll();

GetDataFromFirebase();

//        LoadInt();
if (orderCounter ==1) {
orderStudents();
}


}
private void GetDataFromFirebase() {
Query query = myRef.child("student");

query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
ClearAll();
for(DataSnapshot snapshot: dataSnapshot.getChildren()) {
Students student = new Students();
if (snapshot.child("url").getValue() == null) {
student.setImageUrl(snapshot.child("imageUrl").getValue().toString());
}
else {
student.setImageUrl(snapshot.child("url").getValue().toString());

}
//                    student.setAge(mEditTextAge.getText().toString());
//                    student.setAssignment(mEditTextAssignment.getText().toString().trim());
student.setName(snapshot.child("name").getValue().toString());
if (snapshot.child("age").getValue().toString()!=null ) {
student.setAge(snapshot.child("age").getValue().toString());
}
if (snapshot.child("Daily Grade").getValue().toString()!=null) {
student.setGrade(snapshot.child("Daily Grade").getValue().toString());
}
if (snapshot.child("assignment").getValue().toString()!=null) {
student.setAssignment(snapshot.child("assignment").getValue().toString());
}


students.add(student);
unorderedStudents.add(student);
}
recyclerAdapter = new RecyclerAdapter(getApplicationContext(), students);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.setOnItemClickListener(new RecyclerAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position) {
student = students.get(position);
realPos = position;
Intent viewProf = new Intent(ViewStudents.this, ViewProfile.class);
startActivity(viewProf);
}
});
recyclerAdapter.notifyDataSetChanged();

}

@Override
public void onCancelled(@NonNull DatabaseError databaseError) {

}
});
}
private void ClearAll() {
if (unorderedStudents != null) {
unorderedStudents.clear();
}
unorderedStudents = new ArrayList<>();
if (students != null) {
students.clear();

if(recyclerAdapter != null) {
recyclerAdapter.notifyDataSetChanged();
}
}
students = new ArrayList<>();
}
public void orderStudents() {
orderCounter = 1;
SaveInt();
Collections.sort( students, new Comparator<Students>() {
@Override
public int compare( Students o1, Students o2 ) {
return o1.name.compareTo( o2.name );
}
});
recyclerAdapter.notifyDataSetChanged();

}
private void SaveInt() {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(checkIfOrderedClick, orderCounter);
editor.clear().commit();
}
private void LoadInt() {
orderCounter = sharedPreferences.getInt(checkIfOrderedClick, 0);
}
}

RecyclerAdapter.java

package com.example.studenttracker;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
private static final String Tag = "RecyclerView";
private Context mContext;
private ArrayList<Students> studentsArrayList;
public RecyclerAdapter(Context mContext, ArrayList<Students> studentsArrayList) {
this.mContext = mContext;
this.studentsArrayList = studentsArrayList;
}
@NonNull
@Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.student_item,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
//TextView
holder.textView.setText(studentsArrayList.get(position).getName());
Glide.with(mContext).load(studentsArrayList.get(position).getImageUrl()).into(holder.imageView);


}
@Override
public int getItemCount() {
return studentsArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView textView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
textView = itemView.findViewById(R.id.textView);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
});
}
}
}

activity_view_students.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ViewStudents">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/addStudentButton" >
</androidx.recyclerview.widget.RecyclerView>
<Button
android:id="@+id/addStudentButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Students"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/orderStudents"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Order Students"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="@+id/homeButton"
android:layout_width="42dp"
android:layout_height="38dp"
android:layout_marginTop="8dp"
app:layout_constraintEnd_toStartOf="@+id/addStudentButton"
app:layout_constraintStart_toEndOf="@+id/orderStudents"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/ic_home_icon_foreground" />
</androidx.constraintlayout.widget.ConstraintLayout>

activity_view_profile.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ViewProfile">
<EditText
android:id="@+id/editAssignment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintBaseline_toBaselineOf="@+id/textView4"
app:layout_constraintStart_toEndOf="@+id/textView4" />
<EditText
android:id="@+id/editDailyGrade"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintBaseline_toBaselineOf="@+id/textView5"
app:layout_constraintStart_toEndOf="@+id/textView5" />
<ImageView
android:id="@+id/profile_Image"
android:layout_width="235dp"
android:layout_height="231dp"
android:layout_marginStart="16dp"
android:layout_marginTop="20dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="32dp"
android:text="Name: "
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/profile_Image" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="24dp"
android:text="Age:"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="24dp"
android:text="Assignment:"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView3" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="24dp"
android:text="Daily Grade:"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView4" />
<EditText
android:id="@+id/editName"
android:layout_width="202dp"
android:layout_height="42dp"
android:layout_marginStart="32dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintBaseline_toBaselineOf="@+id/textView2"
app:layout_constraintStart_toEndOf="@+id/textView2" />
<EditText
android:id="@+id/editAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:ems="10"
android:inputType="number"
app:layout_constraintBaseline_toBaselineOf="@+id/textView3"
app:layout_constraintStart_toEndOf="@+id/textView3" />
<Button
android:id="@+id/saveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="18dp"
android:layout_marginBottom="27dp"
android:text="Save"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="@+id/editButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:layout_marginEnd="17dp"
android:text="Edit"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/cancelButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="17dp"
android:layout_marginBottom="27dp"
android:text="Cancel"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

activity_student_item.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".DailyGrading">

<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:foreground="?android:attr/selectableItemBackground"
app:cardElevation="2dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</androidx.cardview.widget.CardView>
<RelativeLayout
android:id="@+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="50dp"
android:paddingTop="20dp"
android:scaleType="centerCrop" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imageView"
android:layout_margin="10dp"
android:textSize="16sp" />

</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

我们需要在这两个活动类中进行许多更改,其中很少是-

  1. 无需在GetDataFromFirebase((中设置回收适配器方法
  2. 更改回收视图侦听器,以传递StudentID
  3. 将StudentID传递给ViewProfile Activity将是一个不错的选择让ViewProfile活动找到学生的价值观使用相同的ID更新值
  4. 对于排序,只需有一个方法来更新现有ArrayList,而不是维护两个不同的列表
  5. ViewProfile活动中不需要任何回收视图

修改代码可以如下-

回收适配器

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private static final String Tag = "RecyclerView";
private Context mContext;
private ArrayList<Students> studentsArrayList;
private OnItemClickListener mListener;
public RecyclerAdapter(Context mContext) {
this.mContext = mContext;
}
public interface OnItemClickListener {
void onItemClick(Student student, int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}

@NonNull
@Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.student_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
//TextView
holder.textView.setText(studentsArrayList.get(position).getName());
Glide.with(mContext).load(studentsArrayList.get(position).getImageUrl()).into(holder.imageView);
}
@Override
public int getItemCount() {
if (studentsArrayList == null)
return 0;
else
return studentsArrayList.size();
}
public void setStudentArrayList(ArrayList<Students> studentsArrayList) {
this.studentsArrayList = studentsArrayList;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView textView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
textView = itemView.findViewById(R.id.textView);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(student,position);
}
}
}
});
}
}
}

ViewStudent.java

public class ViewStudents extends AppCompatActivity{
private RecyclerView recyclerView;
private Button addStudent;
private DatabaseReference myRef;
public ArrayList<Students> students;
private RecyclerAdapter recyclerAdapter;
ImageButton homeButton;
private SharedPreferences sharedPreferences;
private EditText mEditTextAge;
private EditText mEditTextAssignment;
private Button order;
private final String checkIfOrderedClick = "orderedCheck";
// User boolean value to check if the list is order or not
private boolean isOrder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_students);
recyclerView = findViewById(R.id.recyclerView);
homeButton = findViewById(R.id.homeButton);
addStudent = findViewById(R.id.addStudentButton);
mEditTextAge = findViewById(R.id.EditTextAge);
order = findViewById(R.id.orderStudents);
mEditTextAssignment = findViewById(R.id.EditTextAssignment);
myRef = FirebaseDatabase.getInstance().getReference();
order.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isOrder)
orderStudents();
else
Toast.makeText(ViewStudents.this, "Oder Already", Toast.LENGTH_SHORT).show();
}
});
homeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(ViewStudents.this, MainMenu.class));
}
});
addStudent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(ViewStudents.this, AddStudent.class));
}
});
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
recyclerView.setHasFixedSize(true);
recyclerAdapter = new RecyclerAdapter(getApplicationContext());
//student array is null but we can pass it because there is already a check on getItemCount method
recyclerAdapter.setStudentArrayList(students);
recyclerView.setAdapter(recyclerAdapter);
GetDataFromFirebase();
recyclerAdapter.setOnItemClickListener(new RecyclerAdapter.OnItemClickListener() {
@Override
public void onItemClick(Student student, int position) {
//Take selected student ID and pass the ID to ViewProfile Activity
//TODO you can remove position from parameter as well
String studentID = student.getID();
Intent viewProf = new Intent(ViewStudents.this, ViewProfile.class);
viewProf.putExtra("STUDENT_ID", studentID);
startActivity(viewProf);
}
});
}
private void GetDataFromFirebase() {
//initialize student array list
students = new ArrayList<>();
Query query = myRef.child("student");
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
ClearAll();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Students student = new Students();
if (snapshot.child("url").getValue() == null) {
student.setImageUrl(snapshot.child("imageUrl").getValue().toString());
} else {
student.setImageUrl(snapshot.child("url").getValue().toString());
}
student.setName(snapshot.child("name").getValue().toString());
if (snapshot.child("age").getValue().toString() != null) {
student.setAge(snapshot.child("age").getValue().toString());
}
if (snapshot.child("Daily Grade").getValue().toString() != null) {
student.setGrade(snapshot.child("Daily Grade").getValue().toString());
}
if (snapshot.child("assignment").getValue().toString() != null) {
student.setAssignment(snapshot.child("assignment").getValue().toString());
}
students.add(student);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
//now student array has the students so we can update the student list
recyclerAdapter.setStudentArrayList(students);
}
public void orderStudents() {
isOrder = true;
Collections.sort(students, new Comparator<Students>() {
@Override
public int compare(Students o1, Students o2) {
return o1.name.compareTo(o2.name);
}
});
//now student is sorted so we can again update student list
recyclerAdapter.setStudentArrayList(students);
}
}

ViewProfile.java

public class ViewProfile extends AppCompatActivity {
Button addStudent;
private DatabaseReference myRef;
ImageButton homeButton;
private EditText mEditTextAge;
private EditText mEditTextAssignment;
public static Students student;
private final String checkIfOrderedClick = "orderedCheck";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_students);
recyclerView = findViewById(R.id.recyclerView);
homeButton = findViewById(R.id.homeButton);
addStudent = findViewById(R.id.addStudentButton);
mEditTextAge = findViewById(R.id.EditTextAge);
mEditTextAssignment = findViewById(R.id.EditTextAssignment);
addStudent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(ViewStudents.this, AddStudent.class));
finish();
}
});
myRef = FirebaseDatabase.getInstance().getReference();
if(getIntent()!=null){
String studentID = getIntent().getStringExtra("STUDENT_ID");
getStudentFromID(studentID);
}
}
private void getStudentFromID(String studentID) {
Query query = myRef.child("student");
CollectionReference collectionReference = FirebaseFirestore.getInstance()
.collection("Student");
Query query = collectionReference.whereEqualTo("studentID", studentID);
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
if (task.getResult().isEmpty()) {
// if you end up here then studentID is not matching with any saved student value
// try to check the studentID
} else {
//found matching student simply setup values
}
} else {
Log.e(TAG, "onComplete: " + task.getException());
}
}
});
}
}

另一种方法可以是传递所选学生的值,并使用它们来更新学生字段。为此,我们需要将回收视图点击监听器更新为

public interface OnItemClickListener {
void onItemClick(Student student, String name, int age, String assignment, String grade);
}

并且ViewStudent活动上的onClickListener将为-

recyclerAdapter.setOnItemClickListener(new RecyclerAdapter.OnItemClickListener() {
@Override
public void onItemClick(Student student, String name, int age, String assignment, String grade) {
//Take selected student ID and pass the ID to ViewProfile Activity
String studentID = student.getID();
Intent viewProf = new Intent(ViewStudents.this, ViewProfile.class);
viewProf.putExtra("STUDENT_ID", studentID);
viewProf.putExtra("STUDENT_NAME", name);
viewProf.putExtra("STUDENT_AGE", age);
viewProf.putExtra("STUDENT_ASSIGNMENT", assignment);
viewProf.putExtra("STUDENT_GRADE", grade);
startActivity(viewProf);
}
});

这样就不需要为所选学生的值查询firebase,但同样需要studentID来保存对学生值的更改。

可能还有很多事情需要注意,比如删除不必要的变量和优化代码,但我想你一定能做到。:(

快乐编码!!

编辑(不同项目被编辑的原因(

您在不同条目中进行编辑的真正原因是,您使用的位置是从firebase而不是StudentID获取文档。Firebase不是SQLite数据库,这意味着它不会像SQL数据库那样维护任何表结构。这就是为什么您永远无法确定哪个文档将位于位置1。同样的解决方案是使用StudentID。

最新更新