Android Learning Course--Implementation of News Client

Posted by jotate on Tue, 25 Jun 2019 00:11:11 +0200

To realize the news client, you need to know what json is
1.json:
JSON: JavaScript Object Notation. Independent of language and platform, it is smaller, faster and easier to parse than XML. Nowadays, JSON data has become the transmission mode of most data in the Internet, so we must master it skillfully.
Android platform has its own JSON parsing API, which can transform data in files and input streams into JSON objects, and then obtain data content saved by JSON from objects.

The JSON parsing part of Android is under package org.json. There are mainly the following categories:
JSONObject: It can be seen as a JSON object, which is the basic unit of the system about the definition of JSON, which contains a pair of key / value values. Its response to External (value output by applying toString() method) calls is embodied in a standard string (e.g. {"JSON": "Hello, World"}, the outermost braces wrapped, where Key and Value are coloned:"separated). It has a slight format for internal behavior, such as initializing a JSONObject instance and adding values by referring to the internal put() method: new JSONObject().put("JSON", "Hello, World!"), separated by commas between Key and Value. Value types include: Boolean, JSONArray, JSONObject, Number, String, or the default JSONObject.NULL object.

JSONStringer: JSON text construction class, according to official interpretation, this class can help create JSON text quickly and conveniently. Its greatest advantage is that it can reduce program exceptions caused by format errors. Referring to this class can automatically and strictly create JSON text in accordance with JSON syntax rules. Each JSONStringer entity can only create a JSON text. Its greatest advantage is that it can reduce program exceptions caused by format errors. Referring to this class can automatically and strictly create JSON text in accordance with JSON syntax rules. Each JSONStringer entity can only create a JSON text correspondingly.

JSONArray: It represents an ordered set of values. Convert it to String output (toString) in the form of square brackets wrapped with commas for values. "Separation (e.g. [value1,value2,value3], you can personally use short code to understand its format more intuitively. The inner part of this class also has query behavior. Both get() and opt() methods can return the specified value through index, and put() method can be used to add or replace the value. Also, the value types of this class can include: Boolean, JSONArray, JSONObject, Number, String, or the default JSONObject.NULL object.

JSONTokener: json parsing class
Exceptions used in JSONException: json

Matters needing attention:
Be sure to start the tomcat server before running the Android application, otherwise the data cannot be loaded.
Be sure to add network access permission in the manifest file, otherwise you can't connect to the server.
The server domain name request must write the specific address of the server, not the localhost, because the localhost is the accessed android native server.
Note the differences between json parsing and xml
Main interface code:

?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="Loading information..." />
        </LinearLayout>
        <ListView
            android:id="@+id/lv_news"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>
</LinearLayout>

listview loaded custom layout:

<?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="I'm the title."
        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="I'm describing it."
        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="comment"
        android:textColor="#99000000"
        android:textSize="12sp" />

</RelativeLayout>

Entity class of json file

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;
    }
}

Analytical Class

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("Comments:"+fruit.getComment());
                viewHolder.tv_type.setTextColor(Color.BLUE);
                break;
            case 2:
                viewHolder.tv_type.setText("special");
                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;
    }
}

Main interface code:

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,"Failure of parsing",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,"request was aborted",Toast.LENGTH_SHORT).show();

            }
        });



    }

}

Open webapps file in tomca installation directory and place NewsInfo.xml file under root file. Online json editor: http://www.qqe2.com/json
Add relevant permissions

uses-permission android:name="android.permission.INTERNET"/>
1
1
[
  {
    "icon": "http://192.168.1.109:8080/images/a.jpg",
    "title": "Technology Warms the World",
    "content": "Enter a more loving field",
    "type": "1",
    "comment": "69"
  },
  {
    "icon": "http://172.20.103.1:8080/images/b.jpg",
    "title": "<Shenwu",
    "content": "New Art Resources Inventory, New Visual Experience",
    "type": "2",
    "comment": "35"
  },
  {
    "icon": "http://172.20.103.1:8080/images/c.jpg",
    "title": "North and South Cars officially announced merger",
    "content": "North-South Cars will be officially announced today",
    "type": "3",
    "comment": "2"
  },
  {
    "icon": "http://172.20.103.1:8080/images/d.jpg",
    "title": "Dumbfounded! Wang Xing sleeps soundly with his doll in his arms",
    "content": "Wang Xing sleeps soundly with his dolls in his arms and turns over his netizens.",
    "type": "1",
    "comment": "25"
  },
  {
    "icon": "http://172.20.103.1:8080/images/e.jpg",
    "title": "Wind Power Entering Campus",
    "content": "Wind Power Generation Entering Campus",
    "type": "2",
    "comment": "26"
  },
  {
    "icon": "http://172.20.103.1:8080/images/f.jpg",
    "title": "Earth Hour",
    "content": "earth hour",
    "type": "1",
    "comment": "23"
  },
  {
    "icon": "http://172.20.103.1:8080/images/g.jpg",
    "title": "Best Highway",
    "content": "The most beautiful highway, unimaginable",
    "type": "1",
    "comment": "23"
  }
]

Final effect

Topics: Android JSON Java xml