如何将动态生成的按钮记录到SQLite数据库中

时间:2017-04-27 02:50:01

标签: java android sqlite

我正在构建一个应用程序,用户通过Java代码动态生成学期(按钮)。让我们说用户生成大约4个按钮(用户最多可以生成8个),我想将其存储到我创建的SQLite数据库中。这是我的第一个应用程序,可能是我第一次使用SQLite数据库。我浏览了SQLite Android教程,但我的应用程序与他们使用的示例相比有点不同。

我需要帮助的是,能够将动态生成的按钮存储到我的数据库中,以便下次再次启动应用程序时保存完全相同的数量。我还需要使用onUpgrade连接delete(menuItem和alertdialog)函数。

这是我的Mainactivity.java。这是我生成所有UI的地方。它也是我的主页。

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);

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

        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++;
            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;
            }
        });
    }
}

这是我的合同类:

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";
    }
}

最后这是我的数据库助手:

public class SemesterDBHelper extends SQLiteOpenHelper{

    public SemesterDBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    public static final String DATABASE_NAME = "semesters.db";
    public static final int DATABASE_VERSION = 1;

    @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) {

    }
}

我感谢所有的帮助。

0 个答案:

没有答案