码迷,mamicode.com
首页 > 移动开发 > 详细

android查看新闻简单案例

时间:2015-07-28 12:34:36      阅读:441      评论:0      收藏:0      [点我收藏+]

标签:

 

AndroidMainfest.xml

技术分享
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mytest.news"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".NewsDetailActivity" >
        </activity>
    </application>

    <uses-permission android:name="android.permission.INTERNET" />

</manifest>
View Code

 

新闻列表布局activiti_main.xml

技术分享
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ListView
        android:id="@+id/listview_news"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="" />

</LinearLayout>
View Code

新闻item布局news_item.xml

技术分享
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/news_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>
View Code

新闻详细布news_detail.xml

技术分享
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
View Code

 

mainActivity.java加载新闻列表

技术分享
package com.mytest.news;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

    private static final String LOG_TAG = "MainActivity";

    private ListView newsListView;
    private List<News> newsList = new ArrayList<News>();
    private NewsAdapter adapter;
    // private final String HTTP_URL_NEWSLIST =
    // "http://api.1-blog.com/biz/bizserver/news/list.do";
    //
//    private final String HTTP_URL_NEWSLIST = "http://192.168.23.1:8080/testapp/newsjsondata.txt";
    private final String HTTP_URL_NEWSLIST = "http://api.1-blog.com/biz/bizserver/news/list.do";

    private Handler handler = new Handler() {

        public void handleMessage(android.os.Message msg) {

            String newsJsonData = (String) msg.obj;
//            Log.v("MainActivity", "newsJsonData.length:" + newsJsonData.length());
            
            //注意,必须把newsList当作参数传入进去,直接往newsList对象中添加,不能再重新创建list对象。否则执行notifyDataSetChanged,不会执行getView更新页面。
            NewsUtil.getNewsListByJsonData(newsJsonData,newsList);
            

            if (newsList != null) {
                Log.v("MainActivity", "newsList.length:" + newsList.size());
            }else{
                Log.v("MainActivity", "newsList is null" );
            }
            
            adapter.notifyDataSetChanged();
        };
    };

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

        newsListView = (ListView) findViewById(R.id.listview_news);

        adapter = new NewsAdapter(this, newsList);
        newsListView.setAdapter(adapter);
        
        newsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                News news = newsList.get(position);
                Intent intent = new Intent(MainActivity.this, NewsDetailActivity.class);
                intent.putExtra("content_url", news.getArticle_url());
                startActivity(intent);
            }
            
        });
        
        getNewsJsonData();
        

    }

    private void getNewsJsonData() {
        new Thread() {
            @Override
            public void run() {
                String newsJson = NewsUtil.getNewsJsonFromNet(HTTP_URL_NEWSLIST);
                if (newsJson != null && !"".equals(newsJson)) {
                    Message message = handler.obtainMessage(0);
                    message.obj = newsJson;
                    handler.sendMessage(message);
                }
            }
        }.start();

    }

}
View Code

 

NewsUtil.java

技术分享
package com.mytest.news;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpClientConnection;
import org.apache.http.HttpConnection;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import android.util.Log;

public class NewsUtil {

    private static final String LOG_TAG = "NewsUtil";

    public static String getNewsJsonFromNet(String httpurl) {
        StringBuffer newsJson = new StringBuffer();

        try {

            HttpURLConnection conn = (HttpURLConnection) new URL(httpurl).openConnection();
            InputStream is = conn.getInputStream();
            BufferedReader bufReader = new BufferedReader(new InputStreamReader(is));
            String line = "";
            while ((line = bufReader.readLine()) != null) {
                newsJson.append(line);
            }

            bufReader.close();
            is.close();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return newsJson.toString();
    }

    public static List<News> getNewsListByJsonData(String newsJsonData,List<News> newsList) {

        Log.v(LOG_TAG, "getNewsListByJsonData");

        try {

            /**
             * JSONTokener jt = new JSONTokener(newsJsonData);
             * 
             * JSONObject obj = (JSONObject)jt.nextValue(); String title =
             * obj.getString("title"); String source = obj.getString("source");
             * String articleurl = obj.getString("article_url"); News news = new
             * News(title,source,articleurl); Log.v(LOG_TAG, news.toString());
             * 
             * newsList.add(news);
             */

            JSONObject jsonobj = new JSONObject(newsJsonData);
            String status = jsonobj.getString("status");
            JSONArray arr = jsonobj.getJSONArray("detail");
            for (int i = 0; i < arr.length(); i++) {
                JSONObject obj = arr.getJSONObject(i);
                String title = obj.getString("title");
                String source = obj.getString("source");
                String articleurl = obj.getString("article_url");
                News news = new News(title, source, articleurl);
//                Log.v(LOG_TAG, news.toString());
                newsList.add(news);
            }

        } catch (JSONException e) {
            Log.v(LOG_TAG, e.getMessage());
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return newsList;
    }
}
View Code

 

NewsAdapter.java

技术分享
package com.mytest.news;

import java.util.List;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class NewsAdapter extends BaseAdapter {

    private Context context;
    private List<News> newsList;

    public NewsAdapter(Context context, List<News> newsList) {
        this.context = context;
        this.newsList = newsList;
    }

    @Override
    public int getCount() {
        return newsList.size();
    }

    @Override
    public Object getItem(int position) {
        return newsList.get(position)
;    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView tvTitle =null;
        if(convertView==null){
            convertView = LayoutInflater.from(context).inflate(R.layout.news_item, null);

            tvTitle = (TextView) convertView.findViewById(R.id.news_title);
        }
        
        
        Log.v("getView", "title--->"+newsList.get(position).getTitle());
        tvTitle.setText(newsList.get(position).getTitle());

        return convertView;
    }

}
View Code

 

News.java

技术分享
package com.mytest.news;

public class News {

    private String title;
    private String article_url;
    private String source;
    
    
    public News(){
        
    }
    
    public News(String title, String source, String article_url) {
        this.title = title;
        this.source = source;
        this.article_url = article_url;
    }
    
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getArticle_url() {
        return article_url;
    }
    public void setArticle_url(String article_url) {
        this.article_url = article_url;
    }
    public String getSource() {
        return source;
    }
    public void setSource(String source) {
        this.source = source;
    }
    
    
    @Override
    public String toString() {
        return "[title:‘"+title+"‘,source:‘"+source+"‘,article_url:‘"+article_url+"‘]";
    }
    
    
    
}
View Code

 

NewsDetailActivity.java

技术分享
package com.mytest.news;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;

public class NewsDetailActivity extends Activity {

    private WebView webView;

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

        webView = (WebView) findViewById(R.id.webView);

        String content_url = getIntent().getStringExtra("content_url");
        Log.v("NewsDetail", "pic_url" + content_url);
        // webView.loadUrl("http://www.baidu.com");
        webView.loadUrl(content_url);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

    }

}
View Code

 

android查看新闻简单案例

标签:

原文地址:http://www.cnblogs.com/2015android/p/4682180.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!