I wanted to pass a selected menu name in listview to another intent class so that the new submenu is recognized by its parent-menu. So I used the getExtras to get Menu name as belows in KatagoriPengeluaran.java
public void displayListView() {
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
String countryCode =
cursor.getString(cursor.getColumnIndexOrThrow("katagori_label"));
Intent ourIntent = new Intent(KatagoriPengeluaran.this, Pengeluaran.class);
ourIntent.putExtra("cek", countryCode);
startActivity(ourIntent);
}
});
And in the new class which is Pengeluaran.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pengeluaran);
dbHelper = new Database(this);
dbHelper.open();
Bundle extras = this.getIntent().getExtras();
String sub = extras.getString("cek");
// dbHelper.deleteAllData();
//dbHelper.insertSomeData();
//Generate ListView from SQLite Database
displayListView(sub);
}
private void displayListView(final String su) {
cursor = dbHelper.fetchPengeluaran(su);
// The desired columns to be bound
allAdapter = new PengeluaranCursorAdapter(this, cursor);
ListView listView = (ListView) findViewById(android.R.id.list);
// Assign adapter to ListView
listView.setAdapter(allAdapter);
Here's my database and the fetch function
public class Database {
// Katagori Pengeluaran
public static final String RIK = "_id";
public static final String RLK = "katagori_label";
public static final String RJK = "katagori_jumlah";
//Pengeluaran
public static final String KEY_RPI = "_id";
public static final String KEY_RLP = "pengeluaran_label";
public static final String KEY_RSK = "pengeluaran_sub";
public static final String KEY_RNP = "nominal";
public static final String KEY_RTP = "tanggal";
public Cursor fetchPengeluaran(String su) {
Cursor mCursor = mDb.query(PENGELUARAN_TABLE, new String[] {KEY_RPI,
KEY_RLP, KEY_RSK, KEY_RNP, KEY_RTP}, "KEY_RLP like " + su
,null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
But while executing it says NullPointerException, Unable to Inisiate Activity Component in the log cat. Please help.
Use this method to getExtra
sub = (String) getIntent().getSerializableExtra("cek");
EDIT
Just you Log.i("Activity", countryCode );
To make your your countrycode is not null
Why do you get a cursor back from your listView? That doesn't look like a good idea to me. You should separate presentation and data.
You can try using the following in the first class instead. Use putString() instead of putExtra()
ourIntent.putString("cek", countryCode);
ListView & Adapter
Other than that I can't find anything I would do different. But like I said in the first place, review having a cursor object in your presentation (listView). Instead have String objects in an ArrayAdapter for example so you can get the String countryCode directly.
More information on listViews here: http://www.vogella.com/articles/AndroidListView/article.html
Debug
Anyway I would double check in debug mode that the object returned from your Cursor is what you expect and most of all not null.
Related
Hi I have been working through several different tutorials on getting data from a sql database into a listview. I can add data, get data from database and populate the list view, and have a working onclick listener (will fire off a Toast message). However I can not get any data from the listview when clicked. I have tried different combinations of getitem and getItemAtPosition but they all return a empty string(blank toast). Would someone be kind enough to look at my code and tell me if what I am trying to do is possible. In my listview i have four items in each entry, I would like to either get the fourth item directly or get all the items (as string?) then I can pull out the data I need.
Thanks in advance for your time.
public class ListViewActivity extends Activity {
SQLiteHelper SQLITEHELPER;
SQLiteDatabase SQLITEDATABASE;
Cursor cursor;
SQLiteListAdapter ListAdapter ;
ArrayList<String> ID_ArrayList = new ArrayList<String>();
ArrayList<String> GENRE_ArrayList = new ArrayList<String>();
ArrayList<String> NAME_ArrayList = new ArrayList<String>();
ArrayList<String> URL_ArrayList = new ArrayList<String>();
ListView LISTVIEW;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
LISTVIEW = (ListView) findViewById(R.id.listView1);
SQLITEHELPER = new SQLiteHelper(this);
}
#Override
protected void onResume() {
ShowSQLiteDBdata() ;
super.onResume();
}
private void ShowSQLiteDBdata() {
SQLITEDATABASE = SQLITEHELPER.getWritableDatabase();
cursor = SQLITEDATABASE.rawQuery("SELECT * FROM demoTable1", null);
ID_ArrayList.clear();
GENRE_ArrayList.clear();
NAME_ArrayList.clear();
URL_ArrayList.clear();
if (cursor.moveToFirst()) {
do {
ID_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_ID)));
GENRE_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Genre)));
NAME_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Name)));
URL_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Url)));
} while (cursor.moveToNext());
}
ListAdapter = new SQLiteListAdapter(ListViewActivity.this,
ID_ArrayList,
GENRE_ArrayList,
NAME_ArrayList,
URL_ArrayList
);
LISTVIEW.setAdapter(ListAdapter);
LISTVIEW.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// String text = (String) LISTVIEW.getAdapter().getItem(position);
String text = (String) LISTVIEW.getItemAtPosition(position);
//String text = (String) lv.getItemAtPosition(0);
// Object item = (Object) LISTVIEW.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
cursor.close();
}
}
LISTVIEW.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String value1 = ID_ArrayList.get(position);
String value2 = GENRE_ArrayList.get(position);
String value3 = NAME_ArrayList.get(position);
String value4 = URL_ArrayList.get(position);
Toast.makeText(getApplicationContext(),value1+" "+value2+" "+value3+" "+value4, Toast.LENGTH_SHORT).show();
}
});
try to change the line
String text = (String) LISTVIEW.getItemAtPosition(position);
with
String text = (String) parent.getItemAtPosition(position);
this should be the way ListView works.
Also i suggest you to not use Capital Cases with variables, usually in Java is used a CamelCase convention. And also have a look at RecyclerView, that usually is implemented today much more than ListView, because allow a great level of customization
Pls use below code within listview setOnItemClickListener :-
String genreID = ID_ArrayList.get(position);
String genre = GENRE_ArrayList.get(position);
String genreName = NAME_ArrayList.get(position);
String genreUrl = URL_ArrayList.get(position);
Toast.makeText(getApplicationContext(), genreID+", "+genre+","+genreName+", "+genreUrl+", "+, Toast.LENGTH_SHORT).show();
its return render data of listview.
try this,
ShowSQLiteDBdata() in onCreate() instead of onResume() method
Im busy with a Bible app, I use an SQLite db from my assets folder to retrieve the data, I use 3 listviews, each in its own activity, it goes like this:
DB column names: Book name, book id, chapter number, chapter id, verse text, verse id
1st activity, user selects a book, Genesis, Exodus, Leviticus, etc... and 2nd activity starts
2nd activity, db gets filtered so user can select chapters under that book...and 3rd activity starts
3rd activity, db gets filtered and shows all the verses under that chapter...
What I want is to put a text view at the top of the 2nd list view and then after the user selected from the 1st listview and the 2nd activity starts to show all chapters, it should show the book name that was selected from the 1st activity. And in the 3rd list view it should show the book name and chapter number that was selected from the previous two activities, I've tried using the intend, but I get errors.
Adapter:
public class customAdapterHoofstuk extends BaseAdapter {
private Context mContext;
private List<defineBybeldbAlles> defineBybeldbAlles;
public customAdapterHoofstuk(Context mContext, List<defineBybeldbAlles> defineBybelDBList) {
this.mContext = mContext;
this.defineBybeldbAlles = defineBybelDBList;
}
#Override
public int getCount() {
return defineBybeldbAlles.size();
}
#Override
public Object getItem(int position) {
return defineBybeldbAlles.get(position);
}
#Override
public long getItemId(int position) {
return (defineBybeldbAlles.get(position).getHoofstuk_id());
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = View.inflate(mContext, R.layout.custom_row_hoofstuk, null);
//this works->
TextView hoofstuknommer = (TextView)v.findViewById(R.id.custom_row_hoofstuktext);
hoofstuknommer.setText (defineBybeldbAlles.get(position).getHoofstuk_nommer());
//this works-->
TextView hoofstukid = (TextView)v.findViewById(R.id.hoofstuk_id);
hoofstukid.setText(String.valueOf(defineBybeldbAlles.get(position).getHoofstuk_id()));
//this doesnt work->
TextView boeknaambyhoofstuk = (TextView)v.findViewById(R.id.boeknaambyhoofstuklys);
boeknaambyhoofstuk.setText(defineBybeldbAlles.get(position).get_hebreeus());
return v;
}
}
Activity where it should be shown:
public class BybelActivityHoofstuk extends Activity {
private ListView listviewHoofstuk;
private customAdapterHoofstuk adapter_customAdapterHoofstuk;
private List<defineBybeldbAlles> defineBybeldbAllesList;
private DBHandlerHoofstuk DBHandlerHoofstuk;
ArrayList<HashMap<String, String>> HoofstukList;
//Boek id
String boek_id_na_hoofstuk;
#Override
public void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bybel_hoofstuk);
listviewHoofstuk = (ListView) findViewById(R.id.BybelHoofstukListView);
DBHandlerHoofstuk = new DBHandlerHoofstuk(this);
//Check exists database
File Database = getApplicationContext().getDatabasePath(DBHandlerHoofstuk.DBNAME);
if(false == Database.exists()){
DBHandlerHoofstuk.getReadableDatabase();}
//Get boek id
Intent boekIntent = getIntent();
boek_id_na_hoofstuk = boekIntent.getStringExtra("boek_id");
//hashmap for listview
HoofstukList = new ArrayList<HashMap<String, String>>();
//Get bybel list in db when db exists
defineBybeldbAllesList = DBHandlerHoofstuk.getListHoofstuk(boek_id_na_hoofstuk);
//Init adapter
adapter_customAdapterHoofstuk = new customAdapterHoofstuk(this,defineBybeldbAllesList);
//Set adapter for listview
listviewHoofstuk.setAdapter(adapter_customAdapterHoofstuk);
//Listview item click listener
//BybelActivityVers will be launched by passing hoofstuk_id
listviewHoofstuk.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick (AdapterView<?> arg0, View view, int arg2, long arg3){
//on selecting a hoofstk
//BybelActivityVers will be launched to show verse inside
Intent hoofstukIntent = new Intent(BybelActivityHoofstuk.this,BybelActivityVers.class);
//send hoofstuk_id to VersActivity to get verse under that book
String hoofstuk_id_na_vers = ((TextView)view.findViewById(R.id.hoofstuk_id)).getText().toString();
hoofstukIntent.putExtra("hoofstuk_id", hoofstuk_id_na_vers);
startActivity(hoofstukIntent);
}
});
}
}
DBHandler:
public class DBHandlerHoofstuk extends SQLiteOpenHelper{
public static final int DATABASE_VERSION = 1;
public static final String DBNAME = "pwl14082016-5.db";
public static final String DBLOCATION = "location goes here";
private Context mContext;
private SQLiteDatabase mDatabase;
public static final String COLUMN_BOEK_ID = "boek_id";
public static final String COLUMN_HEBREEUS = "_hebreeus";
public static final String COLUMN_AFRIKAANS = "_afrikaans";
public static final String COLUMN_HOOFSTUK_ID = "hoofstuk_id";
public static final String COLUMN_HOOFSTUK_NOMMER = "hoofstuk_nommer";
public static final String COLUMN_VERS_ID = "vers_id";
public static final String COLUMN_VERS_NOMMER = "vers_nommer";
public static final String COLUMN_VERS_TEXT = "vers_text";
public DBHandlerHoofstuk(Context context) {
super(context, DBNAME, null, DATABASE_VERSION);
this.mContext = context;
}
//Blank want db bestaan klaar
#Override
public void onCreate(SQLiteDatabase db) {
}
//blank want db word ekstern geupgrade
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
//maak db oop
public void opendatabase(){
String dbPath = mContext.getDatabasePath(DBNAME).getPath();
if (mDatabase !=null && mDatabase.isOpen()) {
return;
}
//verander dalk na 'mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);' as OPEN_READONLY nie werk nie
mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
//maak db toe
public void closeDatabase(){
if (mDatabase!=null) {
mDatabase.close();
}
}
public List<defineBybeldbAlles> getListHoofstuk(String boek_id_na_hoofstuk){
defineBybeldbAlles defineBybeldbHoofstuk = null;
List<defineBybeldbAlles> defineBybeldbAllesList = new ArrayList<>();
opendatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM PWLBybel WHERE " + COLUMN_BOEK_ID + " = '" + boek_id_na_hoofstuk + "'GROUP BY hoofstuk_id ORDER BY hoofstuk_id * 1 ASC", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
defineBybeldbHoofstuk = new defineBybeldbAlles(cursor.getInt(0), cursor.getString(1),cursor.getString(2),cursor.getInt(3),cursor.getString(4),cursor.getInt(5),cursor.getString(6),cursor.getString(7));
defineBybeldbAllesList.add(defineBybeldbHoofstuk);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return defineBybeldbAllesList;
}
}
XML where it gets displayed:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".defineBybeldbAlles">
<ListView
android:id="#+id/BybelHoofstukListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#ff303030"
android:dividerHeight="1dp"
android:layout_marginTop="21dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Boek naam:"
android:id="#+id/boeknaambyhoofstuklys"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textColor="#000063"
android:textSize="20dp" />
</RelativeLayout>
You can send the string through intent using
String KEY = "PUT_ANY_KEY_HERE";
String VALUE = "BOOK_NAME/CHAPTER_NAME";
Intent i = new Intent(FROM_CLASS.this, TO_CLASS.class);
i.putExtra(KEY,VALUE);
startActivity(i);
and get the string in the 2nd activity using
Intent intent = getIntent();
if(intent!=null)
String VALUE = intent.getExtras().getString(KEY);
now set the VALUE string in your textview. Also you need to put the chapterName textview above your listview or add the VALUE string as your 1st entry in the arraylist that you might be using to populate listview in 2nd and 3rd activity.
If someone might come across this, I wasn't able to pass the book and chapter name to the heading or bar, but I was able to figure out to set a title.
In your manifest under each activity, just put in android:label="title here"
to at least get a heading or title you want.
this is a succesor to this question
At first everything worked fine but after 2 deletes the misery starts. The database entries start with ID 1, then 2 and so on. Lets say I have three database entries. The listview IDs for these three entries are 2,1 and 0.
The database entries are 1,2 and 3. 1 and 2 will be deleted with the onitemclicklistener but since the listview doesn´t have an ID 3, the corresponding database entry will never ever be deleted.
So the question is, how can I "sync" those two IDs?
Listview-Class
public class anzeigen extends AppCompatActivity {
private static final String TAG = anlegen.class.getSimpleName();
private static final String FILENAME = TAG + ".kdf";
private List valueList = new ArrayList<String>();
final VorgangDataSource dataSource = new VorgangDataSource(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_anzeigen);
Log.d(TAG,"Die Datenquelle wird geöffnet!");
dataSource.open();
final List<vorgangsdaten> vorgangsdatenList = dataSource.getAllVorgangsDaten();
final ArrayAdapter<vorgangsdaten> VorgangArrayAdapter = new ArrayAdapter<>(
this,
R.layout.mylistlayout,
vorgangsdatenList
);
final ListView lv = (ListView)findViewById(R.id.listView);
lv.setAdapter(VorgangArrayAdapter);
lv.setItemsCanFocus(false);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s_id = String.valueOf(id);
Log.d(s_id,"id_in_onitem");
String p_id = String.valueOf(position);
Log.d(p_id,"position_on_item");
int pos = position;
vorgangsdatenList.remove(pos);
dataSource.deleteRow(id);
VorgangArrayAdapter.notifyDataSetChanged();
}
});
//ActionBar Costumization
android.support.v7.app.ActionBar ab = getSupportActionBar();
ab.setIcon(R.drawable.search1);
ab.setDisplayShowHomeEnabled(true);
ab.setDisplayUseLogoEnabled(true);
}
#Override
protected void onDestroy() {
super.onDestroy();
dataSource.close();
}
}
deleteRow-Method:
public void deleteRow(long id){
String s_id;
s_id = String.valueOf(id);
Log.d(s_id,"id_value");
database.delete(VorgangDbHelper.TABLE_VORGAENGE_LIST,VorgangDbHelper.COLUMN_ID + " = ?", new String[] {s_id});
long deleteID = database.delete(VorgangDbHelper.TABLE_VORGAENGE_LIST,VorgangDbHelper.COLUMN_ID + " = ?", new String[] {s_id});
String s_del = String.valueOf(deleteID);
Log.d(s_del,"delete_row_value");
}
If you need more code just let me know :)
You have no synchronicity between your Database and the ListView items.
When selecting the data, select the ID from the table, and keep it in memory as well.
Since vorgangsdaten looks german or sweden, I am having trouble understanding the meaning of those words. The ListView has its own "id" for each item, to keep a list of them shown, and the rest "hidden". What you must do is have an Object with details that are syncronized with the database, and when a list item is clicked, the "list id" is used to query an Object and delete from the database.
An example would be:
ArrayList<MyObject> arrayListData = new ArrayList<>();
ArrayList<String> arrayListNames = new ArrayList<>();
MyObject stuffs = database.query(); // In here, fetch the data
/* I am simplifing the MyObject to [String name, String aValue, int aNumber] */
for(MyObject s: stuffs){
arrayListData.add(s);
arrayListNames.add(s.name);
}
arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
arrayListNames
);
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MyObject thing = arrayListData.get(position);
database.delete(thing.aNumber);
}
}
);
listView.setAdapter(arrayAdapter);
After trying Bonattis answer and experimenting a little bit I found another answer.
deleteRow-Method
public void deleteRow(long id){
String s_id; //String for long id
s_id = String.valueOf(id); //assign String value of id
String s_rowId = null; //String for rowid
long rowId = 0;
long deleteId = 0;
String s_deleteId = null;
Log.d(s_id,"id_value");
Cursor cursor = database.query(VorgangDbHelper.TABLE_VORGAENGE_LIST,columns,null,null,null,null,null);
if(cursor.moveToFirst()) {
s_rowId = cursor.getString(cursor.getColumnIndex(VorgangDbHelper.COLUMN_ID));
rowId = Long.parseLong(s_rowId);
deleteId = rowId + id;
s_deleteId = String.valueOf(deleteId);
Log.d(s_rowId,"rowID");
Log.d(s_deleteId,"deleteID");
}
database.delete(VorgangDbHelper.TABLE_VORGAENGE_LIST,VorgangDbHelper.COLUMN_ID + " = ?", new String[] {s_deleteId});
}
How does it work now?
So the deleteRow-Method(dRM) gets the id of the first database entry (s_rowId) and converts it to long (rowId).
Now I take the long id passed from the listview and add it to rowId which is my deleteId. With this I have the correct database value to what I clicked in the listview and can pass it over to database.delete
I'm trying to save text from the selected item of a ListView in OnItemClick.
I've tried so many different methods to no avail, I think I'm missing something really stupidly obvious here...
SnakesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String choice = SnakesListView.getItemAtPosition(position).toString();
Intent intent = new Intent(SnakeList.this, SnakeProfile.class);
intent.putExtra("SelectedSnakeName", choice);
startActivity(intent);
}
});
The data is being displayed fine, I just can't seem to reference it.
The line causing the exception:
String choice = SnakesListView.getItemAtPosition(position).toString();
Full code for this activity
public class SnakeList extends Activity {
ListView SnakesListView;
Cursor cursor;
Button NewSnakeBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snake_list);
SnakesListView = (ListView) findViewById(R.id.SnakesListView);
NewSnakeBtn = (Button) findViewById(R.id.NewSnake);
SQLiteDatabase db = openOrCreateDatabase("snakeDB", Context.MODE_PRIVATE, null); // ACCESSES DB
cursor = db.rawQuery("SELECT name FROM snakes", null); // SETS cursor TO RESULTS OF QUERY
List<String> SnakeNamesList = new ArrayList<String>();
ArrayAdapter SnakeNamesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, SnakeNamesList);
SnakeNamesList.clear(); // REMOVES ANY NAMES CURRENTLY IN NAME ARRAY TO AVOID DUPLICATES
SnakesListView.setAdapter(SnakeNamesAdapter);
if (cursor.moveToFirst()) {
cursor.moveToFirst(); // MOVES CURSOR TO FIRST POSITION
do SnakeNamesList.add(cursor.getString(0)); // RETURNS STRING FROM FIRST COLUMN (NAME)
while (cursor.moveToNext());
}
NewSnakeBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(SnakeList.this, NewSnake.class));
}
});
SnakesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String choice = SnakesListView.getItemAtPosition(position).toString();
Intent intent = new Intent(SnakeList.this, SnakeProfile.class);
intent.putExtra("SelectedSnakeName", choice);
startActivity(intent);
}
});
}
No use of referencing the ListView; you can get the value from adapter itself.
Change
String choice = SnakesListView.getItemAtPosition(position).toString();
to
String choice = SnakeNamesAdapter.getItem(position).toString();
declare the string arraylist(SnakeNamesList) as global variable and
change
String choice = SnakesListView.getItemAtPosition(position).toString();
to
String choice = SnakeNamesList.get(position);
I've been able to successfully link two spinners to a database using a SimpleCursorAdapter. But, I need to make the second spinner selection dependant on the first spinner selection.
Here is how I linked the data:
public class epa_estimates_button extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.epa_estimates);
final Cursor cYear;
final Cursor cMake;
final Spinner mMakeSpinner;
final Spinner mModelSpinner;
cYear = (Cursor) DataBaseHelper.getEPADataYear();
this.startManagingCursor(cYear);
SimpleCursorAdapter scaYear = new SimpleCursorAdapter(this, R.layout.spinner_layout,cYear,new String[] {DataBaseHelper.EPA_COLUMN_ONE},new int[]{R.id.text1});
scaYear.setDropDownViewResource(R.layout.spinner_dropdown);
mYearSpinner = (Spinner) findViewById(R.id.yearSpinner);
mYearSpinner.setAdapter(scaYear);
cMake = (Cursor) DataBaseHelper.getEPADataMake();
this.startManagingCursor(cMake);
SimpleCursorAdapter scaMake = new SimpleCursorAdapter(this, R.layout.spinner_layout,cMake,new String[] {DataBaseHelper.EPA_COLUMN_TWO},new int[]{R.id.text1});
scaMake.setDropDownViewResource(R.layout.spinner_dropdown);
mMakeSpinner = (Spinner) findViewById(R.id.makeSpinner);
mMakeSpinner.setAdapter(scaMake);
}}
Here is my DataBaseHelper
public class DataBaseHelper extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/org.application.ocdmpg/databases/";
private static String DB_NAME = "ocd_mpg.mp3";
private final int DB_VERSION = 1;
private static SQLiteDatabase myDataBase;
private final Context myContext;
private static final String EPA_TABLE_NAME = "epa_data";
private static final String EPA_COLUMN_ID = "_id";
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
public static Cursor getEPADataYear()
{
return myDataBase.query(EPA_TABLE_NAME, //table name
new String[] {EPA_COLUMN_ID, EPA_COLUMN_ONE}, //list of columns to return
null, //filter declaring which rows to return; formatted as SQL WHERE clause
null,
EPA_COLUMN_ONE, //filter declaring how to group rows; formatted as SQL GROUP BY clause
null, //filter declaring which row groups to include in cursor; formatted as SQL HAVING clause
null); //how to order rows; formatted as SQL ORDER BY clause
}
public static Cursor getEPADataMake()
{
return myDataBase.query(EPA_TABLE_NAME, new String[] {
EPA_COLUMN_ID,
EPA_COLUMN_TWO,
},
null,
null,
EPA_COLUMN_TWO,
null,
null);
}}
I've found code for setOnItemSelectedListener and tried to add my code for linking the data to the spinner but the startManagingCursor method and SimpleCursorAdapter constructors give me an error as undefined. Should I use an ArrayAdapter to populate my spinners? Or is there a way to correct the code below?
mYearSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
cMake = (Cursor) DataBaseHelper.getEPADataMake();
this.startManagingCursor(cMake);
SimpleCursorAdapter scaMake = new SimpleCursorAdapter(this, R.layout.spinner_layout,cMake,new String[] {DataBaseHelper.EPA_COLUMN_TWO},new int[]{R.id.text1});
scaMake.setDropDownViewResource(R.layout.spinner_dropdown);
mMakeSpinner = (Spinner) findViewById(R.id.makeSpinner);
mMakeSpinner.setAdapter(scaMake);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
Updated based on your edit and comments
Your call to this.startManagingCursor(cMake) needs to be changed to either startManagingCursor(cMake) or epa_estimates_button.this.startManagingCursor(cMake), since it's being made from within an inner class (an OnItemSelectedListener). It works without 'this' (the former case) because, well, basically, Java figures out which this you meant. And it works with the classname because that makes explicit what Java would have figured out for itself. But the unqualified this implies that you're referring to the inner class this, and that wouldn't work.
Very similarly, in your onItemSelectedListener, your call to startManagingCursor needs to be rewritten as:
SimpleCursorAdapter scaMake = new SimpleCursorAdapter(epa_estimates_button.this,
R.layout.spinner_layout,cMake,new String[] {DataBaseHelper.EPA_COLUMN_TWO},
new int[]{R.id.text1});
(I think your database queries are going to need work -- you don't seem to use any sort of WHERE clause to restrict the 'make' results to the appropriate year. But if you do get stuck on that, please post it as another question.)