Доступен тот же заголовок вопроса, но требования разные.
Выбор первого счетчика должен загружаться из базы данных, а второй и третий счетчик должны меняться в зависимости от выбора первого первого счетчика.
Текущий:
- ![Spinner2&Spinner3 display based on spinner1](https://i.stack.imgur.com/frAKA.jpg)
Как я вижу, что-то не так вSQL-запрос, который я не могу найти.
Проблема:
- Spinner1 должен отображать игнорировать дублирование вместо двух P1 он должен отображаться как P1, P2,N1.
- Spinner2 должен отображать все записи, относящиеся к P1, тогда как он показывает только одну запись
Требование:
Второй счетчик и третийсчетчик должен заполнять данные, основанные на первом счетчике, тогда как задача состоит в том, чтобы второй счетчик отображал все данные, которые соответствуют счетчику1.
Макет: 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;
}
}
База данных
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
);
}
}