Same question header is available but requirement is different.
First spinner selection should load from database and second spinner and third spinner should change based one first spinner selection.
Current:
-
As i can see there is something wrong in sql query which i am unable to find.
Issue :
Spinner1 should display ignore the duplication instead of two P1 it should display like P1,P2,N1.
Spinner2 should display all records which relevant to P1 whereas its shows only one record
Requirement :
Second spinner and third spinner should populate data based on first spinner whereas challenge is second spinner should display all data which is matched by spinner1.
Layout:SpinnerEx4Activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="8dip" android:text="#string/lblAcc" />
<Spinner android:id="#+id/spinner4" android:layout_width="138dp" android:layout_height="wrap_content" android:drawSelectorOnTop="true" />
<Spinner android:id="#+id/spinner1" android:layout_width="368dp" android:layout_height="wrap_content" android:drawSelectorOnTop="true" android:layout_toRightOf="#+id/spinner4" android:layout_alignBaseline="#+id/spinner4" />
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="8dip" android:text="#string/lblSubAcc" />
<Spinner android:id="#+id/spinner2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dip" android:layout_marginLeft="8dip" android:layout_marginRight="8dip" />
<TextView android:id="#+id/textView2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Visit Day" />
<CheckBox android:id="#+id/checkBox2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Sunday" />
<CheckBox android:id="#+id/checkBox3" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Monday" />
<CheckBox android:id="#+id/checkBox4" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Tuesday" />
<CheckBox android:id="#+id/checkBox5" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Wednesday" />
<CheckBox android:id="#+id/checkBox6" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Thursday" />
<CheckBox android:id="#+id/checkBox" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Saturday" />
<CheckBox android:id="#+id/checkBox7" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Outlet is Closed" />
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal">
<TextView android:id="#+id/textView6" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollHorizontally="false" android:text="Total Outlet" android:textSize="10dp" android:textStyle="bold" android:layout_weight="1" />
<TextView android:id="#+id/textView7" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollHorizontally="false" android:text="T Outlet" android:textSize="19dp" android:textStyle="bold" android:layout_weight="1" />
<TextView android:id="#+id/textView9" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollHorizontally="false" android:text="Completed Outlet" android:textSize="10dp" android:textStyle="bold" android:layout_weight="1"
/>
<TextView android:id="#+id/textView8" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollHorizontally="false" android:text="C.Outlet" android:textSize="19dp" android:textStyle="bold" android:layout_weight="1" />
</LinearLayout>
<Spinner android:id="#+id/spinner3" android:layout_width="match_parent" android:layout_height="wrap_content" />
<EditText android:id="#+id/input_label" android:layout_width="match_parent" android:layout_height="0dp" android:ems="10" android:inputType="textPersonName" />
<Button android:id="#+id/btn_add" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Save" />
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal">
<Button android:id="#+id/btnexport" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollHorizontally="false" android:text="Download" android:textSize="15dp" android:textStyle="bold" android:layout_weight="1" />
<Button android:id="#+id/btn_send_mail" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollHorizontally="false" android:text="Send" android:textSize="15dp" android:textStyle="bold" android:layout_weight="1" />
</LinearLayout>
<Button android:id="#+id/btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollHorizontally="false" android:text="Import" android:textSize="15dp" android:textStyle="bold" android:layout_weight="1" />
</LinearLayout>
MainActivity.Java
public class SpinnerEx4Activity extends AppCompatActivity {
Spinner s1,s2,s3,s4;
Button btnAdd;
Button send;
Button ok;
Button btn_send_mail;
private Button btnexport;
EditText inputLabel;
TextView tex,tex1;
DatabaseHandler dbhndlr;
Cursor spinner1csr, spinner2csr, spinner3csr;
SimpleCursorAdapter sca, sca2,sca3;
long spinner1_selected = 0;
long spinner4_selected = 0;
long spinner3_selected = 0;
CheckBox ck1,ck2,ck3,ck4,ck5,ck6,ck7,ck8;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_ex4);
s1 = (Spinner)findViewById(R.id.spinner1);
s2 = (Spinner)findViewById(R.id.spinner2);
s3 = (Spinner)findViewById(R.id.spinner3);
s4 = (Spinner)findViewById(R.id.spinner4);
btnAdd = (Button) findViewById(R.id.btn_add);
inputLabel = (EditText) findViewById(R.id.input_label);
dbhndlr = new DatabaseHandler(this);
ck1=(CheckBox) findViewById(R.id.checkBox);
ck2=(CheckBox)findViewById(R.id.checkBox2);
ck3=(CheckBox)findViewById(R.id.checkBox3);
ck4=(CheckBox)findViewById(R.id.checkBox4);
ck6=(CheckBox) findViewById(R.id.checkBox5);
ck7=(CheckBox)findViewById(R.id.checkBox6);
ck8=(CheckBox)findViewById(R.id.checkBox7);
final Button btnexport = (Button) findViewById(R.id.btnexport);
btn_send_mail = (Button) findViewById(R.id.btn_send_mail);
ok = (Button) findViewById(R.id.btn);
loadSpinnerData();
TextView tex = (TextView) findViewById(R.id.textView7);
TextView tex1 = (TextView) findViewById(R.id.textView8);
if (DatabaseUtils.queryNumEntries(dbhndlr.getWritableDatabase(),DatabaseHandler.TABLE_LABELS) < 1) {
dbhndlr.insertlabel("1" ,"P1","Henry","9001234");
dbhndlr.insertlabel("2","P1","Malik","9004567");
dbhndlr.insertlabel("3","P2","ermarket","900356");
dbhndlr.insertlabel("4","N1","Veli","9003456");
}
if (DatabaseUtils.queryNumEntries(dbhndlr.getWritableDatabase(),DatabaseHandler.TABLE_LABELS1) < 2) {
dbhndlr.insertlabel12("14","0001 Daily");
dbhndlr.insertlabel12("21","0007 Weekly");
dbhndlr.insertlabel12("34","0014 Days");
dbhndlr.insertlabel12("44","0021 Days");
dbhndlr.insertlabel12("54","0028 Days");
}
spinner1csr = dbhndlr.getAllLabelsAsCursor();
s1.setAdapter(sca);
sca3 = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,spinner1csr,
new String[]{DatabaseHandler.KEY_ID1},
new int[]{android.R.id.text1},
0
);
s4.setAdapter(sca3);
class SendMail extends AsyncTask <String, Integer, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(SpinnerEx4Activity.this, "Please wait", "Sending mail", true, false);
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
protected Void doInBackground(String... params) {
Mail m = new Mail("d.com", "t3e");
String[] toArr = {"fdm.bh"};
m.setTo(toArr);
m.setFrom("owMobile");
m.setSubject("This is emaster Data Application");
m.setBody("Find attached excoute,Thank you.");
try {
m.addAttachment(Environment.getExternalStorageDirectory()+"/android/data/com.example.ok.myapplication/files/w.csv");
if(m.send()) {
Toast.makeText(SpinnerEx4Activity.this, "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(SpinnerEx4Activity.this, "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
Log.e("MailApp", "Could not send email", e);
}
return null;
}
}
});
///////////////////////////////
s4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id1) {
spinner4_selected = id1;
spinner1csr = dbhndlr.getByRowid(spinner4_selected);
spinner2csr = dbhndlr.getByRowid(spinner4_selected);
sca.swapCursor(spinner1csr);
sca2.swapCursor(spinner2csr);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
sca = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
spinner1csr,
new String[]{DatabaseHandler.KEY_NAME},
new int[]{android.R.id.text1},
0
);
sca2 = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
spinner1csr,
new String[]{DatabaseHandler.KEY_ID},
new int[]{android.R.id.text1},
0
);
s1.setAdapter(sca);
s2.setAdapter(sca2);
private void loadSpinnerData() {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
List<String> lables = db.getAllLabels();
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
dataAdapter1
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
/
s3.setAdapter(dataAdapter1);
}
#Override
public void onDestroy() {
spinner1csr.close();
spinner2csr.close();
spinner3csr.close();
super.onDestroy();
}
protected Void doInBackground(String... params) {
Mail m = new Mail("d.com", "4#");
String[] toArr = {"d.gw"};
m.setTo(toArr);
m.setFrom("Mata");
m.setSubject("This is tion");
m.setBody("Find ute,Thank you.");
try {
m.addAttachment(Environment.getExternalStorageDirectory() + "/Android/data/com.example.ok.myapplication/files/ce.csv");
if (m.send()) {
Toast.makeText(SpinnerEx4Activity.this, "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(SpinnerEx4Activity.this, "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e("MailApp", "Could not send email", e);
}
return null;
}
}
Database
public class DatabaseHandler extends SQLiteOpenHelper {
// Database Version
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "spinnerExample";
private static String DB_PATH = "/data/data/com.example.ok.myapplication/databases/";
private final Context myContext;
private SQLiteDatabase myDataBase;
// Database Name
// Labels table name
public static final String TABLE_LABELS = "labels"; //<<<< Made public
public static final String TABLE_LABELS1= "labels1";
public static final String TABLE_LABELS2= "labels2";
// Labels Table Columns names
public static final String KEY_ID4 = "input_label";
public static final String KEY_ID12 = "id2"; //<<<< Made public
public static final String KEY_ID = "id";
public static final String KEY_99 = "sno"; //<<<< Made public//<<<< Made public
public static final String KEY_NAME = "name"; //<<<< made public
public static final String KEY_ID1 = "id1"; //<<<< Made public
public static final String KEY_NAME1 = "name1";
public static final String KEY_1 = "number"; //<<<< Made public
public static final String KEY_2 = "outletname"; //<<<< made public
public static final String KEY_3 = "sunday"; //<<<< Made public
public static final String KEY_4 = "monday";
public static final String KEY_5 = "tuesday";
public static final String KEY_6 = "wednesday";
public static final String KEY_7 = "thursday";
public static final String KEY_8 = "saturday";
public static final String KEY_9 = "closed";
public static final String KEY_10 = "calling";
public static final String KEY_11 = "id3";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
myDataBase = this.getWritableDatabase();
this.myContext = context;
Log.e("Path 1", DB_PATH);
}
// Creating Tables
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DATABASE_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
#Override
public void onCreate(SQLiteDatabase db) {
boolean dbExist = checkDataBase();
// Category table create query
String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("+ KEY_99 + " INTEGER,"
+ KEY_ID1 + " TEXT," + KEY_ID + " TEXT," + KEY_NAME + " TEXT)";
String CREATE_CATEGORIES_TABLE1 = "CREATE TABLE " + TABLE_LABELS1 + "("
+ KEY_ID1+ " TEXT," + KEY_NAME1+ " TEXT)";
String CREATE_CATEGORIES_TABLE2 = "CREATE TABLE " + TABLE_LABELS2 + "("
+ KEY_11+ " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_1+ " TEXT," + KEY_2+ " TEXT," + KEY_3+ " INTEGER," + KEY_4+ " INTEGER,"+ KEY_5+ " INTEGER," + KEY_6+ " INTEGER," + KEY_7+ " INTEGER," + KEY_8+ " INTEGER," + KEY_9+ " INTEGER," + KEY_10+ " TEXT)";
db.execSQL(CREATE_CATEGORIES_TABLE);
db.execSQL(CREATE_CATEGORIES_TABLE1);
db.execSQL(CREATE_CATEGORIES_TABLE2);
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DATABASE_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
String outFileName = DB_PATH + DATABASE_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[10];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS1);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS2);
// Create tables again
onCreate(db);
}
// Added for adding new data
public void insertlabel(String text,String id1,String id, String label) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_99,text);
cv.put(KEY_ID1,id1);
cv.put(KEY_ID,id);
cv.put(KEY_NAME,label);
db.insert(TABLE_LABELS,null,cv);
db.close();
}
public void insertlabel12(String id1, String label1) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv1 = new ContentValues();
cv1.put(KEY_ID1,id1);
cv1.put(KEY_NAME1,label1);
db.insert(TABLE_LABELS1,null,cv1);
db.close();
}
/**
* Inserting new lable into lables table
* */
public void insertLabel(String message1, String message2,String message3,String message4,String message5,String message6,String message7,String message8,String message9,String message10){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_1, message1);
values.put(KEY_2, message2);
values.put(KEY_10,message10);
values.put(KEY_4,message4);
values.put(KEY_5,message5);
values.put(KEY_6,message6);
values.put(KEY_7,message7);
values.put(KEY_3,message3);
values.put(KEY_9,message9);
values.put(KEY_8,message8);
// Inserting Row
db.insert(TABLE_LABELS2, null, values);
db.close(); // Closing database connection
}
public void insertLabel1(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME1, label);
// Inserting Row
db.insert(TABLE_LABELS1, null, values);
db.close(); // Closing database connection
}
public void insertLabel2(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME1, label);
values.put(KEY_10, label);
values.put(KEY_ID, label);
db.insert(TABLE_LABELS2, null, values);
db.close(); // Closing database connection
}
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS1;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
public List<String> andrew(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
public Cursor getAllEntries(){
String selectQuery = "SELECT count (*) FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cur = db.rawQuery(selectQuery, null);
return cur;
}
public Cursor getAllEntries1(){
String selectQuery = "SELECT count (*) FROM " + TABLE_LABELS2;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cur1 = db.rawQuery(selectQuery, null);
return cur1;
}
public List<String> getAllLabels1(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT count (*) FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor1 = db.rawQuery(selectQuery, null);
final ArrayList<String> row1 = new ArrayList<String>();
// looping through all rows and adding to list
if (cursor1.moveToFirst()) {
do {
labels.add(cursor1.getString(1));
} while (cursor1.moveToNext());
}
// closing connection
cursor1.close();
db.close();
// returning lables
return labels;
}
// Added to get Cursor for Simple CursorAdapter
public Cursor getAllLabelsAsCursor() {
String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
return this.getWritableDatabase().query(TABLE_LABELS,columns,null,null,null,null,null);
}
public Cursor getAllLabelsExceptedSelected(long selected) {
String[] columns = new String[]{"rowid AS _id, *"};
String whereclause = "rowid <> ?";
String[] whereargs = new String[]{String.valueOf(selected)};
return this.getWritableDatabase().query(TABLE_LABELS,
columns,
whereclause,
whereargs,
null,
null,
null
);
}
public Cursor getByRowid(long id) {
String[] columns = new String[]{"rowid AS _id, *"};
return this.getWritableDatabase().query(TABLE_LABELS, columns, "rowid=?", new String[]{String.valueOf(id)},
null, null, null
);
}
}
The following is an example based upon some of the code from the question, that has 3 spinners the 2nd listing values as determined according to what is selected by spinner1. Likewise the 3rd listing values as determined by what is selected by spinner2.
In short each spinner has a manageSprinner? method (? being 1, 2 and 3 respectively).
The manageSpinner? methods retrieve the respective data.
For 2 and 3 the respective data is determined according to the value passed, this value being the selected item from the spinner above it in the hierarchy (i.e. for spinner2 the selected item in spinner1, for spinner3 the selected item in spinner2).
They, the managedSpinner? methods instantiate the adapter if not already instantiated and for Spinners 1 and 2 add the onIstemSelected listener that invokes the managerSpinner? method of the spinner below it in the hierarchy.
If the respective adapter is already instantiated then it swaps the cursor to refresh the data displayed by the spinner.
Note as manageSpinner1 invokes managerSpinner2 and as manageSpinner2 invokes manageSpinner3. There is only the need to invoke manageSpinner1. That is there is always an item that is selected so the onItemSelected method is called from the outset.
The layout for the Activity activity_main.xml :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Spinner
android:id="#+id/spinner2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Spinner
android:id="#+id/spinner3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
The Database helper Databasehandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
// Database Version
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "spinnerExample";
private final Context myContext;
private SQLiteDatabase myDataBase;
// Database Name
// Labels table name
public static final String TABLE_LABELS = "labels"; //<<<< Made public
public static final String TABLE_LABELS1= "labels1";
public static final String TABLE_LABELS2= "labels2";
// Labels Table Columns names
public static final String KEY_ID4 = "input_label";
public static final String KEY_ID12 = "id2"; //<<<< Made public
public static final String KEY_ID = "id";
public static final String KEY_99 = "sno"; //<<<< Made public//<<<< Made public
public static final String KEY_NAME = "name"; //<<<< made public
public static final String KEY_ID1 = "id1"; //<<<< Made public
public static final String KEY_NAME1 = "name1";
public static final String KEY_1 = "number"; //<<<< Made public
public static final String KEY_2 = "outletname"; //<<<< made public
public static final String KEY_3 = "sunday"; //<<<< Made public
public static final String KEY_4 = "monday";
public static final String KEY_5 = "tuesday";
public static final String KEY_6 = "wednesday";
public static final String KEY_7 = "thursday";
public static final String KEY_8 = "saturday";
public static final String KEY_9 = "closed";
public static final String KEY_10 = "calling";
public static final String KEY_11 = "id3";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
myDataBase = this.getWritableDatabase();
this.myContext = context;
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
//boolean dbExist = checkDataBase();
// Category table create query
String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("+ KEY_99 + " INTEGER,"
+ KEY_ID1 + " TEXT," + KEY_ID + " TEXT," + KEY_NAME + " TEXT)";
String CREATE_CATEGORIES_TABLE1 = "CREATE TABLE " + TABLE_LABELS1 + "("
+ KEY_ID1+ " TEXT," + KEY_NAME1+ " TEXT)";
String CREATE_CATEGORIES_TABLE2 = "CREATE TABLE " + TABLE_LABELS2 + "("
+ KEY_11+ " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_1+ " TEXT," + KEY_2+ " TEXT," + KEY_3+ " INTEGER," + KEY_4+ " INTEGER,"+ KEY_5+ " INTEGER," + KEY_6+ " INTEGER," + KEY_7+ " INTEGER," + KEY_8+ " INTEGER," + KEY_9+ " INTEGER," + KEY_10+ " TEXT)";
db.execSQL(CREATE_CATEGORIES_TABLE);
db.execSQL(CREATE_CATEGORIES_TABLE1);
db.execSQL(CREATE_CATEGORIES_TABLE2);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS1);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS2);
// Create tables again
onCreate(db);
}
/**
* Inserting new lable into lables table
* */
public void insertLabel(String message1, String message2,String message3,String message4,String message5,String message6,String message7,String message8,String message9,String message10){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_1, message1);
values.put(KEY_2, message2);
values.put(KEY_10,message10);
values.put(KEY_4,message4);
values.put(KEY_5,message5);
values.put(KEY_6,message6);
values.put(KEY_7,message7);
values.put(KEY_3,message3);
values.put(KEY_9,message9);
values.put(KEY_8,message8);
// Inserting Row
db.insert(TABLE_LABELS2, null, values);
//db.close(); // Closing database connection
}
public void insertLabel1(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME1, label);
db.insert(TABLE_LABELS1, null, values);
//db.close(); // Closing database connection
}
public void insertLabel2(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, label);
db.insert(TABLE_LABELS, null, values);
db.close(); // Closing database connection
}
public Cursor getAllLabelsForSpinner1AsCursor() {
String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
return this.getWritableDatabase().query(TABLE_LABELS2,columns,null,null,null,null,null);
}
public Cursor getAllLabelsForSpinner2AsCursor(String keyFromSinner1) {
String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
return this.getWritableDatabase().query(
TABLE_LABELS1,columns,
DatabaseHandler.KEY_NAME1 + " LIKE ?",
new String[]{keyFromSinner1+"%"},
null,null,null
);
}
public Cursor getAllLabelsForSpinner3AsCursor(String keyFromSpinner2) {
String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
return this.getWritableDatabase().query(
TABLE_LABELS,columns,
DatabaseHandler.KEY_NAME + " LIKE ?",
new String[]{keyFromSpinner2 + "%"},
null,null,null);
}
}
This has had the code not required for the example removed
The Activity MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHandler mDH;
Spinner mSpinner1,mSpinner2,mSpinner3;
Cursor mSpinner1Csr,mSpinner2Csr,mSpinner3Csr;
SimpleCursorAdapter mSpinner1Adapter,mSpinner2Adapter,mSpinner3Adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSpinner1 = this.findViewById(R.id.spinner1);
mSpinner2 = this.findViewById(R.id.spinner2);
mSpinner3 = this.findViewById(R.id.spinner3);
mDH = new DatabaseHandler(this);
addSomeTestingData(); // ADD testing data if none
manageSpinner1(); // Manages spinner1 not that spinner 1 invokes manage spinner2 and spinnr manages spinner3
}
private void addSomeTestingData() {
if(DatabaseUtils.queryNumEntries(mDH.getWritableDatabase(),DatabaseHandler.TABLE_LABELS) > 0) return;
// Data for LABELS2 table (spinner 1 (note 1st column listed in spinner))
mDH.insertLabel("A1","A2","A3","A4","A5","A6","A7","A8","A9","A10");
mDH.insertLabel("B1","B2","B3","B4","B5","B6","B7","B8","B9","B10");
mDH.insertLabel("L1","L2","L3","L4","L5","L6","L7","L8","L9","L10");
// Data for LABELS1 table (spinner 2)
mDH.insertLabel1("A1EXTRA1");
mDH.insertLabel1("A1EXTRA2");
mDH.insertLabel1("B1EXTRA1");
mDH.insertLabel1("B1EXTRA2");
mDH.insertLabel1("L1EXTRA1");
mDH.insertLabel1("L1EXTRA2");
// Data for LABELS table (spinner 3)
mDH.insertLabel2("A1EXTRA1MORE1");
mDH.insertLabel2("A1EXTRA1MORE2");
mDH.insertLabel2("A1EXTRA2MORE1");
mDH.insertLabel2("A1EXTRA2MORE2");
mDH.insertLabel2("B1EXTRA1MORE1");
mDH.insertLabel2("B1EXTRA1MORE2");
mDH.insertLabel2("B1EXTRA2MORE1");
mDH.insertLabel2("B1EXTRA2MORE2");
mDH.insertLabel2("L1EXTRA1MORE1");
mDH.insertLabel2("L1EXTRA1MORE2");
mDH.insertLabel2("L1EXTRA2MORE1");
mDH.insertLabel2("L1EXTRA2MORE2");
}
private void manageSpinner1() {
mSpinner1Csr = mDH.getAllLabelsForSpinner1AsCursor();
if (mSpinner1Adapter == null) {
mSpinner1Adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mSpinner1Csr,
new String[]{DatabaseHandler.KEY_1},
new int[]{android.R.id.text1},
0
);
mSpinner1.setAdapter(mSpinner1Adapter);
mSpinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
manageSpinner2(mSpinner1Csr.getString(mSpinner1Csr.getColumnIndex(DatabaseHandler.KEY_1)));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} else {
mSpinner1Adapter.swapCursor(mSpinner1Csr);
}
}
private void manageSpinner2(String keyFromSpinner1) {
mSpinner2Csr = mDH.getAllLabelsForSpinner2AsCursor(keyFromSpinner1);
if (mSpinner2Adapter == null) {
mSpinner2Adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mSpinner2Csr,
new String[]{DatabaseHandler.KEY_NAME1},
new int[]{android.R.id.text1},
0
);
mSpinner2.setAdapter(mSpinner2Adapter);
mSpinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
manageSpinner3(mSpinner2Csr.getString(mSpinner2Csr.getColumnIndex(DatabaseHandler.KEY_NAME1)));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} else {
mSpinner2Adapter.swapCursor(mSpinner2Csr);
}
}
private void manageSpinner3(String keyForSpinner3) {
mSpinner3Csr = mDH.getAllLabelsForSpinner3AsCursor(keyForSpinner3);
if (mSpinner3Adapter == null) {
mSpinner3Adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mSpinner3Csr,
new String[]{DatabaseHandler.KEY_NAME},
new int[]{android.R.id.text1},
0
);
mSpinner3.setAdapter(mSpinner3Adapter);
} else {
mSpinner3Adapter.swapCursor(mSpinner3Csr);
}
}
}
Note
The above is intended solely as a demonstration of the technique and as such the technique will need to be incorporated and thus that code be adapted as part of that incorporation
I am at ends wit with my code. I can not get a fragment to display after it is called by another fragment (via Activity). I read the Android Developer guide and many SO's related topic on Fragment/FragmentPagerAdapter/FragmentTransactions and could not resolve my issue. This one would have been an obvious solution Is it possible to remove a fragment without replacing it by another fragment
I have an activity class that will host a fragment based on the tab selected. These fragments are dynamically created by the FragmentPagerAdapter based on user's selection of the tab. In the first tab, it creates FragmentA (ListFragment) which consists of a list of items. When a user clicks on any of the item, it should display another fragment with that item's details but to much of my dismay (and eyes burning), all it does is print out my log in logcat. Please see my code. Perhaps, I am staring at it too long and/or just don't know enough of android to see what's going on. I suspect it has to do with this line: fragTransaction.replace(R.id.curriculumParent, fragC); Now I know this would work if the 1st parameter was a fragment container in the activity's layout file was define but since it is not done statically, I don't know what to put there except for the calling FragmentB's layout file.
Thanks in advance!
MainActivity.java
public class MainActivity extends FragmentActivity implements
FragmentB.OnColorSelectedListener {
private static final String TAG = "MainActivity";
private final Handler handler = new Handler();
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
FragmentManager fm = getSupportFragmentManager();
adapter = new MyPagerAdapter(fm);
pager.setAdapter(adapter);
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4,
getResources().getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
}
...
...
...
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = { "FragmentB", "2ndTabFragment", "3rdTabFragment" };
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position)
{
return TITLES[position];
}
#Override
public int getCount()
{
return TITLES.length;
}
#Override
public Fragment getItem(int position)
{
Fragment fragment = null;
switch (position) {
case 0:
fragment = Fragment.instantiate(getBaseContext(), FragmentB.class.getName());
break;
case 1:
fragment = Fragment.instantiate(getBaseContext(), SecondTabFragment.class.getName());
break;
case 2:
fragment = Fragment.instantiate(getBaseContext(), ThirdTabFragment.class.getName());
break;
}
return fragment;
}
}
#Override
public void onColorLevelSelected(int position)
{
Log.i(TAG, "Got Here!");
FragmentC fragC = new FragmentC();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragTransaction = fm.beginTransaction();
**fragTransaction.replace(R.id.curriculumParent, fragC);**
fragTransaction.addToBackStack(null);
fragTransaction.commit();
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip"
android:background="#drawable/background_tabs" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tabs"
tools:context=".MainActivity" />
</RelativeLayout>
FragmentB.java
public class FragmentB extends ListFragment{
OnColorSelectedListener mCallback;
private String[] colorLevel = new String[]{
"Yellow",
"Orange",
"Green",
"Blue",
"pink",
"Black"
};
private int[] colorImages = new int[]{
R.drawable.yellow,
R.drawable.orange,
R.drawable.green,
R.drawable.blue,
R.drawable.pink,
R.drawable.black
};
public interface OnColorSelectedListener{
public void onItemLevelSelected(int position);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
List<HashMap<String, String>> colorList = new ArrayList<HashMap<String, String>>();
for(int i = 0; i < 6; i++){
HashMap<String, String> colorMap = new HashMap<String, String>();
colorMap.put("lvl", colorLevel[i]);
colorMap.put("img", Integer.toString(colorImages[i]));
colorList.add(colorMap);
}
String[] from = {"img", "lvl"};
int[] to = {R.id.colorLevelImg, R.id.colorLevelTxt};
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(),colorList, R.layout.fragment_b ,from, to);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
try{
mCallback = (OnColorSelectedListener) activity;
}catch(ClassCastException e){
throw new ClassCastException(activity.toString()
+ " must implement OnColorSelectedListener");
}
}
#Override
public void onListItemClick(ListView l, View v, int pos, long id){
Toast.makeText(getActivity(), "selected color :" + colorLevel[pos],
Toast.LENGTH_LONG).show();
mCallback.onColorLevelSelected(pos);
}
}
fragment_b.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
**android:id="#+id/curriculumParent"**
...
...
android:background="#FEFDFB">
<ImageView
android:id="#+id/colorLevelImg"
...
android:paddingBottom="10dp" />
<LinearLayout
...
android:orientation="vertical" >
<TextView
android:id="#+id/colorLevelTxt"
...
android:textSize="25sp" />
</LinearLayout>
</LinearLayout>
FragmentC.java
public class FragmentC extends Fragment{
public static final String TAG = "Fragment C";
public FragmentC(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
Log.i(TAG, "HI");
return inflater.inflate(R.layout.fragment_c, container, false);
}
}
fragment_c.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFCC00" >
<TextView
android:id="#+id/editText1"
...
android:layout_margin="16dp"
android:text="This is the C Fragment that will replace the B Fragment" >
</TextView>
</RelativeLayout>
I noticed FragmentB.java does not explicitly point to any layout file to inflate. In case you don't know,
ListFragment has a default layout that consists of a single list view
, documented # ListFragment. So you're still fine if you only want a simple ListView, but maybe NOT. But then you have code that references another layout to FragmentB:
new SimpleAdapter(getActivity().getBaseContext(),colorList, R.layout.fragment_b...
Note: R.layout.fragment_b is the layout specified for the ArrayAdapter only! Not for the fragment. But this is normal and may be fine.
In MainActivity, onColorLevelSelected():
fragTransaction.replace(R.id.curriculumParent,...
Note:
I think this replaces the layout only for the adapter and not the fragment.
Perhaps you want to inflate a layout file containing a ListView, and use that for the fragments.
Your problem is basically the layout, work with that.
EDIT:
Code suggestion:
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(),colorList, R.layout.fragment_x
public void onColorLevelSelected(int position)
FragmentC fragX = new FragmentX();
...
fragTransaction.replace(R.id.curriculumParent, fragX);
Notes:
Notice I am using an example of an arbitrary FragmentX. The Adapter and the replace() matches each other.
I understand this code change is somewhat considerable. Since I said it, here is a new code suggestion:
public void onListItemClick(ListView l, View v, int pos, long id){
Toast.makeText(getActivity(), "selected color :" + colorLevel[pos], Toast.LENGTH_LONG).show();
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(),colorList, R.layout.fragment_b ,from, to);
...
setListAdapter(adapter);
...
mCallback.onColorLevelSelected(pos); }
Note: This code change is made only to be simpler, my attempt. The idea is when the user click on a row in ListView, you know which layout and fragment is used. Hopefully that makes code less complicated.