我尽力解决这个问题,但它仍然给我一个错误。希望有人在这里帮助我。我不知道代码中的问题是什么。
public class StudentListActivity extends AppCompatActivity implements View.OnClickListener {
private View scanqr, viewqr;
final Context context = this;
private ListView studentlist;
private DatabaseReference mDatabase, mDatabase1;
private ArrayList<String> mUsername = new ArrayList<>();
private ArrayList<String> mUserId = new ArrayList<>();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String message, qrcodevalue, selectedItem, value, values;
private IntentIntegrator qrScan;
private DatabaseReference ref, ref0, ref1;
private FirebaseAuth.AuthStateListener authListener;
private FirebaseAuth auth;
LstViewAdapter1 adapter;
private String value3;
private EditText inputSearch;
ArrayAdapter<String> arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_list);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
scanqr = findViewById(R.id.scanqr);
//viewqr = findViewById(R.id.viewqr);
studentlist = (ListView) findViewById(R.id.studentlist);
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.setVisibility(View.GONE);
message = getIntent().getStringExtra("secname").toString(); // Now, message has Drawer title
setTitle(message);
//get firebase auth instance
auth = FirebaseAuth.getInstance();
//get current user
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
authListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull final FirebaseAuth firebaseAuth) {
final FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// user auth state is changed - user is null
// launch login activity
} else {
//user auth state is not existed or closed, return to Login activity
startActivity(new Intent(StudentListActivity.this, LoginActivity.class));
finish();
}
}
};
//intializing scan object
qrScan = new IntentIntegrator(this);
//attaching onclick listener
scanqr.setOnClickListener(this);
adapter= new LstViewAdapter1(this, R.layout.listitem1,R.id.id, mUsername, mUserId);
studentlist.setAdapter(adapter);
mDatabase = FirebaseDatabase.getInstance().getReference().child("users").child("teacher").child(user.getUid().toString().trim()).child("class").child(message).child("Listofstudents");
mDatabase.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
value = dataSnapshot.getKey().toString().trim();
mUserId.add(value);
ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").child("student").child(value).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value0 = dataSnapshot.child("firstname").getValue().toString().trim();
String value1 = dataSnapshot.child("middlename").getValue().toString().trim();
String value2 = dataSnapshot.child("lastname").getValue().toString().trim();
mUsername.add(value0+" "+value1+" "+value2);
studentlist.invalidateViews();
adapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
studentlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedItem = (String) parent.getItemAtPosition(position);
TextView userId=(TextView) view.findViewById(R.id.id);
TextView userName=(TextView) view.findViewById(R.id.txt);
String name = userName.getText().toString().trim();
String uid = userId.getText().toString().trim();
Intent intent = new Intent(StudentListActivity.this, StudentAttendanceDetailsActivity.class);
intent.putExtra("name", name);
intent.putExtra("secsub", uid);
startActivity(intent);
}
});
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
adapter.getFilter().filter(cs.toString()); }
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
if (id == R.id.refresh) {
restartThis();
//Do something
return true;
} else if (id == R.id.add) { //<------- CODE FOR BUTTON IN ADDING STUDENT
Intent intent = new Intent(StudentListActivity.this, AddsStudentActivity.class);
intent.putExtra("secname", message);
intent.putExtra("arraylist", mUsername);
intent.putExtra("useridvalue", mUserId);
startActivity(intent);
return true;
} else if (id == R.id.search) {
inputSearch.setVisibility(View.VISIBLE);
inputSearch.requestFocus();
return true;
} else if (id == R.id.view) {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try {
qrcodevalue = "{"+"\"userid\""+":"+"\""+user.getUid().toString().trim()+"\""+","+"\"secsub\""+":"+"\""+message+"\""+"}";
Intent intent = new Intent(StudentListActivity.this, GenerateQrCodeActivity.class);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
BitMatrix bitMatrix = multiFormatWriter.encode(qrcodevalue, BarcodeFormat.QR_CODE,500,500);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bytes = stream.toByteArray();
intent.putExtra("bitmap",bytes);
startActivity(intent);
} catch (WriterException e) {
e.printStackTrace();
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
//Getting the scan results
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
String content = result.getContents();
if (result != null && resultCode == RESULT_OK) {
//if qrcode has nothing in it
if (content == null || content =="") {
Toast.makeText(this, "Result Not Found", Toast.LENGTH_SHORT).show();
} else if (!content.contains("useridcontent")) {
Toast.makeText(this, "Unregistered QR Code", Toast.LENGTH_SHORT).show();
} else {
//if qr contains data
try {
//converting the data to json
JSONObject obj = new JSONObject(result.getContents());
//setting values to textviews
final String qrcodecontent = obj.getString("useridcontent");
final String date = new SimpleDateFormat("MMM d, yyyy").format(new Date());
final String datetime = DateFormat.getDateTimeInstance().format(new Date());
ref1 = FirebaseDatabase.getInstance().getReference();
ref1.child("users").child("teacher").child(user.getUid().toString().trim()).child("class").child(message).child("Listofstudents").child(qrcodecontent).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
ref1 = FirebaseDatabase.getInstance().getReference();
ref1.child("users").child("teacher").child(user.getUid().toString().trim()).child("class").child(message).child("Listofstudents").child(qrcodecontent).child("attendance").child(date).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Toast.makeText(StudentListActivity.this, "Your already took attendance", Toast.LENGTH_SHORT).show();
} else {
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("users").child("teacher").child(user.getUid().toString().trim()).child("class").child(message).child("Listofstudents").child(qrcodecontent).child("attendance").child(date);
mDatabase.child("date&time").setValue(datetime);
mDatabase.child("status").setValue("present");
Toast.makeText(StudentListActivity.this, "Time come in: "+datetime, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
android.support.v7.app.AlertDialog.Builder builder2=new android.support.v7.app.AlertDialog.Builder(StudentListActivity.this);
builder2.setTitle("Add Student");
builder2.setMessage("This student is not yet added in this class"+"\n"+"\n"+"Add this student in this class?");
builder2.setIcon(R.drawable.add);
builder2.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DatabaseReference mDatabase1 = FirebaseDatabase.getInstance().getReference().child("users").child("teacher").child(user.getUid().toString().trim()).child("class").child(message).child("Listofstudents").child(qrcodecontent);
mDatabase1.child("date&timejoin").setValue(datetime);
DatabaseReference mDatabase2 = FirebaseDatabase.getInstance().getReference().child("users").child("teacher").child(user.getUid().toString().trim()).child("class").child(message).child("Listofstudents").child(qrcodecontent).child("attendance").child(date);
mDatabase2.child("date&time").setValue(datetime);
mDatabase2.child("status").setValue("present");
}
});
builder2.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
android.support.v7.app.AlertDialog dialog = builder2.show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Toast.makeText(this, obj.getString("userid")+obj.getString("secsub"), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
//if control comes here
//that means the encoded format not matches
//in this case you can display whatever data is available on the qrcode
//to a toast
Toast.makeText(this, result.getContents(), Toast.LENGTH_LONG).show();
}
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public void onClick(View view) {
//initiating the qr code scan
qrScan.initiateScan();
}
private void restartThis() {
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
overridePendingTransition(0, 0);
}
private static void doKeepDialog(Dialog dialog){
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
dialog.getWindow().setAttributes(lp);
}
class LstViewAdapter1 extends BaseAdapter implements Filterable {
private Context context;
private int resource;
private int ids;
private ArrayList arrayList;
private List<String> originalData=null;
private List<String>filteredData=null;
List<String> title;;
private FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
private LstViewAdapter1.ItemFilter mFilter = new LstViewAdapter1.ItemFilter();
private LayoutInflater inflater;
public LstViewAdapter1(Context context, int resource, int id, ArrayList title, ArrayList userId){
this.context = context;
this.resource = resource;
this.ids = id;
this.title = title;
this.arrayList = userId;
this.filteredData = userId ;
this.originalData = userId ;
inflater = LayoutInflater.from(context);
}
public int getCount() {
return filteredData.size();
}
public Object getItem(int position) {
return filteredData.get(position);
}
public long getItemId(int position) {
return position;
}
// Hold views of the ListView to improve its scrolling performance
private class ViewHolder {
public TextView type;
public TextView uid;
public ImageButton removeButton;
}
public View getView(final int position, final View convertView, ViewGroup parent) {
View rowView = convertView;
// Inflate the list_item.xml file if convertView is null
if(rowView==null){
rowView = inflater.inflate(R.layout.listitem, null);
rowView= inflater.inflate(resource, parent, false);
LstViewAdapter1.ViewHolder viewHolder = new LstViewAdapter1.ViewHolder();
viewHolder.type= (TextView) rowView.findViewById(R.id.txt);
viewHolder.uid= (TextView) rowView.findViewById(R.id.id);
viewHolder.removeButton= (ImageButton) rowView.findViewById(btn_del);
rowView.setTag(viewHolder);
}
final String x = (String) arrayList.get(position);
final String y = arrayList.get(position).toString().trim();
// Set text to each TextView of ListView item
LstViewAdapter1.ViewHolder holder = (LstViewAdapter1.ViewHolder) rowView.getTag();
holder.uid.setText(x);
holder.removeButton.setBackgroundResource(R.drawable.deletes);
holder.removeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
final AlertDialog.Builder builder2=new AlertDialog.Builder(context);
final View dialogView = inflater.inflate(R.layout.customdialog, null);
builder2.setView(dialogView);
final EditText input = (EditText) dialogView.findViewById(R.id.edit1);
final TextInputLayout inputs = (TextInputLayout) dialogView.findViewById(R.id.text_field);
TextWatcher watcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
inputs.setErrorEnabled(false);
inputs.setError(null);
}
};
input.addTextChangedListener(watcher);
builder2.setTitle("Delete Class");
builder2.setMessage("Do you want to delete "+y+" from this class?");
builder2.setPositiveButton("ok", null);
builder2.setNegativeButton("cancel", null);
builder2.setIcon(R.drawable.deletes);
final AlertDialog mAlertDialog = builder2.create();
mAlertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(final DialogInterface dialog) {
Button a = mAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
a.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// TODO Do something
if (input.getText().toString().equalsIgnoreCase("delete")) {
arrayList.remove(position);
notifyDataSetChanged();
Toast.makeText(v.getContext(), y + " has been deleted in this class", Toast.LENGTH_SHORT).show();
ref0 = FirebaseDatabase.getInstance().getReference();
ref0.child("users").child("student").orderByChild("name").equalTo(y).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
String hello = child.getKey();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("users").child("teacher").child(user.getUid().toString().trim()).child("class").child(message).child("Listofstudents").child(hello);
mDatabase.setValue(null);
dialog.dismiss();
notifyDataSetChanged();
restartThis();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
inputs.setError("Enter word \"DELETE\"");
}
}
});
Button b = mAlertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// TODO Do something
dialog.dismiss();
}
});
}
});
mAlertDialog.show();
}
});
holder.type.setText(title.get(position));
holder.uid.setText(filteredData.get(position));
return rowView;
}
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<String> list = originalData;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
}
}
这是发生错误的部分。
答案 0 :(得分:0)
您的问题从此时开始:title
因为标题为空
=&GT;试着找出它为什么空=&gt; LstViewAdapter1
是来自public LstViewAdapter1(Context context, int resource, int id, ArrayList title, ArrayList userId)
adapter= new LstViewAdapter1(this, R.layout.listitem1,R.id.id, mUsername, mUserId);
=&GT;您的构造函数来自:title
=&gt;与mUsername
对应的是mUsername
=&GT;在使用ArrayList
时,您只需要mUsername
,但不要在其中添加任何值,以免造成错误。
我看到你为mUsername
增加了价值,但在你身后使用它。请更改您的代码:在尝试使用之前将值添加到items = [{key: 1, name: 'name1'}, {key: 2, name: 'name2'}, ... ]
。