簡體   English   中英

將值分配給TextView時為空值

[英]Null Value When Assigning Value to TextView

我一直在准備過這個問題了幾個小時。 我敢肯定,我在正確的分配值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的TextView時,它為null。

這是我的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 );
    }
}

在上面的代碼中,您可以看到我正在使用以下方法將文本設置為TextView leagueId.setText(savedLeagueId); 在openDialog()內部。

有人可以指出我做錯了什么嗎? 我在堆棧上瀏覽了多個不同的帖子,看起來我做得正確,但是無論我如何嘗試分配我不斷得到的值

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)

意圖與從返回null的findViewById中獲取TextView的方式沒有關系。

java.lang.NullPointerException:嘗試在*空對象引用上調用虛擬方法'void android.widget.TextView.setText(java.lang.CharSequence)'

正如我注意到的leagueId您在“對話”窗口中有您的leagueId 因此,請確保您在activity_bowlers_dialog布局文件中具有帶tvLeagueId id的tvLeagueId

然后在您的openDialog函數中使用view.findViewById引用textview

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM