2015-08-08 61 views
0

我有一個應用程序,可以寫入數據庫和從數據庫中刪除。我有一個2數據庫中的2個不同列生成的spinners。我想運行一個查詢來匹配從給定的下拉微調器中選擇的項目的所有記錄。截至目前一切正常,但是當我從下拉菜單中選擇一項時,沒有任何反應。我知道我錯過了什麼,只是不知道在哪裏或哪裏。請幫助查詢數據庫使用從下拉菜單中選擇的項目

這裏是我的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

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只問,但我不認爲這是必要的,我沒有發佈我的logcat,因爲它不會給我一個錯誤。

+1

怎麼可能是95%PF傢伙在這裏使用'ArrayAdapter'在處理sqlite數據?你從哪裏得到這個不好的例子? – pskink

+0

很確定它在YouTube上,但使用ArrayAdapter的部分工作正常......它用來從我的數據庫中拉列的值來填充一個下拉微調器,它工作得很好..我現在需要能夠選擇其中一個值,並運行所有記錄的列= valueSelected ...我認爲它涉及「SELECT * FROM table_name WHERE column_name = itemSelected」,但我不知道如何或在哪裏做到這一點。 – thatdude1087

+0

如何或在哪裏做到這一點?當你的數據模型是sqlite db時,開始忘記'ArrayAdapter',真的 – pskink

回答

0

從您發佈的代碼,你似乎缺少選擇的項偵聽器,添加以下,例如,您的onCreate:

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

這並沒有完全解決我的問題但肯定地指出我在正確的方向謝謝你。 – thatdude1087

相關問題