Problem of displaying data into custom listView - android

I'm not good at using Custom Listview but I want to display my SQLite data into it.When I try it doesn't show me any thing in List.
thanks, guys to tell me what is the problem in advance:
Rq: Retrieving data works fine And my table has 3 rows :
my source code:
new_facture.java:
Databasehelper mydatabase;
ArrayAdapter<String> adapter;
ArrayList<String> itemList;
ArrayList<Product> arrayList;
CustomAdaptorLP customAdaptorLP;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_facture);
ListView LP = (ListView)findViewById(R.id.productLV);
mydatabase = new Databasehelper(this);///-----Inialisation de base
arrayList = new ArrayList<>();
arrayList = mydatabase.getallProductdataintolist();
customAdaptorLP = new CustomAdaptorLP(this,arrayList);
Product product = new Product();
Log.d("stat", " offline mode");
LP.setAdapter(customAdaptorLP);
CustomAdaptorLP.java::
private Activity activity;
private ArrayList<Product> Items;
private LayoutInflater inflater;
TextView tvId,tvname,tvprix;
Product sm;
public CustomAdaptorLP(Activity activity, ArrayList<Product> items) {
this.activity = activity;
this.Items = items;
}
#Override
public int getCount() {
return 0;
}
#Override
public Product getItem(int position) {
return Items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(inflater == null){
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if(convertView==null){
convertView = inflater.inflate(R.layout.lp_layout,null);
}
tvId = (TextView)convertView.findViewById(R.id.id_product);
tvname = (TextView)convertView.findViewById(R.id.name_product);
tvprix = (TextView)convertView.findViewById(R.id.prix_product);
sm = Items.get(position);
tvId.setText(sm.id);
tvname.setText(sm.produit);
tvprix.setText(sm.prix);
return convertView;
}
and Product is a class has 3 Strings id/produit/prix with GET/SET and those two constructs:
public Product(String id, String produit, String prix) {
this.id = id;
this.produit = produit;
this.prix = prix;
}
public Product() {
}
Databasehelper.java
public ArrayList<Product> getallProductdataintolist(){
ArrayList<Product> list = new ArrayList<>();
String sql = "select * from " + Table2;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db .rawQuery(sql,null);
if(cursor.moveToFirst()){
do{
Product sm = new Product();
sm.setId(cursor.getString(0));
sm.setProduit(cursor.getString(1));
sm.setPrix(cursor.getString(2));
}while (cursor.moveToNext());
}
return list;
}

I think you return 0 in getCount() method instead Items.size(); change your Adapter class method like below.
#Override
public int getCount() {
return Items.size();
}

Related

Display the total amount from TextView values in a Custom Listview

I have a shopping cart in my app, and I have been wondering how would I be able to get the sum of the values from the textviews in my listview, and then display it in another class?
That orderTotal array is the amount of quantity of products in each row
This is My Adapter Class:
public class ListCartAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> orderTotal;
public ListCartAdapter(Context context, ArrayList<String> orderTotal){
this.context = context;
this.orderTotal = orderTotal;
}
#Override
public int getCount() {
return orderName.size();
}
#Override
public Object getItem(int position) {
return orderName.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final cartDatabaseHelper db = new cartDatabaseHelper(context);
final View listView;
final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listView = inflater.inflate(R.layout.cart_list_item, null);
TextView total = (TextView) listView.findViewById(R.id.textOrderTotal);
total.setText(orderTotal.get(position));
return listView;
}
And this is MainActivity class:
//CART LISTVIEW
private ArrayList<String> orderid;
private ArrayList<String> orderName;
private ArrayList<String> orderSize;
private ArrayList<String> orderQuantity;
private ArrayList<String> orderTotal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
//CART LISTVIEW
orderid = new ArrayList<>();
orderName = new ArrayList<>();
orderSize = new ArrayList<>();
orderQuantity = new ArrayList<>();
orderTotal = new ArrayList<>();
TextView textTotal = (TextView) findViewById(R.id.textOrderSumTotal);
ListView listView = (ListView) findViewById(R.id.listView);
ListCartAdapter adapter = new ListCartAdapter(cart.this, orderid, orderName, orderSize, orderQuantity, orderTotal);
listView.setAdapter(adapter);
Cursor data = db.getListContents();
if(data.getCount() == 0){
btnCheckout.setVisibility(View.GONE);
}
else
{
btnCheckout.setVisibility(View.VISIBLE);
data.moveToFirst();
do{
orderid.add(data.getString(0));
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
orderTotal.add(data.getString(4));
} while (data.moveToNext());
}
data.close();
listView.setEmptyView(findViewById(R.id.emptyView));
}
The textTotal is where I am planning to display the total of the values from the listview.
Can anybody point me to the right direction? Thanks in advance!
Its simple if you've all prices listed in your array list named orderTotal. Iterate over the list and add all the values as following:
int total = 0;
for(String s : orderTotal){
total += Integer.parseInt(s);
}
display this total wherever you want. If price is float, then use Float.parseFloat(YOUR_FLOAT_STRING);

Android ArrayList Adapter doesn't show the ListView

I have an ArrayList to represent in a ListView by an Adapter:
private ArrayList <Contact> listContacts = new ArrayList <Contact> ();
This is the (simple) Contact Class:
public class Contact {
String pic;
String name;
String surname1;
String surname2;
String phonenumber;
}
And this is the Adapter Class:
public class ContactsAdapter extends ArrayAdapter<Contact> {
private static class ViewHolder {
ImageView pic;
TextView name;
TextView surname1;
TextView surname2;
TextView phonenumber;
}
Context context;
public ContactsAdapter(Context context, int textViewResourceId, ArrayList<Contact> items) {
super(context, textViewResourceId, items);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(this.getContext())
.inflate(R.layout.layout_contact, parent, false);
holder = new ViewHolder();
holder.pic= (ImageView) convertView.findViewById(R.id.pic);
holder.name= (TextView) convertView.findViewById(name);
holder.surname1= (TextView) convertView.findViewById(R.id.surname1);
holder.surname2= (TextView) convertView.findViewById(R.id.surname2);
holder.phonenumber= (TextView) convertView.findViewById(R.id.phonenumber);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Contact item = getItem(position);
if (item!= null) {
int idImage = context.getResources().getIdentifier(item.pic, "drawable", context.getPackageName());
holder.pic.setImageResource(idImage);
holder.name.setText(item.name);
holder.surname1.setText(item.surname1);
holder.surname2.setText(item.surname2);
holder.phonenumber.setText(item.phonenumber);
}
return convertView;
}
}
The MainActivity is like this:
public class MainActivity extends ListActivity {
private ArrayList <Contact> listContacts = new ArrayList <Contact> ();
ContactsAdapter contactsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean result = loadListFromFiles();
if (result) {
loadContacts();
}
}
private void loadContacts() {
contactsAdapter = new ContactsAdapter(getApplicationContext(), R.layout.activity_main, listContacts);
setListAdapter(contactsAdapter);
}
The loadListFromFiles code:
private boolean loadListFiles(){
boolean result = false;
Context context = getApplicationContext();
File path = context.getFilesDir();
File[] files = path.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
Log.d("Files", "FileName:" + files[i].getName());
result = loadFile(files[i].getName());
}
return resultado;
}
private boolean loadFile(String fileName) {
String[] arrayContact = new String[4];
try
{
BufferedReader fin =
new BufferedReader(
new InputStreamReader(
openFileInput(fileName)));
int i = 0;
String line= "";
while ((line= fin.readLine()) != null) {
arrayContact[i] = linea;
i++;
}
fin.close();
Contact contact = new Contact();
contact.pic = arrayContact[3];
contact.name= arrayContact[0];
contact.surname1 = arrayContact[1];
contact.surname2 = arrayContact[2];
contact.phonenumber= arrayContact[3];
listContacts.add(contact);
return true;
}
catch (Exception ex)
{
Log.e("Files", "Error to read file by memory");
return false;
}
}
The ArrayList is right, but the layout don't show anything.
Override getCount() and getItem() methods to return count and contact item.
#Override
public int getCount() {
if(items == null)
return 0;
return items.size();
}
#Override
public Contact getItem(int i) {
return items.get(i);
}
Also, create one variable items in Adapter class and assign it to parameter passed to adapter constructor.
ArrayList<Contact> items;
public ContactsAdapter(Context context, int textViewResourceId, ArrayList<Contact> items) {
super(context, textViewResourceId, items);
this.context = context;
this.items = items;
}

How do I retrieve two fields from a prepopulate sqlite db and assign it to custom list view?

I want to retrieve data from two fields from prepopulate sqlite database. The fields are Organization Name (org_name) and Contact Number (contact_no). After that I need to assign org_name data to a large text field and contact_no to small text field in my custom list view.
I have tried this only with one field. It's working fine. But when I'm trying to retrieve two fields it's not working. This is what I tried. Please help me to solve this issue.
ContactView class
public class ContactView extends Activity {
private ListView listView;
private ListView listView1;
List<Organization> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
DBAccess databaseAccess = DBAccess.getInstance(this);
databaseAccess.open();
List<String> quotes = databaseAccess.getQuotes(getIntent().getStringExtra("ID_EXTRA"));
databaseAccess.close();
List<Organization> rowItem=new ArrayList<Organization>();
for(String quote:quotes){
Organization temp=new Organization(quote);
rowItem.add(temp);
}
listView = (ListView)findViewById(R.id.listView);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.single_row_item, rowItem);
listView.setAdapter(adapter);
}
Database Access Class
public class DBAccess {
private SQLiteOpenHelper openHelper;
private SQLiteDatabase database;
private static DBAccess instance;
String passedVar = null;
private ListView listView;
public DBAccess(Context context) {
this.openHelper = new HelloDatabase(context);
}
public static DBAccess getInstance(Context context) {
if (instance == null) {
instance = new DBAccess(context);
}
return instance;
}
public void open() {
this.database = openHelper.getWritableDatabase();
}
public void close() {
if (database != null) {
this.database.close();
}
}
public List<String> getQuotes(String id) {
List<String> list = new ArrayList<>();
Integer value;
if (id != null) {
Cursor cursor = database.rawQuery("SELECT org_name,contact_no FROM org_name WHERE category_id = \"" + id + "\"", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));
list.add(cursor.getString(cursor.getColumnIndex("contact_no")));
cursor.moveToNext();
}
cursor.close();
}
return list;
}}
Bean class
public class Organization {
public String title;
public String telenum;
public Organization(String title,String telenum) {
this.title = title;
this.telenum=telenum;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTelenum(){
return telenum;
}
public void setTelenum(String telenum){
this.telenum=telenum;
}
}
CustomListViewAdapter class
public class CustomListViewAdapter extends ArrayAdapter<Organization> {
Context context;
public CustomListViewAdapter(Context context, int layout,
List<Organization> items) {
super(context, layout, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
TextView txtTitle;
TextView txtTele;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Organization rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.single_row_item, null);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView.findViewById(R.id.org_name);
holder.txtTele = (TextView) convertView.findViewById(R.id.tele_num);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtTitle.setText(rowItem.getTitle());
holder.txtTele.setText(rowItem.getTelenum());
return convertView;
}}
Note : If any one facing the same issue, kindly use SimpleCursorAdapter. Its simple, easy to use and efficient. Find a simple example here or checkout my answer on this thread https://stackoverflow.com/a/37560755/5460053
It is not working for two fields because of the following lines in getQuotes() method of DBAccess class :
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));//Adding org_name first. org_name is added at indexes : 0,2,4,...
list.add(cursor.getString(cursor.getColumnIndex("contact_no")));//Then adding contact_no. contact_no is added at indexes : 1,3,5,...
cursor.moveToNext();
}
Then while creating a datasource for the adapter, org_name and contact_no are added at alternate indexes
List<Organization> rowItem=new ArrayList<Organization>();
for(String quote:quotes){
Organization temp=new Organization(quote);//I wonder how this worked as there is only one contructor for Organization which is expecting 2 parameters
rowItem.add(temp);
}
Change your DBAccess class getQuotes() to this :
public List<Organization> getQuotes(String id) {
List<Organization> list = new ArrayList<>();
if (id != null) {
Cursor cursor = database.rawQuery("SELECT org_name,contact_no FROM org_name WHERE category_id = \"" + id + "\"", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Organization org = new Organization(cursor.getString(0),
cursor.getString(cursor.getColumnIndex("contact_no")));
list.add(org);
cursor.moveToNext();
}
cursor.close();
}
return list;
}
And change your ContactView Activity's onCreate() to this :
public class ContactView extends Activity {
private ListView listView;
private ListView listView1;
List<Organization> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
DBAccess databaseAccess = DBAccess.getInstance(this);
databaseAccess.open();
List<Organization> rowItem = databaseAccess.getQuotes(getIntent().getStringExtra("ID_EXTRA"));
databaseAccess.close();
listView = (ListView)findViewById(R.id.listView);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.single_row_item, rowItem);
listView.setAdapter(adapter);
}

Android: fill list view with data from sqlite

Overview: The programme I'm now trying to make has the following steps.
get the input data from users and store them in the SQLite database.
Fill the list view with the data retrieved from the database.
In order to implement 1, I first created the addNewItem() method as follows.
public void addNewPost(Post post) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
// get the variables which are to be put into the database row.
String uploader = post.getUploader();
String content = post.getContent();
String privacy_level = post.getPrivacyLevel();
String uploaded_at = post.getUploadedAt();
String edited_at = post.getEditedAt();
values.put(KEY_UPLOADER, uploader);
values.put(KEY_CONTENT, content);
values.put(KEY_PRIVACY_LEVEL, privacy_level);
values.put(KEY_UPLOADED_AT, uploaded_at);
values.put(KEY_EDITED_AT, edited_at);
db.insert(TABLE_POST, null, values);
db.close();
}
And for 2, I created another method called initListView().
private void initListView() {
SQLiteDatabase db = sqliteHandler.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + SQLiteHandler.TABLE_POST, null);
username.clear();
uploaded_at.clear();
content.clear();
if(cursor.moveToFirst()) {
do {
username.add(cursor.getString(cursor.getColumnIndex(DataKeyLists.KEY_UPLOADER)));
uploaded_at.add(cursor.getString(cursor.getColumnIndex(DataKeyLists.KEY_UPLOADED_AT)));
content.add(cursor.getString(cursor.getColumnIndex(DataKeyLists.KEY_CONTENT)));
} while(cursor.moveToNext());
}
FeedAdapter adapter = new FeedAdapter(this, username, uploaded_at, content);
listView.setAdapter(adapter);
cursor.close();
}
And finally this is the FeedAdapter class.
public class FeedAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> username;
private ArrayList<String> uploaded_at;
private ArrayList<String> content;
public FeedAdapter(Context context, ArrayList<String> username, ArrayList<String> uploaded_at, ArrayList<String> content) {
this.context = context;
this.username = username;
this.uploaded_at = uploaded_at;
this.content = content;
}
public int getCount() {
return username.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater;
if(convertView == null) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.feed_item, null);
ImageView ivFeedThumbnail = (ImageView) convertView.findViewById(R.id.ivFeedThumbnail);
TextView tvFeedUsername = (TextView) convertView.findViewById(R.id.tvFeedUsername);
TextView tvFeedUploaded = (TextView) convertView.findViewById(R.id.tvFeedCreated);
TextView tvFeedText = (TextView) convertView.findViewById(R.id.tvFeedText);
TextView tvFeedLikes = (TextView) convertView.findViewById(R.id.tvFeedLikes);
TextView tvFeedComments = (TextView) convertView.findViewById(R.id.tvFeedComments);
Button btnLike = (Button) convertView.findViewById(R.id.btnLike);
Button btnComment = (Button) convertView.findViewById(R.id.btnComment);
tvFeedUsername.setText(username.get(position));
tvFeedUploaded.setText(uploaded_at.get(position));
tvFeedText.setText(content.get(position));
}
return convertView;
}
}
The code seems to have no problem, but when I run the application, the list is still empty.
Any tips for the solution will be very much appreciated.

Press button in listView adapter to get data in this row

I have a listView that shows data that in sqlite, I'm using baseAdapter.
The list row contains text and button.
I press the button in each row to give me each data of the selected row from the database (not pressing the row itself)
This is code of listView:
tipsList = new ArrayList<HashMap<String, String>>();
list = (ListView) rootView.findViewById(R.id.tipList);
do {
map = new HashMap<String, String>();
map.put(DAO.TIP_ID, c.getString(c.getColumnIndex(c.getColumnName(0))));
map.put(DAO.TIP_CONTENT, c.getString(c.getColumnIndex(c.getColumnName(1))));
map.put(DAO.TIP_FAVORITE, c.getString(c.getColumnIndex(c.getColumnName(2))));
// adding HashList to ArrayList
tipsList.add(map);
} while (c.moveToNext());
tipsAdapter = new TipsAdapter(getActivity(), tipsList, tipType, db);
list.setAdapter(tipsAdapter);
And this is code of TipsAdapter.java
public class TipsAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
Context context;
Typeface tf;
String tipID;
String tipText;
String isFavorite;
DAO db;
HashMap<String, String> quote;
int selectedTipType;
public TipsAdapter(Activity a, ArrayList<HashMap<String, String>> d, int selectedTipType, DAO db) {
activity = a;
data = d;
context = a;
this.selectedTipType = selectedTipType;
this.db = db;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// ==============================================================================
public int getCount() {
return data.size();
}
// ==============================================================================
public Object getItem(int position) {
return position;
}
// ==============================================================================
public long getItemId(int position) {
return position;
}
// ==============================================================================
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.tip_list_row, null);
TextView tipContent = (TextView) vi.findViewById(R.id.tip_text); // tip
final ImageView favStar = (ImageView) vi.findViewById(R.id.favorite_star);
tf = Typeface.createFromAsset(activity.getAssets(), "fonts/bauhausm_0.ttf");
tipContent.setTypeface(tf);
quote = new HashMap<String, String>();
quote = data.get(position);
tipText = quote.get(DAO.TIP_CONTENT).trim();
favStar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// I want here get all data like tipId - tipText - tipFavotite of the current row in toast
}
});
return vi;
}
}
How to get the data of the current row when press the button?
Hope anyone got my mean.
Thanks in advance.
Maybe you can set the tag of your button.
favStar.setTag(position);
favStar.setOnClickListener (new OnClickListener()
{
#Override
public void onClick(View view) {
int position = (int) view.getTag();
HashMap<String, String>() quote = data.get(position);
String tipText = qout.get(DAO.TIP_CONTENT);
String tipContent = ......;
}
}
I Solved it by myself by making position as final and put quote = data.get(position); inside the listener of the button.

Categories

Resources