0

我正在关注关于 RSS 阅读器的在线移动教程,在我完成完整教程之前,它被删除了。我已经等了一段时间了(它还没有回来!),我试图自己完成代码。就我自己而言,我已经能够让我的应用程序解析数据并显示到 ListView 中。我需要一些帮助,以便在单击任何项​​目后,它会打开一个 WebView 并显示与附加到该项目的 URL 关联的内容。有人可以告诉我我在这里错过了什么和做错了吗?我一直在尽力填补空白,但我从 ListView 中单击的项目仍然没有任何作用。

主要活动

public class MainActivity extends Activity implements OnItemClickListener {

ListView feedListView;
List<FeedStructure> rssStr;
private FeedListAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    feedListView = (ListView) findViewById(R.id.list);
    feedListView.setVerticalFadingEdgeEnabled(true);
    RssFeedTask rssTask = new RssFeedTask();
    rssTask.execute();
}

//setup asynctask
private class RssFeedTask extends AsyncTask<String, Void, String> {

    private ProgressDialog Dialog;
    String response = "";

    @Override
    protected void onPreExecute() {
        Dialog = new ProgressDialog(MainActivity.this);
        Dialog.setMessage("Loading...");
        Dialog.show();
    }

    @Override 
    protected String doInBackground(String... urls) {
        try {
            String feed = "http://feeds.feedburner.com/drxeno/home";
            XMLHandler rh = new XMLHandler();
            rssStr = rh.getLatestArticles(feed);
        } catch (Exception e) {
        }   
        return response;        
    }

    @Override
    protected void onPostExecute(String result) {
        if (rssStr != null) {
            adapter = new FeedListAdapter(MainActivity.this, rssStr);
            feedListView.setAdapter(adapter);
        }
        Dialog.dismiss();
    }   
}

//@Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {

    ListView lv = (ListView) findViewById(R.id.list);
    adapter = new FeedListAdapter(this, rssStr);
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(this);


    Intent intent = new Intent(MainActivity.this, WebviewActivity.class);
    new Bundle();
    intent.putExtra("b", rssStr.get(pos).getLink());

    //get the selected item and do the further process  
    lv.getItemAtPosition(pos);
    ((FeedStructure) lv.getItemAtPosition(pos)).getLink();
    }   
}

饲料结构

public class FeedStructure {

private String title;
private String pubDate;
private String imgLink;
private String creator;
private String link;
private long item;

//@param item set item
public void setItem(long item) {
    this.item = item;
}

//@return item
public long getItem() {
    return item;
}

//@param title set title
public void setTitle(String title) {
    this.title = title;
}

//@return title
public String getTitle() {
    return title;
}

//truncate title
public String toString() {
    if (title.length() > 10) {
        return title.substring(0, 10) + "...";
    }
    return title;
}

//@param pubDate set pubDate
public void setPubDate(String pubDate) {
    this.pubDate = pubDate;
}

//@return pubDate
public String getPubDate() {
    return pubDate;
}

//@param imgLink set imgLink
public void setImgLink(String imgLink) {
    this.imgLink = imgLink;
}

//@return imgLink
public String getImgLink() {
    return imgLink;
}

//@param creator set creator
public void setCreator(String creator) {
    this.creator = creator;
}

//@return creator
public String getCreator() {
    return creator;
}   

//@param creator set URL
public void setLink(String link) {
    this.link = link;
}

//@return URL
public String getLink() {
    return link;
}

}

处理程序

public class XMLHandler extends DefaultHandler {

private FeedStructure feedStr = new FeedStructure();
private List<FeedStructure> rssList = new ArrayList<FeedStructure>();

private int acticlesAdded = 0;

private static final int ARTICLES_LIMIT = 50;
StringBuilder chars = new StringBuilder();

public void startElement(String uri, String localName, String qName, Attributes atts) 
        throws SAXException {

    // TODO Auto-generated method stub
    super.startElement(uri, localName, qName, atts);
    chars = new StringBuilder();
}

public void endElement(String uri, String localName, String qName) throws SAXException {
    // TODO Auto-generated method stub
    super.endElement(uri, localName, qName);

    if (localName.equalsIgnoreCase("title")) {
        feedStr.setTitle(chars.toString());
    }
    else if (localName.equalsIgnoreCase("pubDate")) {
        feedStr.setPubDate(chars.toString());
    }       
    else if (localName.equalsIgnoreCase("creator")) {
        feedStr.setCreator(chars.toString());
    }
    else if (localName.equalsIgnoreCase("link")) {
        feedStr.setLink(chars.toString());
    }
    if (localName.equalsIgnoreCase("item")) {
        rssList.add(feedStr);

        feedStr = new FeedStructure();
        acticlesAdded++;
        if (acticlesAdded >= ARTICLES_LIMIT) {
            throw new SAXException();
        }
    }
}

public void characters(char ch[], int start, int length) {
    chars.append(new String(ch, start, length));
}

public List<FeedStructure> getLatestArticles(String feedUrl) {
    URL url = null;
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        url = new URL(feedUrl);
        xr.setContentHandler(this);
        xr.parse(new InputSource(url.openStream()));
    } catch (IOException e) { Log.d(TAG, "IOException");
    } catch (SAXException e) { Log.d(TAG, "SAXException");
    } catch (ParserConfigurationException e) { 
    }   
    return rssList; 
}

}

适配器

public class FeedListAdapter extends ArrayAdapter<FeedStructure> {

List<FeedStructure> metaData = null;
public FeedListAdapter(Activity activity, List<FeedStructure> metaDataParse) {
    super(activity, 0, metaDataParse);
    metaData = metaDataParse;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    Activity activity = (Activity) getContext();
    LayoutInflater inflater = activity.getLayoutInflater();

    View rowView = inflater.inflate(R.layout.activity_main_format, null);
    TextView titleTextView = (TextView) rowView.findViewById(R.id.title_format);
    TextView creatorTextView = (TextView) rowView.findViewById(R.id.creator_format);
    TextView dateTextView = (TextView) rowView.findViewById(R.id.date_format);
    ImageView imageView = (ImageView) rowView.findViewById(R.id.image_format);
        try {
            titleTextView.setText(metaData.get(position).getTitle());
            creatorTextView.setText("Creator: " + metaData.get(position).getCreator());

            //reformat current date into another format
            if (metaData.get(position).getPubDate() != null) {
                String pubDate = metaData.get(position).getPubDate();

                SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy", Locale.ENGLISH);

                try {
                    Date pDate = df.parse(pubDate);
                    dateTextView.setText("Published: " + df.format(pDate));
                } catch (ParseException e) {

                }
            }

            //pull in ImgLink, if there is no image use static image
            if (metaData.get(position).getImgLink() != null) {
                URL feedImage = new URL (metaData.get(position).getImgLink().toString());
                                    if (!feedImage.toString().equalsIgnoreCase("null")) {
                    HttpURLConnection conn = (HttpURLConnection)feedImage.openConnection();
                    InputStream is = conn.getInputStream();
                    Bitmap img = BitmapFactory.decodeStream(is);
                    imageView.setImageBitmap(img);
                } else {
                    imageView.setBackgroundResource(R.drawable.img2);
                }
            }

        } catch (MalformedURLException e) { 
        } catch (IOException e) { 
        }
        return rowView;
    }

}

网络视图活动

public class WebviewActivity extends Activity {
private WebView webview;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);

    this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
    getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);  

    Bundle b = getIntent().getExtras();
    String KEY_LINK = b.getString("link");

    WebView myWebView = (WebView) findViewById(R.id.webview);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    webview.setWebViewClient(new MyWebViewClient(this));
    webview.getSettings().setAppCacheEnabled(false);
    webview.getSettings().setBuiltInZoomControls(true); 

    webview.getSettings().setDisplayZoomControls(true); 
    webview.getSettings().setAllowContentAccess(true); 
    webview.getSettings().setSupportZoom(true);

    webview.setInitialScale(1);
    webview.loadUrl(KEY_LINK);

    final Activity MyActivity = this;

    myWebView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress)
        {
            MyActivity.setTitle("Loading test...");
            MyActivity.setProgress(progress * 100); 
            if (progress == 100) {
                MyActivity.setTitle(R.string.app_name);
            }   
        }
    });

}

}

WebViewClient

public class MyWebViewClient extends WebViewClient {

public MyWebViewClient(WebviewActivity webviewActivity) {
    // TODO Auto-generated constructor stub
}

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) { 
    if (Uri.parse(url).getHost().equals("www.ljtatum.blog.com")) {

        return false;
    }

    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    return true;
}

}

几个星期以来,我一直在努力填补空白,并多次联系作者。希望您能帮帮我,谢谢!

4

4 回答 4

0

快速浏览说您需要将一些代码从您的 OnClickMethod 移动到您的 onCreate()。

例子:

// Find the ListView from the XML
list = (ListView)view.findViewById(R.id.faq_list);
// Set the vertical edges to fade
list.setVerticalFadingEdgeEnabled(true);

// Create a new adapter
adapter = new FeedListAdapter(this, feed);
// Set the adapter to the list
list.setAdapter(adapter);

// Set on item click listener to the ListView
list.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // Do your onClick
    }
});

这就是我编写 RSS 内容的方式,仅在 onCreate 中进行,而您将其拆分到 Async 中,这不是最好的方法(并且可能会使跟踪错误变得更加困难)。

尝试使用上面的代码,看看它是否对您有帮助,任何问题都可以发表评论。:)

编辑:

通常要走的路是让您的 AsyncTask 返回您解析的提要并在您的 onCreate 中执行feed = new AsyncTask(params);,然后按照我上面发布的代码进行操作。

这应该可行,因为我现在正在查看我的一个 RSS 项目:p

于 2013-08-03T14:59:53.590 回答
0

尝试 :

  public class MainActivity extends ListActivity implements OnItemClickListener{...} 

希望它有效。

于 2013-10-06T12:52:22.617 回答
0

我想出了自己问题的答案。有两个缺失的部分。需要下面的一块startActivity(intent)。没有这一行,即使有正确的点击事件代码,WebviewActivity也无法启动。

//@Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {

ListView lv = (ListView) findViewById(R.id.list);
adapter = new FeedListAdapter(this, rssStr);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);


Intent intent = new Intent(MainActivity.this, WebviewActivity.class);
new Bundle();
intent.putExtra("b", rssStr.get(pos).getLink());

//get the selected item and do the further process  
lv.getItemAtPosition(pos);
((FeedStructure) lv.getItemAtPosition(pos)).getLink();
startActivity(intent);
}   

}

正如“Chor WaiChun”所说,我还需要添加feedListView.setOnItemClickListener(this);

感谢大家的帮助!

于 2013-08-04T20:01:15.227 回答
0

试着把它放在你的主要活动中:

feedListView = (ListView) findViewById(R.id.list);
feedListView.setVerticalFadingEdgeEnabled(true);
// Add this line
feedListView.setOnItemClickListener(this);
于 2013-08-03T14:52:50.447 回答