简体   繁体   English

ListView不显示在新活动中

[英]ListView Not Displaying in New Activity

I am trying to get a ListView to appear in a new activity. 我正在尝试让ListView出现在新活动中。 I can see the record ID in the logcat, and I can see that the proper ID is being selected in debug view, but when I go to the new activity the list array is empty. 我可以在logcat中看到记录ID,并且可以看到在调试视图中选择了正确的ID,但是当我转到新活动时,列表数组为空。

This is what I am seeing in debug view: 这是我在调试视图中看到的:

调试视图

In the logcat I see this: logcat中,我看到以下内容:

2018-10-07 11:39:09.286 12624-12624/ca.rvogl.tpbcui D/SAVEDLEAGUEID_VAL: 1
2018-10-07 11:39:09.286 12624-12624/ca.rvogl.tpbcui D/LEAGUEID_VAL: android.support.v7.widget.AppCompatTextView{e67a170 G.ED..... ......I. 0,0-0,0 #7f080112 app:id/tvLeagueId}
2018-10-07 11:39:09.293 12624-12624/ca.rvogl.tpbcui D/GETALLBOWLERS-SQL: SQL used = >>>>SELECT  * FROM bowlers WHERE league_id = '1' ORDER BY timestamp DESC<<<<
2018-10-07 11:39:09.298 12624-12624/ca.rvogl.tpbcui D/GETALLBOWLERS-CNT: Number of rows retrieved = 0
2018-10-07 11:39:09.299 12624-12624/ca.rvogl.tpbcui D/GETALLBOWLERS-CNT: Number of elements in bowlerslist = 0

As you can see from the logcat the savedLeagueId is being passed to the SQLite Query that is suppose to be getting the list of Bowlers for the listview. 从日志猫中可以看到,已保存的LeagueId将传递给SQLite查询,该SQLite查询假定正在获取listview的Bowlers列表。 However the number of elements in the bowlerslist is 0. 但是,常礼帽列表中的元素数量为0。

I have gone through the code over and over again but I am unable to isolate where the issue is. 我已经一遍又一遍地遍历代码,但是我无法找出问题所在。

LeagueAdapter.java LeagueAdapter.java

public class LeagueAdapter extends RecyclerView.Adapter<LeagueAdapter.MyViewHolder> {

    private Context context;
    private List<League> leaguesList;

    public void notifyDatasetChanged(List<League> newleagueslist) {
        leaguesList.clear();
        leaguesList.addAll(newleagueslist);
        super.notifyDataSetChanged();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView name;
        public TextView basescore;
        public TextView basescorepercentage;
        public TextView id;
        public TextView wins;
        public TextView losses;
        public TextView timestamp;
        public TextView buttonViewOption;

        public MyViewHolder(View view) {
            super(view);
            id = view.findViewById( R.id.tvLeagueId);
            name = view.findViewById(R.id.tvSeriesName );
            basescore = view.findViewById(R.id.tvBaseScore );
            basescorepercentage = view.findViewById(R.id.tvBaseScorePercentage );
            wins = view.findViewById(R.id.tvLeagueWins );
            losses = view.findViewById(R.id.tvLeagueLosses );
            timestamp = view.findViewById(R.id.timestamp);
            buttonViewOption = (TextView) view.findViewById(R.id.buttonViewOptions);
        }
    }


    public LeagueAdapter(Context context, List<League> leaguesList) {

        this.context = context;
        this.leaguesList = leaguesList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.listview_league, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        League league = leaguesList.get(position);
        int id = league.getId();
        Log.d("id", String.valueOf(id));
        int leagueId = id;
        Log.d("leagueId", String.valueOf(leagueId));
        holder.id.setText(String.valueOf(leagueId));
        holder.name.setText(league.getName());
        holder.basescore.setText(league.getBaseScore());
        holder.basescorepercentage.setText(league.getBaseScorePercentage());

        holder.wins.setText(league.getWins());
        holder.losses.setText(league.getLosses());
        /*if (league.getAverage() != "") {
            holder.leagueAverage.setText(String.format("League Avg: %s", league.getAverage()));
        } else {
            holder.leagueAverage.setText(String.format("League Avg: %s", "0"));
        }*/
        //Formatting And Displaying Timestamp
        holder.timestamp.setText(formatDate(league.getTimestamp()));
        holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //creating a popup menu
                PopupMenu popup = new PopupMenu(context, holder.buttonViewOption);
                //inflating menu from xml resource
                popup.inflate(R.menu.league_options_menu);
                //adding click listener
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.profile:
                                Log.d("leagueId", String.valueOf(position));
                                int leagueId = league.getId();
                                String savedLeagueId = String.valueOf(id);
                                Intent myIntent = new Intent(context, LeagueProfileViewActivity.class);
                                myIntent.putExtra("leagueId", leagueId);
                                context.startActivity(myIntent);
                                break;
                            case R.id.delete:
                                ((MainActivity) context).deleteLeague(position);
                                break;
                        }
                        return false;
                    }
                });
                //displaying the popup
                popup.show();

            }
        });
        holder.name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //String leagueId = String.valueOf(leaguesList.get(position).getId());

                int leagueId = league.getId();
                String savedLeagueId = String.valueOf(id);
                Log.d("leagueId", String.valueOf(position));
                Intent myIntent = new Intent(context, BowlerActivity.class);
                myIntent.putExtra("leagueId", savedLeagueId);
                context.startActivity(myIntent);

            }
        });
    }


    @Override
    public int getItemCount() {
        return leaguesList.size();
    }

    //Formatting TimeStamp to 'EEE MMM dd yyyy (HH:mm:ss)'
    //Input  : 2018-05-23 9:59:01
    //Output : Wed May 23 2018 (9:59:01)
    private String formatDate(String dateStr) {
        try {
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = fmt.parse(dateStr);
            SimpleDateFormat fmtOut = new SimpleDateFormat("EEE MMM dd yyyy (HH:mm:ss)");
            return fmtOut.format(date);
        } catch (ParseException e) {

        }

        return "";
    }
}

I am moving to the BowlerActivity using holder.name, where I am passing the League ID using an intent. 我将使用holder.name移至BowlerActivity,并在其中使用意图传递联赛ID。

BowlerActivity.java BowlerActivity.java

public class BowlerActivity extends AppCompatActivity {

    private BowlerAdapter mAdapter;
    private final List<Bowler> bowlersList = new ArrayList<>();
    private TextView noBowlersView;

    private DatabaseHelper db;

    private TextView leagueId;
    private String savedLeagueId;

    /*private TextView seriesleagueId;
    private String seriesLeagueId;
    private TextView bowlerAverage;
    private TextView bowlerHandicap;
    private String savedBowlerAverage;*/


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

        mAdapter.notifyDatasetChanged( db.getAllBowlers(savedLeagueId ) );
    }

    @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 = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        Objects.requireNonNull( getSupportActionBar() ).setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getApplicationContext(),MainActivity.class));
                finish();
                overridePendingTransition(0, 0);

            }
        });

        savedLeagueId = String.valueOf(getIntent().getStringExtra("leagueId"));
        leagueId = findViewById(R.id.tvLeagueId);
        Log.d("SAVEDLEAGUEID_VAL", String.valueOf(savedLeagueId));
        Log.d("LEAGUEID_VAL", String.valueOf(leagueId));
        /*bowlerAverage = (TextView) findViewById(R.id.tvBowlerAverage);

                bowlerHandicap = (TextView) findViewById(R.id.tvBowlerHandicap);*/

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

        db = new DatabaseHelper(this);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.add_bowler_fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //showBowlerDialog(false, null, -1);
                boolean shouldUpdate = false;
                int bowlerId = -1;
                String leagueId = String.valueOf(savedLeagueId);
                Intent intent = new Intent(getApplicationContext(), BowlerProfileEditActivity.class);
                intent.putExtra("shouldUpdate", shouldUpdate);
                intent.putExtra("leagueId", leagueId);
                intent.putExtra("bowlerId", bowlerId);
                startActivity(intent);
                finish();
                overridePendingTransition(0, 0);

            }
        });

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

        toggleEmptyBowlers();
    }

    //Inserting New Bowler In The Database And Refreshing The List
    private void createBowler(String leagueId, String bowlerName) {
        String bowlerAverage = "0";
        //Inserting Bowler In The Database And Getting Newly Inserted Bowler Id
        long id = db.insertBowler(savedLeagueId, bowlerName, bowlerAverage);

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

        if (n != null) {
            //Adding New Bowler To The Array List At Position 0
            bowlersList.add( 0, n );
            //Refreshing The List
            mAdapter.notifyDatasetChanged(db.getAllBowlers(savedLeagueId));
            //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.setLeagueId(savedLeagueId);
        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) {

        Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "Series will be deleted.", Snackbar.LENGTH_LONG)
                .setActionTextColor(Color.YELLOW)
                .setAction("OK", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //Deleting The Bowler From The Database
                        db.deleteBowler(bowlersList.get(position));
                        //Removing The Bowler From The List
                        bowlersList.remove(position);
                        mAdapter.notifyItemRemoved(position);
                        //db.leagueAverageScore(savedLeagueId);
                        toggleEmptyBowlers();
                    }
                });
        snackbar.show();
    }

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

    @Override
    public void onRestart() {
        super.onRestart();
        //When BACK BUTTON is pressed, the activity on the stack is restarted
        //Do what you want on the refresh procedure here
    }

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

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        //Check If Request Code Is The Same As What Is Passed - Here It Is 1
        if(requestCode==1)
        {
            String savedLeagueId=data.getStringExtra("seriesLeagueId");
            String seriesBowlerId=data.getStringExtra("seriesBowlerId");
            bowlersList.addAll(db.getAllBowlers(savedLeagueId));
        }
    }

    @Override
    public void onBackPressed() {
        startActivity(new Intent(getApplicationContext(),MainActivity.class));
        finish();
        overridePendingTransition(0, 0);
    }
}

Bowler Methods in DatabaseHelper.java DatabaseHelper.java中的 Bowler 方法

public long insertBowler(String leagueId, String bowlerName, String bowlerAverage) {
    String bowlerHandicap ="0";

    //Get Writable Database That We Want To Write Data Too
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();

    //`id` and `timestamp` Will Be Inserted Automatically
    values.put(Bowler.COLUMN_LEAGUE_ID, leagueId);
    values.put(Bowler.COLUMN_NAME, bowlerName);
    values.put(Bowler.COLUMN_BOWLER_AVERAGE, bowlerAverage);
    values.put(Bowler.COLUMN_BOWLER_HANDICAP, bowlerHandicap);

    //Insert Row
    //long id = db.insert(Bowler.TABLE_NAME, null, values);
    long id = db.insertOrThrow( Bowler.TABLE_NAME, null, values );
    Log.d("INSERTBOWLER","Number of bowlers in db = " + String.valueOf( DatabaseUtils.queryNumEntries(db,Bowler.TABLE_NAME)));
    //Close Database Connection
    db.close();

    //Return Newly Inserted Row Id
    return id;
}

public Bowler getBowler(String leagueId) {
    //Get Readable Database If We Are Not Inserting Anything
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query( Bowler.TABLE_NAME,
            new String[]{Bowler.COLUMN_ID, Bowler.COLUMN_LEAGUE_ID, Bowler.COLUMN_NAME, Bowler.COLUMN_BOWLER_AVERAGE, Bowler.COLUMN_BOWLER_HANDICAP, Bowler.COLUMN_TIMESTAMP},
            Bowler.COLUMN_LEAGUE_ID + "=?",
            new String[]{String.valueOf(leagueId)}, null, null, null, null);

    Bowler bowler = null;
    if (cursor.moveToFirst()) {

        //Prepare Bowler Object
        bowler = new Bowler(
                cursor.getInt(cursor.getColumnIndex(Bowler.COLUMN_ID)),
                cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_LEAGUE_ID)),
                cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_NAME)),
                cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_BOWLER_AVERAGE)),
                cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_BOWLER_HANDICAP)),
                cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_TIMESTAMP)));

        //Close Database Connection
        cursor.close();
        return bowler;
    } else {
        return bowler;
    }
}
public List<Bowler> getAllBowlers(String leagueId) {
    List<Bowler> bowlers = new ArrayList<>();

    //Select All Query
    String selectQuery = "SELECT  * FROM " + Bowler.TABLE_NAME + " WHERE " + Bowler.COLUMN_LEAGUE_ID + " = '" + leagueId + "'" + " ORDER BY " +
            Bowler.COLUMN_TIMESTAMP + " DESC";

    Log.d("GETALLBOWLERS-SQL","SQL used = >>>>" +selectQuery + "<<<<");

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    Log.d("GETALLBOWLERS-CNT","Number of rows retrieved = " + String.valueOf(cursor.getCount()));


    //Looping Through All Rows And Adding To The List
    if (cursor.moveToFirst()) {
        do {
            Bowler bowler = new Bowler();
            bowler.setId(cursor.getInt(cursor.getColumnIndex(Bowler.COLUMN_ID)));
            bowler.setLeagueId(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_LEAGUE_ID)));
            bowler.setName(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_NAME)));
            bowler.setAverage(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_BOWLER_AVERAGE)));
            bowler.setHandicap(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_BOWLER_HANDICAP)));
            bowler.setTimestamp(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_TIMESTAMP)));
            bowlers.add(bowler);
        } while (cursor.moveToNext());
    }
    cursor.close();
    //Close Database Connection
    db.close();
    Log.d("GETALLBOWLERS-CNT","Number of elements in bowlerslist = " + String.valueOf(bowlers.size()));

    //Return Bowlers List
    return bowlers;
}

public int getBowlersCount() {
    String countQuery = "SELECT  * FROM " + Bowler.TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);

    int count = cursor.getCount();
    cursor.close();

    //Return The Count
    return count;
}

public int updateBowler(Bowler bowler) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(Bowler.COLUMN_LEAGUE_ID, bowler.getLeagueId());
    values.put(Bowler.COLUMN_NAME, bowler.getName());
    values.put(Bowler.COLUMN_BOWLER_AVERAGE, bowler.getAverage());

    //Updating Row
    return db.update(Bowler.TABLE_NAME, values, Bowler.COLUMN_ID + " = ?",
            new String[]{String.valueOf(bowler.getId())});
}

public void deleteBowler(Bowler bowler) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete( Bowler.TABLE_NAME, Bowler.COLUMN_ID + " = ?",
            new String[]{String.valueOf( bowler.getId())});
    db.close();
}

I am hoping that someone will be able to point out what I am doing incorrectly in order to fix this issue. 我希望有人能够指出我在做什么,以解决此问题。

If any additional information is need please let me know and I will post it. 如果需要任何其他信息,请告诉我,我将其发布。

在此处输入图片说明 在此处输入图片说明

I have figured out why all my new bowler entries have an id of 2 . 我已经弄清楚了为什么所有新的常礼帽条目的ID都是2 In my edit Bowler Profile Activity I have the following : leagueId = String.valueOf(getIntent().getIntExtra("leagueId",2)); 在我的Bowler Profile Activity编辑中,我具有以下内容: leagueId = String.valueOf(getIntent().getIntExtra("leagueId",2)); The default value is 2 and because I was not grabbing the information being passed to the new Activity in the proper manner the app was always using 2 as the BowlerId. 默认值为2,并且因为我没有以正确的方式获取传递给新Activity的信息,所以应用程序始终使用2作为BowlerId。

I changed the code that was capturing the information from the intent to the following: 我将捕获信息的代码从意图更改为以下代码:

Intent intent = getIntent();
        leagueId = intent.getStringExtra("leagueId");

With this change I was able to capture all the bowlers that belong to a particular league. 通过此更改,我得以捕获属于某个特定联赛的所有保龄球员。 I only realized that I was passing the information incorrectly after reading through the following post: 在阅读了以下文章之后,我才意识到我错误地传递了信息:

Pass a String from one Activity to another Activity in Android 将字符串从一个活动传递到Android中的另一个活动

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM