TextViews not populating with data from SQLite database in RecyclerView - java

I'm new to Java, Android and SQLite, so quite frankly I'm amazed that I have gotten this far.
I am trying to create a simple cataloguing app for my bonsai collection which displays a summary of my collection in a RecyclerView on the MainActivity.
I've got the database working, in that I can add items to it (checked through DB Browser for SQLite). The trouble I'm having is displaying that data in the RecyclerView. Currently it is just showing the laucher icon placeholder image and not populating the TextViews with the data from the DB. The number of views that are showing in the RecyclerView correspond with the number of entries in the DB.
I'm not sure what I'm doing wrong, so any help would be greatly appreciated.
MainActivity.java
Datasource mDataSource;
Button btnAddNew;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDataSource = new Datasource(this);
mDataSource.open();
List<DataModel> listFromDB = mDataSource.getAllItems();
DataItemAdapter adapter = new DataItemAdapter(this, listFromDB);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rvItems);
recyclerView.setAdapter(adapter);
btnAddNew = (Button) findViewById(R.id.btnInsert);
}
DataModel.Java
public class DataModel {
private String itemId;
private String itemName;
private String itemCommonName;
public DataModel() {
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemCommonName() {
return itemCommonName;
}
public void setItemCommonName(String itemCommonName) {
this.itemCommonName = itemCommonName;
}
Datasource.java
public class Datasource {
private Context mContext;
private SQLiteDatabase mDatabase;
SQLiteOpenHelper mDbHelper;
public Datasource(Context context){
this.mContext = context;
mDbHelper = new DatabaseHelper(mContext);
mDatabase = mDbHelper.getWritableDatabase();
}
public void open(){
mDatabase = mDbHelper.getWritableDatabase();
}
public void close(){
mDatabase.close();
}
public boolean insertData(String name, String commonName, String scientificName){
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME, name);
contentValues.put(COL_COMMON_NAME, commonName);
contentValues.put(COL_SCI_NAME, scientificName);
long result = db.insert(DATABASE_TABLE, null, contentValues);
db.close();
if(result == -1) {
return false;
}else{
return true;
}
}
public List<DataModel> getAllItems(){
List<DataModel> dataModels = new ArrayList<>();
Cursor cursor = mDatabase.query(DATABASE_TABLE, ItemsTable.ALL_COLUMNS,
null, null, null, null, null);
while (cursor.moveToNext()){
DataModel item = new DataModel();
item.setItemId(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_ID)));
item.setItemId(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_NAME)));
item.setItemId(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_COMMON_NAME)));
item.setItemId(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_SCI_NAME)));
dataModels.add(item);
}
return dataModels;
}
DataItemAdapter.java
public class DataItemAdapter extends RecyclerView.Adapter<DataItemAdapter.ViewHolder> {
private List<DataModel> mItems;
private Context mContext;
public DataItemAdapter(Context context, List<DataModel> items) {
this.mContext = context;
this.mItems = items;
}
#Override
public DataItemAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View itemView = inflater.inflate(R.layout.list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(itemView);
return viewHolder;
}
#Override
public void onBindViewHolder(DataItemAdapter.ViewHolder holder, int position) {
final DataModel item = mItems.get(position);
holder.tvName.setText(item.getItemName());
holder.tvCommonName.setText(item.getItemCommonName());
}
#Override
public int getItemCount() {
return mItems.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvName, tvCommonName;
public ImageView ivProfilePic;
public View mView;
public ViewHolder(View itemView){
super(itemView);
tvName = (TextView) itemView.findViewById(R.id.tvName);
tvCommonName = (TextView) itemView.findViewById(R.id.tvCommonName);
ivProfilePic = (ImageView) itemView.findViewById(R.id.ivProfilePic);
mView = itemView;
}
}
RecyclerView object in activity_main.xml
<android.support.v7.widget.RecyclerView
android:id="#+id/rvItems"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="LinearLayoutManager"/>
TextViews and Image view list_item.xml
<ImageView
android:id="#+id/ivProfilePic"
android:layout_width="75dp"
android:layout_height="75dp"
app:srcCompat="#mipmap/ic_launcher_round"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:contentDescription="Profile Pic"
tools:ignore="HardcodedText"/>
<TextView
android:id="#+id/tvName"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginStart="19dp"
android:layout_toEndOf="#+id/ivProfilePic"
android:text="TextView"
android:textSize="18sp"
android:visibility="visible"/>
<TextView
android:id="#+id/tvCommonName"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="TextView"
android:visibility="visible"/>
Screenshot of what the MainActivity currently looks like:
Any other information required, just ask and I'll try to post it up.

Sorted it out, seems so simple now that I look at it.
In the Cursor, I hadn't changed the item setters to the correct ones after I copied and pasted the first line, just the column names.
Also I was identifying the ID column as a string, where it should have been an integer - also updated this in the DataModel class
while (cursor.moveToNext()){
DataModel item = new DataModel();
item.setItemId(cursor.getInt(
cursor.getColumnIndex(ItemsTable.COL_ID)));
item.setItemName(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_NAME)));
item.setItemCommonName(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_COMMON_NAME)));
item.setItemSciName(cursor.getString(
cursor.getColumnIndex(ItemsTable.COL_SCI_NAME)));
dataModels.add(item);
}
return dataModels;
}

Related

I want to make a recyclerview that shows data to a new Activity from SQLITE database

I'm working on a project, I have a sqlite database that has id, title, content
I want to make a recyclerview and get titles from database and set it to recyclerview items per position and when the user click on some item, they will be able to read the content from database. Hope my question is clear! Thank you.
Here is my DatabaseHelper class
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "alQais.db";
private Context context;
private SQLiteDatabase sqLiteDatabase;
public DatabaseHelper(Context mContext){
super(mContext, DBNAME, null, 1);
this.context = mContext;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void openDatabase(){
String dbPath = context.getDatabasePath(DBNAME).getPath();
if(sqLiteDatabase != null && sqLiteDatabase.isOpen()){
return;
}
sqLiteDatabase = SQLiteDatabase.openDatabase(dbPath, null,SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase(){
if(sqLiteDatabase != null){
sqLiteDatabase.close();
}
}
public ArrayList getAllTitles(){
ArrayList arrayList = new ArrayList();
openDatabase();
Cursor cursor = sqLiteDatabase.rawQuery("select * from muallaqat", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
arrayList.add(cursor.getString(cursor.getColumnIndex("title")));
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return arrayList;
}
public String getMuallaqa(String title){
String muallaqat;
openDatabase();
Cursor cursor = sqLiteDatabase.rawQuery("select * from muallaqat where title like '" + title + "'", null);
cursor.moveToFirst();
muallaqat = cursor.getString(cursor.getColumnIndex("muallaqa"));
cursor.close();
closeDatabase();
return muallaqat;
}}
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper db = new DatabaseHelper(this);
ListView listView;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
listView = findViewById(R.id.listView);
File database = getBaseContext().getDatabasePath(db.DBNAME);
if(false == database.exists()){
db.getReadableDatabase();
if(copyDatabase(this)){
Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
return;
}
}
ArrayList lstTitles = db.getAllTitles();
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.item_layout, lstTitles);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String title = String.valueOf(parent.getItemAtPosition(position));
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.putExtra("title", title);
startActivity(intent);
}
});
}
private boolean copyDatabase(Context mContext){
try{
InputStream inputStream = mContext.getAssets().open(db.DBNAME);
String outFileName = db.DBLOCATION + db.DBNAME;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[] buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0){
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
return true;
}catch (Exception e){
return false;
}
}}
This is the activity that shows the content coming from sqlite
Main2Activity.java
public class Main2Activity extends AppCompatActivity {
DatabaseHelper db = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Typeface face = Typeface.createFromAsset(getAssets(), "font/Amiri-Regular.ttf");
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
final TextView muallaqa = findViewById(R.id.muallaqa);
muallaqa.setMovementMethod(new ScrollingMovementMethod());
muallaqa.setTypeface(face);
Intent intent = getIntent();
String title = intent.getStringExtra("title");
String fullMuallaqa = db.getMuallaqa(title);
muallaqa.setText(fullMuallaqa);
this.setTitle(title);
}}
For Reference Follow Steps
1)create setter and getter methods for id, title, content
for example
public class settter
{
int id;
String name;
String content;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
2)add recyclerview in xml mainactivity
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
3)In MainActivity remove all listview releated code and add code given below
RecyclerView recyclerView=(RecyclerView)findViewById(R.id.recycler_view2);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//make array list object with setter class
ArrayList<setter> name =db.getAllTitles();
//new adapter(ArrayList<setter>, context) ,so initiate adapter
recyclerView.setAdapter(new adapter(name,getApplicationContext()));
//draw line
recyclerView.addItemDecoration(new
DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL));
4) create layout file which hold your data and inflate inside recyclerview
name: recycler_content_holder.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/recycler_content_holder"
>
<TextView
android:layout_width="50dp"
android:layout_height="match_parent"
android:gravity="center"
android:id="#+id/tv_id"/>
<TextView
android:layout_width="100dp"
android:layout_height="match_parent"
android:layout_marginLeft="30dp"
android:id="#+id/tv_title"
android:gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="30dp"
android:gravity="center|right"
android:id="#+id/tv_content"/>
</LinearLayout>
5) Create Adapter class
public class adapter extends RecyclerView.Adapter<adapter.AdapterViewHolder>
{
ArrayList<settter> data;
Context context;
public adapter(ArrayList<settter> data,Context context)
{
this.data=data;
this.context=context;
}
#NonNull
#Override
public AdapterViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
LayoutInflater layoutInflater=LayoutInflater.from(viewGroup.getContext());
View view=layoutInflater.inflate(R.recycler_content_holder,viewGroup,false);
return new ProgramingViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, final int i)
{
viewHolder.id.setText(""+data.get(i).getId());
viewHolder.title.setText(data.get(i).getTitle());
viewHolder.content.setText(data.get(i).getContent());
viewHolder.linearLayout.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String title = String.valueOf(data.get(i).getTitle());
Intent intent = new Intent(context, Main2Activity.class);
intent.putExtra("title", title);
startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return data.size();
}
//class programingViewHolder
public class AdapterViewHolder extends RecyclerView.ViewHolder
{
TextView id,title,content;
LinearLayout linearLayout;
public AdapterViewHolder(#NonNull View itemView) {
super(itemView);
id=(TextView)itemView.findViewById(R.id.tv_id);
title=(TextView)itemView.findViewById(R.id.tv_mtrNo);
content=(TextView)itemView.findViewById(R.id.tv_nm);
linearLayout=(LinearLayout)itemView.findViewById(R.id.recycler_content_holder);
}
}
}
6) change method in DatabaseHelper
public ArrayList<setter> getAllTitles(){
ArrayList<setter> arrayList = new ArrayList();
openDatabase();
setter set=new setter();
Cursor cursor = sqLiteDatabase.rawQuery("select * from muallaqat", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
set.setTitle(cursor.getString(cursor.getColumnIndex("title")));
//add object to arralist
arrayList.add(set);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return arrayList;
}
Just Copy, paste and understand, I hope it will help you.
If I understand correctly you want to use a recyclerview with data from an SQLite database? and you want open a new activity when you click on an item and populate it with data from the item? Check out this article
Implementation of RecyclerView with Cursor Adapter
Just Do one thing
That Take id and title from database and show title in recyclerview. And When onItemClick on recyclerview pass the id of perticular position to next activity.
And In next activity fetch id which is passed from previous activity.
And fetch data from data with id. You will get all the data.
And show fetched data to activity.

RecyclerView only display the first item

I'm trying to get data from a SQLite Database , and display it on a RecyclerView . However , the adapter only displays the first item . Many related topics are talking about changing the height of the parent layout to xxdp or to wrap_content , which I tried . Here is the code :
QuoteAdapter.java:
public class QuoteAdapter extends RecyclerView.Adapter<QuoteAdapter.QuoteViewHolder> {
private QuoteItemBinding binding;
private Context mContext;
private Cursor mCursor;
public QuoteAdapter(Context context,Cursor cursor) {
this.mContext = context;
this.mCursor = cursor;
}
#Override
public QuoteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
binding = DataBindingUtil.setContentView(
(Activity)mContext, R.layout.quote_item);
int quoteLayoutId = R.layout.quote_item;
LayoutInflater inflater = LayoutInflater.from(mContext);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(quoteLayoutId,parent,shouldAttachToParentImmediately);
QuoteViewHolder quoteViewHolder = new QuoteViewHolder(view);
return quoteViewHolder;
}
#Override
public void onBindViewHolder(QuoteViewHolder holder, int position) {
if(!mCursor.moveToPosition(position)) {
return;
}
String category = mCursor.getString(mCursor.getColumnIndex(QuoteContract.QuoteEntry.COLUMN_CATEGORY));
String author = mCursor.getString(mCursor.getColumnIndex(QuoteContract.QuoteEntry.COLUMN_AUTHOR));
String quote = mCursor.getString(mCursor.getColumnIndex(QuoteContract.QuoteEntry.COLUMN_CONTENT));
Log.d(this.getClass().getSimpleName(),quote);
holder.mQuoteAuthor.setText(author);
holder.mQuoteCategory.setText(category);
holder.mQuoteTextView.setText(quote);
//Passer l'ID en tag du itemView avec holder.itemView.setTag(id) si on veut une action paritculiere sur un item
}
#Override
public int getItemCount() {
return mCursor.getCount();
}
public void swapCursor(Cursor newCursor) {
if(mCursor != null) mCursor.close();
mCursor = newCursor;
if(newCursor != null) {
this.notifyDataSetChanged();
}
}
public class QuoteViewHolder extends RecyclerView.ViewHolder{
public TextView mQuoteTextView;
public TextView mQuoteAuthor;
public TextView mQuoteCategory;
public QuoteViewHolder(View itemView) {
super(itemView);
mQuoteTextView = binding.quote;
mQuoteAuthor = binding.quoteAuthor;
mQuoteCategory = binding.quoteCategory;
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,"Selected",Toast.LENGTH_LONG).show();
}
});
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private QuoteAdapter mQuoteAdapter;
private SQLiteDatabase mDb;
private static final String TAG = MainActivity.class.getSimpleName();
private ActivityMainBinding mainBinding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main);
RecyclerView quoteListRecycler = mainBinding.recyclerMain;
quoteListRecycler.setLayoutManager(new LinearLayoutManager(this));
QuoteDbHelper dbHelper = new QuoteDbHelper(this);
mDb = dbHelper.getWritableDatabase();
Cursor cursor = getAllQuotes();
mQuoteAdapter = new QuoteAdapter(this,cursor);
quoteListRecycler.setAdapter(mQuoteAdapter);
}
private Cursor getAllQuotes() {
return mDb.query(QuoteContract.QuoteEntry.TABLE_NAME,
null,
null,
null,
null,
null,
QuoteContract.QuoteEntry.COLUMN_DATE);
}
}
quote_item.xml
<?xml version="1.0" encoding="utf-8"?>
android:paddingBottom="#dimen/quote_item_padding"
android:paddingTop="#dimen/quote_item_padding"
android:id="#+id/item_for_recycler"
android:layout_width="match_parent"
android:layout_height="56dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/quoteCategory"
style="#style/TextAppearance.AppCompat.Display2"
android:paddingLeft="#dimen/quote_item_padding"
android:paddingTop="#dimen/quote_item_padding"
android:textSize="10sp"
tools:text="Category : Business"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/quote"
tools:text="Hello there"
android:layout_gravity="center"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/quoteAuthor"
android:layout_gravity="bottom|right"
style="#style/TextAppearance.AppCompat.Display2"
android:paddingLeft="#dimen/quote_item_padding"
android:paddingTop="#dimen/quote_item_padding"
android:paddingRight="#dimen/quote_item_padding"
android:textSize="10sp"
tools:text="Leonardo DeMontesquieu"
/>
</FrameLayout>
</layout>
Thank you in advance !

Blank ListView with BaseAdapter

I am trying to fill my list from database using BaseAdapter. Logcat don't show any error. Here is my code.
In this DatabaseHelper class, I have one table STUDENTS.
DatabaseHelper.java
public long saveData(Student std) {
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("NAME",std.name);
cv.put("CITY",std.city);
cv.put("AGE",std.age);
long id = db.insert("STUDENTS", null, cv);
db.close();
return id;
}
public ArrayList<Student> getAllStudent() {
ArrayList<Student> studentArrayList = new ArrayList<Student>();
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.query("STUDENTS",null,null,null,null,null,null);
Log.e("COUNT",""+cursor.getCount());
while (cursor.moveToNext()) {
Student s = new Student();
s.name = cursor.getString(cursor.getColumnIndex("NAME"));
s.city = cursor.getString(cursor.getColumnIndex("CITY"));
s.age = cursor.getString(cursor.getColumnIndex("AGE"));
studentArrayList.add(s);
}
db.close();
return studentArrayList;
}
MyBaseAdapter.java
public class MyBaseAdapter extends BaseAdapter {
ArrayList<Student> myList = new ArrayList<Student>();
LayoutInflater inflater;
Context context;
public MyBaseAdapter(Context context,ArrayList<Student> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public Student getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
myViewHolder viewHolder;
if(convertView == null){
convertView = inflater.inflate(R.layout.single_row, null);
viewHolder = new myViewHolder();
convertView.setTag(viewHolder);
} else {
viewHolder = (myViewHolder) convertView.getTag();
}
viewHolder.nameTextView = (TextView) convertView.findViewById(R.id.nameTextView);
viewHolder.cityTextView = (TextView) convertView.findViewById(R.id.cityTextView);
viewHolder.ageTextView = (TextView) convertView.findViewById(R.id.ageTextView);
viewHolder.nameTextView.setText(myList.get(position).name);
viewHolder.cityTextView.setText(myList.get(position).city);
viewHolder.ageTextView.setText(myList.get(position).age);
return convertView;
}
public class myViewHolder {
TextView nameTextView, cityTextView, ageTextView;
}
}
This is my model class
Student.java
public class Student {
String name;
String city;
String age;
}
and in my MainActivity I am trying to fill data into list.
MainActivity.java
public class MainActivity extends ActionBarActivity {
public EditText searchEditText;
public Button addButton;
public ListView studentListView;
public DatabaseHelper dbHelper;
public ArrayList<Student> arrayList;
public MyBaseAdapter myBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchEditText = (EditText)findViewById(R.id.searchEditText);
addButton = (Button)findViewById(R.id.addButton);
studentListView = (ListView) findViewById(R.id.studentListView);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,AddNewStudent.class);
startActivity(i);
}
});
dbHelper = new DatabaseHelper(getApplicationContext());
arrayList = dbHelper.getAllStudent();
myBaseAdapter = new MyBaseAdapter(MainActivity.this,arrayList);
studentListView.setAdapter(myBaseAdapter);
myBaseAdapter.notifyDataSetChanged();
}
}
single_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
android:id="#+id/container">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/nameTextView" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/cityTextView" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/ageTextView" />
</LinearLayout>
I don't know where I went wrong.
Finally, I have found the answer for this. You just need to add couple of line in getView() method to assign value from list to model class object.
public View getView(int position, View convertView, ViewGroup parent) {
Student std = new Student(); //this line I added
std = myList.get(position); //this line I added
myViewHolder viewHolder;
if(convertView == null){
convertView = inflater.inflate(R.layout.single_row, null);
viewHolder = new myViewHolder();
convertView.setTag(viewHolder);
} else {
viewHolder = (myViewHolder) convertView.getTag();
}
viewHolder.nameTextView = (TextView) convertView.findViewById(R.id.nameTextView);
viewHolder.cityTextView = (TextView) convertView.findViewById(R.id.cityTextView);
viewHolder.ageTextView = (TextView) convertView.findViewById(R.id.ageTextView);
viewHolder.nameTextView.setText(myList.get(position).name);
viewHolder.cityTextView.setText(myList.get(position).city);
viewHolder.ageTextView.setText(myList.get(position).age);
return convertView;
}

drag-sort-listview Drag is not working Android

I'm using drag-sort-listview to sort rows of my ListView, and I have created a demo using this library, but it is not working. When I try to drag rows it is not working.
public class MainActivity extends Activity implements OnItemClickListener {
public static final String[] titles = new String[] { "Strawberry",
"Banana", "Orange", "Mixed" };
public static final String[] descriptions = new String[] {
"It is an aggregate accessory fruit",
"It is the largest herbaceous flowering plant", "Citrus Fruit",
"Mixed Fruits" };
public static final Integer[] images = { R.drawable.drag,
R.drawable.drag, R.drawable.drag, R.drawable.drag };
//ListView listView;
DragSortListView listView;
List<RowItem> rowItems;
CustomListViewAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i], descriptions[i]);
rowItems.add(item);
}
listView = (DragSortListView) findViewById(R.id.listview);
//listView = (ListView) findViewById(R.id.list);
final CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
listView.setDropListener(new DropListener() {
#Override
public void drop(int from, int to) {
if (from != to) {
//DragSortListView list = getListView();
RowItem item = adapter.getItem(from);
adapter.remove(item);
adapter.insert(item, to);
listView.moveCheckState(from, to);
//Log.d("DSLV", "Selected item is " + listView.getCheckedItemPosition());
}
}
});
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(), "Item "
+ (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:dslv="http://schemas.android.com/apk/res/com.example.testingui"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.mobeta.android.dslv.DragSortListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:dividerHeight="5dp"
dslv:collapsed_height="2dp"
dslv:drag_enabled="true"
dslv:drag_handle_id="#drawable/drag"
dslv:drag_scroll_start="0.33"
dslv:drag_start_mode="onMove"
dslv:float_alpha="0.6"
dslv:max_drag_scroll_speed="0.5"
dslv:remove_enabled="true"
dslv:remove_mode="flingRemove"
dslv:slide_shuffle_speed="0.3"
dslv:sort_enabled="true"
dslv:track_drag_sort="true"
dslv:use_default_controller="true" />
</RelativeLayout>
CustomListViewAdapter.java
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {
Context context;
public CustomListViewAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.descs);
holder.txtTitle = (TextView) convertView.findViewById(R.id.titles);
holder.imageView = (ImageView) convertView.findViewById(R.id.icons);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
return convertView;
}
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/icons"
android:layout_width="80dp"
android:layout_height="80dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/titles"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/icons"
android:paddingBottom="10dp"
android:textColor="#CC0033"
android:textSize="16dp" />
<TextView
android:id="#+id/descs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/titles"
android:layout_toRightOf="#+id/icons"
android:paddingLeft="10dp"
android:textColor="#3399FF"
android:textSize="14dp" />
</RelativeLayout>
RowItem.java
public class RowItem {
private int imageId;
private String title;
private String desc;
public RowItem(int imageId, String title, String desc) {
this.imageId = imageId;
this.title = title;
this.desc = desc;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return title + "\n" + desc;
}
}
Use Drag handle Id in DragSortListView tag in Xml
dslv:drag_handle_id="#id/drag_handle"
Make an id.xml file and put drag handle id as above to make it common and use the same id on dragable handle image view in your row item.
Hope it helps.

Printing SQLite entries into a ListView

I am having some trouble learning the ins and outs of the SQLite world. I have some code that is allowing me to enter data into a DB. But what i want to do is return this data into a listview. At the moment all I could figure out to do was to have each row printed in a toast after a new entry is added. Can someone please show me how to alter my code to print it in a listview? Or to even look at my code and see that i am going about it in the right way. Thanks
This is the code i am using which calls a display record function
//---get all Records---
com.example.rory.dbtest.DBAdapter db = new com.example.rory.dbtest.DBAdapter(this);
db.open();
Cursor c = db.getAllRecords();
if (c.moveToFirst())
{
do {
DisplayRecord(c);
} while (c.moveToNext());
}
db.close();
This is the display record function
public void DisplayRecord(Cursor c)
{
Toast.makeText(this,
"id: " + c.getString(0) + "\n" +
"Item: " + c.getString(1) + "\n" +
"Litres: " + c.getString(2),
Toast.LENGTH_SHORT).show();
}
I know i need to change the second function but i dont know how to do that to make it print into a listview
this is the code of getting data from database and insert into Arraylist and insert into arrayAdapter and than display it in listview .
i just done some editing in your existing code.
com.example.rory.dbtest.DBAdapter db = new com.example.rory.dbtest.DBAdapter(this);
db.open();
ArrayList<String> data_list=new ArrayList<String>();
ListView lv=(ListView)findViewById(R.id.listView1);
Cursor c = db.getAllRecords();
if (c.moveToFirst())
{
do {
data_list.add(c.getString(0));
DisplayRecord(c);
} while (c.moveToNext());
}
ArrayAdapter<String> aa=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, data_list);
lv.setAdapter(aa);
lv - is the object of ListView.
Create a ListView. Then provide cursorAdapter to the ListView as it's adapter to bind the data in the database to the ListView.
There are examples in the samples folder of the SDK you downloaded in the project called ApiDemos.
You need to have, 1) listview, 2) Object class, 3) Custom Adapter
Here I have just tried to implement as per your requirement.
Since I dont have db I did not try to run. The point to is to five you idea.
Because listview is widget that we use more frequently in android. This is the best approach as per my knowledge.
Layouts that required,
activity_list.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".ListActivity" >
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
row_item.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"
android:padding="10dp" >
<TextView
android:id="#+id/Item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item" />
<TextView
android:id="#+id/Litres"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="litres" />
</LinearLayout>
ListActivity.java :
public class ListActivity extends Activity {
ArrayList<RowData> rowDataArrayList = new ArrayList<RowData>();
ListView list;
ListAdapter listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
list = (ListView) findViewById(R.id.list);
listAdapter = new ListAdapter(ListActivity.this, rowDataArrayList);
list.setAdapter(listAdapter);
getDataFromDB();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.list, menu);
return true;
}
private void getDataFromDB() {
rowDataArrayList.clear();
com.example.rory.dbtest.DBAdapter db = new com.example.rory.dbtest.DBAdapter(
this);
db.open();
Cursor c = db.getAllRecords();
if (c.moveToFirst()) {
do {
/**
* Set your data in class
*/
RowData rowData = new RowData();
rowData.setId(c.getString(0));
rowData.setItem(c.getString(1));
rowData.setLitres(c.getString(2));
rowDataArrayList.add(rowData);
} while (c.moveToNext());
}
db.close();
/**
* To reflect new data set change in listview
*/
listAdapter.notifyDataSetChanged();
}
}
RowData.java : Model[pojo] class to save data and to bind in custom adapter.
public class RowData {
String Id;
String Item;
String Litres;
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getItem() {
return Item;
}
public void setItem(String item) {
Item = item;
}
public String getLitres() {
return Litres;
}
public void setLitres(String litres) {
this.Litres = litres;
}
}
ListAdapter.java : custom adapter to bind in listview
public class ListAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<RowData> rowDataArrayList = new ArrayList<RowData>();
public ListAdapter(Context context, ArrayList<RowData> rowData) {
mContext = context;
rowDataArrayList = rowData;
}
#Override
public int getCount() {
return rowDataArrayList == null ? 0 : rowDataArrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
Holder holder = new Holder();
view = View.inflate(mContext, R.layout.row_item, null);
holder.tvtItem = (TextView) view.findViewById(R.id.Item);
holder.tvtLitres = (TextView) view.findViewById(R.id.Litres);
view.setTag(holder);
} else {
view = convertView;
}
Holder holder = (Holder) view.getTag();
holder.tvtItem.setText(rowDataArrayList.get(position).getItem());
holder.tvtLitres.setText(rowDataArrayList.get(position).getLitres());
return view;
}
class Holder {
TextView tvtItem;
TextView tvtLitres;
}
}
public class ListAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<RowData> rowDataArrayList = new ArrayList<RowData>();
public ListAdapter(Context context, ArrayList<RowData> rowData) {
mContext = context;
rowDataArrayList = rowData;
}
#Override
public int getCount() {
return rowDataArrayList == null ? 0 : rowDataArrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
Holder holder = new Holder();
view = View.inflate(mContext, R.layout.row_item, null);
holder.tvtItem = (TextView) view.findViewById(R.id.Item);
holder.tvtLitres = (TextView) view.findViewById(R.id.Litres);
view.setTag(holder);
} else {
view = convertView;
}
Holder holder = (Holder) view.getTag();
holder.tvtItem.setText(rowDataArrayList.get(position).getItem());
holder.tvtLitres.setText(rowDataArrayList.get(position).getLitres());
return view;
}
class Holder {
TextView tvtItem;
TextView tvtLitres;
}
}

Categories

Resources