This is the updated code for my RececlerView to show data in my SQLite Database but still I cant make the data to show in my recycler view but there is no errors in my app.
The applications only show "No API Data" which is from this part of my code.
Toast.makeText(this, "No API Data", Toast.LENGTH_SHORT).show();
I will show you the codes.
This is a part of my DatabaseHelper the method on Listing the data in myDatabase for RecyclerView.
public boolean checkUser(String email) {
// array of columns to fetch
String[] columns = {
Timerecordshelper.BeneficiaryEntry._ID
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = Timerecordshelper.BeneficiaryEntry.COL_1 + " = ?";
// selection argument
String[] selectionArgs = {email};
// query user table with condition
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id FROM user WHERE user_email = 'test#gmail.com';
*/
Cursor cursor = db.query(Timerecordshelper.BeneficiaryEntry.TABLE_NAME_IN, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
public List<TimeinData> getAllTimeinData() {
// array of columns to fetch
String[] columns = {
Timerecordshelper.BeneficiaryEntry.COL_1,
Timerecordshelper.BeneficiaryEntry.COL_2,
Timerecordshelper.BeneficiaryEntry.COL_3,
Timerecordshelper.BeneficiaryEntry.COL_4,
Timerecordshelper.BeneficiaryEntry.COL_5,
};
// sorting orders
String sortOrder =
Timerecordshelper.BeneficiaryEntry.COL_1 + " ASC";
List<TimeinData> TimeList = new ArrayList<TimeinData>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Timerecordshelper.BeneficiaryEntry.TABLE_NAME_IN, //Table to query
columns, //columns to return
null, //columns for the WHERE clause
null, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
sortOrder); //The sort order
// Traversing through all rows and adding to list
if (cursor.moveToFirst()) {
do {
TimeinData Timerecords = new TimeinData();
Timerecords.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Timerecordshelper.BeneficiaryEntry.COL_1))));
Timerecords.setIn(cursor.getString(cursor.getColumnIndex(Timerecordshelper.BeneficiaryEntry.COL_2)));
Timerecords.setCustomer(cursor.getString(cursor.getColumnIndex(Timerecordshelper.BeneficiaryEntry.COL_3)));
Timerecords.setBranch(cursor.getString(cursor.getColumnIndex(Timerecordshelper.BeneficiaryEntry.COL_4)));
Timerecords.setMachine(cursor.getString(cursor.getColumnIndex(Timerecordshelper.BeneficiaryEntry.COL_5)));
// Adding user record to list
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return user list
return TimeList;
}
TimeinRecyclerAdapter.java
package com.example.serviceapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class TimeinRecyclerAdapter extends
RecyclerView.Adapter<TimeinRecyclerAdapter.BeneficiaryViewHolder> {
private ArrayList<TimeinData> listBeneficiary;
public ImageView overflow;
private Context mContext;
private ArrayList<TimeinData> mFilteredList;
public TimeinRecyclerAdapter(ArrayList<TimeinData> listBeneficiary, Context
mContext) {
this.listBeneficiary = listBeneficiary;
this.mContext = mContext;
this.mFilteredList = listBeneficiary;
}
public class BeneficiaryViewHolder extends RecyclerView.ViewHolder {
public AppCompatTextView textViewName;
public AppCompatTextView textViewEmail;
public AppCompatTextView textViewAddress;
public AppCompatTextView textViewCountry;
public BeneficiaryViewHolder(View view) {
super(view);
textViewName = view.findViewById(R.id.textViewName);
textViewEmail = view.findViewById(R.id.textViewEmail);
textViewAddress = view.findViewById(R.id.textViewAddress);
textViewCountry = view.findViewById(R.id.textViewCountry);
}
}
#Override
public BeneficiaryViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
// inflating recycler item view
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_timeinrecycler, parent, false);
return new BeneficiaryViewHolder(itemView);
}
#Override
public void onBindViewHolder(final BeneficiaryViewHolder holder, int
position) {
holder.textViewName.setText(listBeneficiary.get(position).getId());
holder.textViewName.setText(listBeneficiary.get(position).getIn());
holder.textViewEmail.setText(listBeneficiary.get(position).getCustomer());
holder.textViewAddress.setText(listBeneficiary.get(position).getBranch());
holder.textViewCountry.setText(listBeneficiary.get(position).getMachine());
}
#Override
public int getItemCount() {
return mFilteredList.size();
}
}
Timerecordshelper.java
package com.example.serviceapplication;
import android.provider.BaseColumns;
public class Timerecordshelper {
public static final class BeneficiaryEntry implements BaseColumns {
public static final String TABLE_NAME_IN = "TABLE_NAME_IN";
public static final String COL_1 = "Job ID";
public static final String COL_2 = "Time In";
public static final String COL_3 = "Customer:";
public static final String COL_4 = "Branch";
public static final String COL_5 = "Machine";
}
}
This codes acts as the gettersetter for my Recycleview to get data in SQLite.
TimeinData.java
package com.example.serviceapplication;
public class TimeinData {
private int id;
private String In;
private String Customer;
private String Branch;
private String Machine;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIn() {
return In;
}
public void setIn(String In) {
this.In = In;
}
public String getCustomer() {
return Customer;
}
public void setCustomer(String Customer) {
this.Customer = Customer;
}
public String getBranch() {
return Branch;
}
public void setBranch(String Branch) {
this.Branch = Branch;
}
public String getMachine() {
return Machine;
}
public void setMachine(String Machine) {
this.Machine = Machine;
}
}
TimerecordsListActivity.java
package com.example.serviceapplication;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SearchView;
import android.widget.Toast;
import android.widget.Toolbar;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class TimerecordsListActivty extends AppCompatActivity {
private AppCompatActivity activity = TimerecordsListActivty.this;
Context context = TimerecordsListActivty.this;
private RecyclerView recyclerViewBeneficiary;
private ArrayList<TimeinData> listBeneficiary;
private TimeinRecyclerAdapter beneficiaryRecyclerAdapter;
private DatabaseHelper databaseHelper;
SearchView searchBox;
private ArrayList<TimeinData> filteredList;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeinrec);
initViews();
initObjects();
Intent intentThatStartedThisActivity = getIntent();
if (intentThatStartedThisActivity.hasExtra("Job ID")) {
//get all needed extras intent
int id = getIntent().getExtras().getInt("ID");
String in = getIntent().getExtras().getString("Time In");
String customer = getIntent().getExtras().getString("Customer");
String branch = getIntent().getExtras().getString("Branch");
String machine = getIntent().getExtras().getString("Machine");
}else{
Toast.makeText(this, "No API Data", Toast.LENGTH_SHORT).show();
}
}
/**
* This method is to initialize views
*/
private void initViews() {
recyclerViewBeneficiary = (RecyclerView)
findViewById(R.id.recyclerViewBeneficiary);
}
/**
* This method is to initialize objects to be used
*/
private void initObjects() {
listBeneficiary = new ArrayList<>();
beneficiaryRecyclerAdapter = new TimeinRecyclerAdapter(listBeneficiary,
this);
RecyclerView.LayoutManager mLayoutManager = new
LinearLayoutManager(getApplicationContext());
recyclerViewBeneficiary.setLayoutManager(mLayoutManager);
recyclerViewBeneficiary.setItemAnimator(new DefaultItemAnimator());
recyclerViewBeneficiary.setHasFixedSize(true);
recyclerViewBeneficiary.setAdapter(beneficiaryRecyclerAdapter);
databaseHelper = new DatabaseHelper(activity);
getDataFromSQLite();
}
/**
* This method is to fetch all user records from SQLite
*/
private void getDataFromSQLite() {
// AsyncTask is used that SQLite operation not blocks the UI Thread.
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
listBeneficiary.clear();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
beneficiaryRecyclerAdapter.notifyDataSetChanged();
}
}.execute();
}
}
And this is the XML Layouts of my following codes just showing you to understand more about ID i assigned.
Activity_timeinrec.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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"
android:fitsSystemWindows="true"
tools:context="com.example.serviceapplication.TimerecordsListActivty">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewBeneficiary"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:layout_marginTop="?actionBarSize"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
activity_timeinrecycler.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
card_view:cardCornerRadius="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/textViewName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/textViewEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/textViewAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/textViewCountry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
I expect that the apps shows all the data in TABLE_NAME_IN, but on the otherhand as I said it only shows the No "API Data".
Related
If I scroll this list RecycleView with the mouse wheel my items in the list look like unordered.
I do not understand , why?
An incorrect clicked item in the new activity from RecycleView
I have tried to create the separate class CrimeAdapter extends RecyclerView.Adapter<CrimeAdapter.CrimeHolder> and
class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener in the separate file, but I couldn't do it right.
Unfornuntely, I do not have enough experience for this.
I do not know how to write the correct code in the method public void onClick(View v)
Crime.java
package com.bignerdranch.android.criminalintent;
import java.util.Date;
import java.util.UUID;
public class Crime{
private UUID mId;
private String mTitle;
private Date mDate;
private boolean mSolved;
private boolean mRequiresPolice;
public Crime() {
// Generate unique identifier
this(UUID.randomUUID());
}
public Crime(UUID id) {
mId = id;
mDate = new Date();
}
public UUID getId() {
return mId;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
public Date getDate() {
return mDate;
}
public void setDate(Date date) {
mDate = date;
}
public boolean isSolved() {
return mSolved;
}
public void setSolved(boolean solved) {
mSolved = solved;
}
public boolean isRequiresPolice() {
return mRequiresPolice;
}
public void setRequiresPolice(boolean requiresPolice) {
mRequiresPolice = requiresPolice;
}
}
CrimeLab.java
package com.bignerdranch.android.criminalintent;
import android.content.Context;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
public class CrimeLab {
private static CrimeLab sCrimeLab;
private List<Crime> mCrimes;
public static CrimeLab get(Context context) {
if (sCrimeLab == null) {
sCrimeLab = new CrimeLab(context);
}
return sCrimeLab;
}
private CrimeLab(Context context){
mCrimes = new ArrayList<>();
for (int i = 0; i < 100; i++) {
Crime crime = new Crime();
crime.setTitle("Crime #" + i);
crime.setSolved(i % 2 == 0);
if (i % 4 == 0 ) {crime.setRequiresPolice(true);}
else {crime.setRequiresPolice(false);}
mCrimes.add(crime);
}
}
public List<Crime> getCrimes() {
return mCrimes;
}
public Crime getCrime(UUID id){
for (Crime crime : mCrimes){
int rez = id.compareTo(crime.getId());
if (crime.getId().equals(id)){
return crime;
}
}
return null;
}
}
CrimeListFragment.java
package com.bignerdranch.android.criminalintent;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.LayoutRes;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.Date;
import java.util.List;
public class CrimeListFragment extends Fragment {
private static final int REQUEST_CRIME = 1;
private static final int NOT_REQUIRES_POLICE = 0;
private static final int REQUIRES_POLICE = 1;
private RecyclerView mCrimeRecyclerView;
private CrimeAdapter mAdapter;
private TextView mTitleTextView;
private TextView mDateTextView;
private ImageView mSolvedImageView;
private Button mButtonCallPolice;
private Crime mCrime;
private CharSequence mDateFormat;
private int layout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container,
false);
mCrimeRecyclerView = (RecyclerView) view
.findViewById(R.id.crime_recycler_view);
mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
private class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public CrimeHolder(int layout, LayoutInflater inflater, ViewGroup parent ) {
super(inflater.inflate(layout, parent, false));
mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
mSolvedImageView = (ImageView) itemView.findViewById(R.id.crime_solved);
if (itemView.findViewById(R.id.call_police)!=null) {
mButtonCallPolice = (Button) itemView.findViewById(R.id.call_police);
}
itemView.setOnClickListener(this);
}
public void bind(Crime crime) {
mCrime = crime;
mTitleTextView.setText(mCrime.getTitle());
mDateFormat = DateFormat.format("EEE, MMM dd, yyyy", mCrime.getDate());
mDateTextView.setText(mDateFormat);
mSolvedImageView.setVisibility(mCrime.isSolved() ? View.VISIBLE :
View.GONE);
if(mCrime.isRequiresPolice()){
mButtonCallPolice.setEnabled(true);
}
}
#Override
public void onClick(View view) {
Intent intent = CrimePagerActivity.newIntent(getActivity(),
CrimeLab.get(requireActivity()).getCrimes().get((getAdapterPosition())).getId());
startActivityForResult(intent, REQUEST_CRIME);
}
}
private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
private List<Crime> mCrimes;
public CrimeAdapter(List<Crime> crimes) {
mCrimes = crimes;
}
#Override
public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
if (viewType==1) { layout = R.layout.list_item_crime_police;}
else { layout = R.layout.list_item_crime; }
return new CrimeHolder (layout, layoutInflater, parent);
}
#Override
public void onBindViewHolder(CrimeHolder holder, int position) {
Crime crime = mCrimes.get(position);
holder.bind(crime);
}
#Override
public int getItemCount() {
return mCrimes.size();
}
public int getItemViewType(int position) {
Crime crime = mCrimes.get(position);
return (crime.isRequiresPolice()) ? 1 : 0;
}
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
private void updateUI() {
CrimeLab crimeLab = CrimeLab.get(getActivity());
List<Crime> crimes = crimeLab.getCrimes();
if (mAdapter == null) {
mAdapter = new CrimeAdapter(crimes);
mCrimeRecyclerView.setAdapter(mAdapter);
} else {
mAdapter.notifyDataSetChanged();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CRIME) {
// Обработка результата
}
}
public void returnResult() {
getActivity().setResult(Activity.RESULT_OK, null);
}
}
CrimePagerActivity.java
package com.bignerdranch.android.criminalintent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;
import java.util.List;
import java.util.UUID;
public class CrimePagerActivity extends AppCompatActivity {
private static final String EXTRA_CRIME_ID = "com.bignerdranch.android.criminalintent.crime_id";
private ViewPager mViewPager;
private List<Crime> mCrimes;
MyAdapter mAdapter;
public static Intent newIntent(Context packageContext, UUID crimeId) {
Intent intent = new Intent(packageContext, CrimePagerActivity.class);
intent.putExtra(EXTRA_CRIME_ID, crimeId);
return intent;
}
#Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime_pager);
UUID crimeId = (UUID) getIntent().getSerializableExtra(EXTRA_CRIME_ID);
mViewPager = (ViewPager) findViewById(R.id.crime_view_pager);
mCrimes = CrimeLab.get(this).getCrimes();
mAdapter = new MyAdapter(getSupportFragmentManager(),mCrimes);
mViewPager.setAdapter(mAdapter);
for (int i = 0; i < mCrimes.size(); i++) {
if (mCrimes.get(i).getId().equals(crimeId)) {
mViewPager.setCurrentItem(i);
break;
}
}
}
public static class MyAdapter extends FragmentStatePagerAdapter {
private List<Crime> mCrimesCopy;
public MyAdapter(FragmentManager fm, List<Crime> mCrimesParametr) {
//super(fm);
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
this.mCrimesCopy = mCrimesParametr;
}
#Override
public int getCount() {
return mCrimesCopy.size();
}
#Override
public Fragment getItem(int position) {
Crime crime = mCrimesCopy.get(position);
return CrimeFragment.newInstance(crime.getId());
}
}
}
fragment_crime_list.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/crime_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
fragment_crime.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:layout_margin="16dp"
android:orientation="vertical">
<TextView
style="?android:listSeparatorTextViewStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_title_label"/>
<EditText
android:id="#+id/crime_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/crime_title_hint"
android:inputType=""
android:autofillHints="" />
<TextView
style="?android:listSeparatorTextViewStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_details_label"/>
<Button
android:id="#+id/crime_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<CheckBox
android:id="#+id/crime_solved"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_solved_label"/>
</LinearLayout>
list_item_crime_police.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:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/crime_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:text="#string/crime_title"
android:textColor="#android:color/black"
android:textSize="18sp"
app:layout_constraintEnd_toStartOf="#+id/crime_solved"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/crime_date"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text="#string/crime_date"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/crime_solved" />
<Button
android:id="#+id/call_police"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="#string/call_police"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/crime_date" />
<ImageView
android:id="#+id/crime_solved"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="16dp"
android:contentDescription="#string/todo"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_solved" />
</androidx.constraintlayout.widget.ConstraintLayout>
list_item_crime.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:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/crime_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:text="#string/crime_title"
android:textColor="#android:color/black"
android:textSize="18sp"
app:layout_constraintEnd_toStartOf="#+id/crime_solved"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/crime_date"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text="#string/crime_date"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/crime_solved" />
<ImageView
android:id="#+id/crime_solved"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_solved"
android:contentDescription="#string/todo" />
</androidx.constraintlayout.widget.ConstraintLayout>
activity_crime_pager.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.viewpager.widget.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/crime_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.viewpager.widget.ViewPager>
activity_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
I think the items in the RecyclerView are unordered because the references for views which are present in your list_item_crime_police.xml or list_item_crime.xml layout file is declared as class members of CrimeListFragment and not inside CrimeHolder class as :
public class CrimeListFragment extends Fragment {
// your other views and variables related declarations
// these are problematic declaration that keeps on being reused
private TextView mTitleTextView;
private TextView mDateTextView;
private ImageView mSolvedImageView;
private Button mButtonCallPolice;
// your other declarations
// your other code
}
That's why, the same view instances such as mTitleTextView, mDateTextView, mSolvedImageView, mButtonCallPolice, etc. are being reused for every CrimeHolder instances causing the unordering of the items in the list. Now, in order to fix this problem, you can simply move these lines to code to CrimeHolder class as class variable which would ensures that every new CrimeHolder instance will have separate instances of above-mentioned views as :
private class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
// declare all of them here so there will be unique instances of these views for unique viewholder
private TextView mTitleTextView;
private TextView mDateTextView;
private ImageView mSolvedImageView;
private Button mButtonCallPolice;
public CrimeHolder(int layout, LayoutInflater inflater, ViewGroup parent ) {
View itemView = inflater.inflate(layout, parent, false));
super(itemView);
mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
mSolvedImageView = (ImageView) itemView.findViewById(R.id.crime_solved);
if (itemView.findViewById(R.id.call_police)!=null) {
mButtonCallPolice = (Button) itemView.findViewById(R.id.call_police);
}
itemView.setOnClickListener(this);
}
public void bind(Crime crime) {
mCrime = crime;
mTitleTextView.setText(mCrime.getTitle());
mDateFormat = DateFormat.format("EEE, MMM dd, yyyy", mCrime.getDate());
mDateTextView.setText(mDateFormat);
mSolvedImageView.setVisibility(mCrime.isSolved() ? View.VISIBLE :
View.GONE);
if(mCrime.isRequiresPolice()){
mButtonCallPolice.setEnabled(true);
}
}
#Override
public void onClick(View view) {
Intent intent = CrimePagerActivity.newIntent(getActivity(),
CrimeLab.get(requireActivity()).getCrimes().get((getAdapterPosition())).getId());
startActivityForResult(intent, REQUEST_CRIME);
}
}
It fixed my problem and I hope it will fix yours too.
This question already has answers here:
RecyclerView adapter show only first item
(3 answers)
Closed 3 years ago.
I use recycler view before and i never have this problems. The principal difference between the other recycler views that i made is that i use SQLite for this one.
I want all the items appears one between other and without white spaces between them.
LEADER BOARD ACTIVITY WHERE I INITIALIZE MY RECYCLER
public class LeaderBoard extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerController mAdapter;
private RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leader_board);
DaoSQLite manager=new DaoSQLite(this);
SQLiteDatabase db=manager.getReadableDatabase();
layoutManager=new LinearLayoutManager(this);
recyclerView=findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
mAdapter=new RecyclerController(manager.getSortScores());
recyclerView.setAdapter(mAdapter);
}
}
VIEW FOR RECYCLER
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/txtNameOption"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/lbName"
android:layout_width="129dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="16dp"
android:layout_marginTop="21dp"
android:fontFamily="serif"
android:text="Name"
android:textAlignment="textStart"
android:textAppearance="#style/TextAppearance.AppCompat.Display2"
android:textIsSelectable="false"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/lbLevel2"
android:layout_width="109dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="154dp"
android:layout_marginTop="21dp"
android:fontFamily="serif"
android:text="Level"
android:textAlignment="textStart"
android:textAppearance="#style/TextAppearance.AppCompat.Display2"
android:textIsSelectable="false"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/lbScore"
android:layout_width="132dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="266dp"
android:layout_marginTop="21dp"
android:fontFamily="serif"
android:text="Score"
android:textAlignment="textStart"
android:textAppearance="#style/TextAppearance.AppCompat.Display2"
android:textIsSelectable="false"
android:textSize="15sp"
android:textStyle="bold" />
<View
android:id="#+id/view"
android:layout_width="wrap_content"
android:layout_height="79dp"
android:background="#604697"
android:backgroundTint="#34BE3838"
android:backgroundTintMode="src_in"
android:hapticFeedbackEnabled="false" />
</RelativeLayout>
THIS IS THE SQLite DAO
package com.example.quizappjava.DataBase;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.quizappjava.Beans.User;
public class DaoSQLite extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Game.db";
private static final String TABLE_NAME_SCORES = "puntuaciones";
private SQLiteDatabase sqLiteDatabase = getWritableDatabase();
public DaoSQLite(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+ TABLE_NAME_SCORES +" (_id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT (15) NOT NULL,score INTEGER NOT NULL, level INTEGER NOT NULL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor getSortScores(){
return getReadableDatabase().query(TABLE_NAME_SCORES,null,null,null,null,null,"score");
}
public void insertNewScore(User user){
sqLiteDatabase.insert(TABLE_NAME_SCORES,null,user.toContentValues());
}
}
RECYCLER CONTROLLER
package com.example.quizappjava.JavaClasses;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.quizappjava.Beans.User;
import com.example.quizappjava.R;
import java.util.ArrayList;
public class RecyclerController extends RecyclerView.Adapter<RecyclerController.ViewHolder> {
private ArrayList<User> userArraList = new ArrayList<User>();
public RecyclerController(Cursor queryRequest) {
ParseData(queryRequest);
}
private void ParseData(Cursor queryRequest) {
for (queryRequest.moveToFirst(); !queryRequest.isAfterLast(); queryRequest.moveToNext()) {
userArraList.add(
new User(
queryRequest.getString(queryRequest.getColumnIndex("name")),
queryRequest.getInt(queryRequest.getColumnIndex("score")),
queryRequest.getInt(queryRequest.getColumnIndex("level"))
));
}
}
#NonNull
#Override
public RecyclerController.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerController.ViewHolder holder, int position) {
holder.user=userArraList.get(position);
holder.lbName.setText(userArraList.get(position).getName());
holder.lbScore.setText(userArraList.get(position).getScore()+"");
holder.lbLevel.setText(userArraList.get(position).getLevel()+"");
}
#Override
public int getItemCount() {
return userArraList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView lbName;
private TextView lbScore;
private TextView lbLevel;
private User user;
public ViewHolder(#NonNull View itemView) {
super(itemView);
lbName=itemView.findViewById(R.id.lbName);
lbLevel=itemView.findViewById(R.id.lbLevel2);
lbScore=itemView.findViewById(R.id.lbScore);
}
}
}
This images shows how i see the leader board when i execute the app, the first image is how i see one item and the second one is the blank space between both items
Try
edit this :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/txtNameOption"
android:layout_width="match_parent"
android:layout_height="match_parent">
To:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/txtNameOption"
android:layout_width="match_parent"
android:layout_height="wrap_content">
You should have the same problem explained and resolved here.
The Relative Layout passed to your Recycler has android:layout_height="match_parent, but should have android:layout_height="wrap_content, otherwhise every item will be height as much as RecylerView is.
You have to adjust your recyclerview's cell height to wrap content instead of match parent:
VIEW FOR RECYCLER
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/txtNameOption"
android:layout_width="match_parent"
android:layout_height="wrap_content">
match_parent height would scale the cell to the height of the parent view
i am making an application where data is being saved in the database.i am lacking in displaying the data in the recyclerview using recyclerview adapter.don't know what code should be written. please check.
here is my files: MainActivity.java
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView applist;
ArrayList<Guides> guides;
GuideAdapter adapter;
GuideDB guideDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
guideDB = new GuideDB(this);
guides = new ArrayList<>();
applist = (RecyclerView) findViewById(R.id.app_list);
applist.setHasFixedSize(true);
applist.setLayoutManager(new LinearLayoutManager(this));
adapter = new GuideAdapter(this,guides);
applist.setAdapter(adapter);
try {
Cursor cursor = guideDB.getGuides("SELECT * FROM GUIDE_LIST");
while (cursor.moveToNext()){
int guide_id = cursor.getInt(0);
String post_tile = cursor.getString(1);
String post_desc = cursor.getString(2);
String post_address = cursor.getString(3);
byte [] post_image = cursor.getBlob(4);
Guides g = new Guides(guide_id,post_tile,post_desc,post_address,post_image);
guides.add(g);}
}catch (Exception e){e.printStackTrace();}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.action_add){
startActivity(new Intent(MainActivity.this,PostActivity.class));
}
return super.onOptionsItemSelected(item);
}
}
PostActivity.java
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class PostActivity extends AppCompatActivity {
public ImageButton mSelectImage;
public EditText mPostTitle;
public EditText mPostDesc;
public EditText mPostAddress;
public Button mSubmitbtn;
private static final int GALLERY_REQUEST= 1;
GuideDB guideDB;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
guideDB = new GuideDB(this);
mSelectImage = (ImageButton) findViewById(R.id.imageSelect);
mPostTitle = (EditText) findViewById(R.id.titleField);
mPostDesc = (EditText) findViewById(R.id.descField);
mPostAddress = (EditText) findViewById(R.id.addressField);
mSubmitbtn = (Button) findViewById(R.id.submitButton);
mSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,GALLERY_REQUEST);
}
});
mSubmitbtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
if(!mPostTitle.getText().toString().isEmpty() && !mPostDesc.getText().toString().isEmpty() && !mPostAddress.getText().toString().isEmpty())
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,50,outputStream);
byte[] byteArray = outputStream.toByteArray();
try {
guideDB.addGuide(mPostTitle.getText().toString(),
mPostDesc.getText().toString(),
mPostAddress.getText().toString(),byteArray
);
Toast.makeText(getApplicationContext(),"Added successfully!",Toast.LENGTH_LONG).show();
}catch (Exception e){e.printStackTrace();}
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_REQUEST && resultCode == RESULT_OK) {
Uri mimageUri = data.getData();
try {
InputStream inputstream = getContentResolver().openInputStream(mimageUri);
bitmap = BitmapFactory.decodeStream(inputstream);
mSelectImage.setImageBitmap(bitmap);
}catch (FileNotFoundException e){e.printStackTrace();}
}
}
}
GuideDB.java
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
/**
* Created by 291 on 14.12.2017.
*/
public class GuideDB extends SQLiteOpenHelper {
private static final int DATABASE_VERSION= 1;
private static final String DATABASE_NAME= "guide_db";
private static final String TABLE_NAME = "GUIDE_LIST";
private static String GUIDE_ID = "guide_id";
private static String GUIDE_TITLE = "guide_title";
private static String GUIDE_DESC = "guide_desc";
private static String GUIDE_ADDRESS = "guide_address";
private static String GUIDE_IMG = "guides_image";
public GuideDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE" + TABLE_NAME + "("
+ GUIDE_ID + "INTEGER PRIMARY KEY AUTOINCREMENT"
+ GUIDE_TITLE + "TEXT"
+ GUIDE_DESC + "TEXT"
+ GUIDE_ADDRESS + "TEXT"
+ GUIDE_IMG + "BLOB" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
onCreate(db);
}
public void addGuide (String title,String desc,String address,byte[] image){
SQLiteDatabase gdb = getWritableDatabase();
try
{
String sql = "INSERT INTO GUIDE_LIST VALUES(NULL,?,?,?)";
SQLiteStatement statement = gdb.compileStatement(sql);
statement.clearBindings();
statement.bindString(1,title);
statement.bindString(2,desc);
statement.bindString(3,address);
statement.bindBlob(4,image);
statement.execute();
}catch (Exception e){e.printStackTrace();}
}
public Cursor getGuides(String sql){
SQLiteDatabase gdb = getReadableDatabase();
return gdb.rawQuery(sql,null);
}
}
GuideAdapter.java
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by 291 on 14.12.2017.
*/
public class GuideAdapter extends RecyclerView.Adapter<GuideAdapter.ViewHolder> {
private Context ctx;
private ArrayList<Guides> guidelist;
public GuideAdapter(Context ctx, ArrayList<Guides> guidelist) {
this.ctx = ctx;
this.guidelist = guidelist;
}
#Override
public GuideAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.guide_row,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(GuideAdapter.ViewHolder holder, int position) {
Guides guides = guidelist.get(position);
holder.psttitle.setText(guides.getPost_title());
holder.pstdesc.setText(guides.getPost_desc());
holder.pstaddres.setText(guides.getPost_address());
byte [] postimg = guides.getPost_image();
Bitmap bitmap = BitmapFactory.decodeByteArray(postimg,0,postimg.length);
holder.pstimg.setImageBitmap(bitmap);
}
#Override
public int getItemCount() {
return guidelist.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public ImageView pstimg;
public TextView psttitle;
public TextView pstdesc;
public TextView pstaddres;
public int id;
public ViewHolder(View itemView) {
super(itemView);
pstimg = (ImageView) itemView.findViewById(R.id.post_image);
psttitle = (TextView) itemView.findViewById(R.id.post_title);
pstdesc = (TextView) itemView.findViewById(R.id.post_title);
pstaddres = (TextView) itemView.findViewById(R.id.post_address);
}
}
}
Guides.java
public class Guides {
private int guide_id;
private String post_title,post_desc,post_address;
private byte [] post_image;
public Guides(int guide_id, String post_title, String post_desc, String post_address, byte [] post_image) {
this.guide_id = guide_id;
this.post_title = post_title;
this.post_desc = post_desc;
this.post_address = post_address;
this.post_image = post_image;
}
public int getGuide_id() {
return guide_id;
}
public void setGuide_id(int guide_id) {
this.guide_id = guide_id;
}
public String getPost_title() {
return post_title;
}
public void setPost_title(String post_title) {
this.post_title = post_title;
}
public String getPost_desc() {
return post_desc;
}
public void setPost_desc(String post_desc) {
this.post_desc = post_desc;
}
public String getPost_address() {
return post_address;
}
public void setPost_address(String post_address) {
this.post_address = post_address;
}
public byte[] getPost_image() {
return post_image;
}
public void setPost_image(byte[] post_image) {
this.post_image = post_image;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.ugurcangursen.guideappsqlite.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/app_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:padding="10dp"></android.support.v7.widget.RecyclerView>
</RelativeLayout>
activity_post.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.ugurcangursen.guideappsqlite.PostActivity">
<ImageButton
android:id="#+id/imageSelect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:adjustViewBounds="true"
android:background="#00ffffff"
android:scaleType="centerCrop"
app:srcCompat="#drawable/add_btn" />
<EditText
android:id="#+id/titleField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/imageSelect"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:background="#drawable/input_outline"
android:hint="Post Title..."
android:inputType="textPersonName"
android:padding="10dp"
android:singleLine="true" />
<EditText
android:id="#+id/descField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/titleField"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:background="#drawable/input_outline"
android:hint="Post Description..."
android:inputType="textMultiLine"
android:padding="10dp" />
<EditText
android:id="#+id/addressField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/descField"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:background="#drawable/input_outline"
android:hint="Adres..."
android:inputType="textMultiLine"
android:padding="10dp" />
<Button
android:id="#+id/submitButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#color/colorPrimary"
android:text="SUBMIT POST"
android:textColor="#android:color/white" />
</RelativeLayout>
guide_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/post_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
app:srcCompat="#drawable/add_btn" />
<TextView
android:id="#+id/post_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:textSize="16dp"
android:textStyle="bold"
tools:text="Başlık" />
<TextView
android:id="#+id/post_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
tools:text="Açıklama" />
<TextView
android:id="#+id/post_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
tools:text="Adres" />
</LinearLayout>
</android.support.v7.widget.CardView>
I'm not reviewing all the code you have posted. However, it does appear that you are setting the adpater with an empty source (guides), so it would then display nothing.
The following version of the onCreate method may result in the data being displayed
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
guideDB = new GuideDB(this);
guides = new ArrayList<>();
applist = (RecyclerView) findViewById(R.id.app_list);
applist.setHasFixedSize(true);
applist.setLayoutManager(new LinearLayoutManager(this));
//adapter = new GuideAdapter(this,guides); //<<<< MOVED
//applist.setAdapter(adapter); //<<<< MOVED
try {
Cursor cursor = guideDB.getGuides("SELECT * FROM GUIDE_LIST");
while (cursor.moveToNext()){
int guide_id = cursor.getInt(0);
String post_tile = cursor.getString(1);
String post_desc = cursor.getString(2);
String post_address = cursor.getString(3);
byte [] post_image = cursor.getBlob(4);
Guides g = new Guides(guide_id,post_tile,post_desc,post_address,post_image);
guides.add(g);}
}catch (Exception e){e.printStackTrace();}
adapter = new GuideAdapter(this,guides); //<<<< MOVED
applist.setAdapter(adapter); //<<<< MOVED
}
I have made an adapter of CardView through the RecyclerView for me to use the same template of card for this feature of mine.
The objective is to create certain cards with different colors, based on the parameter inc_status in INCCards.java. But it doesn't just seem to work.
Here's the source code for the template card:
item_inc_card.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/spacing_medium"
android:paddingRight="#dimen/spacing_medium"
android:paddingTop="#dimen/spacing_medium"
android:background="#color/tertiary">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="#dimen/spacing_none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/spacing_large"
android:paddingRight="#dimen/spacing_large"
android:paddingTop="#dimen/spacing_large"
android:paddingBottom="#dimen/spacing_medium"
android:id="#+id/relative_layout">
<TextView
android:id="#+id/course_code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:textColor="#color/white"
android:textSize="#dimen/text_headline"
android:text="#string/course_code"
android:textStyle="bold"/>
<TextView
android:id="#+id/course_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/course_code"
android:textColor="#color/white"
android:textSize="#dimen/text_subhead"
android:text="#string/course_title" />
<TextView
android:id="#+id/faculty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/white"
android:layout_below="#+id/course_title"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textStyle="italic"
android:textSize="#dimen/text_body"
android:text="#string/faculty" />
<ImageView
android:id="#+id/status_icon"
android:src="#drawable/icon_avatar"
android:layout_width="#dimen/size_user_icon"
android:layout_height="#dimen/size_user_icon"
android:layout_above="#+id/faculty"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:id="#+id/inc_grade"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/text_body"
android:layout_below="#+id/status_icon"
android:layout_alignRight="#+id/status_icon"
android:layout_alignEnd="#+id/status_icon"
android:layout_alignLeft="#+id/status_icon"
android:layout_alignStart="#+id/status_icon"
android:gravity="center"
android:textAlignment="center"
android:textColor="#color/white"
android:text="#string/equiv_grade"/>
</RelativeLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="0.001dp"
android:background="#FFFFFF"
android:id="#+id/line_divider"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/spacing_large"
android:paddingRight="#dimen/spacing_medium"
android:paddingBottom="#dimen/spacing_medium"
android:layout_marginTop="#dimen/spacing_medium"
android:id="#+id/semesterInfoLinearLayout">
<TextView
android:id="#+id/section"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/text_caption"
android:text="#string/section"
android:textColor="#color/white"
android:layout_weight="0.33" />
<TextView
android:id="#+id/semester"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/text_caption"
android:text="#string/semester"
android:textColor="#color/white"
android:layout_weight="0.33"
android:gravity="center" />
<TextView
android:id="#+id/acad_year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/text_caption"
android:text="#string/acad_year"
android:textColor="#color/white"
android:layout_weight=".33"
android:gravity="right" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
And for the fragment layout:
item_inc_card.xml
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_inc_cards"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/tertiary"/>
To where each card is initialized by the object
INCCards.java
package ph.edu.amitypipduo.myiit;
public class INCCards {
String course_code, course_title, faculty, section, semester, acad_year;
int inc_status, status_icon;
final String inc_grade = "INC 3.00";
public INCCards(String course_code, String course_title, String faculty, String section, String semester, String acad_year, String inc_status) {
this.course_code = course_code;
this.course_title = course_title;
this.faculty = faculty;
this.section = section;
this.semester = semester;
this. acad_year = acad_year;
switch (inc_status) {
case "notice":
this.inc_status = R.color.inc_notice;
this.status_icon = R.drawable.inc_notice;
break;
case "alert":
this.inc_status = R.color.inc_alert;
this.status_icon = R.drawable.inc_alert;
break;
case "warning":
this.inc_status = R.color.inc_warning;
this.status_icon = R.drawable.inc_warning;
break;
case "danger":
this.inc_status = R.color.inc_danger;
this.status_icon = R.drawable.inc_danger;
break;
}
}
}
I tried setting the background color of the card at method onBindViewHolder by:
cardViewHolder.card_view.setCardBackgroundColor(inc_cards.get(i).inc_status);
as seen here in
INCAdapter.java
package ph.edu.amitypipduo.myiit;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class INCAdapter extends RecyclerView.Adapter<INCAdapter.CardViewHolder> {
List<INCCards> inc_cards;
public INCAdapter(List<INCCards> inc_cards){
this.inc_cards = inc_cards;
}
#Override
public CardViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_inc_card, viewGroup, false);
CardViewHolder card_view_holder = new CardViewHolder(view);
return card_view_holder;
}
#Override
public void onBindViewHolder(CardViewHolder cardViewHolder, int i) {
cardViewHolder.course_code.setText(inc_cards.get(i).course_code);
cardViewHolder.course_title.setText(inc_cards.get(i).course_title);
cardViewHolder.faculty.setText(inc_cards.get(i).faculty);
cardViewHolder.section.setText(inc_cards.get(i).section);
cardViewHolder.semester.setText(inc_cards.get(i).semester);
cardViewHolder.acad_year.setText(inc_cards.get(i).acad_year);
cardViewHolder.inc_grade.setText(inc_cards.get(i).inc_grade);
cardViewHolder.status_icon.setImageResource(inc_cards.get(i).status_icon);
cardViewHolder.card_view.setCardBackgroundColor(inc_cards.get(i).inc_status);
}
#Override
public int getItemCount() {
return inc_cards.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public static class CardViewHolder extends RecyclerView.ViewHolder {
CardView card_view;
TextView course_code, course_title, faculty, section, semester, acad_year, inc_grade;
ImageView status_icon;
CardViewHolder(View itemView) {
super(itemView);
card_view = (CardView) itemView.findViewById(R.id.card_view);
course_code = (TextView) itemView.findViewById(R.id.course_code);
course_title = (TextView) itemView.findViewById(R.id.course_title);
faculty = (TextView) itemView.findViewById(R.id.faculty);
inc_grade = (TextView) itemView.findViewById(R.id.inc_grade);
section = (TextView) itemView.findViewById(R.id.section);
semester = (TextView) itemView.findViewById(R.id.semester);
acad_year = (TextView) itemView.findViewById(R.id.acad_year);
status_icon = (ImageView) itemView.findViewById(R.id.status_icon);
}
}
}
Then initializing the data in the fragment class and inflating the layout:
INCMonitorFragment.java
package ph.edu.amitypipduo.myiit;
import android.app.Activity;
import android.app.Fragment;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
public class INCMonitorFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private RecyclerView recycler_view;
private LinearLayoutManager linear_layout_manager;
private INCAdapter inc_adapter;
private List<INCCards> inc_cards;
private void initializeData() {
inc_cards = new ArrayList<>();
inc_cards.add(new INCCards("CSC 198", "Methods of Research", "Prof. Cyrus Gabilla", "CS-1A", "SECOND SEMESTER", "AY 2014-2015", "danger"));
inc_cards.add(new INCCards("POLSCI 2", "Philippine Govt. & Const.", "Prof. Cyrus Gabilla", "AB4", "SUMMER SEMESTER", "AY 2013-2014", "warning"));
inc_cards.add(new INCCards("ENG 2N", "Writing in Discipline", "Prof. Rabindranath Polito", "B4", "FIRST SEMESTER", "AY 2012-2013", "alert"));
inc_cards.add(new INCCards("MATH 51", "I Forgot the Course Title", "Prof. Forgotten Name", "69", "SECOND SEMESTER", "AY 2012-2013", "notice"));
}
// TODO: Rename and change types and number of parameters
public static INCMonitorFragment newInstance(String param1, String param2) {
INCMonitorFragment fragment = new INCMonitorFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public INCMonitorFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
initializeData();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_inc_monitor, container, false);
recycler_view = (RecyclerView) view.findViewById(R.id.fragment_inc_cards);
recycler_view.setHasFixedSize(true);
linear_layout_manager = new LinearLayoutManager(getActivity().getApplicationContext());
recycler_view.setLayoutManager(linear_layout_manager);
inc_adapter = new INCAdapter(inc_cards);
recycler_view.setAdapter(inc_adapter);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
But it only shows this:
Why does it not recognize the color? How come the R.drawable..... was recognized by the onBindViewHolder and not the R.color.....?
Change
cardViewHolder.card_view.setCardBackgroundColor(inc_cards.get(i).inc_status);
to
int colorId = inc_cards.get(i).inc_status;
int color = cardViewHolder.card_view.getContext().getResources().getColor(colorId);
cardViewHolder.card_view.setCardBackgroundColor(color);
You are using the value from R.color instead of the value you set in your XML.
I'm getting a more reliable color overriding with this line:
setBackgroundTintList(ColorStateList.valueOf(color));
instead of:
setCardBackgroundColor(color).
One thing to add, make sure you have the alpha in your color number and if you don't just add ff at the begining of your color, otherwise it won't work correctly.
For example this works
view.setCardBackgroundColor(0xff2ecc71)
While this one shows a white background
view.setCardBackgroundColor(0x2ecc71)
Try to use Material Card View Instead
then Do something LIke this:
private MaterialCardView imgIgnition;
imgIgnition = findViewById(R.id.imgIgnition);
imgIgnition.setCardBackgroundColor(Color.parseColor("#198754"));
I am really sorry for such an abstract question but I am loosing my mind here. HERE is my code for RecyclerView activity.
Please tell me what am I missing, because I am new to Android and I've tried for 4 days to figure the CardView out.
The error is
02-26 13:17:36.570 1138-1138/com.parse.starter E/CrashReporting﹕ ParseCrashReporting caught a NullPointerException exception for com.parse.starter. Building report.
02-26 13:17:36.580 1138-1138/com.parse.starter E/CrashReporting﹕ Handling exception for crash
java.lang.NullPointerException
at com.misha.adaptor.ContactAdapter.onBindViewHolder(ContactAdapter.java:31)
at com.misha.adaptor.ContactAdapter.onBindViewHolder(ContactAdapter.java:14)
The main Activity class
package com.parse.starter;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.misha.adaptor.ContactAdapter;
import com.misha.to.ContactInfo;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.util.ArrayList;
import java.util.List;
public class CardActivity extends Activity {
String column;
TextView name;
String result;
List<ContactInfo> resultContacts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card);
// getContacts()
List<ContactInfo> list = new ArrayList<>();
ContactInfo ci = new ContactInfo();
ci.name = "Mihail";
ci.gender = "male";
ci.email = "test#gmail.com";
ci.phone = "4152346153";
list.add(ci);
RecyclerView recList = (RecyclerView) findViewById(R.id.cardList);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
ContactAdapter adapter = new ContactAdapter(list);
recList.setAdapter(adapter);
// name = (TextView) findViewById(R.id.txtName);
// getMessage("fevK9QPFUW", "Message");
}
public void getMessage(String key, String columnName) {
this.column = columnName;
ParseQuery<ParseObject> query = ParseQuery.getQuery("Messages");
query.getInBackground(key, new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
name.setText(object.getString(column).toString());
} else {
result = "did not work";
}
}
});
}
public List<ContactInfo> getContacts() {
resultContacts = new ArrayList<>();
ParseQuery<ParseObject> contacts = ParseQuery.getQuery("Messages");
List<ParseQuery<ParseObject>> queries = new ArrayList<>();
queries.add(contacts);
ParseQuery<ParseObject> mainQuery = ParseQuery.or(queries);
mainQuery.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> results, ParseException e) {
if (e == null) {
for (ParseObject obj : results) {
String s = obj.getString("Message");
ContactInfo ci = new ContactInfo();
ci.name = s;
ci.email = "email";
ci.phone = "phone";
ci.gender = "gender";
resultContacts.add(ci);
}
}
}
});
return resultContacts;
}
#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_card, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
The Adaptor
package com.misha.adaptor;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.misha.to.ContactInfo;
import com.parse.starter.R;
import java.util.List;
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {
private List<ContactInfo> contactList;
public ContactAdapter(List<ContactInfo> contactList) {
this.contactList = contactList;
}
#Override
public int getItemCount() {
return contactList.size();
}
#Override
public void onBindViewHolder(ContactViewHolder contactViewHolder, int i) {
ContactInfo ci = contactList.get(i);
System.out.println("The ContactInfo = " + ci);
contactViewHolder.vName.setText(ci.name);
contactViewHolder.vPhone.setText(ci.phone);
contactViewHolder.vEmail.setText(ci.email);
contactViewHolder.vGender.setText(ci.gender);
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.activity_card, viewGroup, false);
return new ContactViewHolder(itemView);
}
public class ContactViewHolder extends RecyclerView.ViewHolder {
protected TextView vName;
protected TextView vPhone;
protected TextView vEmail;
protected TextView vGender;
public ContactViewHolder(View v) {
super(v);
vName = (TextView) v.findViewById(R.id.txtName);
vPhone = (TextView) v.findViewById(R.id.txtPhone);
vEmail = (TextView) v.findViewById(R.id.txtEmail);
vGender = (TextView) v.findViewById(R.id.txtGender);
}
}
}
and Here are my layOuts:
activity_card.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".CardActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/cardList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
card_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
card_view:cardCornerRadius="4dp"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtName"
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#color/bkg_card"
android:text="Name"
android:gravity="center_vertical"
android:textColor="#android:color/white"
android:textSize="14dp" />
<TextView
android:id="#+id/txtPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone"
android:gravity="center_vertical"
android:textSize="10dp"
android:layout_below="#id/txtName"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp" />
<TextView
android:id="#+id/txtEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:gravity="center_vertical"
android:textSize="10dp"
android:layout_below="#id/txtPhone"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp" />
<TextView
android:id="#+id/txtGender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gender"
android:textSize="10dp"
android:layout_marginTop="10dp"
android:layout_alignParentRight="true"
android:layout_marginRight="150dp"
android:layout_alignBaseline="#id/txtEmail" />
</RelativeLayout>
</android.support.v7.widget.CardView>
contactViewHolder.vName is null in your example.
You need to call the constructor for ContactViewHolder in the ContactAdapter constructor.
Got it
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.card_layout, viewGroup, false);
return new ContactViewHolder(itemView);
}
the R.layout.card_layout was set to R.layout.my_activity