SQLite数据库不填充listview

时间:2016-12-19 00:59:44

标签: java android sqlite android-sqlite

我有一个新闻阅读器应用程序,如果你想稍后阅读它们,它有一个数据库来保存故事,但是我无法在savedStoriesActivity上显示这些故事。这是DB类:

public class newsReaderDB {
    RSSItem insertRSSItem = new RSSItem();
    // database constants
    public static final String DB_NAME = "newsReader.db";
    public static final int DB_VERSION = 1;

    //table constants
    public static final String newsReader_TABLE = "savedStories";

    public static final String storyID = "_id";
    public static final int storyID_COL = 0;

    public static final String storyName = "storyName";
    public static final int storyName_COL = 2;

    public static final String storyDescription = "Description";
    public static final int storyDescription_COL = 3;

    public static final String storyLink = "storyLink";
    public static final int storyLink_COL = 4;

    public static final String storySource = "storySource";
    public static final int storySource_COL = 5;

    public static final String CREATE_newsReader_TABLE =
            "CREATE TABLE " + newsReader_TABLE + " (" +
                    storyID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    storyName + " INTEGER, " +
                    storyDescription + " TEXT, " +
                    storyLink + " TEXT, " +
                    storySource + " TEXT);";

    public static final String DROP_newReader_TABLE =
            "DROP TABLE IF EXISTS " + newsReader_TABLE;


    private static class DBHelper extends SQLiteOpenHelper {

        public DBHelper(Context context, String name,
                        CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // create tables
            db.execSQL(CREATE_newsReader_TABLE);
        }
        @Override
        public void onUpgrade(SQLiteDatabase db,
                              int oldVersion, int newVersion) {

            Log.d("Task list", "Upgrading db from version "
                    + oldVersion + " to " + newVersion);

            db.execSQL(newsReaderDB.DROP_newReader_TABLE);
            onCreate(db);
        }
    }
    // database and database helper objects
    private SQLiteDatabase db;
    private DBHelper dbHelper;

    public newsReaderDB(Context context) {
        dbHelper = new DBHelper(context, DB_NAME, null, DB_VERSION);
    }
    private void openReadableDB() {
        db = dbHelper.getReadableDatabase();
    }

    private void openWriteableDB() {
        db = dbHelper.getWritableDatabase();
    }

    private void closeDB() {
        if (db != null)
            db.close();
    }

    public ArrayList<RSSItem> getLists() {
        ArrayList<RSSItem> lists = new ArrayList<RSSItem>();
        openReadableDB();
        Cursor cursor = db.query(newsReader_TABLE,
                null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            RSSItem list = new RSSItem();
            list.setId(Integer.parseInt(cursor.getString(storyID_COL)));
            list.setTitle(cursor.getString(storyName_COL));
            list.setDescription(cursor.getString(storyDescription_COL));
            list.setLink(cursor.getString(storyLink_COL));
            list.setSource(cursor.getString(storySource_COL));

            lists.add(list);
        }
        if (cursor != null)
            cursor.close();
        closeDB();

        return lists;
    }

    public RSSItem getList(String name) {
        String where = storyName + "= ?";
        String[] whereArgs = { name };

        openReadableDB();
        Cursor cursor = db.query(newsReader_TABLE, null,
                where, whereArgs, null, null, null);
        RSSItem list = null;
        cursor.moveToFirst();
        list = new RSSItem();

        list.setId(cursor.getInt(storyID_COL));
        list.setTitle(cursor.getString(storyName_COL));
        list.setDescription(cursor.getString(storyDescription_COL));
        list.setLink(cursor.getString(storyLink_COL));
        list.setSource(cursor.getString(storySource_COL));
        if (cursor != null)
            cursor.close();
        this.closeDB();

        return list;
    }

    public ArrayList<RSSItem> getStories(String storyName) {

        String where =
                storyID + " = ?";
        int listID = getList(storyName).getId();
        String[] whereArgs = { Integer.toString(listID) };

        this.openReadableDB();
        Cursor cursor = db.query(newsReader_TABLE, null,
                where, whereArgs,
                null, null, null);
        ArrayList<RSSItem> tasks = new ArrayList<RSSItem>();
        while (cursor.moveToNext()) {
            tasks.add(getStoryFromCursor(cursor));
        }
        if (cursor != null)
            cursor.close();
        this.closeDB();

        return tasks;
    }


    private static RSSItem getStoryFromCursor(Cursor cursor) {
        if (cursor == null || cursor.getCount() == 0){
            return null;
        }
        else {
            try {
                RSSItem story = new RSSItem();
                story.setTitle(cursor.getString(storyName_COL));
                story.setSource(cursor.getString(storySource_COL));
                story.setDescription(cursor.getString(storyDescription_COL));
                story.setLink(cursor.getString(storyLink_COL));

                return story;
            }
            catch(Exception e) {
                return null;
            }
        }
    }

    public long insertStory(RSSItem story) {
        ContentValues cv = new ContentValues();
        cv.put(storyName, story.getTitle());
        cv.put(storyDescription, story.getDescription());
        cv.put(storyLink, story.getLink());
        cv.put(storySource, story.getSource());

        this.openWriteableDB();
        long rowID = db.insert(newsReader_TABLE, null, cv);
        this.closeDB();

        return rowID;
    }



    public int deleteStory(long id) {
        String where = storyID+ "= ?";
        String[] whereArgs = { String.valueOf(id) };

        this.openWriteableDB();
        int rowCount = db.delete(newsReader_TABLE, where, whereArgs);
        this.closeDB();

        return rowCount;
    }
}

这是我的savedStoryActivity:

public class savedStoryList extends AppCompatActivity {

    SharedPreferences sharedpreferences;
    private static final String pref_file = "pref_file";
    private RSSItem feed;
    private ArrayList<RSSItem> feeds;
    private FileIO io;
    private ListView listViewNews;
    private HashMap items;
    newsReaderDB db = new newsReaderDB(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_saved_story_list);


        listViewNews = (ListView) findViewById(R.id.listViewNews);

        io = new FileIO(getApplicationContext());

       listViewNews.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                items = (HashMap) listViewNews.getItemAtPosition(position);


                //Date parsing
                Date date = new Date();
                DateFormat outputFormat = new SimpleDateFormat("yyyy.MM.dd (HH:mm)");
                DateFormat inputFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");

                String inputText = feed.getPubDate();

                try {
                    date = inputFormat.parse(inputText);
                } catch (Exception e) {
                    Log.d("Date Parser", e.getMessage());
                }
                String dateOutput = outputFormat.format(date);

                Intent intent = new Intent(view.getContext(), ItemActivity.class);

                intent.putExtra("source", items.get("source").toString());
                intent.putExtra("pubdate", dateOutput);
                intent.putExtra("title", feed.getTitle());
                intent.putExtra("description", feed.getDescription());
                intent.putExtra("link", feed.getLink());
                startActivity(intent);
            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_spillover_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_settings:
                startActivity(new Intent(getApplicationContext(), SettingsActivity.class));
                return true;
            case R.id.menu_about:
                startActivity(new Intent(getApplicationContext(), AboutActivity.class));
                return true;
            case R.id.menu_savedStories:
                startActivity(new Intent(getApplicationContext(),savedStoryList.class));
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }


    public void updateDisplay() {

        if (feeds == null) {
            Toast.makeText(getApplicationContext(), "Feed is null", Toast.LENGTH_SHORT).show();
        }

        ArrayList<HashMap<String, String>> data =
                new ArrayList<HashMap<String, String>>();

        for (int i = 0; i < feeds.size(); ++i) {
            feed = feeds.get(i);

            //Date parsing
            Date date = new Date();
            DateFormat outputFormat = new SimpleDateFormat("yyyy.MM.dd (HH:mm)");
            DateFormat inputFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");

            String inputText = feed.getPubDate();

            try {
                date = inputFormat.parse(inputText);
            } catch (Exception e) {
                Log.d("Date Parser", e.getMessage());
            }
            String dateOutput = outputFormat.format(date);

           for (RSSItem item :feeds) {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("source", item.getSource());
                map.put("date", dateOutput); //map.put("date", item.getPubDateFormatted());
                map.put("title", item.getTitle());
                data.add(map);
            }
        }

        // create the resource, from, and to variables
        int resource = R.layout.news_list;
        String[] from = {"source","date", "title"};
        int[] to = {R.id.lblSource, R.id.lblPubDate, R.id.lblHeadline};

        // create and set the adapter
        SimpleAdapter adapter =
                new SimpleAdapter(this, data, resource, from, to);
        listViewNews.setAdapter(adapter);

        Log.d("News reader", "Feed displayed");
    }
}

我以为我有它工作,但不确定什么是错的,我也没有错误。

1 个答案:

答案 0 :(得分:0)

顺便说一下,我正在修改你的班级命名是正确的 - 以大写字母开头。

您从未在活动代码中使用过数据库...

不清楚是否存在其他错误,但您应该在onCreate内初始化数据库,其中活动的上下文不为空。

public class SavedStoryListActivity extends AppCompatActivity {

    private ArrayList<RSSItem> feeds;
    private ListView listViewNews;
    private ArrayAdapter<RSSItem> adapter;

    private NewsReaderDB db; // Don't initialize yet

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_saved_story_list);

        db = new NewsReaderDB(this); // Initialize db here

        listViewNews = (ListView) findViewById(R.id.listViewNews);
        feeds = db.getLists();
        adapter = new ArrayAdapter<RSSItem>(this, android.R.simple_list_item_1, feeds);
        listViewNews.setAdapter(adapter);
    }
}

正如评论中所指出的那样,您必须在某个时候致电updateDisplay(),或者实际使用NewsReaderDB db.getLists()

您可能想尝试使用CursorAdapter的变体,这意味着将数据库值显示到ListView

相关问题