Android - "i share" APP development Day06

Posted by Imagine3 on Wed, 06 Nov 2019 18:11:23 +0100

Continue the content of the previous article, write the FindFragment.java file. Based on the three functions in the previous article, you can basically show the hot content. Next, you can mainly deal with the event of find person and find article button

  1. Since we need to find people later, we need to create a bean file to store user information
  • Create a java file under the com.example.bean package -- FindPeople.java
  • Handle the setting and obtaining of user related properties

——The complete code of FindPeople.java file is as follows

package com.example.bean;

public class FindPeople {
    String userName;    //User nickname
    String signature;   //User signature
    String userLogImage;   //User head
    String passWord;   //User password


    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }


    public String getSignature() {
        return signature;
    }
    public void setSignature(String signature) {
        this.signature = signature;
    }

    public String getUserLogImage() {
        return userLogImage;
    }
    public void setUserLogImage(String userLogImage) {
        this.userLogImage = userLogImage;
    }

    public String getPassWord() { return passWord; }
    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

}

2. Next, we will start to deal with the event of two buttons: find a person and find a document

  • Add an event to the find text button to get the user's input when clicking
  • Send the requested content to the background service, get the information of relevant users, parse the returned Json and save the data in the bean, then update the UI through the adapter
  • Similarly, when you click the find person button, you can get the input content and request data from the background service. In this step, the adapter and Json data processing required are different from the above content processing, so you need to create another
  • It should be noted that after each network request, the content in ListView needs to be cleared, the adapter needs to be reinitialized, and the query content needs to be updated to the page
  • Handle the event of clearing the input box button. When you click clear, on the one hand, you should set the content in EditText to be empty, and at the same time, you should update the content of ListView to popular content

——After all, the processing logic is similar. For details, see FindTabFragment.java file. The complete code is as follows:

 

package com.example.discover;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.INotificationSideChannel;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.bean.FindInfo;
import com.example.bean.FindPeople;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class FindTabFragment extends Fragment implements AbsListView.OnScrollListener{
    Activity mActivity;     //Store current activity
    String baseUrl = "http://10.0.2.2: 8080 / ishareservice / servlet / "; / / address of web server
    String imgBaseUrl = "http://10.0.2.2:8080/iShareService/images / "; / / image resources

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View findLayout = inflater.inflate(R.layout.find_tab_content, container, false);
        return findLayout;
    }
    private ListView listView;
    private EditText searchView;  //Search content box
    private Button clearInfo;  //Search button
    private Button seekPeople;  //Search button
    private Button seekInfo;  //Search button
    private TextView hintTv;  //Prompt information


    private String keyWord;  //Search box text
    private Boolean isHot = true;  //Used to determine whether to load the hot text or find the content
    private int page = 1; //Requested page number
    private int visibleLastIndex = 0;  //Last visual index
    private int visibleItemCount;    // Total visible items in the current window
    private int dataSize = 28;     //Number of data sets
    private FindTabFragment.PaginationAdapter adapter;   //Store popular and search information
    private FindTabFragment.PeopleAdapter peopleAdapter;   //Depositing investigators
    private Handler handler = new Handler();

    //Return test information
    /*TextView testTxt;*/

    /** Called when the activity is first created. */
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //Return test information
        /* testTxt = (TextView)getActivity().findViewById(R.id.test_discover_tab);*/

        listView = (ListView)getActivity().findViewById(R.id.find_listView);
      /*  listView.addFooterView(loadMoreView);  //Set bottom view of list*/
        initializeAdapter();   //Initialize, fill in hot
        listView.setAdapter(adapter);
        /*listView.setOnScrollListener(this);*/

        //Input box
        searchView = (EditText)getActivity().findViewById(R.id.et_seek_search);

        //Find person, find text button, button to clear the content of text box
        seekPeople = (Button) getActivity().findViewById(R.id.find_search_by_name);
        seekInfo = (Button) getActivity().findViewById(R.id.find_search_by_keyWord);
        clearInfo = (Button) getActivity().findViewById(R.id.seek_bt_clear);

        //Prompt information
        hintTv = (TextView) getActivity().findViewById(R.id.seek_list_hint_info);

        seekPeople.setOnClickListener(new mClick());
        seekInfo.setOnClickListener(new mClick());
        clearInfo.setOnClickListener(new mClick());
    }

    class mClick implements View.OnClickListener {

        public void onClick(View v) {
            keyWord = searchView.getText().toString();

            if(keyWord == ""){
                Toast.makeText(getActivity(), "Search content cannot be empty!", Toast.LENGTH_LONG).show();
                return;
            }

            if (v == seekPeople) {
                //Click to find someone
                hintTv.setText("Query results:");
                listView.setAdapter(null);   //Empty the contents of the ListView control
                initSearchPeopleAdapter();
                listView.setAdapter(peopleAdapter);   //Insert query results into the page

                peopleAdapter.notifyDataSetChanged();
            }else if(v == seekInfo){
                //Click to find the article
                isHot = false;
                hintTv.setText("Query results:");
                listView.setAdapter(null);
                initSearchInfoAdapter();
                listView.setAdapter(adapter);

                adapter.notifyDataSetChanged();
            }else if(v == clearInfo){
                //Click Clear
                isHot = true;
                hintTv.setText("Everyone is watching:");

                listView.setAdapter(null);
                initializeAdapter();   //Initialize, fill in hot
                listView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                searchView.setText("");
            }

        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        int itemsLastIndex = adapter.getCount()-1; //Index of the last entry in the dataset
        int lastIndex = itemsLastIndex + 1;
        if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE
                && visibleLastIndex == lastIndex) {
            // If it is automatic loading, you can place the code for asynchronous data loading here
        }
    }


    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        this.visibleItemCount = visibleItemCount;
        visibleLastIndex = firstVisibleItem + visibleItemCount - 1;  //Last visual index

        //If all record options equal the number of data sets, remove the bottom view of the list
        if(totalItemCount == dataSize+1){
            Toast.makeText(getActivity(),  "All data loaded!", Toast.LENGTH_LONG).show();
        }
    }
    /**
     * Querying data in a database
     */
    private JSONArray loadDataFromDataBase(String QueryInfoUrl){

        //Toast.makeText(getActivity(), "save", Toast.LENGTH_SHORT).show();
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader buffer = null;
        HttpURLConnection connGET = null;

        try {
            URL url = new URL(QueryInfoUrl);
            connGET = (HttpURLConnection) url.openConnection();
            connGET.setConnectTimeout(5000);
            connGET.setRequestMethod("GET");
            if (connGET.getResponseCode() == 200) {
                buffer = new BufferedReader(new InputStreamReader(connGET.getInputStream()));
                for (String s = buffer.readLine(); s != null; s = buffer.readLine()) {
                    stringBuilder.append(s);
                }

                //Return test information
                JSONArray jsonArray = new JSONArray(stringBuilder.toString());
                /*   testTxt.setText(baseUrl+"QueryDiscover?page="+page+"&count="+count);*/
                //Get the data, analyze Json
                page = page+1;  //Update request page after a successful request
                buffer.close();

                return jsonArray;
            }else{
                Toast.makeText(getActivity(),"Non 200", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getActivity(), "get Submission err.." + e.toString(), Toast.LENGTH_LONG).show();
        }
        return null;
    }

    //Initialize setting details to FindInfo bean
    public List<FindInfo> initSetDataToBean(String detail){
        List<FindInfo> findInfo = new ArrayList<FindInfo>();
        try {
            JSONArray detailJsonArray = new JSONArray(detail);
            for (int i = 0; i < detailJsonArray.length(); i++) {
                FindInfo items = new FindInfo();

                JSONObject temp = (JSONObject) detailJsonArray.get(i);

                Integer infoId = temp.getInt("infoId");    //Content ID
                String infoTitle = temp.getString("infoTitle");   //Content headings
                String infoDescribe = temp.getString("infoDescribe");   //Content brief
                String infoDetail = temp.getString("infoDetail");   //Content details

                Integer type = temp.getInt("infoType");    //Type: 0 for diary, 1 for fun
                Integer support = temp.getInt("infoSupport");   //Praise points
                String infoAuthor = temp.getString("infoAuthor");  //author

                items.setInfoId(infoId);
                items.setInfoTitle(infoTitle);
                items.setInfoDescribe(infoDescribe);
                items.setInfoDetail(infoDetail);
                items.setType(type);
                items.setSupport(support);
                items.setInfoAuthor(infoAuthor);
                findInfo.add(items);
            }
            return findInfo;

        }catch (JSONException e){
            Toast.makeText(getActivity(), "initSetDataToBean abnormal err.." + e.toString(), Toast.LENGTH_LONG).show();
            return null;
        }
    }

    //Initialize setting details to FindInfo bean
    public List<FindPeople> initSetPeopleDataToBean(String detail){
        List<FindPeople> findPeople = new ArrayList<FindPeople>();
        try {
            JSONArray detailJsonArray = new JSONArray(detail);
            for (int i = 0; i < detailJsonArray.length(); i++) {
                FindPeople items = new FindPeople();

                JSONObject temp = (JSONObject) detailJsonArray.get(i);

                String userName = temp.getString("userName");    //User nickname
                String signature = temp.getString("signature");   //User signature
                String userLogImage = temp.getString("userLogImage");   //User head

                items.setUserName(userName);
                items.setSignature(signature);
                items.setUserLogImage(userLogImage);
                findPeople.add(items);
            }
            return findPeople;

        }catch (JSONException e){
            Toast.makeText(getActivity(), "initSetPeopleDataToBean abnormal err.." + e.toString(), Toast.LENGTH_LONG).show();
            return null;
        }
    }

    /**
     * Initialize the adapter of ListView, that is, open the data displayed on the page
     */
    private void initializeAdapter(){
        // Set thread policy
        setVersion();
        String QueryHotInfoUrl = baseUrl+"QueryHotInfo";
        JSONArray jsonArray = loadDataFromDataBase(QueryHotInfoUrl);
        try {
            JSONObject totalObject = (JSONObject)jsonArray.get(0);

            dataSize = totalObject.getInt("totalRecord");  //Total number of records
            String detail= totalObject.getString("RecordDetail");   //details

            if(initSetDataToBean(detail)!=null) {
                adapter = new PaginationAdapter(initSetDataToBean(detail));   //Set details to bean
            }

        }catch (JSONException e){
            Toast.makeText(getActivity(), "initializeAdapter abnormal err.." + e.toString(), Toast.LENGTH_LONG).show();
        }

    }

    /**
     * Initialize the adapter of ListView to display the result of the lookup file
     */
    private void initSearchInfoAdapter(){
        // Set thread policy
        setVersion();
        String QueryHotInfoUrl = baseUrl+"QueryInfoByKey?key="+keyWord;
        JSONArray jsonArray = loadDataFromDataBase(QueryHotInfoUrl);
        try {
            JSONObject totalObject = (JSONObject)jsonArray.get(0);

            dataSize = totalObject.getInt("totalRecord");  //Total number of records
            String detail= totalObject.getString("RecordDetail");   //details

            if(initSetDataToBean(detail)!=null) {
                adapter = new PaginationAdapter(initSetDataToBean(detail));   //Set details to bean
            }

        }catch (JSONException e){
            Toast.makeText(getActivity(), "initializeAdapter abnormal err.." + e.toString(), Toast.LENGTH_LONG).show();
        }

    }
    /**
     * Initialize the adapter of ListView to display the results of finder
     */
    private void initSearchPeopleAdapter(){
        // Set thread policy
        setVersion();
        String QueryPeopleInfoUrl = baseUrl+"QueryPeopleInfoByKey?nameKey="+keyWord;
        JSONArray jsonArray = loadDataFromDataBase(QueryPeopleInfoUrl);
        try {
            JSONObject totalObject = (JSONObject)jsonArray.get(0);

            dataSize = totalObject.getInt("totalRecord");  //Total number of records
            String detail= totalObject.getString("RecordDetail");   //details

            if(initSetPeopleDataToBean(detail)!=null) {
                peopleAdapter = new PeopleAdapter(initSetPeopleDataToBean(detail));   //Set details to bean
            }

        }catch (JSONException e){
            Toast.makeText(getActivity(), "initializeAdapter abnormal err.." + e.toString(), Toast.LENGTH_LONG).show();
        }

    }

    //If the APP requests network operation in the main thread, it will throw an exception, so it needs to use the thread to operate the network request
    void setVersion() {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork()
                .penaltyLog()
                .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects() //Probe SQLite database operation
                .penaltyLog() //Print logcat
                .penaltyDeath()
                .build());
    }
    /**
     * Convert Int to String
     */
    private  String IntToString(Integer num){
        try {
            String str = num.toString();    //How many pages
            return str;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Set the card style according to the returned article type
     */

    class PaginationAdapter extends BaseAdapter {

        List<FindInfo> newsItems;

        public PaginationAdapter(List<FindInfo> newsitems){
            this.newsItems = newsitems;
        }

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

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

        @Override
        public long getItemId(int position) {
            return position;
        }


        //Set the Item to each card here
        @Override
        public View getView(int position, View view, ViewGroup parent) {
            if(view == null){
                view = getLayoutInflater().inflate(R.layout.activity_seek_list_item, null);
            }
            //Remove popular logo
            if(!isHot){
                TextView textViewImgBc = (TextView)  view.findViewById(R.id.seek_list_textView);
                textViewImgBc.setCompoundDrawables(null, null, null, null);
            }

            //Content headings
            TextView tvTitle = (TextView)view.findViewById(R.id.seek_list_textView);
            tvTitle.setText(newsItems.get(position).getInfoTitle());

            //Content likes
            TextView tvSupport = (TextView)view.findViewById(R.id.seek_list_textView2);
            String num = IntToString(newsItems.get(position).getSupport());
            tvSupport.setText(num);

            return view;
        }

        /**
         * Add data list item
         * @param infoItem
         */
        public void addNewsItem(FindInfo infoItem){
            newsItems.add(infoItem);
        }

    }

    /**
     * Get screen width
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }
    /**
     * Set the card style according to the returned user
     */

    class PeopleAdapter extends BaseAdapter {

        List<FindPeople> newsItems;

        public PeopleAdapter(List<FindPeople> newsitems){
            this.newsItems = newsitems;
        }

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

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

        @Override
        public long getItemId(int position) {
            return position;
        }


        //Set the Item to each card here
        @Override
        public View getView(int position, View view, ViewGroup parent) {
            if(view == null){
                view = getLayoutInflater().inflate(R.layout.activity_seek_list_item, null);
            }

            //User nickname
            TextView tvTitle = (TextView)view.findViewById(R.id.seek_list_textView);
            tvTitle.setText(newsItems.get(position).getUserName());

            //User signature
            TextView tvSupport = (TextView)view.findViewById(R.id.seek_list_textView2);

            tvSupport.setText(newsItems.get(position).getSignature());

            //User head
            //Get pictures through Internet links
            String imgUrl = newsItems.get(position).getUserLogImage();
            Bitmap one;
            ImageView userImg = (ImageView) view.findViewById(R.id.seek_list_imgView);

          /*  //Set picture size adaption
            int screenWidth = getScreenWidth(getContext());
            ViewGroup.LayoutParams lp = userImg.getLayoutParams();
            lp.width = screenWidth;
            lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
            userImg.setLayoutParams(lp);

            userImg.setMaxWidth(screenWidth);
            userImg.setMaxHeight(screenWidth * 5); *//*Actually, it can be determined according to the demand. I test it here as 5 times of the maximum width*/

            try {
                one= LoadImgByNet.getBitmap(imgBaseUrl+imgUrl);
                userImg.setImageBitmap(one);
            }catch(IOException e){
                e.printStackTrace();
            }
            /*TableRow userImg = (TableRow) view.findViewById(R.id.seek_list_tableRow);*/
            TextView textViewImgBc = (TextView)  view.findViewById(R.id.seek_list_textView);
            textViewImgBc.setCompoundDrawables(null, null, null, null);
          /*  String imgUrl = newsItems.get(position).getUserLogImage();
            Bitmap one;
            try {
                one= LoadImgByNet.getBitmap(imgBaseUrl+imgUrl);
                *//*userImg.setBackground(new BitmapDrawable(getResources(),one));    //Set the head image as a background*//*

                Drawable drawable = new BitmapDrawable(getResources(),one);
                // This step must be done, otherwise it will not be displayed
                drawable.setBounds(drawable.getMinimumWidth(), 0,0 , drawable.getMinimumHeight());
                textViewImgBc.setCompoundDrawables(drawable, null, null, null);

            }catch(IOException e){
                e.printStackTrace();
            }*/

            return view;
        }

        /**
         * Add data list item
         * @param infoItem
         */
        public void addNewsItem(FindPeople infoItem){
            newsItems.add(infoItem);
        }
    }
}

 

——The search page is almost over here. As for the entry details, we will leave them later. Next, we will deal with the release page first

Topics: Android Java JSON network