利用下拉微调所选项目数据库查询 [英] Query Database using selected item from drop down spinner

查看:86
本文介绍了利用下拉微调所选项目数据库查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序写入,并从数据库中删除。我有一个从该数据库中的2个不同的列都产生一个2纺纱。我想运行所有从给定的下拉微调匹配所选项目的记录的查询。截至目前一切工作正常但是当我从下拉列表中选择一个项目下来,什么也没有发生。我知道我失去了一些东西只是不知道或者。请帮忙

I have an app that writes to and deletes from a database. I have a 2 spinners that are generated from 2 different columns in that database. I want to run a query for all records matching the selected item from the given drop down spinner. As of right now everything works fine however when I select an item from the drop down, nothing happens. I know I'm missing something just not sure what or where. Please help

下面是我的Dbhelper.Java

Here is my Dbhelper.Java

package com.gamingbrothers.pat.passwordencrypter;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//table structure
public class Dbhelper extends SQLiteOpenHelper {
public static final String DB_NAME = "LogInInfo.db";
public static final String TABLE_NAME = "LogInInfo_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "USER_NAME";
public static final String COL_3 = "USER_PASSWORD";
public static final String COL_4 = "APPLICATION";
public static final String COL_5 = "CUSTOMER";


public Dbhelper(Context context) {
    super(context, DB_NAME, null, 1);
}

c.close();
return notes_array;
}
    @Override
    public void onCreate (SQLiteDatabase db) {
        db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT," +
                                                 "USER_NAME TEXT,USER_PASSWORD TEXT," +
                                                   "APPLICATION TEXT,CUSTOMER TEXT)");
}

    //Query Database with item selected from drop down
public Cursor getChoiceData() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor result = db.rawQuery("select * from LogInInfo_table where CUSTOMER = ?",null);
    return result;
}


  //Gather Data
public Cursor getAllData() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor result = db.rawQuery("select * from LogInInfo_table",null);
    return result;
}

//getting customers for drop down
public List<String> getAllCustomers(){
    List<String> customers = new ArrayList<String>();

    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_NAME;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToPosition(0)) {
        do {
            customers.add(cursor.getString(4));
        } while (cursor.moveToNext());
    }

    // closing connection
    cursor.close();
    db.close();

    // returning customers
    return customers;
}


//getting apps for drop down
public List<String> getAllApps(){
    List<String> apps = new ArrayList<String>();

    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_NAME;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToPosition(0)) {
        do {
            apps.add(cursor.getString(3));
        } while (cursor.moveToNext());
    }

    // closing connection
    cursor.close();
    db.close();

    // returning apps
    return apps;
}


//creating update data function
public boolean updateData(String ID,String User_Name,String Password,String Application,String Customer){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_1,ID);
    contentValues.put(COL_2,User_Name);
    contentValues.put(COL_3,Password);
    contentValues.put(COL_4, Application);
    contentValues.put(COL_5,Customer);
    db.update(TABLE_NAME,contentValues, "ID = ?",new String[] {ID});
    return true;
}

//deleting data
public Integer deleteData (String ID){
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(TABLE_NAME, "ID = ?",new String[]{ID});
}
}

下面是我的MainActivity.Java

Here is my MainActivity.Java

package com.gamingbrothers.pat.passwordencrypter;
//Created by Pat 8/6/15

import android.app.AlertDialog;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.List;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

Dbhelper myDB;
Button btnAdd;
Button btnDelete;
Button btnView;
Button btnUpdate;
Spinner spinner;
Spinner spinner2;
String itemSelected;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myDB = new Dbhelper(this);

    //initializing objects
    editUserName = (EditText) findViewById(R.id.editText_user);
    editPassword = (EditText) findViewById(R.id.editText_pass);
    editApplication = (EditText) findViewById(R.id.editText_app);
    editID = (EditText) findViewById(R.id.editText_id);
    editCustomer = (EditText) findViewById(R.id.editText_customer);
    btnAdd = (Button) findViewById(R.id.button_Add);
    btnDelete = (Button) findViewById(R.id.button_Delete);
    btnView = (Button) findViewById(R.id.button_View);
    btnUpdate = (Button) findViewById(R.id.button_update);
    spinner = (Spinner) findViewById(R.id.spinner);
    spinner2 = (Spinner) findViewById(R.id.spinner2);


    AddData();
    viewAll();
    UpdateData();
    DeleteData();
    loadSpinnerData();
    loadSpinner2Data();



}


public void loadSpinner2Data() {
    //db handler
    Dbhelper db2 = new Dbhelper(getApplicationContext());

    //Spinner drop elem.
    List<String> apps = db2.getAllApps();

    //Create adapter for spinner
    ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, apps);

    // Drop down layout style - list view with radio button
    dataAdapter2
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    //attaching data adapter
    spinner2.setAdapter(dataAdapter2);
}


private void loadSpinnerData() {
    // database handler
    Dbhelper db = new Dbhelper(getApplicationContext());

    // Spinner Drop down elements
    List<String> customers = db.getAllCustomers();

    // Creating adapter for spinner
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, customers);


    // Drop down layout style - list view with radio button
    dataAdapter
            .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);


    // attaching data adapter to spinner
    spinner.setAdapter(dataAdapter);

}


public void DeleteData() {
    btnDelete.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Integer deletedRows = myDB.deleteData(editID.getText().toString());
                    if(deletedRows >0)
                        Toast.makeText(MainActivity.this, "Data Deleted", Toast.LENGTH_LONG).show();
                    else
                        Toast.makeText(MainActivity.this, "Data not Deleted", Toast.LENGTH_LONG).show();
                }
            }
    );
}

//creating update data function
public void UpdateData() {
    btnUpdate.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean isUpdated = myDB.updateData(editID.getText().toString(),
                            editUserName.getText().toString(),
                            editPassword.getText().toString(),
                            editApplication.getText().toString(),
                            editCustomer.getText().toString());
                    //Parse update completion
                    if (isUpdated == true)
                        Toast.makeText(MainActivity.this, "Data Updated", Toast.LENGTH_LONG).show();
                    else
                        Toast.makeText(MainActivity.this, "Data not Updated", Toast.LENGTH_LONG).show();

                }
            });
}

//add data to database
public void AddData() {
    btnAdd.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean isInserted = myDB.insertData(editUserName.getText().toString(),
                            editPassword.getText().toString(),
                            editApplication.getText().toString(),
                            editCustomer.getText().toString());
                    //parse add completion
                    if (isInserted == true)
                        Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
                    else
                        Toast.makeText(MainActivity.this, "Data not Inserted", Toast.LENGTH_LONG).show();
                }
            });
}

//Get results from database when button is clicked
public void viewAll() {
    btnView.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Cursor result = myDB.getAllData();
                    //Check if database is empty
                    if (result.getCount() == 0) {
                        //Show Message
                        showMessage("Error", "No Data Found");
                        return;
                    }

                    StringBuffer buffer = new StringBuffer();
                    while (result.moveToNext()) {
                        buffer.append("ID:" + result.getString(0) + "\n");
                        buffer.append("User Name:" + result.getString(1) + "\n");
                        buffer.append("Password:" + result.getString(2) + "\n");
                        buffer.append("App:" + result.getString(3) + "\n");
                        buffer.append("Customer:" + result.getString(4) + "\n\n");
                    }

                    //Show all data
                    showMessage("Data", buffer.toString());
                }
            }
    );
}

//show data
public void showMessage(String title,String Message){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.setMessage(Message);
    builder.show();
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    String label = parent.getItemAtPosition(position).toString();
    myDB.getChoiceData().toString();
    Toast.makeText(parent.getContext(), "Here is your information: "+ label,Toast.LENGTH_LONG).show();


}

@Override
public void onNothingSelected(AdapterView<?> parent) {

    }
}

如果你需要我发表我的XML只问,但我并不认为这是neccessary,我没有发表我的logcat的,因为它没有给我一个错误。

If you need me to post my XML just ask, but I didn't think it was neccessary and I didn't post my logcat because it doesn't give me an error.

推荐答案

从code你贴你似乎缺少选择的项目监听器,添加以下,例如,您的onCreate:

From the code you posted you seem to be missing the selected item listener, add the following, for example, to your onCreate:

 spinner.setOnItemSelectedListener(this);
 spinner2.setOnItemSelectedListener(this);

这篇关于利用下拉微调所选项目数据库查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆