为文本视图赋值时为空值



我已经讨论了这个问题几个小时了。 我很确定我正确地将值saveLeagueId分配给TextView。

我正在尝试做的是将一个值从 MainActivity 传递给 BowlerActivity。

这是我使用意图传递值的代码;

@Override
            public void onClick(View view, final int position) {
                int leagueId = leaguesList.get(position).getId();
                String savedLeagueId = String.valueOf( leagueId );
                Intent myIntent = new Intent(MainActivity.this, BowlerActivity.class);
                Log.d("Passing League Id ", "Passed Value is " + leagueId);
                myIntent.putExtra("leagueId", savedLeagueId);
                startActivity(myIntent);
                overridePendingTransition(0, 0);
            }

我可以看到它实际上是将值传递给 BowlerActivity

2019-07-09 20:47:06.694 8596-8596/ca.vogl.r.tenpinbowlingcompanion D/Passing League Id: Passed Value is 2
2019-07-09 20:47:06.777 8596-8596/ca.vogl.r.tenpinbowlingcompanion D/GETALLBOWLERS-SQL: SQL used = >>>>SELECT  * FROM bowlers WHERE league_id = 'null' ORDER BY timestamp DESC<<<<
2019-07-09 20:47:06.785 8596-8596/ca.vogl.r.tenpinbowlingcompanion D/GETALLBOWLERS-CNT: Number of rows retrieved = 0
2019-07-09 20:47:06.786 8596-8596/ca.vogl.r.tenpinbowlingcompanion D/GETALLBOWLERS-CNT: Number of elements in bowlerslist = 0
2019-07-09 20:47:06.786 8596-8596/ca.vogl.r.tenpinbowlingcompanion D/SAVEDLEAGUEID --->: 2

但是,当我尝试将值传递给名为 leagueId 的文本视图时,它是空的。

这是我的BowlerActivity代码

public class BowlerActivity extends AppCompatActivity {
    private BowlerAdapter mAdapter;
    private List<Bowler> bowlersList = new ArrayList<>();
    private RecyclerView recyclerView;
    private TextView noBowlersView;
    public View view;
    private AdView mAdView;
    private DatabaseHelper db;
    private TextView leagueId;
    private String savedLeagueId;
    //Preference Variables
    private static final String PREFS_NAME = "prefs";
    private static final String PREF_BLUE_THEME = "blue_theme";
    private static final String PREF_GREEN_THEME = "green_theme";
    private static final String PREF_ORANGE_THEME = "purple_theme";
    private static final String PREF_RED_THEME = "red_theme";
    private static final String PREF_YELLOW_THEME = "yellow_theme";
    @Override
    protected void onResume() {
        super.onResume();
        db = new DatabaseHelper(this);
        view=getWindow().getDecorView().getRootView();
        Admob.createLoadBanner(getApplicationContext(), view);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //Use Chosen Theme
        SharedPreferences preferences = getSharedPreferences( PREFS_NAME, MODE_PRIVATE );
        boolean useBlueTheme = preferences.getBoolean( PREF_BLUE_THEME, false );
        if (useBlueTheme) {
            setTheme( R.style.AppTheme_Blue_NoActionBar );
        }
        boolean useGreenTheme = preferences.getBoolean( PREF_GREEN_THEME, false );
        if (useGreenTheme) {
            setTheme( R.style.AppTheme_Green_NoActionBar );
        }
        boolean useOrangeTheme = preferences.getBoolean( PREF_ORANGE_THEME, false );
        if (useOrangeTheme) {
            setTheme( R.style.AppTheme_Orange_NoActionBar );
        }
        boolean useRedTheme = preferences.getBoolean( PREF_RED_THEME, false );
        if (useRedTheme) {
            setTheme( R.style.AppTheme_Red_NoActionBar );
        }
        boolean useYellowTheme = preferences.getBoolean( PREF_YELLOW_THEME, false );
        if (useYellowTheme) {
            setTheme( R.style.AppTheme_Yellow_NoActionBar );
        }
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_bowler );
        Toolbar toolbar = findViewById( R.id.toolbar );
        MobileAds.initialize(this, "ca-app-pub-3736316423083905~2418480949");
        db = new DatabaseHelper(this);
        bowlersList.addAll(db.getAllBowlers(savedLeagueId));
        savedLeagueId = String.valueOf(getIntent().getStringExtra("leagueId"));
        Log.d("SAVEDLEAGUEID ---> ",  savedLeagueId);
        leagueId = findViewById(R.id.tvLeagueId);
        CoordinatorLayout coordinatorLayout = findViewById( R.id.coordinator_layout );
        recyclerView = findViewById(R.id.recycler_view);
        noBowlersView = findViewById(R.id.empty_bowlers_view);
        setSupportActionBar( toolbar );
        FloatingActionButton fab = findViewById( R.id.add_bowler_fab );
        fab.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openDialog(false, null,-1);
            }

        });
        mAdapter = new BowlerAdapter(this, bowlersList);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setAdapter(mAdapter);
        //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 bowlerId = bowlersList.get(position).getId();
                //Intent myIntent = new Intent(MainActivity.this, BowlerActivity.class);
                //Log.d("Passing Bowler Id ", "Passed Value is " + bowlerId);
                //myIntent.putExtra("bowlerId", bowlerId);
                //startActivity(myIntent);
                //overridePendingTransition(0, 0);
            }
            @Override
            public void onLongClick(View view, int position) {
                //showActionsDialog(position);
            }
        }));
    }
    //Opening Dialog to Add / Edit Bowler Profile
    public void openDialog(final boolean shouldUpdate, final Bowler bowler, final int position) {
        LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
        View view = View.inflate(this, R.layout.activity_bowlers_dialog, null);
        AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(BowlerActivity.this);
        alertDialogBuilderUserInput.setView(view);
        leagueId.setText(savedLeagueId);
        final EditText inputBowler = view.findViewById(R.id.etBowlerName);
        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(MainActivity.this, "Enter Bowler!", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    alertDialog.dismiss();
                }
                //Check If User Is Updating Bowler
                if (shouldUpdate && bowler != null) {
                    //Update Bowler By It's Id
                    updateBowler(inputBowler.getText().toString(), position);
                } else {
                    //Create New Bowler
                    createBowler(leagueId.getText().toString(), inputBowler.getText().toString());
                }
            }
        });
    }
    //Inserting New Bowler In The Database And Refreshing The List
    private void createBowler(String leagueId, String bowlerName) {
        //Inserting Bowler In Database And Getting Newly Inserted Bowler Id
        long id = db.insertBowler(leagueId, bowlerName);
        //Get The Newly Inserted Bowler From The Database
        Bowler n = db.getBowler(leagueId);
        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 bowlerName,  int position) {
        Bowler n = bowlersList.get(position);
        //Updating Bowler Text
        n.setName(bowlerName);
        //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
    public void deleteBowler(int position) {
        //Deleting The Bowler From The Database
        db.deleteBowler(bowlersList.get(position));
        //Removing Bowler From The List
        bowlersList.remove(position);
        mAdapter.notifyItemRemoved(position);
        toggleEmptyBowlers();
    }
    private void toggleEmptyBowlers() {
        // you can check notesList.size() > 0
        if (db.getBowlersCount() > 0) {
            noBowlersView.setVisibility( View.GONE);
        } else {
            noBowlersView.setVisibility( View.VISIBLE);
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate( R.menu.menu_main, menu );
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
            overridePendingTransition(0, 0);
            return true;
        }
        return super.onOptionsItemSelected( item );
    }
}

在上面的代码中,您可以看到我正在使用以下内容将文本设置为openDialog((中的TextView leagueId.setText(savedLeagueId);

有人可以指出我做错了什么吗? 我已经在堆栈上浏览了多个不同的帖子,看起来我这样做是正确的,但是无论我如何尝试分配我不断获得的值

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at ca.vogl.r.tenpinbowlingcompanion.views.BowlerActivity.openDialog(BowlerActivity.java:159)
        at ca.vogl.r.tenpinbowlingcompanion.views.BowlerActivity$1.onClick(BowlerActivity.java:117)

正如我注意到的那样,您在对话框窗口中有leagueId文本视图。因此,请确保在activity_bowlers_dialog布局文件中具有具有tvLeagueId id 的文本视图。

然后在openDialog函数中使用view.findViewById引用文本视图

public void openDialog(final boolean shouldUpdate, final Bowler bowler, final int position) {
        LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
        View view = View.inflate(this, R.layout.activity_bowlers_dialog, null);
        leagueId = view.findViewById(R.id.tvLeagueId); // <-- Add this line
        AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(BowlerActivity.this);
        alertDialogBuilderUserInput.setView(view);
        leagueId.setText(savedLeagueId);
        final EditText inputBowler = view.findViewById(R.id.etBowlerName);
        // rest of the code

它的意图与如何从返回 null 的 findViewById 获取 TextView 有关,这没有任何问题。

java.lang.NullPointerException:尝试在 * null 对象引用 * 上调用虚拟方法 'void android.widget.TextView.setText(java.lang.CharSequence('

最新更新