I am populating two spinner from sqlite. Now what I want that when my Activity is created then all state populate in spnState. But when I select any state from spinner then I want to bind District from sqlite in spnDistrict. I am getting problem when I select state after that list of district not showing in district spinner it is only showing "select district". How can I achieve that.
public void SpinnerValue(){
/*-----------------------Fill State start here----------------------------*/
try {
ArrayList<String> state_array = new ArrayList<String>();
state_array.add("Select State");
Cursor cursor_State = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nCtgId = 6", null);
if (cursor_State.moveToFirst()) {
do {
//assing values
String stateID = cursor_State.getString(0);
String stateName = cursor_State.getString(1);
stateData = stateName;
state_array.add(stateData);
} while (cursor_State.moveToNext());
}
ArrayAdapter my_Adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, state_array);
spnState.setAdapter(my_Adapter);
cursor_State.close();
spnState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
state = spnState.getSelectedItem().toString();
Cursor cursor = db.rawQuery("SELECT nSerialNo FROM CodeMaster where cCodeName = '" + state + "'", null);
if (cursor.moveToFirst()) {
do {
//assing values
stateCodeId = cursor.getString(0);
} while (cursor.moveToNext());
}
cursor.close();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
/*-----------------------Fill District start here----------------------------*/
try {
ArrayList<String> district_array = new ArrayList<String>();
district_array.add("Select District");
Cursor cursor_District = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nParentSerialNo = '"+stateCodeId+"'", null);
if (cursor_District.moveToFirst()) {
do {
//assing values
String districtID = cursor_District.getString(0);
String districtName = cursor_District.getString(1);
districtData = districtName;
district_array.add(districtData);
} while (cursor_District.moveToNext());
}
ArrayAdapter district_Adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, district_array);
spnDistrict.setAdapter(district_Adapter);
cursor_District.close();
spnDistrict.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
district = spnDistrict.getSelectedItem().toString();
Cursor cursor = db.rawQuery("SELECT nSerialNo FROM CodeMaster where cCodeName = '" + district + "'", null);
if (cursor.moveToFirst()) {
do {
//assing values
districtCodeId = cursor.getString(0);
} while (cursor.moveToNext());
}
cursor.close();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
I have checked your code and you are setting all values in one simple method, therefore it will not take stateId to fetch districts, So just apply below two method and call first in onCreate method to resolve your issue,
Call Below method in onCreate() method
// In onCreate() method call below method
fillStateData();
public void fillStateData()
{
try {
ArrayList<String> state_array = new ArrayList<String>();
state_array.add("Select State");
Cursor cursor_State = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nCtgId = 6", null);
if (cursor_State.moveToFirst())
{
do {
//assing values
String stateID = cursor_State.getString(0);
String stateName = cursor_State.getString(1);
stateData = stateName;
state_array.add(stateData);
} while (cursor_State.moveToNext());
}
ArrayAdapter my_Adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, state_array);
spnState.setAdapter(my_Adapter);
cursor_State.close();
spnState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
state = spnState.getSelectedItem().toString();
Cursor cursor = db.rawQuery("SELECT nSerialNo FROM CodeMaster where cCodeName = '" + state + "'", null);
if (cursor.moveToFirst()) {
stateCodeId = cursor.getString(0);
}
cursor.close();
fillDistrictData(stateCodeId);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public void fillDistrictData(String stateCodeId)
{
try {
ArrayList<String> district_array = new ArrayList<String>();
district_array.add("Select District");
Cursor cursor_District = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nParentSerialNo = '"+stateCodeId+"'", null);
if (cursor_District.moveToFirst()) {
do {
//assing values
String districtID = cursor_District.getString(0);
String districtName = cursor_District.getString(1);
districtData = districtName;
district_array.add(districtData);
} while (cursor_District.moveToNext());
}
ArrayAdapter district_Adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, district_array);
spnDistrict.setAdapter(district_Adapter);
cursor_District.close();
spnDistrict.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
district = spnDistrict.getSelectedItem().toString();
Cursor cursor = db.rawQuery("SELECT nSerialNo FROM CodeMaster where cCodeName = '" + district + "'", null);
if (cursor.moveToFirst()) {
do {
//assing values
districtCodeId = cursor.getString(0);
} while (cursor.moveToNext());
}
cursor.close();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
Related
I am populating spinner from below code and its working perfect. When user select any value from spinner then I am saving stateCodeId in sqlite. Now what I want that when user come again then I want to show the seleted value from ID which already saved in sqlite. How can I show value selected in spinner ?
public void fillStateData() {
try {
State_data = new ArrayList<Map<String, String>>();
State_data.clear();
Cursor cursor_State = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nCtgId = 6", null);
int i = 0;
if (cursor_State.moveToFirst()) {
do {
Map<String, String> datanum = new HashMap<String, String>();
if (i == 0) {
datanum.put("nStateID", "0");
datanum.put("cStateName", "Select State");
State_data.add(datanum);
datanum = new HashMap<String, String>();
datanum.put("nStateID", cursor_State.getString(0));
datanum.put("cStateName", cursor_State.getString(1));
State_data.add(datanum);
} else {
datanum.put("nStateID", cursor_State.getString(0));
datanum.put("cStateName", cursor_State.getString(1));
State_data.add(datanum);
}
i += 1;
} while (cursor_State.moveToNext());
}
String[] fromwhere = {"nStateID", "cStateName"};
int[] viewswhere = {R.id.txtnStateID, R.id.txtcStateName};
StateAdapter = new SimpleAdapter(getActivity(), State_data, R.layout.state_list_template, fromwhere, viewswhere);
spnState.setAdapter(StateAdapter);
cursor_State.close();
spnState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView stateId = (TextView) view.findViewById(R.id.txtnStateID);
stateCodeId = stateId.getText().toString();
fillDistrictData(stateCodeId);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
Like this I am getting ID from sqlite.
Cursor c = db.rawQuery("SELECT nStateId from MemberMaster where nCustID ="+SesPMbrID+"", null);
c.moveToFirst();
String state = c.getString(0);
Use
spinner.setSelection(position);
I have two spinner in my application which populating list from sqlite and it is working fine. When I select State in first spinner then second spinner list populate depend on first spinner. Now what I want that when I select item in both spinner and then I press back and again launch the activity then the list of second spinner still there. I want to clear list of second spinner when I press back button and Populate list in second spinner when user select value in first spinner.
public void fillStateData() {
try {
ArrayList<String> state_array = new ArrayList<String>();
state_array.add("Select State");
Cursor cursor_State = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nCtgId = 6", null);
if (cursor_State.moveToFirst()) {
do {
//assing values
String stateID = cursor_State.getString(0);
String stateName = cursor_State.getString(1);
stateData = stateName;
state_array.add(stateData);
} while (cursor_State.moveToNext());
}
ArrayAdapter my_Adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, state_array);
spnState.setAdapter(my_Adapter);
cursor_State.close();
spnState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
state = spnState.getSelectedItem().toString();
Cursor cursor = db.rawQuery("SELECT nSerialNo FROM CodeMaster where cCodeName = '" + state + "'", null);
if (cursor.moveToFirst()) {
stateCodeId = cursor.getString(0);
}
cursor.close();
fillDistrictData(stateCodeId);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public void fillDistrictData(String stateCodeId) {
try {
district_array = new ArrayList<String>();
district_array.clear();
district_array.add("Select District");
Cursor cursor_District = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nParentSerialNo = '" + stateCodeId + "'", null);
if (cursor_District.moveToFirst()) {
do {
//assing values
String districtID = cursor_District.getString(0);
String districtName = cursor_District.getString(1);
districtData = districtName;
district_array.add(districtData);
} while (cursor_District.moveToNext());
}
district_Adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, district_array);
spnDistrict.setAdapter(district_Adapter);
cursor_District.close();
spnDistrict.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
district = spnDistrict.getSelectedItem().toString();
Cursor cursor = db.rawQuery("SELECT nSerialNo FROM CodeMaster where cCodeName = '" + district + "'", null);
if (cursor.moveToFirst()) {
do {
//assing values
districtCodeId = cursor.getString(0);
} while (cursor.moveToNext());
}
cursor.close();
fillTalukaData(districtCodeId);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
add this method to activity.Hope this will work .
#Override
public void onBackPressed() {
spnDistrict.getAdapter().clear();
spnDistrict.getAdapter().notifyDataSetChanged();
finish();
}
Try using
adapter.clear();
spinner.setAdapter(new ArrayAdapter<String>(YourActivity.this,android.R.layout.simple_dropdown_item_1line,adapter));
Use Onresume for clear the array list you want
#Override
public void onResume() {
Log.e("DEBUG", "onResume of LoginFragment");
state_array.clear();
district_array.clear();
super.onResume();
}
or in onCreate view After Inttilizing array clean both arrayList.
Below is my code from which I am populating state in spinner from sqlite and it is working perfect. Now what I want that I want to add "Select State" hardcoded at first position. How can I achieve this ?
try {
ArrayList<String> state_array = new ArrayList<String>();
Cursor cursor = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nCtgId = 6", null);
if (cursor.moveToFirst()) {
do {
//assing values
String stateID = cursor.getString(0);
String stateName = cursor.getString(1);
stateData = stateName;
state_array.add(stateData);
} while (cursor.moveToNext());
}
ArrayAdapter my_Adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, state_array);
spnState.setAdapter(my_Adapter);
cursor.close();
spnState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
state = spnState.getSelectedItem().toString();
Cursor cursor = db.rawQuery("SELECT nSerialNo FROM CodeMaster where cCodeName = '" + state + "'", null);
if (cursor.moveToFirst()) {
do {
//assing values
stateCodeId = cursor.getString(0);
} while (cursor.moveToNext());
}
cursor.close();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
try this code.
try {
ArrayList<String> state_array = new ArrayList<String>();
state_array.add("Select State");
Cursor cursor = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nCtgId = 6", null);
if (cursor.moveToFirst()) {
do {
//assing values
String stateID = cursor.getString(0);
String stateName = cursor.getString(1);
stateData = stateName;
state_array.add(stateData);
} while (cursor.moveToNext());
}
state_array.add(0, "Select State");
ArrayAdapter my_Adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, state_array);
spnState.setAdapter(my_Adapter);
cursor.close();
These are the methods of spinners
mSpinnerModel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedModel = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected Model: " + selectedModel, Toast.LENGTH_LONG).show();
String sp1 = String.valueOf(mSpinnerModel.getSelectedItem());
if (sp1.contentEquals("College1")) {
List<String> list = new ArrayList<String>();
list.add("MAHARANI UNIVERSITY ");
//list.add("MANIPAL ");
// list.add("ITM UNIVERSITY ");
// list.add("UNIVERSITY1");
// list.add("MAHARANI UNIVERSTY");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter.notifyDataSetChanged();
// selectedMake = parent.getItemAtPosition(position).toString();
mSpinnerMake.setAdapter(dataAdapter);
}
if (sp1.contentEquals("College2")) {
List<String> list1 = new ArrayList<String>();
list1.add("ITM UNIVERSITY");
//list1.add("UNIVERSITY2");
// list1.add("UNIVERSITY3");
// selectedMake = parent.getItemAtPosition(position).toString();
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, list1);
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter2.notifyDataSetChanged();
mSpinnerMake.setAdapter(dataAdapter2);
}
if (sp1.contentEquals("College3")) {
List<String> list = new ArrayList<String>();
list.add("MANIPAL ");
//list.add("UNIVERSITY4");
//list.add("UNIVERSITY5");
ArrayAdapter<String> dataAdapter3 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, list);
dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter3.notifyDataSetChanged();
mSpinnerMake.setAdapter(dataAdapter3);
// selectedMake = parent.getItemAtPosition(position).toString();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
mSpinnerMake.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedMake = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
mSpinnerYear.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedYear = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected Year: " + selectedYear, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
mButtonShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String eligibleBattery=fetchEligibleBattery(mSqLiteDatabase);
mTextViewResult.setText(eligibleBattery);
}
});
}
And this is method for data and query for fetching data but it is not working. when i select data in spinners it shows in logcat but it is not fetching data the query right below is not working please help.
private String fetchEligibleBattery(SQLiteDatabase db) {
String battery="";
String SELECT_BATTERY_QUERY = "SELECT "+ DatabaseConstants.KEY_BATTERY+" FROM " + DatabaseConstants.TABLE_CAR_DETAILS + " WHERE " + DatabaseConstants.KEY_CAR_MAKE + " ='" +selectedMake +
"' AND "+ DatabaseConstants.KEY_CAR_MODEL +" = '"+ selectedModel+ "' AND "+ DatabaseConstants.KEY_CAR_YEAR+"= '"+selectedYear +"' ;";
Log.d("Database", "Battery Select Query : " + SELECT_BATTERY_QUERY);
Cursor cursor = db.rawQuery(SELECT_BATTERY_QUERY, null);
try {
if (cursor.moveToFirst()) {
battery=cursor.getString(cursor.getColumnIndex(DatabaseConstants.KEY_BATTERY));
}
} catch (Exception e) {
Log.d("Database", "Error while trying to get icons from database");
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
return battery;
}
public void fetchDataFromDBForSpinners(SQLiteDatabase db) {
String SELECT_MODELS_QUERY = "SELECT * FROM " + DatabaseConstants.TABLE_CAR_DETAILS + ";";
String model, make, year;
Cursor cursor = db.rawQuery(SELECT_MODELS_QUERY, null);
try {
if (cursor.moveToFirst()) {
do {
model = cursor.getString(cursor.getColumnIndex(DatabaseConstants.KEY_CAR_MODEL));
make = cursor.getString(cursor.getColumnIndex(DatabaseConstants.KEY_CAR_MAKE));
year = cursor.getString(cursor.getColumnIndex(DatabaseConstants.KEY_CAR_YEAR));
models.add(model);
makes.add(make);
years.add(year);
} while (cursor.moveToNext());
}
} catch (Exception e) {
Log.d("DATABASE", "Error while trying to get events from database");
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
This query wrong
Please check carefully my fixed code
String SELECT_BATTERY_QUERY = "SELECT "+ DatabaseConstants.KEY_BATTERY+" FROM " + DatabaseConstants.TABLE_CAR_DETAILS + " WHERE " + DatabaseConstants.KEY_CAR_MAKE + " = " +selectedMake +" AND "+ DatabaseConstants.KEY_CAR_MODEL +" = "+ selectedModel+ " AND "+ DatabaseConstants.KEY_CAR_YEAR+"= "+selectedYear ";
how I can get ID of selected item in Spinner from Database?
I know it's onItemSelected method, but I don't how to use it.
AddActivity:
spSpinner.setOnItemSelectedListener(
new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
id = Integer.parseInt(String.valueOf(((SpinnerObject)spSpinner.getSelectedItem()).getDatabaseId()));
Toast.makeText(getBaseContext(), "You have selected department with ID: " + id, Toast.LENGTH_LONG).show();
Log.d(TAG, "onItemSelected database id: " + id);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
);
DatabaseHandler:
public ArrayList<SpinnerObject> getAllDepartments(){
ArrayList<SpinnerObject> list = new ArrayList<>();
String selectQuery = "SELECT * FROM " + TABLE_DEPARTMENTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
do {
list.add(new SpinnerObject (cursor.getInt(0), cursor.getString(1)));
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return list;
}
in this method I insert values to database. How can I insert id, which I'm getting in Spinner to database?
private void insertInStudentTable(String imie, String nazwisko, int indeks, String email, String telefon) {
SQLiteDatabase db = dbCreate.getWritableDatabase();
//ContentValues data_2 = new ContentValues();
//long idOfDepart = db.insertOrThrow("departments", null, data_2);
ContentValues data = new ContentValues();
data.put("imie", imie);
data.put("nazwisko", nazwisko);
data.put("indeks", indeks);
data.put("email", email);
data.put("numer", telefon);
data.put("dept_id", 1 ); // - here must be inserted an id of department
db.insertOrThrow("students", null, data);
}