我正在尝试制作一个回收列表的讲座,并且使用的数据集存储在SQLite数据库中,我不知道我缺少什么,但列表适配器仍然从列表中记录零计数,因此列表视图没有填充项目
TeacherActivity
import android.annotation.TargetApi;
import android.app.TimePickerDialog;
import android.icu.util.Calendar;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TimePicker;
import android.widget.Toast;
import com.planet.noobs.testproject.Adapters.LecListAdapter;
import com.planet.noobs.testproject.Data.DBHelper;
import com.planet.noobs.testproject.Helpers.InputValidation;
import com.planet.noobs.testproject.Model.Lectures;
import com.planet.noobs.testproject.R;
import java.util.ArrayList;
import java.util.List;
public class TeacherActivity extends AppCompatActivity implements View.OnClickListener {
LecListAdapter listAdapter;
private TextInputEditText editTextSubject;
private TextInputLayout textInputLayoutSubject;
private AppCompatButton buttonTimeSlot;
private AppCompatTextView textViewTime;
private AppCompatButton appCompatButtonSave;
private TimePickerDialog timePickerDialog;
private RecyclerView recyclerViewLec;
private FloatingActionButton fab;
private int mHour, mMinute;
private Lectures lectures;
private InputValidation inputValidation;
private DBHelper dbHelper;
private boolean gotTime = false;
private List<Lectures> lecturesList;
private LinearLayout addLecParent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teacher);
getSupportActionBar();
intiViews();
initListeners();
initObjects();
}
private void intiViews() {
textViewTime = (AppCompatTextView) findViewById(R.id.timeView);
buttonTimeSlot = (AppCompatButton) findViewById(R.id.appCompatButtonTimeSlot);
textInputLayoutSubject = (TextInputLayout) findViewById(R.id.textInputLayoutSubject);
editTextSubject = (TextInputEditText) findViewById(R.id.appCompatEditTextSubject);
appCompatButtonSave = (AppCompatButton) findViewById(R.id.appCompatButtonSave);
recyclerViewLec = (RecyclerView) findViewById(R.id.listview_lectures);
fab = (FloatingActionButton) findViewById(R.id.lec_fab);
addLecParent = (LinearLayout) findViewById(R.id.parent_addlec);
}
private void initListeners() {
appCompatButtonSave.setOnClickListener(this);
buttonTimeSlot.setOnClickListener(this);
fab.setOnClickListener(this);
}
private void initObjects() {
inputValidation = new InputValidation(this);
lectures = new Lectures();
lecturesList = new ArrayList<>();
listAdapter = new LecListAdapter(lecturesList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerViewLec.setLayoutManager(mLayoutManager);
recyclerViewLec.setItemAnimator(new DefaultItemAnimator());
recyclerViewLec.setHasFixedSize(true);
recyclerViewLec.setAdapter(listAdapter);
dbHelper = new DBHelper(getApplicationContext());
refreshItems();
}
private void refreshItems(){
lecturesList.clear();
lecturesList.addAll(dbHelper.getAllLec());
listAdapter.notifyDataSetChanged();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.appCompatButtonTimeSlot:
getTime();
break;
case R.id.appCompatButtonSave:
postDataToDB();
break;
case R.id.lec_fab:
}
}
@TargetApi(Build.VERSION_CODES.N)
public void getTime() {
// Get Current Time
final Calendar c;
c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
textViewTime.setText(new StringBuilder().append(hourOfDay)
.append(" : ")
.append(minute)
.append(getAMPM(hourOfDay)));
textViewTime.setText(textViewTime.getText().toString());
gotTime = true;
}
}, mHour, mMinute, false);
timePickerDialog.show();
}
private String getAMPM(int hourOfDay) {
String format;
if (hourOfDay == 0) {
hourOfDay += 12;
format = "AM";
} else if (hourOfDay == 12) {
format = "PM";
} else if (hourOfDay > 12) {
hourOfDay -= 12;
format = "PM";
} else {
format = "AM";
}
return format;
}
private void postDataToDB() {
if (!inputValidation.isInputEditTextSubject(editTextSubject, textInputLayoutSubject, "Enter the subject first.")) {
return;
}
if (!gotTime) {
Snackbar.make(recyclerViewLec, "Please select the time", Snackbar.LENGTH_LONG).show();
return;
}
lectures.setLecTitle(editTextSubject.getText().toString().trim());
lectures.setLecDateTime(textViewTime.getText().toString());
dbHelper.addLec(lectures);
emptyEditText();
Toast.makeText(this, "Lecture added", Toast.LENGTH_LONG).show();
}
private void emptyEditText(){
editTextSubject.setText(null);
textViewTime.setText(null);
}
}
LecListAdapter
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.planet.noobs.testproject.Model.Lectures;
import com.planet.noobs.testproject.R;
import java.util.List;
public class LecListAdapter extends RecyclerView.Adapter<LecListAdapter.LecViewHolder> {
private List<Lectures> mlec;
public LecListAdapter(List<Lectures> mlec) {
this.mlec = mlec;
}
@Override
public LecViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.teacher_lec_item, parent, false);
return new LecViewHolder(itemView);
}
@Override
public void onBindViewHolder(LecViewHolder holder, int position) {
holder.textViewLecTime.setText(mlec.get(position).toString());
holder.textViewSub.setText(mlec.get(position).toString());
}
@Override
public int getItemCount() {
Log.v(LecListAdapter.class.getSimpleName(), String.valueOf(mlec.size()));
return mlec.size();
}
public class LecViewHolder extends RecyclerView.ViewHolder {
private AppCompatTextView textViewSub;
private AppCompatTextView textViewLecTime;
//private TextView emptyView;
public LecViewHolder(View itemView) {
super(itemView);
//emptyView = (TextView) itemView.findViewById(R.id.emptyView);
textViewSub = (AppCompatTextView) itemView.findViewById(R.id.lec_title);
textViewLecTime = (AppCompatTextView) itemView.findViewById(R.id.lec_time);
}
}
}
DbHelper.java
public class DBHelper extends SQLiteOpenHelper {
public static final String LOG_TAG = "SQL ";
//databse version
private static final int DATABASE_VERSION = 1;
//database name
private static final String DATABASE_NAME = "UserManager.db";
//table name
private static final String TABLE_STUDENT = "student";
//column's name
private static final String COLUMN_USER_ID = "user_id";
private static final String COLUMN_USER_NAME = "user_name";
private static final String COLUMN_CONTACT = "user_contact";
private static final String COLUMN_USER_EMAIL = "user_email";
private static final String COLUMN_USER_PASSWORD = "user_password";
//create table query
private static final String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_STUDENT + "(" +
COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_USER_NAME + " TEXT, " +
COLUMN_CONTACT + " NUMBER, " +
COLUMN_USER_EMAIL + " TEXT, " +
COLUMN_USER_PASSWORD + " TEXT" + ")";
//DROP TABLE IF EXISTS
private static final String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_STUDENT;
//Column's name for Books
/*
private static final String TABLE_BOOKS = "books";
private static final String COLUMN_BOOK_ID = "user_id";
private static final String COLUMN_BOOK_TITLE = "book_title";
private static final String COLUMN_BOOK_DESC = "book_desc";
private static final String COLUMN_BOOK_ISSUE_DATE = "book_issue_date";
private static final String CREATE_BOOK_TABLE = "CREATE TABLE "+ TABLE_BOOKS + "(" +
COLUMN_BOOK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+ COLUMN_BOOK_ID +
" Text, "+ COLUMN_BOOK_TITLE + " Text, " + COLUMN_BOOK_ISSUE_DATE + " Text, " +
COLUMN_BOOK_DESC + " Text" + ")";
private static final String DROP_BOOKS_TABLE = "DROP TABLE IF EXISTS " + TABLE_BOOKS;
*/
// Columns name for lectures table
// Table name
private static final String TABLE_LECTURES = "lectures";
private static final String COLUMN_LEC_ID = "lec_id";
private static final String COLUMN_LEC_SUBJECT = "subject";
private static final String COLUMN_TIME = "lec_time";
private static final String CREATE_LECTURES_TABLE = "CREATE TABLE " + TABLE_LECTURES + "(" +
COLUMN_LEC_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_LEC_SUBJECT + " TEXT, " +
COLUMN_TIME + " TEXT" + ")";
private static final String DROP_LECTURES_TABLE = "DROP TABLE IF EXISTS " + TABLE_LECTURES;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
db.execSQL(CREATE_LECTURES_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// drop student table if exist
/*
db.execSQL(DROP_USER_TABLE);
db.execSQL(DROP_LECTURES_TABLE);
*/
onCreate(db);
}
// Lectures helper methods
public void addLec(Lectures lectures) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_LEC_SUBJECT, lectures.getLecTitle());
values.put(COLUMN_TIME, lectures.getLecDateTime());
db.insert(TABLE_LECTURES, null, values);
Log.v(DBHelper.class.getSimpleName(),"addlec() is Working!");
db.close();
}
public List getAllLec() {
String[] COLUMNS = {
COLUMN_LEC_SUBJECT,
COLUMN_TIME
};
List<Lectures> lecList = new ArrayList<Lectures>();
String sortOrder = COLUMN_LEC_SUBJECT + " ASC";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
TABLE_LECTURES,
COLUMNS,
null,
null,
null,
null,
sortOrder);
if (cursor.moveToFirst()) {
do {
Lectures lec = new Lectures();
lec.setLecTitle(cursor.getString(cursor.getColumnIndex(COLUMN_LEC_SUBJECT)));
lec.setLecDateTime(cursor.getString(cursor.getColumnIndex(COLUMN_TIME)));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return lecList;
}
public List getAllUser() {
//columns to be fetched
String[] columns = {
COLUMN_USER_ID,
COLUMN_USER_EMAIL,
COLUMN_CONTACT,
COLUMN_USER_NAME,
COLUMN_USER_PASSWORD
};
SQLiteDatabase db = this.getReadableDatabase();
List<User> userList = new ArrayList<User>();
String sortOrder = COLUMN_USER_NAME + " ASC";
Cursor cursor = db.query(
TABLE_STUDENT,
columns,
null,
null,
null,
null,
sortOrder
);
if (cursor.moveToFirst()) {
do {
User user = new User();
user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(COLUMN_USER_ID))));
user.setName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_NAME)));
user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL)));
user.setContact(Long.parseLong(cursor.getString(cursor.getColumnIndex(COLUMN_CONTACT))));
user.setPasswd(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PASSWORD)));
userList.add(user);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return userList;
}
// user helpers
public void addUser(User user) {
//open database with write permission
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_NAME, user.getName());
values.put(COLUMN_USER_EMAIL, user.getEmail());
values.put(COLUMN_USER_PASSWORD, user.getPasswd());
values.put(COLUMN_CONTACT, user.getContact());
db.insert(TABLE_STUDENT, null, values);
db.close();
}
/**
* This method is to delete user record
*
* @param user
*/
public void deleteUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
// delete user record by id
db.delete(TABLE_STUDENT, COLUMN_USER_ID + " = ?",
new String[]{String.valueOf(user.getId())});
db.close();
}
public boolean checkUser(String email) {
//columns to be fetched
String[] columns = {
COLUMN_USER_ID
};
SQLiteDatabase db = this.getReadableDatabase();
//selection criteria in where clause
String selection = COLUMN_USER_EMAIL + " = ?";
//selection arguments
String[] selection_arg = {
email
};
Cursor cursor = db.query(
TABLE_STUDENT, // table name
columns, // columns to return
selection, // Where clause selection
selection_arg, //Where clause selection value
null,
null,
null
);
int count = cursor.getCount();
cursor.close();
db.close();
return count > 0;
}
public boolean checkUser(String email, String passwd) {
//columns to be fetched
String[] columns = {
COLUMN_USER_ID
};
SQLiteDatabase db = this.getReadableDatabase();
//selection criteria in where clause
String selection = COLUMN_USER_EMAIL + " = ?" + " AND " + COLUMN_USER_PASSWORD + " = ?";
//selection arguments
String[] selection_arg = {
email,
passwd
};
Cursor cursor = db.query(
TABLE_STUDENT, // table name
columns, // columns to return
selection, // Where clause selection
selection_arg, //Where clause selection value
null,
null,
null
);
int count = cursor.getCount();
cursor.close();
db.close();
return count > 0;
}
}
activity_teacher.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/parent_addlec"
android:layout_width="match_parent"
android:layout_height="120dp"
android:orientation="vertical"
android:padding="10dp"
>
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayoutSubject"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="@+id/appCompatEditTextSubject"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Add Lectures"
android:inputType="text"
android:maxLength="15"
android:maxLines="1"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<android.support.v7.widget.AppCompatTextView
android:id="@+id/timeView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="4dp"
android:layout_marginStart="4dp"
android:layout_weight="1"
android:textSize="20sp" />
<android.support.v7.widget.AppCompatButton
android:id="@+id/appCompatButtonTimeSlot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Time Slot" />
<android.support.v7.widget.AppCompatButton
android:id="@+id/appCompatButtonSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save" />
</LinearLayout>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#ccc" />
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:gravity="center_vertical"
android:text="Lectures Today"
android:textAlignment="center"
android:textSize="25sp"
android:textStyle="bold" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/listview_lectures"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/lec_fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@id/listview_lectures"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_margin="@dimen/fab_margin"
android:src="@drawable/ic_plus" />
</RelativeLayout>
</LinearLayout>
答案 0 :(得分:0)
您将空白列表传递到适配器中,先填充LIST
,然后使用setAdapter方法。
lecturesList = new ArrayList<>();
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerViewLec.setLayoutManager(mLayoutManager);
recyclerViewLec.setItemAnimator(new DefaultItemAnimator());
recyclerViewLec.setHasFixedSize(true);
dbHelper = new DBHelper(getApplicationContext());
refreshItems();
//setAdapter in last after put data into list.
listAdapter = new LecListAdapter(lecturesList);
recyclerViewLec.setAdapter(listAdapter);