1

アプリケーション自体で作成されたデータベース アクティビティの値を表示しようとしています。値は最初に XML ファイルから解析され、DB に格納されました。私はかなりの量の検索を行い、解決策に到達するためのいくつかの方法を試しましたが、行き詰まっているようです. 誰かが私を助けてくれたら、それは素晴らしいことです!

Q, (I) ListView から項目を選択したら、値を TextView に表示する必要があります。これを行うために、ListView アクティビティ (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>

ListRSSItemsActivity:

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 に答える