javascript - 将已传递给新 Activity 的数据保存到 SQLite 数据库中

标签 javascript android android-sqlite primary-key

我已经为此苦苦挣扎了好几天了。当我创建一个新联盟并打开 BowlerActivity 时,我可以看到传递给它的主键值。例如,如果 Dummy League = 5,我可以在下一个 Activity 中看到该值。我的问题是,我希望能够在创建投球手时将此值 (5) 关联到投球手。我似乎无法将传递的值放入对话框中以创建新的投球手;为了将其保存到我数据库中的 Bowler 表中。

使用MainActivity传递主键

//On Long Click On The RecyclerView Item An Alert Dialog Is Opened With The Option To Choose Edit/Delete
        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this,
                recyclerView, new RecyclerTouchListener.ClickListener() {
            @Override
            public void onClick(View view, final int position) {

                int leagueId = leaguesList.get(position).getId();
                Intent myIntent = new Intent(getBaseContext(), BowlerActivity.class);
                myIntent.putExtra("leagueId", leagueId);
                startActivity(myIntent);
             }

Bowler Activity

public class BowlerActivity extends AppCompatActivity {

    private BowlerAdapter mAdapter;
    private List<Bowler> bowlersList = new ArrayList<>();
    private CoordinatorLayout coordinatorLayout;
    private RecyclerView recyclerView;
    private TextView noBowlersView;

    private TextView bowlerLeagueId;

    private DatabaseHelper db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bowler);
        //Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //setSupportActionBar(toolbar);

        String savedExtra = String.valueOf(getIntent().getIntExtra("leagueId",1));
        TextView myText = (TextView) findViewById(R.id.tvLeagueId);
        final String s = myText.toString();
        myText.setText(savedExtra);

        coordinatorLayout = findViewById(R.id.coordinator_layout);
        recyclerView = findViewById(R.id.recycler_view);
        noBowlersView = findViewById(R.id.empty_bowlers_view);


        db = new DatabaseHelper(this);

        bowlersList.addAll(db.getAllBowlers());

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.add_bowler_fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showBowlerDialog(false, null, -1);
            }
        });

        mAdapter = new BowlerAdapter(this, bowlersList);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new MyDividerItemDecoration(this, LinearLayoutManager.VERTICAL, 16));
        recyclerView.setAdapter(mAdapter);

        toggleEmptyBowlers();



        //On Long Click On The RecyclerView Item An Alert Dialog Is Opened With The Option To Choose Edit/Delete
        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this,
                recyclerView, new RecyclerTouchListener.ClickListener() {
            @Override
            public void onClick(View view, final int position) {

                //Intent myIntent = new Intent(getApplicationContext(), SeriesActivity.class);
                //startActivity(myIntent);

            }

            @Override
            public void onLongClick(View view, int position) {
                showActionsDialog(position);
            }
        }));
    }

    //Inserting New Bowler In The Database And Refreshing The List
    private void createBowler(String bowler) {
        //Inserting Bowler In The Database And Getting Newly Inserted Bowler Id
        long id = db.insertBowler(bowler);

        //Get The Newly Inserted Bowler From The Database
        Bowler n = db.getBowler(id);

        if (n != null) {
            //Adding New Bowler To The Array List At Position 0
            bowlersList.add(0, n);

            //Refreshing The List
            mAdapter.notifyDataSetChanged();

            toggleEmptyBowlers();
        }
    }

    //Updating Bowler In The Database And Updating The Item In The List By Its Position
    private void updateBowler(String name, int position) {
        Bowler n = bowlersList.get(position);

        //Updating Bowler Text
        n.setName(name);
        //n.setLeagueId(  );

        //Updating The Bowler In The Database
        db.updateBowler(n);

        //Refreshing The List
        bowlersList.set(position, n);
        mAdapter.notifyItemChanged(position);

        toggleEmptyBowlers();
    }

    //Deleting Bowler From SQLite Database And Removing The Bowler Item From The List By Its Position
    private void deleteBowler(int position) {
        // deleting the note from db
        db.deleteBowler(bowlersList.get(position));

        //Removing The Bowler From The List
        bowlersList.remove(position);
        mAdapter.notifyItemRemoved(position);

        toggleEmptyBowlers();
    }

    //Opens Dialog With Edit/Delete Options
    //Edit - 0
    //Delete - 0
    private void showActionsDialog(final int position) {
        CharSequence colors[] = new CharSequence[]{"Edit", "Delete"};

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choose option");
        builder.setItems(colors, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    showBowlerDialog(true, bowlersList.get(position), position);
                } else {
                    deleteBowler(position);
                }
            }
        });
        builder.show();
    }

    //Show Alert Dialog With EditText Options to Enter/Edit A League
    //When shouldUpdate = true, It Will Automatically Display Old Bowler Name And Change The Button Text To UPDATE
    private void showBowlerDialog(final boolean shouldUpdate, final Bowler bowler, final int position) {
        LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
        View view = layoutInflaterAndroid.inflate(R.layout.dialog_bowler, null);

        AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(BowlerActivity.this);
        alertDialogBuilderUserInput.setView(view);



        final EditText inputBowler = view.findViewById(R.id.etBowlerNameInput);
        //final EditText inputBowlerLeagueId = view.findViewById( R.id.tvLeagueId );
        TextView dialogTitle = view.findViewById(R.id.dialog_title);
        dialogTitle.setText(!shouldUpdate ? getString(R.string.lbl_new_bowler_title) : getString(R.string.lbl_edit_bowler_title));

        if (shouldUpdate && bowler != null) {
            inputBowler.setText(bowler.getName());

        }
        alertDialogBuilderUserInput
                .setCancelable(false)
                .setPositiveButton(shouldUpdate ? "update" : "save", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogBox, int id) {

                    }
                })
                .setNegativeButton("cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialogBox, int id) {
                                dialogBox.cancel();
                            }
                        });

        final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
        alertDialog.show();

        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Show Toast Message When No Text Is Entered
                if (TextUtils.isEmpty(inputBowler.getText().toString())) {
                    Toast.makeText(BowlerActivity.this, "Enter Bowler!", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    alertDialog.dismiss();
                }


                //Check If User Is Updating Bowler
                if (shouldUpdate && bowler != null) {

                    //Updating Bowler By Its Id
                    updateBowler(inputBowler.getText().toString(), position);
                } else {
                    //Creating New Bowler
                    createBowler(inputBowler.getText().toString());
                }
            }
        });
    }

    //Toggling List And Empty Bowler View
    private void toggleEmptyBowlers() {
        //You Can Check bowlerList.size() > 0

        if (db.getBowlersCount() > 0) {
            noBowlersView.setVisibility( View.GONE);
        } else {
            noBowlersView.setVisibility( View.VISIBLE);
        }
    }
}

任何有关此问题的帮助将不胜感激。

最佳答案

我认为您需要为 savedExtra 变量提供更大的范围,然后使用它。所以:-

  1. savedExtra 声明为类变量。
  2. 更改其贴标位置并设置为仅设置值,而不声明它。
  3. 使用 savedExtra 变量设置新投球手的 ID。

以下代码(请参阅带有//<<<< ?????? 的注释以了解更改后的添加代码)我相信可以解决该问题:-

public class BowlerActivity extends AppCompatActivity {

    private BowlerAdapter mAdapter;
    private List<Bowler> bowlersList = new ArrayList<>();
    private CoordinatorLayout coordinatorLayout;
    private RecyclerView recyclerView;
    private TextView noBowlersView;

    private TextView bowlerLeagueId;

    private DatabaseHelper db;
    private String savedExtra; //<<<< Added change 1.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bowler);
        //Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //setSupportActionBar(toolbar);

        savedExtra = String.valueOf(getIntent().getIntExtra("leagueId",1)); //<<<< Saved Extra change 2.
        TextView myText = (TextView) findViewById(R.id.tvLeagueId);
        final String s = myText.toString();
        myText.setText(savedExtra);

        coordinatorLayout = findViewById(R.id.coordinator_layout);
        recyclerView = findViewById(R.id.recycler_view);
        noBowlersView = findViewById(R.id.empty_bowlers_view);


        db = new DatabaseHelper(this);

        bowlersList.addAll(db.getAllBowlers());

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.add_bowler_fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showBowlerDialog(false, null, -1);
            }
        });

        mAdapter = new BowlerAdapter(this, bowlersList);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new MyDividerItemDecoration(this, LinearLayoutManager.VERTICAL, 16));
        recyclerView.setAdapter(mAdapter);

        toggleEmptyBowlers();



        //On Long Click On The RecyclerView Item An Alert Dialog Is Opened With The Option To Choose Edit/Delete
        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this,
                recyclerView, new RecyclerTouchListener.ClickListener() {
            @Override
            public void onClick(View view, final int position) {

                //Intent myIntent = new Intent(getApplicationContext(), SeriesActivity.class);
                //startActivity(myIntent);

            }

            @Override
            public void onLongClick(View view, int position) {
                showActionsDialog(position);
            }
        }));
    }

    //Inserting New Bowler In The Database And Refreshing The List
    private void createBowler(String bowler) {
        //Inserting Bowler In The Database And Getting Newly Inserted Bowler Id
        bowler.setLeagueId(savedExtra); //<<<< ADDED change 3.
        long id = db.insertBowler(bowler);

        //Get The Newly Inserted Bowler From The Database
        Bowler n = db.getBowler(id);

        if (n != null) {
            //Adding New Bowler To The Array List At Position 0
            bowlersList.add(0, n);

            //Refreshing The List
            mAdapter.notifyDataSetChanged();

            toggleEmptyBowlers();
        }
    }

    //Updating Bowler In The Database And Updating The Item In The List By Its Position
    private void updateBowler(String name, int position) {
        Bowler n = bowlersList.get(position);

        //Updating Bowler Text
        n.setName(name);
        //n.setLeagueId(  );

        //Updating The Bowler In The Database
        db.updateBowler(n);

        //Refreshing The List
        bowlersList.set(position, n);
        mAdapter.notifyItemChanged(position);

        toggleEmptyBowlers();
    }

    //Deleting Bowler From SQLite Database And Removing The Bowler Item From The List By Its Position
    private void deleteBowler(int position) {
        // deleting the note from db
        db.deleteBowler(bowlersList.get(position));

        //Removing The Bowler From The List
        bowlersList.remove(position);
        mAdapter.notifyItemRemoved(position);

        toggleEmptyBowlers();
    }

    //Opens Dialog With Edit/Delete Options
    //Edit - 0
    //Delete - 0
    private void showActionsDialog(final int position) {
        CharSequence colors[] = new CharSequence[]{"Edit", "Delete"};

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choose option");
        builder.setItems(colors, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    showBowlerDialog(true, bowlersList.get(position), position);
                } else {
                    deleteBowler(position);
                }
            }
        });
        builder.show();
    }

    //Show Alert Dialog With EditText Options to Enter/Edit A League
    //When shouldUpdate = true, It Will Automatically Display Old Bowler Name And Change The Button Text To UPDATE
    private void showBowlerDialog(final boolean shouldUpdate, final Bowler bowler, final int position) {
        LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
        View view = layoutInflaterAndroid.inflate(R.layout.dialog_bowler, null);

        AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(BowlerActivity.this);
        alertDialogBuilderUserInput.setView(view);



        final EditText inputBowler = view.findViewById(R.id.etBowlerNameInput);
        //final EditText inputBowlerLeagueId = view.findViewById( R.id.tvLeagueId );
        TextView dialogTitle = view.findViewById(R.id.dialog_title);
        dialogTitle.setText(!shouldUpdate ? getString(R.string.lbl_new_bowler_title) : getString(R.string.lbl_edit_bowler_title));

        if (shouldUpdate && bowler != null) {
            inputBowler.setText(bowler.getName());

        }
        alertDialogBuilderUserInput
                .setCancelable(false)
                .setPositiveButton(shouldUpdate ? "update" : "save", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogBox, int id) {

                    }
                })
                .setNegativeButton("cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialogBox, int id) {
                                dialogBox.cancel();
                            }
                        });

        final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
        alertDialog.show();

        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Show Toast Message When No Text Is Entered
                if (TextUtils.isEmpty(inputBowler.getText().toString())) {
                    Toast.makeText(BowlerActivity.this, "Enter Bowler!", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    alertDialog.dismiss();
                }


                //Check If User Is Updating Bowler
                if (shouldUpdate && bowler != null) {

                    //Updating Bowler By Its Id
                    updateBowler(inputBowler.getText().toString(), position);
                } else {
                    //Creating New Bowler
                    createBowler(inputBowler.getText().toString());
                }
            }
        });
    }

    //Toggling List And Empty Bowler View
    private void toggleEmptyBowlers() {
        //You Can Check bowlerList.size() > 0

        if (db.getBowlersCount() > 0) {
            noBowlersView.setVisibility( View.GONE);
        } else {
            noBowlersView.setVisibility( View.VISIBLE);
        }
    }
}

注意这是原则上的代码,尚未经过测试,因此可能包含错误。

关于javascript - 将已传递给新 Activity 的数据保存到 SQLite 数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50591739/

相关文章:

javascript - 如何根据动态下拉菜单选择显示YouTube视频?

javascript - 如何淡入和淡出音频?

android - 如何为 Beta 测试人员和市场构建多个 Android 应用程序版本?

android - 如何在 Android SQlite 中添加 bool 列

javascript - http.get 或 http.request 回调仅在 shell 中显示 - node.js

javascript - 如何仅在首页应用此样式?

android - 如何在 Android 中只允许一个特定 fragment 同时具有纵向和横向方向?

android - 使用构建风格启动 Android 服务的多个实例

java - SQLite聚合查询

android - 无法从 Assets /SQLiteOpenHelper 中复制数据库