Populating a ListView in a different activity with a column of SQLite data:

0 Chris Ciampi · March 9, 2015
Hey,

How would one populate a listview with a column of SQLite data?  

For reference: I'm working on an app right now for kicks that uses SQLite, but I've been stuck on getting Android to recognize the data that's in the database.  

My relevant handler code:

-------------------------------------

    public void addDrink(Drinks drink) { //edit later
        ContentValues values = new ContentValues();
        values.put(COLUMN_DRINKNAME, drink.get_drinkname());
        values.put(COLUMN_ING_1_AMOUNT, drink.get_ing1amount());
        values.put(COLUMN_ING_1, drink.get_ing1());
        values.put(COLUMN_ING_2_AMOUNT, drink.get_ing2amount());
        values.put(COLUMN_ING_2, drink.get_ing2());

        ...

        SQLiteDatabase db = getWritableDatabase(); //database we are going to write to
        db.insert(TABLE_DRINKINFO, null, values);
        db.close();
    }

-------------------------------------


When the "drink" is actually made in the "MakeDrink" activity:

-------------------------------------

    dbHandler dbh;

    ...

    public void onClick(View v) {
        Drinks drink = new Drinks(newDrink.getText().toString());
        dbh.addDrink(drink);
        Context context = getApplicationContext();
        CharSequence toastMessage = newDrink.getText().toString() + " added to drink database.";
        Toast.makeText(context, toastMessage, Toast.LENGTH_SHORT).show();
    }

-------------------------------------

and the code for (ideally) populating the listview:

-------------------------------------

        SQLiteDatabase drinkDB;

        ...

        drinkDB = openOrCreateDatabase("drinkinfo.db", Context.MODE_PRIVATE, null);

        Cursor crs = drinkDB.rawQuery("SELECT * FROM drinkinfo ", null);
        List<String> drinkNames = new ArrayList<String>();
        while(crs.moveToNext()){
            String uname = crs.getString(crs.getColumnIndex("COLUMN_DRINKNAME"));
            drinkNames.add(uname);
        }
        ListAdapter lvAdapater = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, drinkNames);

-------------------------------------

What I've noticed in the debugger is that it doesn't run through the while loop, which suggests the column isn't there, but in the MakeDrink activity, it recognizes the inputs.  

Anyone have any advice?  I've been stuck on this for awhile and any help would be highly appreciated.  

Or in another related veing (similar to my problem) : the SQLite tutorial (49~ region): let's say a button was added taking the user to a different activity that's just a listview with all the products in a non-custom adapter.  How would one go about doing that?

Post a Reply

Replies

Oldest  Newest  Rating
0 Dol Lod · March 9, 2015
You are extending openLiteHelper, right?
I have some sample code that does a similar query for retrieving things of a certain type.

This code is something that works for insertions. 
AllTables refers to an array I made for containing all tables I'm using. Team is a class I made to hold all my membmer variables. GetField is a function I made within the Team Class to generically use an index to retrieve a particular field. TeamsField is an array holding each columnname for that table. 
public void insertTeam(Team team)
{

SQLiteDatabase database = this.getWritableDatabase();

ContentValues values = new ContentValues();
for(int position=1;position<teamsFields.length;position++)
{
values.put(teamsFields[position], team.getField(position));
}
database.insert(allTables[1], null, values);
database.close();
}


Here is code to do updating.


public int updateTeam(Team team) {

SQLiteDatabase database = this.getWritableDatabase();

ContentValues values = new ContentValues();

for(int position=1;position<teamsFields.length;position++)
{
values.put(teamsFields[position], team.getField(position));
}

return database.update("teams", values, teamsFields[0] + " = ?",
new String[] { team.getTeamId() });
}



Now, here is code to do retrieval. 


public ArrayList<Team> getAllTeams()
{

ArrayList<Team> teamsArrayList = new ArrayList<Team>();

String selectQuery=createSelectQuery(allTables[1]);
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
for(Boolean b=cursor.moveToFirst();b;b=cursor.moveToNext())
{
Team team = new Team();
for(int position=0;position<teamsFields.length;position++)
{
team.setField(position,cursor.getString(position));
}
teamsArrayList.add(team);
}

return teamsArrayList;

}

Now for your last request about how to go to an individual activity when you have an adapter.
The main point of the code is to use  the Intent.putExtraString method. This allows you send information from one activity to the next. So you could put the id of the element in a string and then pass that on to some other class that is individual like editing or viewing.

import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;



import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.myteams.myteamsapp.R;
import com.myteams.myteamsapp.DatabaseHandler;

public class MySearchView extends SherlockListActivity
{
public boolean onCreateOptionsMenu(Menu menu)
{
getSupportMenuInflater().inflate(R.menu.my_search_view_menu, menu);
return (super.onCreateOptionsMenu(menu));
}

public boolean onOptionsItemSelected(MenuItem item)
{
// Handle item selection
switch (item.getItemId())
{
case R.id.action_settings:
changeDisplaySettings();
break;
case R.id.homeIcon:
callMainActivity();
break;
case R.id.addNewTeamIcon:
addNewTeam();
break;
}
return super.onOptionsItemSelected(item);
}
ImageView abs__search_button;
TextView abs__search_badge;
EditText searchQuery;
ImageView abs__search_close_btn;
TextView teamId;
ListView listView; //this refers to the listview in the xml layout file
private String searchterm;
private ArrayList<Team> searchResults;
private OnClickListener listener=new OnClickListener
()
{

@Override
public void onClick(View view)
{
switch(view.getId())
{
case R.id.abs__search_button:
search();
break;
case R.id.abs__search_close_btn:
clearSearchTerm();
break;
default:
break;
}

}

};
DatabaseHandler databaseHandler = new DatabaseHandler(this);

@Override
public void onCreate(Bundle savedInstanceState)
{

super.onCreate(savedInstanceState);
setContentView(R.layout.my_search_view);
abs__search_button=(ImageView)findViewById(R.id.abs__search_button);
abs__search_badge=(TextView)findViewById(R.id.abs__search_badge);
searchQuery=(EditText)findViewById(R.id.searchQuery);
abs__search_close_btn=(ImageView)findViewById(R.id.abs__search_close_btn);
listView=getListView(); //this initializes the listview
initializeListeners();
}

public void callMainActivity()
{
Intent theIntent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(theIntent);
}

public void initializeListeners()
{
abs__search_button.setOnClickListener(listener);
abs__search_close_btn.setOnClickListener(listener);
}

public void search()
{
setListAdapter(null); //this resets the adapter since it will be needing a new list
searchterm=searchQuery.getText().toString();
if(searchResults!=null) //this makes sure that all entries are removed
searchResults.removeAll(searchResults);
if(isSearchable())
{
searchResults = databaseHandler.getAllSearchResults(searchterm);

if (searchResults.size() >= 0)
{

listView.setOnItemClickListener(new OnItemClickListener() //this is what executes when an entry on the listview is clicked
{

public void onItemClick(AdapterView<?> parent, View view,
int position, long id) //this is the actual part that overwrites this method
{

teamId = (TextView) view.findViewById(R.id.teamId);


String teamIdValue = teamId.getText()
.toString();

// Signals an intention to do something
// getApplication() returns the application that owns
// this activity

Intent theIndent = new Intent(getApplication(),ViewTeam.class);
theIndent.putExtra("teamId", teamIdValue);
startActivity(theIndent);
}
});

ListAdapter adapter = new TeamAdapter(this,searchResults,R.layout.team_entry); //this adds the list to the adapter
setListAdapter(adapter); //this sets the adapter of the listview
}
}
}

public boolean isSearchable()
{
for(int position=0;position<searchterm.length();position++)
{
Character testedCharacter=searchterm.charAt(position);
testedCharacter=Character.toLowerCase(testedCharacter);
switch(testedCharacter)
{
case ' ':
break;
default:
return true;
}
}
return false;
}

public void changeDisplaySettings()
{
Intent theIntent = new Intent(getApplicationContext(),TeamDisplaySettings.class);
startActivity(theIntent);
}

public void addNewTeam()
{
Intent theIntent = new Intent(getApplicationContext(),addNewTeam.class);
startActivity(theIntent);
}

public void clearSearchTerm()
{
searchterm="";
searchQuery.setText(searchterm);
}
}
0 Chris Ciampi · March 10, 2015
Hey thanks.  I'll try to implement this idea in my program to get around my snag.
0 Dol Lod · March 10, 2015
Np. The Sherlock can be replaced with the native Android Implementation. 
  • 1

Java / Android Development

107,331 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator