使用Sqlite将Edittext输入中的数据填充到Spinner Display

时间:2018-04-28 17:58:47

标签: android sqlite android-spinner

专家请按照我的查询提出建议。 我试图在Android工作室中运行查询。

原样:Spinner根据使用Textwatcher输入的edittext X值显示X值。

要成为:微调器应根据编辑文本中输入的X值显示Y值。

示例:如果我在edittext中输入值“6”,那么我的微调器应该显示vaue“数据结构”

我的数据库如下:enter image description here

数据库遵循

package com.bar.example.myapplication;


import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;

class DBHelper extends SQLiteOpenHelper {

  private Context mContext;

  //TASK: DEFINE THE DATABASE VERSION AND NAME  (DATABASE CONTAINS MULTIPLE TABLES)
  static final String DATABASE_NAME = "OCC";
  private static final int DATABASE_VERSION = 1;

  //TASK: DEFINE THE FIELDS (COLUMN NAMES) FOR THE COURSES TABLE
  public static final String COURSES_TABLE = "Courses";
  public static final String COURSES_KEY_FIELD_ID = "_id";
  public static final String FIELD_ALPHA = "alpha";
  public static final String FIELD_NUMBER = "number";
  public static final String FIELD_TITLE = "title";

  //TASK: DEFINE THE FIELDS (COLUMN NAMES) FOR THE INSTRUCTORS TABLE


  //TASK: DEFINE THE FIELDS (COLUMN NAMES) FOR THE OFFERINGS TABLE
  private static final String OFFERINGS_TABLE = "Offerings";
  private static final String OFFERINGS_KEY_FIELD_ID = "crn";
  private static final String FIELD_SEMESTER_CODE = "semester_code";
  public static final String FIELD_COURSE_ID = "course_id";

  public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    mContext = context;
  }

  @Override
  public void onCreate(SQLiteDatabase database) {
    String createQuery = "CREATE TABLE " + COURSES_TABLE + "(" +
      COURSES_KEY_FIELD_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
      FIELD_ALPHA + " TEXT, " +
      FIELD_NUMBER + " TEXT, " +
      FIELD_TITLE + " TEXT" + ")";
    database.execSQL(createQuery);



    createQuery = "CREATE TABLE " + OFFERINGS_TABLE + "(" +
      OFFERINGS_KEY_FIELD_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
      FIELD_SEMESTER_CODE + " INTEGER, " +
      FIELD_COURSE_ID + " INTEGER, "

      +
      "FOREIGN KEY(" + FIELD_COURSE_ID + ") REFERENCES "

      +
      COURSES_TABLE + "(" + COURSES_KEY_FIELD_ID + ")" +
      ")";
    database.execSQL(createQuery);
  }

  @Override
  public void onUpgrade(SQLiteDatabase database,
    int oldVersion,
    int newVersion) {
    database.execSQL("DROP TABLE IF EXISTS " + COURSES_TABLE);

    database.execSQL("DROP TABLE IF EXISTS " + OFFERINGS_TABLE);
    onCreate(database);
  }

  //********** COURSE TABLE OPERATIONS:  ADD, GETALL, EDIT, DELETE

  public void addCourse(Course course) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put(FIELD_ALPHA, course.getAlpha());
    values.put(FIELD_NUMBER, course.getNumber());
    values.put(FIELD_TITLE, course.getTitle());

    db.insert(COURSES_TABLE, null, values);

    // CLOSE THE DATABASE CONNECTION
    db.close();
  }

  public ArrayList < Course > getAllCourses() {
    ArrayList < Course > coursesList = new ArrayList < > ();
    SQLiteDatabase database = this.getReadableDatabase();
    //Cursor cursor = database.rawQuery(queryList, null);
    Cursor cursor = database.query(
      COURSES_TABLE,
      new String[] {
        COURSES_KEY_FIELD_ID,
        FIELD_ALPHA,
        FIELD_NUMBER,
        FIELD_TITLE
      },
      null,
      null,
      null, null, null, null);

    //COLLECT EACH ROW IN THE TABLE
    if (cursor.moveToFirst()) {
      do {
        Course course =
          new Course(cursor.getInt(0),
            cursor.getString(1),
            cursor.getString(2),
            cursor.getString(3));
        coursesList.add(course);
      } while (cursor.moveToNext());
    }
    return coursesList;
  }

  public void deleteCourse(Course course) {
    SQLiteDatabase db = this.getWritableDatabase();

    // DELETE THE TABLE ROW
    db.delete(COURSES_TABLE, COURSES_KEY_FIELD_ID + " = ?",
      new String[] {
        String.valueOf(course.getId())
      });
    db.close();
  }

  public void deleteAllCourses() {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(COURSES_TABLE, null, null);
    db.close();
  }

  public void updateCourse(Course course) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put(FIELD_ALPHA, course.getAlpha());
    values.put(FIELD_NUMBER, course.getNumber());
    values.put(FIELD_TITLE, course.getTitle());

    db.update(COURSES_TABLE, values, COURSES_KEY_FIELD_ID + " = ?",
      new String[] {
        String.valueOf(course.getId())
      });
    db.close();
  }

  public Course getCourse(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(
      COURSES_TABLE,
      new String[] {
        COURSES_KEY_FIELD_ID,
        FIELD_ALPHA,
        FIELD_NUMBER,
        FIELD_TITLE
      },
      COURSES_KEY_FIELD_ID + "=?",
      new String[] {
        String.valueOf(id)
      },
      null, null, null, null);

    if (cursor != null)
      cursor.moveToFirst();

    Course course = new Course(
      cursor.getInt(0),
      cursor.getString(1),
      cursor.getString(2),
      cursor.getString(3));

    db.close();
    return course;
  }




  //********** OFFERING TABLE OPERATIONS:  ADD, GETALL, EDIT, DELETE

  public void addOffering(int crn, int semesterCode, int courseId) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put(OFFERINGS_KEY_FIELD_ID, crn);
    values.put(FIELD_SEMESTER_CODE, semesterCode);
    values.put(FIELD_COURSE_ID, courseId);


    db.insert(OFFERINGS_TABLE, null, values);

    // CLOSE THE DATABASE CONNECTION
    db.close();
  }

  public ArrayList < Offering > getAllOfferings() {
    ArrayList < Offering > offeringsList = new ArrayList < > ();
    SQLiteDatabase database = this.getReadableDatabase();
    //Cursor cursor = database.rawQuery(queryList, null);
    Cursor cursor = database.query(
      OFFERINGS_TABLE,
      new String[] {
        OFFERINGS_KEY_FIELD_ID,
        FIELD_SEMESTER_CODE,
        FIELD_COURSE_ID
      },
      null,
      null,
      null, null, null, null);

    //COLLECT EACH ROW IN THE TABLE
    if (cursor.moveToFirst()) {
      do {
        Course course = getCourse(cursor.getInt(2));
        //Instructor instructor = getInstructor(cursor.getInt(3));
        Offering offering = new Offering(cursor.getInt(0),
          cursor.getInt(1), course);

        offeringsList.add(offering);
      } while (cursor.moveToNext());
    }
    return offeringsList;
  }

  public void deleteOffering(Offering offering) {
    SQLiteDatabase db = this.getWritableDatabase();

    // DELETE THE TABLE ROW
    db.delete(OFFERINGS_TABLE, OFFERINGS_KEY_FIELD_ID + " = ?",
      new String[] {
        String.valueOf(offering.getCRN())
      });
    db.close();
  }

  public void deleteAllOfferings() {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(OFFERINGS_TABLE, null, null);
    db.close();
  }

  public void updateOffering(Offering offering) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put(FIELD_SEMESTER_CODE, offering.getSemesterCode());
    values.put(FIELD_COURSE_ID, offering.getCourse().getId());


    db.update(OFFERINGS_TABLE, values, OFFERINGS_KEY_FIELD_ID + " = ?",
      new String[] {
        String.valueOf(offering.getCRN())
      });
    db.close();
  }

  public Offering getOffering(int crn) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(
      OFFERINGS_TABLE,
      new String[] {
        OFFERINGS_KEY_FIELD_ID,
        FIELD_SEMESTER_CODE,
        FIELD_COURSE_ID
      },
      OFFERINGS_KEY_FIELD_ID + "=?",
      new String[] {
        String.valueOf(crn)
      },
      null, null, null, null);

    if (cursor != null)
      cursor.moveToFirst();

    Course course = getCourse(cursor.getInt(2));
    //Instructor instructor = getInstructor(cursor.getInt(3));
    Offering offering = new Offering(cursor.getInt(0),
      cursor.getInt(1), course);


    db.close();
    return offering;
  }

  public Cursor getAllLabelsAsCursor() {
    String[] columns = new String[] {
      "rowid AS _id, *"
    }; // Need _id column for SimpleCursorAdapter
    return this.getWritableDatabase().query(COURSES_TABLE, columns, null, null, null, null, null);
  }



  public boolean importCoursesFromCSV(String csvFileName) {
    AssetManager manager = mContext.getAssets();
    InputStream inStream;
    try {
      inStream = manager.open(csvFileName);
    } catch (IOException e) {
      e.printStackTrace();
      return false;
    }

    BufferedReader buffer = new BufferedReader(new InputStreamReader(inStream));
    String line;
    try {
      while ((line = buffer.readLine()) != null) {
        String[] fields = line.split(",");
        if (fields.length != 4) {
          Log.d("OCC Course Finder", "Skipping Bad CSV Row: " + Arrays.toString(fields));
          continue;
        }
        int id = Integer.parseInt(fields[0].trim());
        String alpha = fields[1].trim();
        String number = fields[2].trim();
        String title = fields[3].trim();
        addCourse(new Course(id, alpha, number, title));
      }
    } catch (IOException e) {
      e.printStackTrace();
      return false;
    }
    return true;
  }



  public boolean importOfferingsFromCSV(String csvFileName) {
    AssetManager am = mContext.getAssets();
    InputStream inStream = null;
    try {
      inStream = am.open(csvFileName);
    } catch (IOException e) {
      e.printStackTrace();
    }

    BufferedReader buffer = new BufferedReader(new InputStreamReader(inStream));
    String line;
    try {
      while ((line = buffer.readLine()) != null) {
        String[] fields = line.split(",");
        if (fields.length != 4) {
          Log.d("OCC Course Finder", "Skipping Bad CSV Row: " + Arrays.toString(fields));
          continue;
        }
        int crn = Integer.parseInt(fields[0].trim());
        int semesterCode = Integer.parseInt(fields[1].trim());
        int courseId = Integer.parseInt(fields[2].trim());

        addOffering(crn, semesterCode, courseId);
      }
    } catch (IOException e) {
      e.printStackTrace();
      return false;
    }
    return true;
  }
}

主要活动。

package com.bar.example.myapplication;


import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;


import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;

public class CourseSearchActivity extends AppCompatActivity {

  private DBHelper db;
  private List < Course > allCoursesList;
  private List < Offering > allOfferingsList;
  private List < Offering > filteredOfferingsList;
  public Button reset;
  private EditText courseTitleEditText;
  private Spinner ok;
  private ListView offeringsListView;

  // private selectedInstructorName selectedInstructorName;
  private InstructorSpinnerAdapter instructorSpinnerAdapter;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_course_search);

    deleteDatabase(DBHelper.DATABASE_NAME);
    db = new DBHelper(this);
    db.importCoursesFromCSV("courses.csv");

    db.importOfferingsFromCSV("offerings.csv");
    Button reset = (Button) findViewById(R.id.resetButton);
    allOfferingsList = db.getAllOfferings();
    filteredOfferingsList = new ArrayList < > (allOfferingsList);

    allCoursesList = db.getAllCourses();

    courseTitleEditText = (EditText) findViewById(R.id.courseTitleEditText);
    courseTitleEditText.addTextChangedListener(courseTitleTextWatcher);

    ok = (Spinner) findViewById(R.id.spinner1);


    // offeringListAdapter = new OfferingListAdapter(this, R.layout.offering_list_item, filteredOfferingsList);
    // ok.setAdapter(offeringListAdapter);
    instructorSpinnerAdapter = new InstructorSpinnerAdapter(this, R.layout.offering_list_item, filteredOfferingsList);

    ArrayAdapter < String > instructorSpinnerAdapter = new ArrayAdapter < String >
      (this, android.R.layout.simple_spinner_item, getAllCourse());
    ok.setAdapter(instructorSpinnerAdapter);

    ok.setOnItemSelectedListener(instructorSpinnerListener);


  }


  private String[] getAllCourse1() {
    String[] instructorNames = new String[allCoursesList.size() + 1];
    instructorNames[0] = "[Select Course]";
    for (int i = 1; i < instructorNames.length; i++) {
      instructorNames[i] = allCoursesList.get(i - 1).getTitle();
    }
    return instructorNames;
  }



  private ArrayList < String > getAllCourse() {
    ArrayList < String > instructorNames = new ArrayList < > ();
    instructorNames.add("[Select Course]");
    for (int i = 0; i < allCoursesList.size(); i++) {

      instructorNames.add(allCoursesList.get(i).getTitle());
    }
    return instructorNames;
  }

  public TextWatcher courseTitleTextWatcher = new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }
    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
      String input = charSequence.toString().toLowerCase();
      ArrayAdapter adapter = (ArrayAdapter) ok.getAdapter();
      adapter.clear();
      if (input.equals("")) {
        adapter.addAll(getAllCourse());
      } else {
        Course course;
        for (int j = 0; j < allCoursesList.size(); j++) {
          // If the course title starts with the user input,
          // add it to the listAdapter
          course = allCoursesList.get(j);
          if (course.getTitle().toLowerCase().startsWith(input)) {
            adapter.add(course.getTitle());
          }
        }
      }
      adapter.notifyDataSetChanged();
      if (adapter.getCount() != 0) ok.setSelection(0);
    }
    @Override
    public void afterTextChanged(Editable editable) {


    }
  };

  public AdapterView.OnItemSelectedListener instructorSpinnerListener = new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView << ? > adapterView, View view, int i, long l) {
      String selectedInstructorName = adapterView.getItemAtPosition(i).toString();
      if (selectedInstructorName.equals("[Select Instructor]")) {
        instructorSpinnerAdapter.clear();
        for (Offering offering: allOfferingsList)
          instructorSpinnerAdapter.add(offering);


      } else {

        instructorSpinnerAdapter.clear();

      }

    }


    @Override
    public void onNothingSelected(AdapterView << ? > adapterView) {
      adapterView.setSelection(0);

      // Toast.makeText(getApplicationContext(), "Why?", Toast.LENGTH_SHORT).show();
    }
  };




}

Activity_course_search.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: id = "@+id/activity_course_search"
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: orientation = "vertical"
android: paddingBottom = "@dimen/activity_vertical_margin"
android: paddingLeft = "@dimen/activity_horizontal_margin"
android: paddingRight = "@dimen/activity_horizontal_margin"
android: paddingTop = "@dimen/activity_vertical_margin"
tools: context = "com.bar.example.myapplication.CourseSearchActivity" >

  <
  LinearLayout
android: orientation = "horizontal"
android: layout_width = "match_parent"
android: layout_height = "wrap_content" >

  <
  TextView
android: text = "Filter By  Instructor"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: id = "@+id/textView" /
  >

  <
  Spinner
android: id = "@+id/instructorSpinner"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: layout_weight = "1" / >

  <
  /LinearLayout>

  <
  LinearLayout
android: orientation = "horizontal"
android: layout_width = "match_parent"
android: layout_height = "wrap_content" >

  <
  TextView
android: text = "Filter By Course Title"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: id = "@+id/textView2" /
  >

  <
  EditText
android: id = "@+id/courseTitleEditText"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: inputType = "textPersonName"
android: ems = "10" /
  >

  <
  /LinearLayout>

  <
  LinearLayout
android: orientation = "horizontal"
android: layout_width = "match_parent"
android: layout_height = "wrap_content" >

  <
  Button
android: text = "@string/reset_button_text"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: layout_weight = "1"
android: id = "@+id/resetButton" /
  >

  <
  /LinearLayout>

  <
  ListView
android: id = "@+id/offeringsListView"
android: layout_width = "match_parent"
android: layout_height = "18dp" >

  <
  /ListView>

  <
  Spinner
android: id = "@+id/spinner1"
android: layout_width = "341dp"
android: layout_height = "93dp"
android: layout_weight = "1" / >
  <
  /LinearLayout>

offering_list_item.xml

<< ? xml version = "1.0"
encoding = "utf-8" ? >
  <
  LinearLayout xmlns : android = "http://schemas.android.com/apk/res/android"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"

android: id = "@+id/offeringListLinearLayout" >

  <
  LinearLayout
android: orientation = "vertical"
android: layout_width = "match_parent"
android: layout_height = "match_parent" >

  <
  TextView
android: text = "TextView"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: textSize = "20sp"
android: id = "@+id/offeringListFullNameTextView" / >


  <
  /LinearLayout>


  <
  /LinearLayout>

主屏幕1: enter image description here

要求1 :(工作正常)从数据库中选择微调器。

enter image description here

要求2:工作但需要另一种方式。使用textwacher基于edittext条目从数据库显示微调器。我想要的是,如果输入“数字A170然后我的微调器应该显示”标题“Java编程1从数据库

当前屏幕显示enter image description here

我想以这种方式...... enter image description here

修改了onTextChanged代码。

public TextWatcher courseTitleTextWatcher = new TextWatcher() {
  @Override
  public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

  }
  @Override
  public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    String input = charSequence.toString().toLowerCase();
    ArrayAdapter adapter = (ArrayAdapter) ok.getAdapter();
    adapter.clear();
    if (input.equals("")) {
      adapter.addAll(getAllCourse());
    } else {
      Course course;

      for (int j = 0; j < CoursesList.size(); j++) {
        // If the course title starts with the user input,
        // add it to the listAdapter
        // course = allCoursesList.get(j);
        if (courseTitleEditText.getText().equals(CoursesList.get(j).get("number"))) {
          //adapter.add(course.getTitle());
          ok.setSelection(j);

        }
      }
    }
    // adapter.notifyDataSetChanged();
    //if(adapter.getCount() != 0)
    // ok.setSelection(i);
  }
  @Override
  public void afterTextChanged(Editable editable) {


  }
};

2 个答案:

答案 0 :(得分:1)

试试这个。它应该解决你的问题。

替换if (course.getTitle().toLowerCase().startsWith(input)) {

if (course.getNumber().toLowerCase().startsWith(input)) {

答案 1 :(得分:0)

我想我认为你需要什么

实际上这很简单 我尝试使用你的代码,但不是像你一样的建模方式 它将通过hashmap数组

首先我们需要使用此代码从您的sqlite获取数据

课程DBHelper中的这个

import java.util.HashMap;
import java.util.Map;

这是你需要的导入

public ArrayList<Map<String, String>> getCourses()
{
    ArrayList<Map<String, String>> array_list = new ArrayList<>();

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery("select * from " + COURSES_TABLE, null);
    res.moveToFirst();

    while(res.isAfterLast() == false){
        Map<String, String> datanum = new HashMap<String, String>();
        datanum.put("id", res.getString(res.getColumnIndex(COURSES_KEY_FIELD_ID)));
        datanum.put("alpha", res.getString(res.getColumnIndex(FIELD_ALPHA)));
        datanum.put("number", res.getString(res.getColumnIndex(FIELD_NUMBER)));
        datanum.put("title", res.getString(res.getColumnIndex(FIELD_TITLE)));
        array_list.add(datanum);
        res.moveToNext();
    }
    return array_list;
}

这里的代码将完美无缺,您无需编辑我的课程

现在你需要在你的课程中调用这个方法

课堂上的这个课程搜索活动

DBHelper DB;
ArrayList<Map<String, String>> CoursesList = new ArrayList<Map<String, String>>();

on create

    DB = new DBHelper(this);
    CoursesList= DB.getCourses(); 

现在你已经拥有了CoursesList中的所有内容,现在你需要弄清楚你想要选择哪个微调器位置

所以

你要循环它

Textlistener中的这个

    for(int i = 0 ; i < CoursesList.size() ; i++){
        if(courseTitleEditText.getText().equals(CoursesList.get(i).get("number"))){//ex.A170
// you must to be filled your spinner from same courses db and here you gonna to set your selection by iteration
            ok.setSelection(i);
        } 
    }

也许这对你的代码来说不是正确的,因为我看到你在你的代码中使用建模而我使用Hashmap但我认为从你的代码中看到相同的建模方式很有用 我没有测试它我直接写了这么测试并告诉我发生了什么 希望我帮忙