Easy Tutorial
❮ Verilog2 Udp Logic Zookeeper Setup ❯

12.2 DrySister Viewing Girls Application (First Edition) — 2. Parsing Backend Data

Category Android Basic Tutorial

1. Some BB

In the previous section, we set up a simple project and then hosted the repository on Github. After analysis, we felt it was necessary to optimize the following two points:

>

1.URL hardcoding -> Parsing the Json returned by the interface to handle obtaining the image URL 2.Optimize image loading, add local loading

This section will complete the first point mentioned above!


2. Start Writing Code

1) Create a feature branch on Develop: parse_json

2) Picking at the Json parsing interface data

Data source interface: Gank.io API

Data source interface: Gank.io API

Here we use the interface: http://gank.io/api/data/benefits/{number of requests}/{page number} For example: Display 10 per page, first page: http://gank.io/api/data/benefits/10/1

Let's first look at the Json format returned by the server:

PS: The Json formatter is a Chrome plugin: JSON_handle

Based on this, let's first write our Bean class: Sister.java :

/**
 * Description: Girl business Bean
 *
 * @author coder-pig: 2016/08/06 17:16
 */
public class Sister {

    private String _id;
    private String createAt;
    private String desc;
    private String publishedAt;
    private String source;
    private String type;
    private String url;
    private boolean used;
    private String who;

    // Some get and set methods...

}

Next, let's write a class for parsing network data. The tasks to be done in this class are as follows:

>

-Step 1 : Initiate a Get request through HttpUrlConnection and then obtain the data returned by the backend, which is in the form of a stream

-Step 2 : We need to write a method to convert the stream into a byte array

-Step 3 : After converting the byte array into a string, we get the data returned by the backend. The next thing to do is to write a method to parse this large string of Json. We need to obtain the data we need from the Json and put it into the Bean

-Step 4 : Return the processed collection data

So we write a network request processing class: SisterApi.java :

/**
 * Description: Network request processing related class
 *
 * @author coder-pig: 2016/08/07 14:28
 */
public class SisterApi {
    private static final String TAG = "Network";
    private static final String BASE_URL = "http://gank.io/api/data/benefits/";

    /**
     * Query girl information
     */
    public ArrayList<Sister> fetchSister(int count, int page) {
        String fetchUrl = BASE_URL + count + "/" + page;
        ArrayList<Sister> sisters = new ArrayList<>();
        try {
            URL url = new URL(fetchUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            int code = conn.getResponseCode();
            Log.v(TAG, "Server response: " + code);
            if (code == 200) {
                InputStream in = conn.getInputStream();
                byte[] data = readFromStream(in);
                String result = new String(data, "UTF-8");
                sisters = parseSister(result);
            } else {
                Log.e(TAG, "Request failed: " + code);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sisters;
    }

    /**
     * Method to parse the returned Json data
     */
    public ArrayList<Sister> parseSister(String content) throws Exception {
        ArrayList<Sister> sisters = new ArrayList<>();
        JSONObject object = new JSONObject(content);
        JSONArray array = object.getJSONArray("results");
        for (int i = 0; i < array.length(); i++) {
            JSONObject results = (JSONObject) array.get(i);
            Sister sister = new Sister();
            sister.set_id(results.getString("_id"));
            sister.setCreateAt(results.getString("createdAt"));
            sister.setDesc(results.getString("desc"));
            sister.setPublishedAt(results.getString("publishedAt"));
            sister.setSource(results.getString("source"));
            sister.setType(results.getString("type"));
            sister
case R.id.btn_show:
                if(data != null && !data.isEmpty()) {
                    if (curPos > 9) {
                        curPos = 0;
                    }
                    loader.load(showImg, data.get(curPos).getUrl());
                    curPos++;
                }
                break;
            case R.id.btn_refresh:
                page++;
                new SisterTask(page).execute();
                curPos = 0;
                break;
        }
    }

    private class SisterTask extends AsyncTask&lt;Void,Void,ArrayList<Sister>> {

        private int page;

        public SisterTask(int page) {
            this.page = page;
        }

        @Override
        protected ArrayList<Sister> doInBackground(Void... params) {
            return sisterApi.fetchSister(10,page);
        }

        @Override
        protected void onPostExecute(ArrayList<Sister> sisters) {
            super.onPostExecute(sisters);
            data.clear();
            data.addAll(sisters);
        }
    }

}

---

## 3. Running Effect Display

---

## 4. Submit Code, Merge Branch, Delete Branch

Enter the command to submit the code one by one:

After submitting to Github, you can see:

Since I didn't download the Github client, I'll use the command to merge branches:
Switch to the develop branch and merge parse_json

Then submit the merged develop to Github, (since it's a single person development, so basically no need to deal with conflicts

Okay, after pushing, you can see that the content of develop on Github has changed

So, the parse_json branch we opened is now of no use, we can use the command to delete this branch:

Of course, here we only delete the local repository, Github still has this branch, enter the command again:

Then check on GitHub:

Okay, the branch has been deleted! The code on the develop branch is also the latest code!

---

## Bug Fix - (2016.8.9):

Today, God B in the group gave me feedback on the potential memory overflow issue that may be caused by new AsyncTask,
I thought about it carefully and it is indeed possible. Due to time constraints, I didn't pay attention to this when writing. I specially opened a **asyncTask_bug** branch to fix this problem, and modified the code of MainActivity, the modified code is as follows:

public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button showBtn; private Button refreshBtn; private ImageView showImg;

private ArrayList<Sister> data;
private int curPos = 0; //Which one is currently displayed
private int page = 1;   //Current page number
private PictureLoader loader;
private SisterApi sisterApi;
private SisterTask sisterTask;

@Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sisterApi = new SisterApi();
    loader = new PictureLoader();
    initData();
    initUI();
}

private void initData() {
    data = new ArrayList<>();
}

private void initUI() {
    showBtn = (Button) findViewById(R.id.btn_show);
    refreshBtn = (Button) findViewById(R.id.btn_refresh);
    showImg = (ImageView) findViewById(R.id.img_show);

    showBtn.setOnClickListener(this);
    refreshBtn.setOnClickListener(this);
}

@Override public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_show:
            if(data != null && !data.isEmpty()) {
                if (curPos > 9) {
                    curPos = 0;
                }
                loader.load(showImg, data.get(curPos).getUrl());
                curPos++;
            }
            break;
        case R.id.btn_refresh:
            sisterTask = new SisterTask();
            sisterTask.execute();
            curPos = 0;
            break;
    }
}

private class SisterTask extends AsyncTask&lt;Void,Void,ArrayList<Sister>> {

    public SisterTask() { }

    @Override
    protected ArrayList<Sister> doInBackground(Void... params) {
        return sisterApi.fetchSister(10,page);
    }

    @Override
    protected void onPostExecute(ArrayList<Sister> sisters) {
        super.onPostExecute(sisters);
        data.clear();
        data.addAll(sisters);
        page++;
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
        sisterTask = null;
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    sisterTask.cancel(true);
}

} ```


Source Code Download: DrySister

-1.0 Android Basic Tutorial for Beginners

-1.0.1 Latest Android Basic Tutorial Catalog for 2015

-1.1 Background and System Architecture Analysis

-2.2.3 TableLayout

-2.2.4 FrameLayout

-2.2.5 GridLayout

-2.2.6 AbsoluteLayout

-2.3.1 TextView Detailed Explanation

-2.3.2 EditText Detailed Explanation

-2.3.3 Button and ImageButton

-2.3.4 ImageView

-2.3.5 RadioButton & Checkbox

-2.3.6 ToggleButton and Switch

-2.3.7 ProgressBar

-2.3.8 SeekBar

-2.3.9 RatingBar

-2.4.1 ScrollView

-2.4.2 Date & Time Components (Part 1)

-2.4.3 Date & Time Components (Part 2)

-2.4.4 Adapter Basics

-2.4.5 ListView Simple and Practical Use

-2.4.6 BaseAdapter Optimization

-2.4.7 ListView Focus Issues

-2.4.8 ListView Checkbox Misalignment Issue Resolution

-2.4.9 ListView Data Update Issues

-2.5.0 Building a Reusable Custom BaseAdapter

-2.5.1 ListView Item Multiple Layouts Implementation

-2.5.2 GridView Basic Usage

-2.5.3 Spinner Basic Usage

-2.5.4 AutoCompleteTextView Basic Usage

-2.5.5 ExpandableListView Basic Usage

-2.5.6 ViewFlipper Basic Usage

-2.5.7 Toast Basic Usage

-2.5.8 Notification Detailed Explanation

-2.5.9 AlertDialog Detailed Explanation

-2.6.0 Other Common Dialogs Basic Usage

-2.6.1 PopupWindow Basic Usage

-2.6.2 Menu

-2.6.3 ViewPager Simple Usage

-2.6.4 DrawerLayout Simple Usage

-3.1.1 Event Handling Mechanism Based on Listening

-3.2 Event Handling Mechanism Based on Callback

-3.3 A Brief Analysis of Handler Message Passing Mechanism

-3.4 TouchListener vs OnTouchEvent + Multi-touch

-3.5 Listening to EditText Content Changes

-3.6 Responding to System Setting Events (Configuration Class)

-3.7 AsyncTask Asynchronous Task

-3.8 Gestures

-4.1.1 Activity Basics

-4.1.2 Activity Introduction

-4.1.3 Activity In-Depth

-4.2.1 Service Basics

-4.2.2 Service Advanced

-4.2.3 Service Mastery

-4.3.1 BroadcastReceiver Introduction

-[4.3

❮ Verilog2 Udp Logic Zookeeper Setup ❯