Android#09--OkHttp向挖、fastjson、RecyclerView

2017-3-27

圖中這樣一個(gè)界面的實(shí)現(xiàn)用到了OkHttp獲取數(shù)據(jù)炕舵,fastjson解析數(shù)據(jù)何之,RecyclerView呈現(xiàn)出來。


圖片

【1】布局

【1】activity的布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_my_gift_scene1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@mipmap/bg_my"
    android:orientation="vertical"
    tools:context="com.example.sweetgirl.magiccup1.outdated.MyGiftScene1Activity">

    <include layout="@layout/my_gift_scene1_toolbar"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="3dp"/>
    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/layout_swipe_refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/new_recyclerView"/>
    </android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>

【2】item的布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:background="@drawable/edit_view_shape"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="5dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp">

    <TextView
        android:id="@+id/scene1_tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:textColor="@color/text_b"
        android:text="嘮叨"
        android:paddingTop="10dp"
        tools:ignore="HardcodedText,SpUsage" />
    <TextView
        android:id="@+id/scene1_tv_dep"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:textSize="14sp"
        android:text="說你是愛你"
        android:textColor="@color/text"
        tools:ignore="HardcodedText" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
            <com.jit.lib.SmartImageView
                android:id="@+id/scene1_iv_photo"
                android:layout_width="wrap_content"
                android:layout_height="200dp"
                android:scaleType="fitXY"
                android:layout_marginTop="8dp"
                android:layout_marginLeft="12dp"
                android:layout_marginRight="12dp"
                android:layout_marginBottom="12dp"
                android:src="@mipmap/iv_item"
                tools:ignore="ContentDescription" />
        </LinearLayout>
</LinearLayout>

【2】JavaBean

public class TextImage {

    public String name;   //名字
    public String dep;      //描述
    public String image;   //圖片

    public TextImage(String image, String text,String text1) {
        this.image = image;
        this.name = text;
        this.dep=text1;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDep() {
        return dep;
    }

    public void setDep(String dep) {
        this.dep = dep;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }
}

【3】Adapter

public class MyRecycleViewAdapter extends RecyclerView.Adapter<MyRecycleViewAdapter.ViewHolder> {


   // private final Context context;
    private ArrayList<String> datas;

    private LayoutInflater layoutInflater;
    private VolleySingleton volleySingleton;
    private ImageLoader imageLoader;
    private DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
    private int previousPosition=0;


   private ArrayList<TextImage> textImages=new ArrayList<>();

    public MyRecycleViewAdapter(Context context){
       // this.context=context;
        //this.datas=datas;
        layoutInflater = LayoutInflater.from(context);
        volleySingleton = VolleySingleton.getInstance(context);
        imageLoader = volleySingleton.getImageLoader();
    }

    public void setTextImages(ArrayList<TextImage> textImages){
        this.textImages=textImages;
        notifyItemMoved(0,textImages.size());
    }

    /**
     *相當(dāng)于getView 方法中創(chuàng)建view和ViewHolder
     * * @param
     *
     * */
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType){
        View itemView=layoutInflater.inflate(R.layout.item_scene1, parent,false);
        ViewHolder viewHolder=new ViewHolder(itemView);
        return viewHolder;
    }

    /**
     * 相當(dāng)于getView 方法中創(chuàng)建view和ViewHolder
     * @param
     *
     */
    @Override
    public void  onBindViewHolder(ViewHolder holder, int position){
       // String data=datas.get(position);
        //holder.mText.setText(data);
        TextImage currentTextImage=textImages.get(position);
        holder.mText.setText(currentTextImage.getName());
        holder.mDep.setText(currentTextImage.getDep());

        holder.itemView.setTag(position);

        String url=currentTextImage.getImage();
        loadImages(url,holder);

    }

    private void loadImages(String urlThumbnail, final ViewHolder holder) {
        if (!urlThumbnail.equals(Constants.NA)) {
            imageLoader.get(urlThumbnail, new ImageLoader.ImageListener() {
                @Override
                public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
                    holder.mImage.setImageBitmap(response.getBitmap());
                }

                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
        }
    }

    /**
     *相當(dāng)于getView 方法中創(chuàng)建view和ViewHolder
     * @param
     */
    @Override
    public int  getItemCount(){
        //return datas.size();
        return textImages.size();
    }


    class ViewHolder extends RecyclerView.ViewHolder{
         TextView mDep;
         TextView mText;
         ImageView mImage;

        public ViewHolder(View itemView){
            super(itemView);
            mText = (TextView)itemView.findViewById(R.id.scene1_tv_name);
            mImage = (ImageView)itemView.findViewById(R.id.scene1_iv_photo);
            mDep=(TextView)itemView.findViewById(R.id.scene1_tv_dep);
          //設(shè)置item的點(diǎn)擊事件
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onItemClickListener!=null){
                        onItemClickListener.OnItemClick(v,(int)v.getTag());
                    }
                }
            });
        }
    }
    //定義點(diǎn)擊事件的接口
    public interface OnItemClickListener{
        public void OnItemClick(View view,int position);
    }

    private OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener){
        this.onItemClickListener=onItemClickListener;
    }

}

【4】Activity

【1】找到控件
    private RecyclerView mRecyclerView;
    private SwipeRefreshLayout mRefreshLayout;
    
   mRecyclerView=(RecyclerView) findViewById(R.id.new_recyclerView);
   mRefreshLayout=(SwipeRefreshLayout)findViewById(R.id.layout_swipe_refresh);
【2】下載數(shù)據(jù)
ArrayList<TextImage> list=new ArrayList<>();
 private  boolean doGet(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    enqueue();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return false;
    }
    private void enqueue(){
        //[1]拿到OkHttpClient
        OkHttpClient client = new OkHttpClient();
        //[2]構(gòu)造Request   
        Request request = new Request.Builder()
                .url(path)
                .build();
        //[3]將Request封裝為call
        Call call=client.newCall(request);
        //[4]執(zhí)行call
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                L.i(TAG,"onFailure"+e.getMessage());
                e.printStackTrace();
            }
            @Override
            public void onResponse(Response response) throws IOException {
                String res=response.body().string();
                L.i(TAG,"onResponse"+res);
                jsonParser(res);

            }
        });
    }
 [3]解析數(shù)據(jù)
    private List<TextImage> jsonParser(String jsonData) {
        try {
            JSONTokener jsonTokener = new JSONTokener(jsonData);
            org.json.JSONObject jsonObject = (org.json.JSONObject) jsonTokener.nextValue();
            org.json.JSONArray array = jsonObject.getJSONArray("data");
            for (int i = 0; i < array.length(); i++) {
                org.json.JSONObject object = array.getJSONObject(i);
                String name=object.getString("name");
                String image=object.getString("image");
                String dep=object.getString("depiction");
                L.i(TAG,name);
                L.i(TAG,image);
                L.i(TAG,dep);
                TextImage textImage=new TextImage(image,name,dep);
                list.add(textImage);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
 [4]設(shè)置數(shù)據(jù)
private MyRecycleViewAdapter mmAdapter;
mmAdapter.setTextImages(list);
 [5]設(shè)置Adapter
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this);

        mmAdapter=new MyRecycleViewAdapter(RecyclerViewActivity.this);

        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mRecyclerView.addItemDecoration(new SpaceItemDecoration(12,8,12,30));
        mRecyclerView.setAdapter(mmAdapter);
        mmAdapter.setTextImages(list);
        mmAdapter.setOnItemClickListener(new MyRecycleViewAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view,int position) {
                mName=list.get(position).getName();
                Toast.makeText(RecyclerViewActivity.this,"你選擇了"+mName,Toast.LENGTH_SHORT).show();
            }
        });
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener(){
            public void onRefresh() {
                //數(shù)據(jù)重新加載完成后咽筋,提示數(shù)據(jù)發(fā)生改變溶推,并且設(shè)置現(xiàn)在不在刷新
                mmAdapter.notifyDataSetChanged();
                mRefreshLayout.setRefreshing(false);
            }
        });
        mRecyclerView.addOnScrollListener(new EndLessOnScrollListener(mLinearLayoutManager) {
            @Override
            public void onLoadMore(int currentPage) {
                loadMoreData();
            }
        });
//每次上拉加載的時(shí)候,給RecyclerView的后面添加了10條數(shù)據(jù)數(shù)據(jù)
    private void loadMoreData(){
        for (int i =0; i < 10; i++){
            mmAdapter.notifyDataSetChanged();
        }
    }

demo

【5】分享

最近看了一本書奸攻,叫《街貓》----Le Matou
這本書蒜危,陪伴了我一整個(gè)寒假,書中有黃金屋睹耐,說的就是這樣的書吧辐赞。
另外最近還看到這樣一句話,很喜歡硝训,與你分享响委。

真正的好機(jī)會(huì),永遠(yuǎn)都存在與未知中

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末捎迫,一起剝皮案震驚了整個(gè)濱河市晃酒,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌窄绒,老刑警劉巖贝次,帶你破解...
    沈念sama閱讀 216,651評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異彰导,居然都是意外死亡蛔翅,警方通過查閱死者的電腦和手機(jī)敲茄,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來山析,“玉大人堰燎,你說我怎么就攤上這事∷窆欤” “怎么了秆剪?”我有些...
    開封第一講書人閱讀 162,931評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)爵政。 經(jīng)常有香客問我仅讽,道長(zhǎng),這世上最難降的妖魔是什么钾挟? 我笑而不...
    開封第一講書人閱讀 58,218評(píng)論 1 292
  • 正文 為了忘掉前任洁灵,我火速辦了婚禮,結(jié)果婚禮上掺出,老公的妹妹穿的比我還像新娘徽千。我一直安慰自己,他們只是感情好汤锨,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,234評(píng)論 6 388
  • 文/花漫 我一把揭開白布双抽。 她就那樣靜靜地躺著,像睡著了一般泥畅。 火紅的嫁衣襯著肌膚如雪荠诬。 梳的紋絲不亂的頭發(fā)上琅翻,一...
    開封第一講書人閱讀 51,198評(píng)論 1 299
  • 那天位仁,我揣著相機(jī)與錄音,去河邊找鬼方椎。 笑死聂抢,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的棠众。 我是一名探鬼主播琳疏,決...
    沈念sama閱讀 40,084評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼闸拿!你這毒婦竟也來了空盼?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,926評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤新荤,失蹤者是張志新(化名)和其女友劉穎揽趾,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體苛骨,經(jīng)...
    沈念sama閱讀 45,341評(píng)論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡篱瞎,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,563評(píng)論 2 333
  • 正文 我和宋清朗相戀三年苟呐,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片俐筋。...
    茶點(diǎn)故事閱讀 39,731評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡牵素,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出澄者,到底是詐尸還是另有隱情笆呆,我是刑警寧澤,帶...
    沈念sama閱讀 35,430評(píng)論 5 343
  • 正文 年R本政府宣布粱挡,位于F島的核電站腰奋,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏抱怔。R本人自食惡果不足惜劣坊,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,036評(píng)論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望屈留。 院中可真熱鬧局冰,春花似錦、人聲如沸灌危。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽勇蝙。三九已至沫勿,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間味混,已是汗流浹背产雹。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留翁锡,地道東北人蔓挖。 一個(gè)月前我還...
    沈念sama閱讀 47,743評(píng)論 2 368
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像馆衔,于是被迫代替她去往敵國(guó)和親瘟判。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,629評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容