将动态生成的视图存储到SQLite中

时间:2017-04-27 16:39:47

标签: java android sqlite

我的应用程序(在此阶段)通过Java动态生成最多8个按钮但是,我没有存储用户生成的按钮数量的数据库。目前,如果用户生成大约5个按钮,则在用户退出应用程序时它们将全部丢失。我浏览了一堆SQLite教程,但我的问题与示例有点不同。

我的问题是我想获取用户生成的按钮数量并将它们存储在SQLite表中。以下是我的代码。

这是我的Mainactivity.java:

public class MainActivity extends AppCompatActivity {

    int counter = 0;

    FloatingActionButton addingSemester;
    Button semesterButton;
    LinearLayout semesterLayout;
    GridLayout semesterGridLayout;

    LinearLayout.LayoutParams portraitLayoutParams = new LinearLayout.LayoutParams(
            AppBarLayout.LayoutParams.MATCH_PARENT,
            AppBarLayout.LayoutParams.WRAP_CONTENT);

    SemesterDBHelper mDbHelper;
    SQLiteDatabase db;
    ContentValues values;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDbHelper = new SemesterDBHelper(this);
        db = mDbHelper.getWritableDatabase();
        values = new ContentValues();

        addingSemester = (FloatingActionButton) findViewById(R.id.addActionButton);
        semesterLayout = (LinearLayout) findViewById(R.id.main_layout);

        semesterGridLayout = (GridLayout) findViewById(R.id.semester_grid_layout);

        semesterButton = new Button(MainActivity.this);

        if (savedInstanceState != null) {
            counter = savedInstanceState.getInt("counter");

            for (int i = 0; i < counter; i++) {
                addSemesterButton(i);
            }
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.main, menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.delete) {
            new AlertDialog.Builder(MainActivity.this)
                    .setTitle("Delete entry")
                    .setMessage("Are you sure you want to delete everything?")
                    .setCancelable(true)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
                                if (semesterGridLayout.getChildCount() > 0) {
                                    semesterGridLayout.removeAllViews();
                                } else {
                                    Toast.makeText(MainActivity.this, "There is nothing to delete", Toast.LENGTH_SHORT).show();
                                }
                            } else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
                                if (semesterLayout.getChildCount() > 0) {
                                    semesterLayout.removeAllViews();
                                } else {
                                    Toast.makeText(MainActivity.this, "There is nothing to delete", Toast.LENGTH_SHORT).show();
                                }
                            }
                            counter = 0;
                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    })
                    .show();
            return true;
        }


        return super.onOptionsItemSelected(item);

    }

    public void addSemesterButton(int id) {
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);

        double width = (size.x) / 3;

        semesterButton = new Button(MainActivity.this);
        semesterButton.setId(id + 1);
        semesterButton.setText("Semester " + (id + 1));
        semesterButton.setBackgroundColor(getColor(R.color.colorPrimary));
        semesterButton.setTextColor(Color.WHITE);
        portraitLayoutParams.setMargins(24, 24, 24, 24);

        if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
            GridLayout.LayoutParams params = new GridLayout.LayoutParams();
            params.setMargins(24, 24, 24, 24);
            params.width = (int) width;
            params.height = GridLayout.LayoutParams.WRAP_CONTENT;
            semesterButton.setLayoutParams(params);
            semesterGridLayout.addView(semesterButton);
        } else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
            semesterLayout.addView(semesterButton);
            semesterButton.setLayoutParams(portraitLayoutParams);
        }

        setOnLongClickListenerForSemesterButton();
        setOnClickListenerForSemesterButton(counter);
    }

    public void onFloatActionButtonClick(View view) {
        if (counter < 8) {
            addSemesterButton(counter);

            counter++;
            values.put(SemesterContract.SemesterEntry.COLUMN_SEMESTER_NAME, "semester " + counter);
            db.insert(SemesterContract.SemesterEntry.TABLE_NAME, null, values);
            setOnLongClickListenerForSemesterButton();

        } else if (counter == 8) {
            Toast.makeText(MainActivity.this, "You cannot add more than 8 semesters", Toast.LENGTH_SHORT).show();
        } else if (counter == 0) {

        }
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        savedInstanceState.putInt("counter", counter);
        super.onSaveInstanceState(savedInstanceState);
    }

    private void setOnClickListenerForSemesterButton(int id){
        semesterButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SemesterBuilderActivity.class);
                intent.putExtra("someKey", 1);
                startActivity(intent);
            }
        });
    }

    private void setOnLongClickListenerForSemesterButton() {
        semesterButton.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                final Button b = (Button) v;
                b.setTag(b.getText().toString());
                b.setBackgroundColor(Color.RED);
                b.setText("Delete");

                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Delete entry");
                builder.setMessage("Are you sure you want to delete this entry?");
                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
                            semesterGridLayout.removeView(b);
                            for (int i = 0; i < semesterGridLayout.getChildCount(); i++) {
                                ((Button) semesterGridLayout.getChildAt(i)).setText("Semester " + (i + 1));
                            }
                        } else if (!MainActivity.this.getResources().getBoolean(R.bool.is_landscape)) {
                            semesterLayout.removeView(b);
                            for (int i = 0; i < semesterLayout.getChildCount(); i++) {
                                ((Button) semesterLayout.getChildAt(i)).setText("Semester " + (i + 1));
                            }
                        }
                        counter--;
                    }
                });
                builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        b.cancelLongPress();
                        b.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
                        b.setText(b.getTag().toString());
                        dialog.cancel();

                    }
                });
                builder.show();
                return true;
            }
        });
    }
}

这是我的DBHelper类:

public class SemesterDBHelper extends SQLiteOpenHelper{

    public SemesterDBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public static final String DATABASE_NAME = "semesters.db";
    public static final int DATABASE_VERSION = 1;
    private static final String SQL_DELETE_ENTRIES =
            "DROP TABLE IF EXISTS " + SemesterContract.SemesterEntry.TABLE_NAME;

    @Override
    public void onCreate(SQLiteDatabase db) {
        String SQL_CREATE_SEMESTER_TABLE = "CREATE TABLE " + SemesterContract.SemesterEntry.TABLE_NAME + " ("
                + SemesterContract.SemesterEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + SemesterContract.SemesterEntry.COLUMN_SEMESTER_NAME + " TEXT NOT NULL";

        db.execSQL(SQL_CREATE_SEMESTER_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

这是我的合同:

public final class SemesterContract {

    private SemesterContract(){}

    public static final class SemesterEntry implements BaseColumns{
        public static final String TABLE_NAME = "semesters";
        public static final String _ID = BaseColumns._ID;
        public static final String COLUMN_SEMESTER_NAME = "semester";
    }
}

这是我得到的堆栈跟踪:

FATAL EXCEPTION: main
                                                                                 Process: myapp.onur.journeygpacalculator, PID: 28196
                                                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{myapp.onur.journeygpacalculator/myapp.onur.journeygpacalculator.MainActivity}: android.database.sqlite.SQLiteException: near "NULL": syntax error (code 1): , while compiling: CREATE TABLE semesters (_id INTEGER PRIMARY KEY AUTOINCREMENT, semester TEXT NOT NULL
                                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2726)
                                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2787)
                                                                                     at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1504)
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                     at android.os.Looper.loop(Looper.java:154)
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:6247)
                                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
                                                                                  Caused by: android.database.sqlite.SQLiteException: near "NULL": syntax error (code 1): , while compiling: CREATE TABLE semesters (_id INTEGER PRIMARY KEY AUTOINCREMENT, semester TEXT NOT NULL
                                                                                     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:895)
                                                                                     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:506)
                                                                                     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:726)
                                                                                     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                                     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                                     at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1785)
                                                                                     at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1716)
                                                                                     at myapp.onur.journeygpacalculator.data.SemesterDBHelper.onCreate(SemesterDBHelper.java:28)
                                                                                     at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
                                                                                     at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
                                                                                     at myapp.onur.journeygpacalculator.MainActivity.onCreate(MainActivity.java:52)

修改

这是我试图读取数据。我认为我没有正确实现它,但我试图创建光标。

这些是全球性的:

String[] projection = {
            SemesterContract.SemesterEntry._ID,
            SemesterContract.SemesterEntry.COLUMN_SEMESTER_NAME
    };

    String selection = SemesterContract.SemesterEntry.COLUMN_SEMESTER_NAME + " = ?";
    String[] selectionArgs = { "My Semester" };

    String sortOrder = SemesterContract.SemesterEntry.COLUMN_SEMESTER_NAME + " DESC";

这是我的onCreate:

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDbHelper = new SemesterDBHelper(this);
        db = mDbHelper.getWritableDatabase();
        values = new ContentValues();

        addingSemester = (FloatingActionButton) findViewById(R.id.addActionButton);
        semesterLayout = (LinearLayout) findViewById(R.id.main_layout);

        semesterGridLayout = (GridLayout) findViewById(R.id.semester_grid_layout);

        semesterButton = new Button(MainActivity.this);

        if (savedInstanceState != null) {
            counter = savedInstanceState.getInt("counter");

            for (int i = 0; i < counter; i++) {
                addSemesterButton(i);
            }
        }

        Cursor cursor = db.query(
                SemesterContract.SemesterEntry.TABLE_NAME,// The table to query
                projection,                               // The columns to return
                selection,                                // The columns for the WHERE clause
                selectionArgs,                            // The values for the WHERE clause
                null,                                     // don't group the rows
                null,                                     // don't filter by row groups
                sortOrder                                 // The sort order
        );
    }

1 个答案:

答案 0 :(得分:0)

String SQL_CREATE_SEMESTER_TABLE = "CREATE TABLE " + SemesterContract.SemesterEntry.TABLE_NAME + " ("
                + SemesterContract.SemesterEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + SemesterContract.SemesterEntry.COLUMN_SEMESTER_NAME + " TEXT NOT NULL";

替换

String SQL_CREATE_SEMESTER_TABLE = "CREATE TABLE " + SemesterContract.SemesterEntry.TABLE_NAME + " ("
                + SemesterContract.SemesterEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + SemesterContract.SemesterEntry.COLUMN_SEMESTER_NAME + " TEXT NOT NULL)";

对于数据保存和获取,您必须为此编写相同的函数,请查看本教程,了解如何在sqlite中保存和获取数据https://developer.android.com/training/basics/data-storage/databases.html