将已通过新活动的数据保存到SQLite数据库中

时间:2018-05-29 19:37:57

标签: javascript android android-sqlite primary-key

我几天来一直在努力解决这个问题。当我创建一个新联盟并打开BowlerActivity时,我可以看到传递给它的主键的值。例如,如果Dummy League = 5,我可以在下一个活动中看到此值。我的问题是,我希望能够在创建它时将此值(5)与保龄球联系起来。我似乎无法将传递的值传入Dialog以创建新的投球手;为了将其保存到我的数据库中的投球手表中。

使用

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

BowlerActivity

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

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

2 个答案:

答案 0 :(得分:1)

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

  1. savedExtra 声明为类变量。
  2. 更改decalred的位置并设置为仅设置值,而不是声明它。
  3. 使用 savedExtra 变量设置新投球手的ID。
  4. 以下代码(请参阅//&lt;&lt;&lt;&lt;&lt;&lt; ??????对已更改的代码添加代码的评论)是我认为可以解决此问题: -

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

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

答案 1 :(得分:0)

我将对话框设为DialogFragment并传递其参数包中的值。 DialogFragment优于&#34;裸&#34; AlertDialog,包括在配置更改时自动重新创建。我发现最简单的方法是覆盖片段onCreateDialog以返回AlertDialog。您可以在该方法中检索参数包,并在对话框按钮上的单击侦听器中使用它。