1. 程式人生 > >Android學習歷程--新聞客戶端實現

Android學習歷程--新聞客戶端實現

要實現新聞客戶端就要知道什麼是json
1.json:
JSON:JavaScript 物件表示法(JavaScript Object Notation)。獨立於語言和平臺,比 XML 更小、更快,更易解析。如今JSON資料已經成為了網際網路中大多數資料的傳遞方式,所以必須要熟練掌握。
Android平臺自帶了JSON解析的相關API,可以將檔案、輸入流中的資料轉化為JSON物件,然後從物件中獲取JSON儲存的資料內容。

Android的JSON解析部分都在包org.json下,主要有以下幾個類:
JSONObject:可以看作是一個json物件,這是系統中有關JSON定義的基本單元,其包含一對兒(Key/Value)數值。它對外部(External:應用toString()方法輸出的數值)呼叫的響應體現為一個標準的字串(例如:{“JSON”: “Hello, World”},最外被大括號包裹,其中的Key和Value被冒號”:”分隔)。其對於內部(Internal)行為的操作格式略微,例如:初始化一個JSONObject例項,引用內部的put()方法新增數值:new JSONObject().put(“JSON”, “Hello, World!”),在Key和Value之間是以逗號”,”分隔。Value的型別包括:Boolean、JSONArray、JSONObject、Number、String或者預設值JSONObject.NULL object。

JSONStringer:json文字構建類 ,根據官方的解釋,這個類可以幫助快速和便捷的建立JSON text。其最大的優點在於可以減少由於 格式的錯誤導致程式異常,引用這個類可以自動嚴格按照JSON語法規則(syntax rules)建立JSON text。每個JSONStringer實體只能對應建立一個JSON text。。其最大的優點在於可以減少由於格式的錯誤導致程式異常,引用這個類可以自動嚴格按照JSON語法規則(syntax rules)建立JSON text。每個JSONStringer實體只能對應建立一個JSON text。

JSONArray:它代表一組有序的數值。將其轉換為String輸出(toString)所表現的形式是用方括號包裹,數值以逗號”,”分隔(例如:[value1,value2,value3],大家可以親自利用簡短的程式碼更加直觀的瞭解其格式)。這個類的內部同樣具有查詢行為,get()和opt()兩種方法都可以通過index索引返回指定的數值,put()方法用來新增或者替換數值。同樣這個類的value型別可以包括:Boolean、JSONArray、JSONObject、Number、String或者預設值JSONObject.NULL object。

JSONTokener:json解析類
JSONException:json中用到的異常

注意事項:
在執行Android應用程式前一定要啟動tomcat伺服器, 否則無法載入資料。
一定在清單檔案裡新增網路訪問允許,否則無法連線伺服器。
伺服器域名請求一定要寫伺服器的具體地址, 不能寫localhost,因為localhost是訪問的android本機伺服器。
注意json解析和xml和區別
主介面程式碼:

?xml version="1.0" encoding="utf-8"?>
<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" tools:context=".MainActivity" android:orientation="vertical">
<FrameLayout android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/loading" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" android:visibility="invisible"> <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="正在載入資訊..." /> </LinearLayout> <ListView android:id="@+id/lv_news" android:layout_width="match_parent" android:layout_height="match_parent" /> </FrameLayout> </LinearLayout>

listview 載入的自定義佈局:

<?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="65dp">
    <com.loopj.android.image.SmartImageView
        android:id="@+id/siv_icon"
        android:layout_width="80dp"
        android:layout_height="60dp"
        android:scaleType="centerCrop"
        android:src="@mipmap/ic_launcher"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"></com.loopj.android.image.SmartImageView>
    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="10dp"
        android:layout_toRightOf="@id/siv_icon"
        android:ellipsize="end"
        android:maxLength="20"
        android:singleLine="true"
        android:text="我是標題"
        android:textColor="#000000"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/tv_description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_title"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="5dp"
        android:layout_toRightOf="@id/siv_icon"
        android:ellipsize="end"
        android:maxLength="16"
        android:maxLines="1"
        android:text="我是描述"
        android:textColor="#99000000"
        android:textSize="14sp" />

    <TextView
        android:id="@+id/tv_type"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="5dp"
        android:layout_marginRight="10dp"
        android:text="評論"
        android:textColor="#99000000"
        android:textSize="12sp" />

</RelativeLayout>

json檔案的實體類

package cn.edu.bzu.mynews.entity;
public class NewsInfo {
    private String iconPath;
    private String title;
    private String description;
    private int type;
    private long comment;

    public String getIconPath() {
        return iconPath;
    }

    public void setIconPath(String iconPath) {
        this.iconPath = iconPath;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public long getComment() {
        return comment;
    }

    public void setComment(long comment) {
        this.comment = comment;
    }
}

解析類

package cn.edu.bzu.mynews.Tools;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;

import cn.edu.bzu.mynews.entity.NewsInfo;

public class JsonParse {
    public static List<NewsInfo> getNewInfo(String json){
        Gson gson=new Gson();
        Type listType=new TypeToken<List<NewsInfo>>(){

        }.getType();
        List<NewsInfo> newsInfos=gson.fromJson(json,listType);


       return newsInfos;
    }
}

adapter:

package cn.edu.bzu.mynews.adapter;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.loopj.android.image.SmartImageView;

import java.util.List;

import cn.edu.bzu.mynews.R;
import cn.edu.bzu.mynews.entity.NewsInfo;


public class NewAdapter extends ArrayAdapter<NewsInfo>{
private  int resourceID;
    public NewAdapter(Context context, int resource, List<NewsInfo> objects) {
        super(context, resource, objects);
        resourceID=resource;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        NewsInfo newsInfos=getItem(position);
        View view;
        ViewHolder viewHolder;
        if(convertView==null){
             view=LayoutInflater.from(getContext()).inflate(resourceID,null);
             viewHolder=new ViewHolder();
            viewHolder.siv=(SmartImageView)view.findViewById(R.id.siv_icon);
            viewHolder.tv_title=(TextView)view.findViewById(R.id.tv_title);
            viewHolder.tv_description=(TextView)view.findViewById(R.id.tv_description);
            viewHolder.tv_type=(TextView)view.findViewById(R.id.tv_type);
            view.setTag(viewHolder);

        }else{
            view=convertView;
            viewHolder= (ViewHolder) view.getTag();

        }
        viewHolder.siv.setImageUrl(fruit.getIconPath(),R.drawable.a,R.drawable.ic_launcher);
        viewHolder.tv_title.setText(fruit.getTitle());
        viewHolder.tv_description.setText(fruit.getDescription());
        int type=fruit.getType();
        switch (type){

            case 1:
                viewHolder.tv_type.setText("評論:"+fruit.getComment());
                viewHolder.tv_type.setTextColor(Color.BLUE);
                break;
            case 2:
                viewHolder.tv_type.setText("專題");
                viewHolder.tv_type.setTextColor(Color.BLACK);
                break;
            case 3:
                viewHolder.tv_type.setText("LIVE");
                viewHolder.tv_type.setTextColor(Color.RED);
                break;
        }

        return view;

    }
    class ViewHolder{
        SmartImageView siv;
        TextView tv_title;
        TextView tv_description;
        TextView tv_type;
    }
}

主介面程式碼:

package cn.edu.bzu.mynews;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import cn.edu.bzu.mynews.Tools.JsonParse;
import cn.edu.bzu.mynews.adapter.NewAdapter;
import cn.edu.bzu.mynews.entity.NewsInfo;
import cn.edu.bzu.mynews.model.Fruit;

public class MainActivity extends AppCompatActivity {
    private ListView Iv_news;
    private NewAdapter newAdapter;
    private List<NewsInfo> newInfos;
    private LinearLayout loading;
    private JsonParse jsonParse;



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

        Iv_news= (ListView) findViewById(R.id.lv_news);
        newAdapter =new NewAdapter(this,R.layout.news_item,newInfos);
        loading= (LinearLayout) findViewById(R.id.loading);
        prepareData();


    }

    private void prepareData() {
        AsyncHttpClient asyncHttpClient=new AsyncHttpClient();
        asyncHttpClient.get(getString(R.string.serverurl), new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes) {
                try {
                    String json=new String(bytes,"utf-8");
                    newInfos=jsonParse.getNewInfo(json);
                    if(newInfos==null){
                        Toast.makeText(MainActivity.this,"解析失敗",Toast.LENGTH_SHORT).show();
                    }
                    else {
                        loading.setVisibility(View.INVISIBLE);
                        Iv_news.setAdapter(newAdapter);


                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes, Throwable throwable) {
                Toast.makeText(MainActivity.this,"請求失敗",Toast.LENGTH_SHORT).show();

            }
        });



    }

}

在tomca的安裝目錄下開啟webapps檔案,將NewsInfo.xml檔案放置在root檔案下。線上json編輯器:http://www.qqe2.com/json
新增相關許可權

uses-permission android:name="android.permission.INTERNET"/>
1
1
[
  {
    "icon": "http://192.168.1.109:8080/images/a.jpg",
    "title": "科技溫暖世界",
    "content": "進入一個更有愛的領域",
    "type": "1",
    "comment": "69"
  },
  {
    "icon": "http://172.20.103.1:8080/images/b.jpg",
    "title": "《神武》",
    "content": "新美術資源盤點,視覺新體驗",
    "type": "2",
    "comment": "35"
  },
  {
    "icon": "http://172.20.103.1:8080/images/c.jpg",
    "title": "南北車正式公佈合併",
    "content": "南北車將於今日正式公佈合併",
    "type": "3",
    "comment": "2"
  },
  {
    "icon": "http://172.20.103.1:8080/images/d.jpg",
    "title": "萌呆了!汪星人抱玩偶酣睡",
    "content": "汪星人抱玩偶酣睡,萌翻網友",
    "type": "1",
    "comment": "25"
  },
  {
    "icon": "http://172.20.103.1:8080/images/e.jpg",
    "title": "風力發電進校園",
    "content": "風力發電普進校園",
    "type": "2",
    "comment": "26"
  },
  {
    "icon": "http://172.20.103.1:8080/images/f.jpg",
    "title": "地球一小時",
    "content": "地球熄燈一小時",
    "type": "1",
    "comment": "23"
  },
  {
    "icon": "http://172.20.103.1:8080/images/g.jpg",
    "title": "最美公路",
    "content": "最美公路,難以想象",
    "type": "1",
    "comment": "23"
  }
]

最終效果圖
這裡寫圖片描述