单击项目时显示的值

时间:2018-05-20 16:51:51

标签: android database sqlite

我有一个sqlite数据库,其中包含4列的表格:名称,数量,卡路里和测量值。插入列名称的值将显示在微调器中。现在,我的问题是,是否可以在单击一个项目时显示与名称对应的数量值?如果是,那我该如何获得一些指导呢?

1 个答案:

答案 0 :(得分:1)

这是一个将数据存储到数据库中的数据库类,并且还会对此类执行删除,插入,更新等所有操作。

数据库类

public class DetailDatabase extends SQLiteOpenHelper {

  private static final String DATABASE_NAME = "Detail.db";
  public static final String TABLE_NAME = "Details";

  public static final String COLUMN_NAME = "NAME";
  public static final String COLUMN_QUANTITY = "QUANTITY";
  public static final String COLUMN_CALORIES = "CALORIES";
  public static final String COLUMN_MEASUREMENTS = "MEASUREMENTS";

  public SeriesDetailDatabase(Context context) {
    super(context, DATABASE_NAME, null, 1);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL(
            "create table  " + TABLE_NAME +
                    "( " +
                    COLUMN_NAME + "  varchar ," +
                    COLUMN_QUANTITY + " varchar," +
                    COLUMN_CALORIES + " varchar," +
                    COLUMN_MEASUREMENTS + " varchar)"
    );
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL(" DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
  } 

  public boolean insertOrUpdateDetails(String name, String quantity, String calories, String measurements) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COLUMN_NAME, name);
    contentValues.put(COLUMN_QUANTITY, quantity);
    contentValues.put(COLUMN_CALORIES, calories);
    contentValues.put(COLUMN_MEASUREMENTS, measurements);

    int rows = db.update(TABLE_NAME, contentValues, COLUMN_NAME + " = " + name, null);
    if (rows == 0) {
        db.insert(TABLE_NAME, null, contentValues);
    }
    return true;
  }

  public Cursor getData(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    return db.rawQuery(" select * from " + TABLE_NAME + " where id= " + id + "", null);
  }

  public int numberOfRows() {
    SQLiteDatabase db = this.getReadableDatabase();
    return (int) DatabaseUtils.queryNumEntries(db, TABLE_NAME);
  }

  public boolean updateData(String name, String quantity) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COLUMN_QUANTITY, quantity);
    db.update(TABLE_NAME, contentValues, COLUMN_NAME + " = ? ", new String[]{name});
    return true;
  }

  public Integer deleteData(Integer id) {
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(TABLE_NAME, COLUMN_NAME + " = ? ", new String[]{Integer.toString(id)});
  }

  public void deleteRow(String value) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("DELETE FROM " + TABLE_NAME + " WHERE " + COLUMN_BOOK_ID + "='" + value + "'");
    db.close();
  }

  public List<Model> getAllData() {
    List<Model> list = new LinkedList<>();

    // 1. build the query
    String query = "SELECT  * FROM " + TABLE_NAME + " ORDER BY " + COLUMN_NAME;

    // 2. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);

    // 3. go over each row, build book and add it to list
    Model model = null;
    if (cursor.moveToFirst()) {
        do {
            model = new Model();
            model.setName(cursor.getString(0));
            model.setQuantity(cursor.getString(1));
            model.setCalories(cursor.getString(2));
            model.setMeasurements(cursor.getString(3)) 

            // Add data to list
            list.add(model);
        } while (cursor.moveToNext());
    }

    db.close();
    return list;
  }

  public void deleteAll() {
    SQLiteDatabase db = this.getReadableDatabase();
    db.execSQL("DELETE FROM " + TABLE_NAME);
    db.close();
  }
}

这是一个模型类

模型类

public class Model {
  private  String  Name="";
  private  String  Quantity="";
  private  String  Calories="";
  private  String  Measurements="";

  public String getName() {
    return Name;
  }

  public void setName(String name) {
    Name = name;
  }

  public String getQuantity() {
    return Quantity;
  }

  public void setQuantity(String quantity) {
    Quantity = quantity;
  }

  public String getCalories() {
    return Calories;
  }

  public void setCalories(calories) {
    Calories = calories;
  }

  public String getMeasurements() {
    return Measurements;
  }

  public void setMeasurements(String measurements) {
    Measurements = measurements;
  }
}

spinner有一个适配器类。

适配器类

    public class CustomAdapter extends ArrayAdapter<String> {

        private ArrayList data;
        private LayoutInflater inflater;

        public CustomAdapter(Context homeActivity, int spinner_rows, ArrayList customListViewValuesArr) {
            super(activity, spinner_rows, customListViewValuesArr);
            data = customListViewValuesArr;
            inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
            return getCustomView(position, parent);
        }

        @NonNull
        @Override
        public View getView(int position, View convertView, @NonNull ViewGroup parent) {
            return getCustomView(position, parent);
        }

        private View getCustomView(int position, ViewGroup parent) {

            View row = inflater.inflate(R.layout.list_item, parent, false);

            Model model;
            model = (Model) data.get(position);

            TextView mNameView = row.findViewById(R.id.tvName);

            mNameView.setText(model.getName());

            return row;
        }
    }

这是一个主要的活动类,您可以在其中设置微调器上的适配器。

MainActivity

    package com.vrvirtual.lionservicescitizenapp;

    import android.annotation.SuppressLint;
    import android.app.Notification;
    import android.app.NotificationManager;
    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ArrayList<Model> list;

        private Model model;

        private Spinner mSpinnerView;

        private String Name = "";
        private String Quantity = "";
        private String Calories = "";
        private String Measurements = "";
        private DetailDatabase database;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main); 
            database=new DetailDatabase(this);  
            database.insertOrUpdateDetails("ABC","1","1000","aaa");
            database.insertOrUpdateDetails("xyz","2","3000","bbb");
            try {
                mSpinnerView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
                        model=list.get(position);
                        Name = model.getName();
                        CitQuantityyName = model.getQuantity();
                        Calories = model.getCalories();
                        Measurements = model.getMeasurements();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> adapter) {
                    }
                });
        }

        private void setCityAdapter() {
            try {
                list=database.getAllData();
                ArrayAdapter adapter = new CostomAdapter(this, R.layout.list_item, list);

                mSpinnerView.setAdapter(adapter);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onBackPressed() {
            super.onBackPressed();
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            Log.i(TAG, "On Destroy .....");
        }

        @Override
        protected void onPause() {
            super.onPause();
            Log.i(TAG, "On Pause .....");
        }

        @Override
        protected void onRestart() {
            super.onRestart();
            Log.i(TAG, "On Restart .....");
        }

        @Override
        protected void onResume() {
            super.onResume();
            Log.i(TAG, "On Resume .....");
        }

        @Override
        protected void onStart() {
            super.onStart();
            Log.i(TAG, "On Start .....");
        }

        @Override
        protected void onStop() {
            super.onStop();
            Log.i(TAG, "On Stop .....");
        }
    }

activity_main.xml中

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <Spinner
            android:id="@id/fault_category"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </RelativeLayout>

list_item.xml

    <RelativeLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/tvName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </RelativeLayout>