在第一次启动应用程序时,RecyclerView不会显示

时间:2018-01-23 07:42:06

标签: java android sqlite android-recyclerview android-volley

我的应用程序中有一个recyclerView,其中数据从Web服务器获取并存储在本地数据库中,然后从本地数据库填充该列表。 但是,在清除数据后启动应用程序。列表没有填充,但是当我关闭应用程序并再次打开它时会显示该列表。 数据在第一次启动时插入数据库。但是它没有显示在recyclerView中。

以下是代码:

Database.java:

void addEmployeeIfNotExistsToDatabase(Employee employee){
    SQLiteDatabase database = this.getWritableDatabase();

    String CHECK_EXISTENCE_EMPLOYEE_QUERY = "SELECT id FROM " + TABLE_EMPLOYEES + ";";
    Cursor existChecker = database.rawQuery(CHECK_EXISTENCE_EMPLOYEE_QUERY, null);

    int existFlag = 0;

    if(existChecker.moveToFirst()){
        do {
            if((existChecker.getInt(existChecker.getColumnIndex("id"))) == (employee.getId())){
                existFlag = 1;
            }
        }while (existChecker.moveToNext());
    }
    existChecker.close();

    if (existFlag == 0){
        //DLog.e("Yes", "Being added");
        ContentValues contentValues = new ContentValues();

        contentValues.put("id", employee.getId());
        contentValues.put("firstName", employee.getName().split(" ")[0].trim());
        contentValues.put("lastName", employee.getName().split(" ")[1].trim());
        contentValues.put("dateOfBirth", String.valueOf(employee.getDateOfBirth()));
        contentValues.put("joinDate", String.valueOf(employee.getJoinDate()));
        contentValues.put("gender", employee.getGender());
        contentValues.put("emailId", employee.getEmailId());
        contentValues.put("contactNo", employee.getContactNo());
        contentValues.put("alternateContactNo", employee.getAlternateContactNo());
        contentValues.put("bloodGroup", employee.getBloodGroup());
        contentValues.put("experience", employee.getExperience());
        contentValues.put("status", employee.getStatus());
        contentValues.put("designation", employee.getDesignation());
        contentValues.put("temporaryAddressLine1", employee.getTemporaryAddressLine1());
        contentValues.put("temporaryAddressLine2", employee.getTemporaryAddressLine2());
        contentValues.put("temporaryAddressStateId", employee.getTemporaryAddressStateId());
        contentValues.put("temporaryAddressCityId", employee.getTemporaryAddressCityId());
        contentValues.put("temporaryAddressPincode", employee.getTemporaryAddressPincode());
        contentValues.put("permanentAddressLine1", employee.getPermanentAddressLine1());
        contentValues.put("permanentAddressLine2", employee.getPermanentAddressLine2());
        contentValues.put("permanentAddressStateId", employee.getPermanentAddressStateId());
        contentValues.put("permanentAddressCityId", employee.getPermanentAddressCityId());
        contentValues.put("permanentAddressPincode", employee.getPermanentAddressPincode());
        contentValues.put("profilePicture", employee.getProfilePicture());
        contentValues.put("userName", employee.getUserName());
        contentValues.put("checkedIn", employee.getCheckedIn());

        Log.e("checkout", String.valueOf(employee.getCheckedOut()));

        contentValues.put("checkedOut", employee.getCheckedOut());

        database.insert(TABLE_EMPLOYEES, null, contentValues);
    }
    database.close();
}

ListActivity.java:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list);
    employee_recycler = findViewById(R.id.recycler_view);
    searchqr = findViewById(R.id.search_emp);
    search = findViewById(R.id.searchbtn);

    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    employee_recycler.setLayoutManager(mLayoutManager);

    database = new Database(getApplicationContext());

    employeeList = new ArrayList<>();
    employeeAdapter = new EmployeeAdapter(getApplicationContext(), new ArrayList<Employee>(), this);
    listener = this;

    employee_recycler.setAdapter(employeeAdapter);

    getLoaderManager().initLoader(1, null, this).forceLoad();
}
@Override
public Loader<List<Employee>> onCreateLoader(int id, Bundle args) {
    return new EmployeeLoader(ListActivity.this);
}

@Override
public void onLoadFinished(Loader<List<Employee>> loader, List<Employee> data) {
    employeeAdapter.setEmployees(data);
}

@Override
public void onLoaderReset(Loader<List<Employee>> loader) {
    employeeAdapter.setEmployees(new ArrayList<Employee>());
}

EmployeeAdapter.java:

public class EmployeeAdapter extends RecyclerView.Adapter<EmployeeAdapter.MyViewHolder>{

private Context context;
private List<Employee> employeeListFiltered = new ArrayList<>();
private EmployeeAdapterListener listener;

class MyViewHolder extends RecyclerView.ViewHolder {
    TextView employeeName, employeeId;
    CircleImageView employeeImage;

    MyViewHolder(View itemView) {
        super(itemView);
        employeeName = itemView.findViewById(R.id.name_emp);
        employeeId = itemView.findViewById(R.id.id_emp);
        employeeImage = itemView.findViewById(R.id.img_emp);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onEmployeeSelected(employeeListFiltered.get(getAdapterPosition()));
            }
        });

        Button checkBtn = itemView.findViewById(R.id.checkbtn);

        checkBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onEmployeeSelected(employeeListFiltered.get(getAdapterPosition()));
                Toast.makeText(context, "Punch button clicked", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

public void setEmployees(List<Employee> data) {
    employeeListFiltered.addAll(data);
    notifyDataSetChanged();
}

EmployeeAdapter(Context context, List<Employee> employeeList, EmployeeAdapterListener listener){
    this.context = context;
    this.listener = listener;
    this.employeeListFiltered = employeeList;
}

@Override
public EmployeeAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.employee_element, parent, false);
    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(EmployeeAdapter.MyViewHolder holder, int position) {
    final Employee employee = employeeListFiltered.get(position);
    holder.employeeName.setText(employee.getName());
    holder.employeeId.setText(employee.getUserName());

    //Get status and check with button

    Glide.with(context)
            .load(employee.getProfilePicture())
            .apply(new RequestOptions().placeholder(R.drawable.placeholder_image).error(R.drawable.placeholder_image))
            .into(holder.employeeImage);
}

@Override
public int getItemCount() {
    return employeeListFiltered.size();
}

void filterList(ArrayList<Employee> filteredEmployeeNames) {
    this.employeeListFiltered = filteredEmployeeNames;
    notifyDataSetChanged();
}

public interface EmployeeAdapterListener {
    void onEmployeeSelected(Employee employee);
}

}

EmployeeLoader.java:

public class EmployeeLoader extends AsyncTaskLoader<List<Employee>> {

private Database database;
private Context localContext;
private static final String LOCAL_URL = "http://192.168.1.33:3369/api/v1/employees/c6c2f463db4cb59a6e8bd62783a9f063";

EmployeeLoader(Context context) {
    super(context);
    localContext = context;
    database = new Database(context);
}

@Override
protected void onStartLoading() {
    super.onStartLoading();
}

@Override
public List<Employee> loadInBackground() {
    Log.e("Loader", "Loading in background");
    RequestQueue requestQueue = Volley.newRequestQueue(localContext);
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, LOCAL_URL, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            try {
                Log.e("GET request", response.toString());
                JSONObject allEmployees = response.getJSONObject("data");

                Iterator<String> keys = allEmployees.keys();
                while (keys.hasNext()) {
                    String key = keys.next();
                    JSONObject employee = allEmployees.getJSONObject(key);
                    Employee singleEmployee = new Employee();

                    singleEmployee.setId(Integer.parseInt(employee.getString("id")));
                    singleEmployee.setName(employee.getString("firstName") + " " + employee.getString("lastName"));
                    singleEmployee.setDateOfBirth(java.sql.Date.valueOf(employee.getString("dateOfBirth")));
                    singleEmployee.setJoinDate(java.sql.Date.valueOf(employee.getString("joinDate")));
                    singleEmployee.setGender(employee.getString("gender"));
                    singleEmployee.setEmailId(employee.getString("emailId"));
                    singleEmployee.setContactNo(employee.getString("contactNo"));
                    singleEmployee.setAlternateContactNo(employee.getString("alternateContactNo"));
                    singleEmployee.setBloodGroup(employee.getString("bloodGroup"));
                    singleEmployee.setExperience(Float.parseFloat(employee.getString("experience")));
                    singleEmployee.setStatus(employee.getString("status"));
                    singleEmployee.setDesignation(employee.getString("designation"));
                    singleEmployee.setTemporaryAddressLine1(employee.getString("temporaryAddressLine1"));
                    singleEmployee.setTemporaryAddressLine2(employee.getString("temporaryAddressLine2"));
                    singleEmployee.setTemporaryAddressStateId(employee.getString("temporaryAddressStateId"));
                    singleEmployee.setTemporaryAddressCityId(employee.getString("temporaryAddressCityId"));
                    singleEmployee.setTemporaryAddressPincode(employee.getString("temporaryAddressPincode"));
                    singleEmployee.setPermanentAddressLine1(employee.getString("permanentAddressLine1"));
                    singleEmployee.setPermanentAddressLine2(employee.getString("permanentAddressLine2"));
                    singleEmployee.setPermanentAddressStateId(employee.getString("permanentAddressStateId"));
                    singleEmployee.setPermanentAddressCityId(employee.getString("permanentAddressCityId"));
                    singleEmployee.setPermanentAddressPincode(employee.getString("permanentAddressPincode"));
                    singleEmployee.setProfilePicture(employee.getString("profilePicture"));
                    singleEmployee.setUserName(employee.getString("userName"));
                    singleEmployee.setCheckedIn(Integer.parseInt(employee.getString("isCheckedIn")));
                    singleEmployee.setCheckedOut(Integer.parseInt(employee.getString("isCheckedOut")));

                    database.addEmployeeIfNotExistsToDatabase(singleEmployee);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Error", error.getMessage());
        }
    });

    requestQueue.add(jsonObjReq);
    return database.populateListFromDatabase();
}

}

2 个答案:

答案 0 :(得分:3)

您有很多选择来解决此问题。

  • 您可以使用AsyncTask onPostExecute方法填充Recycler view
  • 您可以使用活动生命周期方法填充Recycler viewonStart, onPause ...)。
  • 您可以设置启动画面并在启动画面中获取数据,然后当数据显示在第二个Activity时。< / LI>

答案 1 :(得分:2)

在加载器内的try catch块中。我添加了finally块并使用deliverResult(database.populateListFromDatabase())即使在第一次启动时也更新了用户界面。