1

我正在尝试显示在应用程序本身中创建的数据库活动的值。这些值最初是从 XML 文件中解析出来的,然后存储到数据库中。我已经进行了大量搜索并尝试了几种解决方案,但我似乎陷入了困境。如果有人可以帮助我,那就太好了!

Q,(I)一旦从 ListView 中选择了一个项目,这些值必须显示在 TextView 中。为此,我在 ListView Activity(ListRSSItemsActivity) 中设置了一个 onItemClickListener 和启动新活动的意图,并创建了相应的布局文件。我或多或少熟悉如何让 TextView 工作。但是,我不确定现在要在 New Activity(ArticleActivity) 文件中添加什么。(II) 当我点击该项目并打开新窗口时,它显示一个空白屏幕。

我已经附加了新的活动类和布局文件。

文章活动:

    public class ArticleActivity extends Activity{


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.article_view);

        String title, description;

        title=this.getIntent().getStringExtra("TAG_TITLE");
        description=this.getIntent().getStringExtra("TAG_DESCRIPTION");     
}
}

article_view.xml:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- Article Title -->
    <TextView android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="10dp"
        android:paddingBottom="8dp"
        android:textSize="18sp"
        android:textStyle="bold"
        android:textColor="#dc6800"/>

    <!-- Article Content -->
    <TextView android:id="@+id/description"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textColor="#acacac"
        android:layout_below="@id/title"/>
</RelativeLayout>

ListRSSItems活动:

public class ListRSSItemsActivity extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Array list for list view
    ArrayList<HashMap<String, String>> rssItemList = new ArrayList<HashMap<String,String>>();

    RSSParser rssParser = new RSSParser();

    List<RSSItem> rssItems = new ArrayList<RSSItem>();

    RSSFeed rssFeed;

    public static String TAG_TITLE = "title";
    private static String TAG_LINK = "link";
    private static String TAG_DESCRIPTION = "description";
    private static String TAG_PUBDATE = "pub_date";
    private static String TAG_GUID = "guid"; // not used

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//        setContentView(R.layout.rss_item_list);

        // get intent data
        Intent i = getIntent();

        // SQLite Row id
        Integer site_id = Integer.parseInt(i.getStringExtra("id"));

        // Getting Single website from SQLite
        RSSDatabaseHandler rssDB = new RSSDatabaseHandler(getApplicationContext());


        WebSite site = rssDB.getSite(site_id);
        String rss_link = site.getRSSLink();

        /**
         * Calling a backgroung thread will loads recent articles of a website
         * @param rss url of website
         * */
        new loadRSSFeedItems().execute(rss_link);

        // selecting single ListView item
        ListView lv = getListView();

        // Launching new screen on Selecting Single ListItem
        lv.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                // getting listview
                View v = (View)view.getParent(); 
                TextView tv = (TextView)v.findViewById(R.id.title);
                String title = tv.getText().toString();
                String description = ((TextView) view.findViewById(R.id.link)).getText().toString();

                // Starting new intent
                Intent ia = new Intent(getApplicationContext(), ArticleActivity.class);
                ia.putExtra("TAG_TITLE", title);
                ia.putExtra("TAG_DESCRIPTION", description);
                startActivity(ia);              
            }
        });
    }

    /**
     * Background Async Task to get RSS Feed Items data from URL
     * */
    class loadRSSFeedItems extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(
                    ListRSSItemsActivity.this);
            pDialog.setMessage("Loading recent articles...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting all recent articles and showing them in listview
         * */
        @Override
        protected String doInBackground(String... args) {
            // rss link url
            String rss_url = args[0];

            // list of rss items
            // using GET method to obtain rssfeeditems. NOTICE: only from RSS_URL here!
            rssItems = rssParser.getRSSFeedItems(rss_url);

            // looping through each item
            for(RSSItem item : rssItems){
                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_TITLE, item.getTitle());
                map.put(TAG_LINK, item.getLink());
                map.put(TAG_PUBDATE, item.getPubDate());

                String description = item.getDescription();
                // taking only 200 chars from description
                if(description.length() > 100){
                    description = description.substring(0, 97) + "..";
                }
                map.put(TAG_DESCRIPTION, description);


                // adding HashList to ArrayList
                rssItemList.add(map);
            }

            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed items into listview
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            ListRSSItemsActivity.this,
                            rssItemList, R.layout.rss_item_list_row,
                            new String[] { TAG_LINK, TAG_TITLE, TAG_PUBDATE, TAG_DESCRIPTION },
                            new int[] { R.id.page_url, R.id.title, R.id.pub_date, R.id.link });

                    // updating listview
                    setListAdapter(adapter);
                }
            });
            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String args) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
        }
    }
}

数据库活动:

    public class RSSDatabaseHandler extends SQLiteOpenHelper{

    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "rssReader";

    // Contacts table name
    private static final String TABLE_RSS = "websites";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_TITLE = "title";
    private static final String KEY_LINK = "link";
    private static final String KEY_RSS_LINK = "rss_link";
    private static final String KEY_DESCRIPTION = "description";
    private static final String KEY_PUBDATE = "pub_date";

    public RSSDatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_RSS_TABLE = "CREATE TABLE " + TABLE_RSS + "(" + KEY_ID
                + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT," + KEY_LINK
                + " TEXT," + KEY_RSS_LINK + " TEXT," + KEY_DESCRIPTION
                + " TEXT," + KEY_PUBDATE + " TEXT" + ")";
        db.execSQL(CREATE_RSS_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_RSS);

        // Create tables again
        onCreate(db);
    }

    /**
     * Adding a new website in websites table Function will check if a site
     * already existed in database. If existed will update the old one else
     * creates a new row
     * */
    public void addSite(WebSite site) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_TITLE, site.getTitle()); // site title
        values.put(KEY_LINK, site.getLink()); // site url
        values.put(KEY_RSS_LINK, site.getRSSLink()); // rss link url
        values.put(KEY_DESCRIPTION, site.getDescription()); // site description
        values.put(KEY_PUBDATE, site.getPubDate());

        // Check if row already existed in database
        if (!isSiteExists(db, site.getRSSLink())) {
            // site not existed, create a new row
            db.insert(TABLE_RSS, null, values);
            db.close();
        } else {
            // site already existed update the row
            updateSite(site);
            db.close();
        }
    }

    /**
     * Reading all rows from database
     * */
    public List<WebSite> getAllSites() {
        List<WebSite> siteList = new ArrayList<WebSite>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_RSS
                + " ORDER BY id DESC";

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

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                WebSite site = new WebSite();
                site.setId(Integer.parseInt(cursor.getString(0)));
                site.setTitle(cursor.getString(1));
                site.setLink(cursor.getString(2));
                site.setRSSLink(cursor.getString(3));
                site.setDescription(cursor.getString(4));
                site.setPubDate(cursor.getString(5));
                // Adding contact to list
                siteList.add(site);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();

        // return contact list
        return siteList;
    }

    /**
     * Updating a single row row will be identified by rss link
     * */
    public int updateSite(WebSite site) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_TITLE, site.getTitle());
        values.put(KEY_LINK, site.getLink());
        values.put(KEY_RSS_LINK, site.getRSSLink());
        values.put(KEY_DESCRIPTION, site.getDescription());
        values.put(KEY_PUBDATE, site.getPubDate());

        // updating row return
        int update = db.update(TABLE_RSS, values, KEY_RSS_LINK + " = ?",
                new String[] { String.valueOf(site.getRSSLink()) });
        db.close();
        return update;

    }

    /**
     * Reading a row (website) row is identified by row id
     * */
    // Declaring 
    public WebSite getSite(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_RSS, new String[] { KEY_ID, KEY_TITLE,
                KEY_LINK, KEY_RSS_LINK, KEY_DESCRIPTION, KEY_PUBDATE }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        WebSite site = new WebSite(cursor.getString(1), cursor.getString(2),
                cursor.getString(3), cursor.getString(4), cursor.getString(5));

        site.setId(Integer.parseInt(cursor.getString(0)));
        site.setTitle(cursor.getString(1));
        site.setLink(cursor.getString(2));
        site.setRSSLink(cursor.getString(3));
        site.setDescription(cursor.getString(4));
        site.setPubDate(cursor.getString(5));
        cursor.close();
        db.close();
        return site;
    }

    /**
     * Deleting single row
     * */
    public void deleteSite(WebSite site) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_RSS, KEY_ID + " = ?",
                new String[] { String.valueOf(site.getId())});
        db.close();
    }

    /**
     * Checking whether a site is already existed check is done by matching rss
     * link
     * */
    public boolean isSiteExists(SQLiteDatabase db, String rss_link) {

        Cursor cursor = db.rawQuery("SELECT 1 FROM " + TABLE_RSS
                + " WHERE rss_link = '" + rss_link + "'", new String[] {});
        boolean exists = (cursor.getCount() > 0);
        return exists;
    }
}
4

2 回答 2

0

删除这些行:

  ia.putExtra("TAG_TITLE", "title");
  ia.putExtra("TAG_DESCRIPTION", "description");

并替换为以下内容:

  ia.putExtra("TAG_TITLE", title);
  ia.putExtra("TAG_DESCRIPTION", description);

更改 ArticleActivity 中的代码:

删除以下代码:

 Bundle extras = getIntent().getExtras();
        if (extras != null) {
            String value = extras.getString(TAG_TITLE, "title");

替换为以下代码:

String title,description;
TextView txtTitle,txtDesc;

txtTitle=(TextView)findViewById(R.id.title);
txtDesc=(TextView)findViewById(R.id.description);

    title=this.getIntent().getStringExtra("TAG_TITLE");
    description=this.getIntent().getStringExtra("TAG_DESCRIPTON");

     txtTitle.setText(title);
     txtDesc.setText(description);
            }

并根据您的需要在您尊重的 TextView 或其他任何地方设置这些值。

于 2013-09-25T12:39:33.463 回答
0


尝试以下
创建一个共享首选项
将适当的数据放在列表项中的共享首选项中选择侦听
器在活动的oncreate中(您希望在其中显示数据),从共享首选项中读取数据并按照你想。

于 2013-09-25T13:22:19.577 回答