SetAdapter doesn't work - java

I have some sort of an issue and I'd really appreciate it, if
you could help me.
Problem: I want to take Data from a SQLite Database and display it in
a Listview or a Gridview, either way.
I watched a tutorial and tried to follow the rules and the idea behind it,
with copying the source code and changing the code piece by piece for my
own purpose. Strangely, the code I'm having issues with works in the tutorial
code, and also in another class in my project, but refuses to work in the
recent file..
So, this is the oncreate of the working file:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_member_list);
mem_op = new Member_Operations(this);
mem_op.open();
List values = mem_op.getAllMembers();
et = (EditText) findViewById(R.id.et1);
et2 = (EditText) findViewById(R.id.et2);
gv = (GridView) findViewById(R.id.gv);
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, values);
gv.setAdapter(adapter);
} // oncreate
and this is the related super-class:
public class Member_Operations {
public DBHelper_Members db_helper;
private SQLiteDatabase database;
private String [] MEMBER_TABLE_COLUMNS = { db_helper.MEMBERS_COLUMN_ID,db_helper.MEMBERS_COLUMN_NAME,db_helper.MEMBERS_COLUMN_PERMISSION};
public Member_Operations(Context context)
{
db_helper = new DBHelper_Members(context);
}
public void open() throws SQLException{
database = db_helper.getWritableDatabase();
}
public void close() {
db_helper.close();
}
public Member addMember(String name, String permission){
ContentValues contentValues = new ContentValues();
contentValues.put(db_helper.MEMBERS_COLUMN_NAME, name);
contentValues.put(db_helper.MEMBERS_COLUMN_PERMISSION,permission);
long MemID = database.insert(db_helper.MEMBER_TABLE, null, contentValues);
Cursor cursor = database.query(db_helper.MEMBER_TABLE,
MEMBER_TABLE_COLUMNS,db_helper.MEMBERS_COLUMN_ID + " = " +
+ MemID, null,null,null,null);
cursor.moveToFirst();
Member newComment = parseMember(cursor);
cursor.close();
return newComment;
}
public void deleteMember(Member mem){
long id = mem.getID();
SQLiteDatabase db = db_helper.getWritableDatabase();
db.delete(db_helper.MEMBER_TABLE, db_helper.MEMBERS_COLUMN_ID + " = " + id,
null);
}
public List getAllMembers(){
List members = new ArrayList();
Cursor cursor = database.query(db_helper.MEMBER_TABLE,
MEMBER_TABLE_COLUMNS,null,null,null,null,null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
Member member = parseMember(cursor);
members.add(member);
cursor.moveToNext();
}
cursor.close();
return members;
}
private Member parseMember(Cursor cursor){
Member member = new Member();
member.setID(cursor.getInt(0));
member.setName(cursor.getString(1));
member.setPermission(cursor.getString(2));
return member;
}
This is the one refusing to work:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
kal_op = new Kalender_Operations(this);
kal_op.open();
List values = kal_op.getAllDays();
ArrayAdapter<Date> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, values);
// here i tried, unlike the first one, to add the Type(Date).
// But either way it doesn't work.
GridView gv = (GridView) findViewById(R.id.gv);
ListActivity la = new ListActivity();
la.setListAdapter(adapter);
}
And its super-class:
public class Kalender_Operations {
SQLiteDatabase database;
DBHelper db_helper;
String [] DATES_TABLE_COLUMNS = { db_helper.JANUARY_COLUMN_ID,
db_helper.JANUARY_COLUMN_DAY,db_helper.JANUARY_COLUMN_EVENT};
public Kalender_Operations(Context context)
{
db_helper = new DBHelper(context);
}
public void open() throws SQLException {
database = db_helper.getWritableDatabase();
}
public void close() {
db_helper.close();
}
public Date addDate (String day, String event){
ContentValues contentValues = new ContentValues();
contentValues.put(db_helper.JANUARY_COLUMN_DAY, day);
contentValues.put(db_helper.JANUARY_COLUMN_EVENT, event);
long DateID = database.insert(db_helper.JANUARY_TABLE,null,contentValues);
Cursor cursor = database.query(db_helper.JANUARY_TABLE,
DATES_TABLE_COLUMNS, db_helper.JANUARY_COLUMN_ID
+ " = " + DateID,null,null,null,null);
cursor.moveToFirst();
Date newComment = parseDate(cursor);
cursor.close();
return newComment;
}
public void showDetails(int i, Context context){
Intent intent = new Intent(context, Test_Intent.class);
intent.putExtra("Position", i);
intent.putExtra("Month", db_helper.JANUARY_TABLE);
intent.putExtra("Year", db_helper.JANUARY_YEAR);
context.startActivity(intent);
}
public List getAllDays(){
List Dates = new ArrayList();
Cursor cursor = database.query(db_helper.JANUARY_TABLE,
DATES_TABLE_COLUMNS, null, null, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
Date date = parseDate(cursor);
Dates.add(date);
cursor.moveToNext();
}
cursor.close();
return Dates;
}
public Date parseDate(Cursor cursor){
Date date = new Date();
date.setID(cursor.getInt(0));
date.setDay(cursor.getString(1));
date.setEvent(cursor.getString(2));
return date;
}
}
Please help me. I really want to continue learning, but I spent a lot of time now trying to figure out why one works, the other one doesn't..

Related

Retrieving data from a database?

I have an SQLite database that is populated when the user create a profile and fill a form with his contact informations in SetUpProfile activity and then retrieve that data and show it back on UserProfile activity.
Question: How to display the profile data (name, phone, address...) in textviews ?
This is what I've done so far:
Profile class
public class Profile {
private int _id = 1;
private String _industryName;
private String _industryType;
private String _email;
private String _phone;
private String _address;
private String _packageType;
public Profile() {
/** stays empty */
}
public Profile(int _id, String _industryName, String _industryType, String _email, String _phone, String _address, String _packageType) {
this._id = _id;
this._industryName = _industryName;
this._industryType = _industryType;
this._email = _email;
this._phone = _phone;
this._address = _address;
this._packageType = _packageType;
}
public Profile(String _industryName, String _industryType, String _email, String _phone, String _address, String _packageType) {
this._industryName = _industryName;
this._industryType = _industryType;
this._email = _email;
this._phone = _phone;
this._address = _address;
this._packageType = _packageType;
}
//getters and setters
}
This is the handler DBHandler class
addProfile() method:
public void addProfile(Profile profile) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_INDUSTRY_NAME, profile.get_industryName());
values.put(KEY_INDUSTRY_TYPE, profile.get_industryType());
values.put(KEY_EMAIL, profile.get_email());
values.put(KEY_PHONE, profile.get_phone());
values.put(KEY_ADDRESS, profile.get_address());
values.put(KEY_PACKAGE_TYPE, profile.get_packageType());
// Inserting Row
db.insert(TABLE_PROFILE, null, values);
db.close();
}
getProfile() method
public Profile getProfile(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_PROFILE, new String[] {
KEY_ID, KEY_INDUSTRY_NAME, KEY_INDUSTRY_TYPE, KEY_EMAIL, KEY_PHONE, KEY_ADDRESS, KEY_PACKAGE_TYPE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Profile profile = new Profile(
Integer.parseInt(cursor.getString(0)),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4),
cursor.getString(5),
cursor.getString(6)
);
return profile;
}
MainActivity class
public class UserProfile extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
//SQLite databes is supposed to populate those textViews
industry_type = (TextView) findViewById(R.id.b_industry);
b_name = (TextView) findViewById(R.id.b_industry_name);
b_email = (TextView) findViewById(R.id.mail);
b_phone = (TextView) findViewById(R.id.phone);
b_address = (TextView) findViewById(R.id.address);
plan_type = (TextView) findViewById(R.id.p_title);
edit_profile = (Button) findViewById(R.id.editProfile);
industry_img = (ImageView) findViewById(R.id.thumbnail);
plan_img = (ImageView) findViewById(R.id.plan_icon);
edit_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditProfile();
}
});
}
This is the approach I used :
SQLiteDatabase db = null;
DBHandler dd = new DBHandler(getBaseContext());
dd.getWritableDatabase();
db= openOrCreateDatabase("profileManager.db", Context.MODE_PRIVATE, null);
Cursor cc = db.rawQuery("SELECT * FROM profile", null);
if(cc.getCount()>=1) {
cc.moveToFirst();
try {
for(int i=0;i < cc.getCount();i++){
bname = cc.getString(1);
btype = cc.getString(2);
bmail = cc.getString(3);
bphone = cc.getString(4);
baddress = cc.getString(5);
bpackage = cc.getString(6);
}
}catch (Exception e){
e.getMessage();
}
}
You need to create getters of your private variables of profile class. For example as below.
public String getIndustryName() {
return _industryName;
}
Then you need to call getProfile() method from your activity class which return Profile object.
From Profile object, you can get all value and set it into relevent TextView and display. For example as below.
b_name.setText(profile.getIndustryName());

Listview isn't updating in Fragment

I know for sure that the updateFromDatabase() function works, I've used print statements to see that the entries put into mCoordinatesArray are there and not empty strings. However when I restart the app, the fragment never populates the list view with items in the database. I think it has something to do with the Fragment Lifecycle, but I have no idea.
Additionally, when I don't restart the app and run it for the first time the list view runs fine. When I rotate or restart the app, the list view no longer populates.
public class LocalFragment extends Fragment{
private ListView mLocalList;
private ArrayAdapter<String> adapter;
private ArrayList<String> mCoordinatesArray;
private BroadcastReceiver mBroadcastReceiver;
private LocationBaseHelper mDatabase;
private DateFormat dateFormat;
private String dateString;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_local,container,false);
// SQLite Setup
mDatabase = new LocationBaseHelper(getActivity());
mLocalList = (ListView) v.findViewById(R.id.lv_local);
mCoordinatesArray = new ArrayList<>();
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, mCoordinatesArray);
if(!mDatabase.size().equals("0")){
updateFromDatabase();
}
mLocalList.setAdapter(adapter);
return v;
}
#Override
public void onResume() {
super.onResume();
if(mBroadcastReceiver == null){
mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
dateFormat = new SimpleDateFormat("MM/dd HH:mm:ss a");
dateString = dateFormat.format(new Date());
String[] data = intent.getStringExtra("coordinates").split(" ");
mDatabase.insertEntry(dateString,data[0],data[1]);
System.out.println(mDatabase.size());
mCoordinatesArray.add(dateString + " " + data[0] + " " + data[1]);
adapter.notifyDataSetChanged();
}
};
}
getActivity().registerReceiver(mBroadcastReceiver, new IntentFilter("location_update"));
}
#Override
public void onDestroy() {
super.onDestroy();
if(mBroadcastReceiver!=null){
getActivity().unregisterReceiver(mBroadcastReceiver);
}
}
// THIS METHOD CAN BE USED TO UPDATE THE ARRAY HOLDING COORDINATES FROM THE LOCAL DATABASE
private void updateFromDatabase(){
//mCoordinatesArray.clear();
mCoordinatesArray = mDatabase.getEntireDatabase();
adapter.notifyDataSetChanged();
}
}
Here's my Helper class, just in case, but I don't think the problem is here.
public class LocationBaseHelper extends SQLiteOpenHelper {
private static final int VERSION = 1;
private static final String D​A​T​A​B​A​S​E​_​N​A​M​E​ = "locationBase.db";
public LocationBaseHelper(Context context) {
super(context, D​A​T​A​B​A​S​E​_​N​A​M​E​, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + LocationTable.NAME + " (" +
LocationTable.Cols.DATE_TIME + " text, " +
LocationTable.Cols.LATITUDE + " text, " +
LocationTable.Cols.LONGITUDE + " text )"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insertEntry(String date_time, String latitude, String longitude){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues content = new ContentValues();
content.put(LocationTable.Cols.DATE_TIME,date_time);
content.put(LocationTable.Cols.LATITUDE,latitude);
content.put(LocationTable.Cols.LONGITUDE,longitude);
db.insert(LocationTable.NAME,null,content);
}
public ArrayList<String> getEntireDatabase(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + LocationTable.NAME,null);
cursor.moveToFirst();
ArrayList<String> values = new ArrayList<>();
do{
String value = (String) cursor.getString(cursor.getColumnIndex(LocationTable.Cols.DATE_TIME)) + " " +
(String) cursor.getString(cursor.getColumnIndex(LocationTable.Cols.LATITUDE)) + " " +
(String) cursor.getString(cursor.getColumnIndex(LocationTable.Cols.LONGITUDE));
values.add(0,value);
}while(cursor.moveToNext());
return values;
}
public String size(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM " + LocationTable.NAME,null);
cursor.moveToFirst();
return cursor.getString(0);
}
}
By calling mCoordinatesArray = mDatabase.getEntireDatabase(); you are changing the reference of mCoordinatesArray, and adapter is still holding the old reference, so it does not see any changes.
Instead of creating new instance of mCoordinateArray, you should rather just update values it contains, something like:
mCoordinateArray.clear();
mCoordinateArray.addAll(mDatabase.getData());
adapter.notifyDataSetChange();
That way you are changing the data that is referenced by adapter, instead of creating completely new set of data which the adapter is not aware of.
Try to recreate your ArrayAdapter instead of using .notifyDataSetChanged():
// update Data
mCoordinatesArray = mDatabase.getEntireDatabase();
// create new adapter with new updated array
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, mCoordinatesArray);
// set adapter for the listview
mLocalList.setAdapter(adapter);
You can put this method in your fragment and call from activity that attach to fragment.
public void updateList(List<?> result) {
if (multimediaListRent.size()>0) {
multimediaGridView.setAdapter(gridMediaListAdapter);
multimediaListRent.clear();
}
gridMediaListAdapter.notifyDataSetChanged();
}

Android cannot resolve constructor ArrayAdapter

I am aware that this question has been asked multiple times before but none of the solutions have worked for me. This is my code:
public class reminderDAO extends dbManager{
public reminderDAO(Context context) {
super(context);
}
// Adding new reminder
public void addReminder(Reminder reminder) {
//dbm.gettingWritable(values);
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(getKEY_DATE(), reminder.getReminderDate());
values.put(getKEY_TITLE(), reminder.getReminderTitle());
values.put(getKEY_DESC(), reminder.getReminderDescription());
values.put(getKEY_TIME(), reminder.getReminderTime());
// Inserting Row
db.insert(getDATABASE_TABLE(), null, values);
db.close(); // Closing database connection
}
public List<Reminder> getAllReminders(ListView lv) {
ArrayList<Reminder> reminderList = new ArrayList<Reminder>();
// Select All Query
String selectQuery = "SELECT * FROM " + getDATABASE_TABLE();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
MainActivity ma = new MainActivity();
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Reminder r = new Reminder();
r.setReminderDate(cursor.getString(0));
r.setReminderTitle(cursor.getString(1));
r.setReminderDescription(cursor.getString(2));
r.setReminderTime(cursor.getString(3));
// Adding reminder to list
reminderList.add(r);
} while (cursor.moveToNext());
}
ArrayAdapter<Reminder> arrayAdapter = new ArrayAdapter<Reminder>(
this,
android.R.layout.simple_list_item_1,
reminderList );
lv.setAdapter(arrayAdapter);
// return reminder list
return reminderList;
}
}
I've got a feeling it is to do with 'this' inside the arrayAdapter. I have tried getActivity(), this.getActivity(), reminderDAO.this.getActivity(), MainActivity.this and reminderDAO.this.
Anyone have a solution?
Create a Context variable in your class. and assign it from the constructor parameter.
private Context context;
public reminderDAO(Context context) {
this.context = context;
super(context);
}
Then use this variable to pass to the ArrayAdapter
ArrayAdapter<Reminder> arrayAdapter = new ArrayAdapter<Reminder>(
this.context,
android.R.layout.simple_list_item_1,
reminderList );

Display data from SQLite database into ListView in Android

Although this question has been asked many times on here, I just can't find the proper answer to fit my code. I realise it may be something small, but I just can't seem to find the problem as I'm only really new to this.
Here's my code getClientNames in DatabaseHelper class:
public Cursor getSitesByClientname(String id) {
String[] args={id};
Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
String results = "";
/*int count = myCursor.getCount();
String[] results = new String[count + 1];
int i = 0;*/
if (myCursor != null) {
if(myCursor.getCount() > 0)
{
for (myCursor.moveToFirst(); !myCursor.isAfterLast(); myCursor.moveToNext())
{
results = results + myCursor.getString(myCursor.getColumnIndex("client_sitename"));
}
}
}
return results;
}
One problem is that I'm returning a 'String' to the 'Cursor', but I'm not sure what is the best way around this, as I think I should be returning a Cursor.
Here's the ClientSites class where I want to display the data:
public class ClientSites extends Activity {
//public final static String ID_EXTRA="com.example.loginfromlocal._ID";
private DBUserAdapter dbHelper = null;
private Cursor ourCursor = null;
private Adapter adapter=null;
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.client_sites);
Intent i = getIntent();
String uID = String.valueOf(i.getIntExtra("userID", 0));
ListView myListView = (ListView)findViewById(R.id.myListView);
dbHelper = new DBUserAdapter(this);
//dbHelper.createDatabase();
dbHelper.openDataBase();
ourCursor = dbHelper.getSitesByClientname(uID);
Log.e("ALERT", uID.toString());
startManagingCursor(ourCursor);
Log.e("ERROR", "After start manage cursor: ");
//#SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null);
CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
adapter = new Adapter(ourCursor);
//Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();
myListView.setAdapter(adapter);
myListView.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "XXERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position,
long id)
{
Intent i=new Intent(ClientSites.this, InspectionPoints.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
};
class Adapter extends CursorAdapter {
#SuppressWarnings("deprecation")
Adapter(Cursor c) {
super(ClientSites.this, c);
}
//#Override
public void bindView(View row, Context ctxt,
Cursor c) {
Holder holder=(Holder)row.getTag();
holder.populateFrom(c, dbHelper);
}
#Override
public View newView(Context ctxt, Cursor c,
ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
Holder holder=new Holder(row);
row.setTag(holder);
return(row);
}
}
static class Holder {
private TextView name=null;
Holder(View row) {
name=(TextView)row.findViewById(R.id.ingredientText);
}
void populateFrom(Cursor c, DBUserAdapter r) {
name.setText(r.getName(c));
}
}
}
Here is the code I'm now using to try and display the data in the Listview. I have altered it somewhat from my original attempt, but still not sure what I'm doing wrong.
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.client_sites);
Intent i = getIntent();
String uID = String.valueOf(i.getIntExtra("userID", 0));
//int uID = i.getIntExtra("userID", 0);
//ListView myListView = (ListView)findViewById(R.id.myListView);
dbHelper = new DBUserAdapter(this);
dbHelper.createDatabase();
dbHelper.openDataBase();
String[] results = dbHelper.getSitesByClientname(uID);
//setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results));
//adapter = new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results);
setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.layout.client_sites, results));
//ListView myListView = (ListView)findViewById(R.id.myListView);
ListView listView = getListView();
listView.setTextFilterEnabled(true);
//ourCursor = dbHelper.getSitesByClientname(uID);
//Log.e("ALERT", uID.toString());
//startManagingCursor(ourCursor);
//Log.e("ERROR", "After start manage cursor: ");
//#SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null); // LOOK AT THIS IN THE MORNING!!!!!!!!!!!
//CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
//adapter = new Adapter(ourCursor);
//Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();
//myListView.setAdapter(adapter);
//myListView.setOnItemClickListener(onListClick);
I Created a Listview from a database. Here is the code I used for my app
Here is part of the database handler. It will return a List of Categories for my listview. It can return a list of Strings if that is what you need.
public List<Category> getAllCategorys() {
ArrayList<Category> categoryList = new ArrayList<Category>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CATEGORY;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
try{
if (cursor.moveToFirst()) {
do {
Category category = new Category();
category.setID(Integer.parseInt(cursor.getString(0)));
category.setCategory(cursor.getString(1));
// Adding category to list
categoryList.add(category);
} while (cursor.moveToNext());
}
}finally{
cursor.close();
}
db.close();
// return category list
return categoryList;
Here is how I fill the ListView by calling the database.
int size = db.getCategoryCount();
List<Category> categoryList = db.getAllCategorys();
category_data = new String[size-1];
int i=0;
for(Category cn : categoryList)
{
category_data[i] = cn.getCategory(); // get the name of the category and add it to array
i++;
}
listAdapter = new ArrayAdapter<String>(this, R.layout.categoryrow, category_data);
listViw.setAdapter(listAdapter);
EDIT: Here is something that should work for you
public List<String> getSitesByClientname(String id) {
String[] args={id};
ArrayList<String> result = new ArrayList<String>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
try{
if (myCursor.moveToFirst()){
do{
result.add(myCursor.getString(myCusor.getString(myCursor.getColumnIndex("client_sitename"));
}while(myCursor.moveToNext());
}
}finally{
myCursor.close();
}
db.close();
return result;
}
Use it like this
List<String> sites_data = dbHelper.getSitesByClientname(uID);
result_data = new String[sites_data.size()];
int i=0;
for(String s : sites_data)
{
result_data[i] = s; // get the name of the category and add it to array
i++;
}
listAdapter = new ArrayAdapter<String>(this, R.layout.client_sites, result_data);
listViw.setAdapter(listAdapter);
If you want to return the Cursor from dbHelper you can do something like this...
public Cursor getSitesByClientname(String id) {
String[] args={id};
return db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
}
I'd also take some time to read the listview tutorial

Android: How to display string on textview from console

I'm trying to display string on the textview. I'm succesfully able to print it on the console from database, but I'm not able to figure out how to print all the strings on different different textviews. Here is my code:
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
EditText search;
Button insert;
TextView txt1, txt2, txt3, txt4, txt5;
DatabaseHandler db;
List<History> history;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHandler(this);
search = (EditText) findViewById(R.id.search_word);
insert = (Button) findViewById(R.id.insert);
txt1 = (TextView) findViewById(R.id.txt1);
txt2 = (TextView) findViewById(R.id.txt2);
txt3 = (TextView) findViewById(R.id.txt3);
txt4 = (TextView) findViewById(R.id.txt4);
txt5 = (TextView) findViewById(R.id.txt5);
insert.setOnClickListener(this);
history = db.getAllHistory();
}
public void onClick(View v) {
db.addHistory(new History(search.getText().toString(), null));
Toast.makeText(getApplicationContext(),
"Inserted: " + search.getText().toString(), Toast.LENGTH_LONG)
.show();
}
#Override
protected void onStart() {
super.onStart();
List<History> history = db.getAllHistory();
for (History cn : history) {
String log = "Search Strings: " + cn.getName();
Log.d("Search Strings: ", log);
}
}
}
This is my activity in which I'm bringing my all database value on onStart() function. Now here I have to set all the data coming from database on the textview. Here is my DabaseHandler class in which I'm taking out each row.
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "historyManager";
private static final String TABLE_HISTORY = "histories";
private static final String KEY_NAME = "history";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_HISTORY_TABLE = "CREATE TABLE " + TABLE_HISTORY + "("
+ KEY_NAME + " TEXT" + ")";
db.execSQL(CREATE_HISTORY_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HISTORY);
onCreate(db);
}
void addHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, history.getName());
db.insert(TABLE_HISTORY, null, values);
db.close();
}
History getHistory(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_HISTORY, new String[] { KEY_NAME },
"=?", new String[] { String.valueOf(id) }, null, null, null,
null);
if (cursor != null)
cursor.moveToFirst();
History history = new History(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
return history;
}
public List<History> getAllHistory() {
List<History> historyList = new ArrayList<History>();
String selectQuery = "SELECT * FROM " + TABLE_HISTORY;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
History contact = new History();
contact.setName(cursor.getString(0));
historyList.add(contact);
} while (cursor.moveToNext());
}
return historyList;
}
public int updateHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, history.getName());
return db.update(TABLE_HISTORY, values, KEY_NAME + " = ?",
new String[] { String.valueOf(history.getName()) });
}
public void deleteHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_HISTORY, KEY_NAME + " = ?",
new String[] { String.valueOf(history.getName()) });
db.close();
}
public int getHistoryCount() {
String countQuery = "SELECT * FROM " + TABLE_HISTORY;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
}
Please help in getting data printed on the textview. On the Log.d I can see all my data coming, one after another. But I'm not able to print all the data.
It's answer for "Thank You for that. Can you tell me how to set the data which I have printed in MainActivity on onStart() method (Log.d("")). If you can give me the code for that, that will be much easier for me."
try this:
List<String> listNames = new ArrayList<String>();//global variable
List<History> history = db.getAllHistory();
for (History cn : history) {
listNames.add(cn.getName());
}
or, if have in History field date try is, after easy will sort:
Map<String, Date> historyMap = new HashMap<String, Date>();
List<History> history = db.getAllHistory();
for (History cn : history) {
historyMap.put(cn.getName, cn.getDate);
}
You need make ListView in which will show your data from DB.Because you have many items datas getting from db.
I suggest to the next version:
In xml file you creat:
<ListView
android:id="#+id/list_names"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
...>
You need create Adapter for your list with next xml resource:
<TextView
android:id="#+id/text_name"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
In java code:
in onCreate:
ListView list = (ListView) findViewById(R.id.list);
OurAdapter adapter = new OurAdapter(..., List<String> yourListWithName);
list.setAdapter(adapter);
if you want a more detailed description of the code tell me.
For add last item in top you need next, create spec. internal class :
class Holder implements Comparable<Holder> {
String key;
Double value;
public int compareTo(Holder another) {
return another.value.compareTo(value);
}
}
and use him how:
List<this.Holder> listSortforLastInTop = new ArrayList<this.Holder>();
and
for(...){
Holder holder = new Holder();
holder.key=...;
older.value=..;
listSortforLastInTop.add(holder);
}

Categories

Resources