ListView 关于Adapter 本地文件中解析json数据完整例子

来源:互联网 发布:hits算法题目 编辑:程序博客网 时间:2024/05/02 01:19

第一步:布局文件

theme.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:orientation="vertical"              android:layout_width="fill_parent"              android:layout_height="fill_parent"              android:background="@color/white"        >    <RelativeLayout            android:layout_width="match_parent"            android:layout_height="50dp"            android:background="@color/yeyy_themeclor"            >        <ImageButton                android:id="@+id/img_back"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:src="@drawable/ky_title_back"                android:background="@color/lucency"                android:layout_marginLeft="20dp"                android:layout_centerVertical="true"                android:visibility="invisible"                />        <TextView                android:id="@+id/theme_tv_title"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:textSize="25dp"                android:textColor="@color/white"                android:layout_centerInParent="true"                android:text="主题"                />    </RelativeLayout><ListView        android:id="@+id/theme_listView"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:divider="@color/yeyy_gray"        android:dividerHeight="1dp"        android:scrollbars="none"        ></ListView></LinearLayout>

theme_item_listview.xml

<?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="80dp"                android:paddingLeft="15dp"                android:paddingRight="15dp"                android:id="@+id/theme_item_listview"        >    <!--<com.ncsyeyy.ncskayi.view.CircleImageView-->        <ImageView            android:id="@+id/theme_head_portrait"            android:layout_width="40dp"            android:layout_height="40dp"            android:src="@drawable/theme_item_image"            android:layout_centerInParent="true"            android:layout_alignParentStart="true"            />    <LinearLayout            android:id="@+id/ltheme_item_content"            android:orientation="vertical"            android:layout_width="match_parent"            android:layout_height="80dp"            android:layout_marginLeft="40dp"            android:layout_marginRight="40dp"            android:paddingTop="5dp"            android:paddingLeft="10dp"            >            <TextView                    android:id="@+id/theme_tv_name"                    android:layout_width="match_parent"                    android:layout_height="30dp"                    android:textSize="20sp"                    android:text="主题"                    android:gravity="center_vertical"                    android:textColor="@color/black"                    android:layout_marginTop="5dp"                    />            <TextView                    android:id="@+id/theme_tv_content"                    android:layout_width="match_parent"                    android:layout_height="30dp"                    android:textSize="15sp"                    android:textColor="#ff919191"                    android:text="轻松拥有公司会议所需的各种卡片"                    android:maxLines="1"                    android:ellipsize="end"                    android:gravity="center_vertical"                    />    </LinearLayout>    <ImageView            android:id="@+id/theme_imageView_in"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:src="@drawable/theme_go"            android:layout_centerInParent="true"            android:layout_alignParentRight="true"            /></RelativeLayout>
theme_details_weeding.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:orientation="vertical"              android:layout_width="match_parent"              android:layout_height="match_parent">    <RelativeLayout            android:layout_width="match_parent"            android:layout_height="50dp"            android:background="@color/yeyy_themeclor">        <ImageButton                android:id="@+id/theme_details_weeding_back"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:src="@drawable/back"                android:background="@color/lucency"                android:layout_marginLeft="10dp"                android:layout_centerVertical="true"/>        <TextView                android:id="@+id/theme_details_weeding_title"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:textSize="25dp"                android:textColor="@color/white"                android:layout_centerInParent="true"                android:text="婚庆系列"                />        <ImageButton                android:id="@+id/theme_details_no"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:src="@drawable/theme_details_no"                android:background="#00000000"                android:layout_alignParentEnd="true"                android:layout_centerVertical="true"                android:layout_marginTop="8dp"                android:layout_marginRight="20px"/>    </RelativeLayout>    <RelativeLayout            android:id="@+id/rlSearchFrameDelete"            android:layout_width="fill_parent"            android:layout_height="50dp"            android:gravity="center_vertical"            android:background="@color/yeyy_gray">        <EditText android:id="@+id/etSearch"                  android:layout_width="fill_parent"                  android:layout_height="30dp"                  android:singleLine="true"                  android:background="@drawable/search_frame"                  android:layout_marginRight="20dp"                  android:layout_marginLeft="20dp"                  android:textSize="12sp"                  android:hint="搜索"/>        <ImageView android:id="@+id/ivDeleteText"                   android:layout_width="wrap_content"                   android:layout_height="wrap_content"                   android:layout_alignParentRight="true"                   android:src="@drawable/delete"                   android:layout_centerInParent="true"                   android:paddingRight="20dp"                   android:visibility="gone"/>    </RelativeLayout>    <ListView            android:id="@+id/theme_details_weeding_listView"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:scrollbars="none"            >    </ListView></LinearLayout>

theme_item_details.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:orientation="vertical"              android:layout_width="match_parent"              android:layout_height="200dp"              android:id="@+id/theme_item_details"        >    <RelativeLayout            android:layout_width="match_parent"            android:layout_height="50dp"            android:layout_marginLeft="15dp"            android:layout_marginRight="15dp"            >        <ImageView                android:id="@+id/theme_item_details_head"                android:layout_width="40dp"                android:layout_height="40dp"                android:src="@drawable/theme_item_image"                android:layout_centerVertical="true"                />        <TextView                android:id="@+id/theme_item_details_name"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="林晓峰"                android:textSize="20dp"                android:layout_toRightOf="@id/theme_item_details_head"                android:layout_centerVertical="true"                android:layout_marginLeft="5dp"                />        <CheckBox                android:id="@+id/theme_item_details_collect"                android:layout_width="36dp"                android:layout_height="37dp"                android:button="@drawable/collect"                android:layout_alignParentRight="true"                android:layout_centerVertical="true"                android:layout_marginLeft="8dp"                android:gravity="center"                />        <View                android:layout_width="1dp"                android:layout_height="30dp"                android:background="@color/yeyy_gray"                android:layout_toRightOf="@id/theme_item_details_collect"                android:layout_centerVertical="true"                />        <TextView                android:id="@+id/theme_item_details_download_number_a"                android:layout_width="wrap_content"                android:layout_height="20dp"                android:text="26"                android:textSize="15dp"                android:textColor="@color/color_red"                android:layout_toLeftOf="@id/theme_item_details_collect"                android:layout_centerVertical="true"                android:layout_marginRight="5dp"                android:gravity="center"                />        <TextView                android:id="@+id/theme_item_details_download"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:textSize="15dp"                android:text="下载"                android:layout_toLeftOf="@id/theme_item_details_download_number_a"                android:layout_centerVertical="true"                android:layout_marginRight="5dp"                android:gravity="center"                />    </RelativeLayout>    <ImageView            android:id="@+id/theme_item_details_works"            android:layout_width="match_parent"            android:layout_height="150dp"            android:scaleType="fitXY"            android:layout_marginLeft="15dp"            android:layout_marginRight="15dp"            android:src="@drawable/forum_formwork_image"            /></LinearLayout>
第二步:对应的activity

ThemeActivity.java

package com.ncsyeyy.YeyyAdapterJSON;import android.app.Activity;import android.content.Context;import android.content.Intent;import android.content.res.AssetManager;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.CheckBox;import android.widget.ImageButton;import android.widget.ListView;import java.util.ArrayList;/** * Created by yeyy on 7/10/2015. */public class ThemeActivity extends Activity {    View view;    private ArrayList<ThemeItemView> themeList = new ArrayList<ThemeItemView>();    private ListView themeListView;    private String fileTheme = "theme.json";    private ThemeListViewAdapter themeListViewAdapter = null;    private Context context;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.theme);        context = this;        initView();        initData();    }    public void initView() {        themeListView = (ListView) findViewById(R.id.theme_listView);        themeListView.setOnItemClickListener(new ItemClickListener());    }    //获取assets下的文件    private void initData() {        String json = ReaderFileTool.getLocalJson(this, fileTheme);//获取json数据        themeList = JsonTool.setThemeData(context, json);//得到json数据,放进对应的控件        themeListViewAdapter = new ThemeListViewAdapter(ThemeActivity.this, themeList);        themeListView.setAdapter(themeListViewAdapter);//适配到listview上    }    class ItemClickListener implements AdapterView.OnItemClickListener {        @Override        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {            Intent intent = new Intent();            intent.setClass(ThemeActivity.this, ThemeWeedingActivity.class);            startActivity(intent);        }    }}
ThemeWeedingActivity.java

package com.ncsyeyy.YeyyAdapterJSON;import android.annotation.TargetApi;import android.app.Activity;import android.content.Context;import android.content.Intent;import android.content.res.AssetManager;import android.os.Build;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.text.Editable;import android.text.TextWatcher;import android.util.Log;import android.view.View;import android.view.WindowManager;import android.widget.EditText;import android.widget.ImageButton;import android.widget.ListView;import android.widget.TextView;import java.util.ArrayList;/** * 婚庆系列,作品列表 * Created by yeyy on 7/17/2015. */public class ThemeWeedingActivity extends Activity {    private  ArrayList<ThemeItemDetailsListView> themeIDListView=new ArrayList<ThemeItemDetailsListView>();    private  ArrayList<ThemeItemDetailsListView> themeIDListView1=new ArrayList<ThemeItemDetailsListView>();    private ImageButton themeWeedingBut;    private ListView themeWeedingLv;    private Context context;    private String fileName = "themeweeding.json";    private ThemeItemDetailsListViewAdapter themeIDLVAdapter;    public AssetManager manager;    String str=null;    private TextView weedingTitle;    private static final String TAG = "====RefreshListByEditText_TAG====";    private EditText etSearch;    private static final int MSG_KEY = 0x1234;    private Handler handler;    private String json;    @TargetApi(Build.VERSION_CODES.CUPCAKE)    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.theme_details_weeding);        getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);        //从适配器ThemeListViewAdapter接收title数据        weedingTitle = (TextView) findViewById(R.id.theme_details_weeding_title);        context = this;        Intent intent=getIntent();        str=getIntent().getStringExtra("title");        weedingTitle.setText(str);        initView();        initData();//data要在view初始化之后,不然会出现空指针异常        btnWeedingBack();        onClick();    }    private void initView() {        themeWeedingBut = (ImageButton) findViewById(R.id.theme_details_weeding_back);        themeWeedingLv = (ListView) findViewById(R.id.theme_details_weeding_listView);        etSearch = (EditText) findViewById(R.id.etSearch);    }    private void initData() {        json = ReaderFileTool.getLocalJson(this, fileName);        //String json =  getLocalJson(fileName);        Log.i("json", "json" + json);        themeIDListView = JsonTool.setProData(context, json,str);        Log.i("themeIDListView","themeIDListView"+themeIDListView.size());        themeIDLVAdapter = new ThemeItemDetailsListViewAdapter(                ThemeWeedingActivity.this, themeIDListView);        themeWeedingLv.setAdapter(themeIDLVAdapter);    }    public void btnWeedingBack(){        themeWeedingBut.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                finish();            }        });    }//搜索功能的实现    private void onClick(){        etSearch.addTextChangedListener(new TextWatcher() {            @Override            public void beforeTextChanged(CharSequence s, int start, int count, int after) {                Log.d(TAG, "afterTextChanged");            }            @Override            public void onTextChanged(CharSequence s, int start, int before, int count) {                Log.d(TAG, "onTextChanged");                Log.w(TAG, "input.text=" + s.toString());                Message msg = new Message();                msg.what = MSG_KEY;                Bundle data = new Bundle();                data.putString("value", s.toString());                msg.setData(data);                handler.sendMessage(msg);            }            @Override            public void afterTextChanged(Editable s) {                Log.d(TAG, "afterTextChanged");            }        });        handler = new Handler() {            @Override            public void handleMessage(Message msg) {                switch (msg.what) {                    case MSG_KEY:                        Log.i("value","value="+msg.getData().get("value").toString());                        refreshListView(msg.getData().get("value").toString());                }            }        };    }    private void refreshListView(String value) {//刷新listview        if (value == null || value.trim().length() == 0){            themeIDLVAdapter = new ThemeItemDetailsListViewAdapter(                    ThemeWeedingActivity.this, themeIDListView);            themeWeedingLv.setAdapter(themeIDLVAdapter);        }        ArrayList<String> tmpList = new ArrayList<String>();        for (ThemeItemDetailsListView t : themeIDListView) {               tmpList.add(t.getTvTName());        }        for(String s:tmpList)        {            Log.i("s.indexOf(value)","s.indexOf(value)"+s.indexOf(value));            if (s.indexOf(value) >= 0) {                themeIDListView1= JsonTool.setProPerson(context, json, str, value);            }        }        if (value.equals("")){            themeIDListView1= JsonTool.setProData(context, json, str);        }        themeIDLVAdapter = new ThemeItemDetailsListViewAdapter(                ThemeWeedingActivity.this, themeIDListView1);        themeWeedingLv.setAdapter(themeIDLVAdapter);        themeWeedingLv.invalidateViews();    }}

第三步:对应的javaBean

ThemeItemView.java

package com.ncsyeyy.YeyyAdapterJSON;/** * Created by yeyy on 7/16/2015. */public class ThemeItemView {    private int id;    private String theme_icon;    private String tv_theme;    private String tv_detail;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getTheme_icon() {        return theme_icon;    }    public void setTheme_icon(String theme_icon) {        this.theme_icon = theme_icon;    }    public String getTv_theme() {        return tv_theme;    }    public void setTv_theme(String tv_theme) {        this.tv_theme = tv_theme;    }    public String getTv_detail() {        return tv_detail;    }    public void setTv_detail(String tv_detail) {        this.tv_detail = tv_detail;    }    public ThemeItemView() {    }}
ThemeItemDetailsListView.java

package com.ncsyeyy.YeyyAdapterJSON;import android.os.Parcel;import android.os.Parcelable;public class ThemeItemDetailsListView implements Parcelable {private String tvTName;private String ivTHead;private String ivTWorks;private int tvTDownloadNum;public ThemeItemDetailsListView() {}public String getTvTName() {return tvTName;}public void setTvTName(String tvTName) {this.tvTName = tvTName;}public String getIvTHead() {return ivTHead;}public void setIvTHead(String ivTHead) {this.ivTHead = ivTHead;}public String getIvTWorks() {return ivTWorks;}public void setIvTWorks(String ivTWorks) {this.ivTWorks = ivTWorks;}public int getTvTDownloadNum() {return tvTDownloadNum;}public void setTvTDownloadNum(int tvTDownloadNum) {this.tvTDownloadNum = tvTDownloadNum;}public static final Creator<ThemeItemDetailsListView>CREATOR = new Creator<ThemeItemDetailsListView>() {public ThemeItemDetailsListView createFromParcel(Parcel source) {ThemeItemDetailsListView themeDetailsListView = new ThemeItemDetailsListView();themeDetailsListView.tvTName = source.readString();themeDetailsListView.ivTHead = source.readString();themeDetailsListView.ivTWorks = source.readString();themeDetailsListView.tvTDownloadNum = source.readInt();return themeDetailsListView;}public ThemeItemDetailsListView[] newArray(int size) {return new ThemeItemDetailsListView[size];}};@Overridepublic int describeContents() {return 0;}@Overridepublic void writeToParcel(Parcel parcel, int flags) {parcel.writeString(tvTName);parcel.writeString(ivTHead);parcel.writeString(ivTWorks);parcel.writeInt(tvTDownloadNum);}}

第四步:对应adapter

ThemeListViewAdapter.java

package com.ncsyeyy.YeyyAdapterJSON;import android.content.Context;import android.content.Intent;import android.content.res.AssetManager;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.ImageView;import android.widget.TextView;import java.io.IOException;import java.io.InputStream;import java.util.ArrayList;/** * Created by yeyy on 7/16/2015. */public class ThemeListViewAdapter extends BaseAdapter {    private LayoutInflater mInflater = null;    private Context context;    private ArrayList<ThemeItemView> themeList;    private String fileName = "themeimage";    private String item_theme;    public ThemeListViewAdapter(Context context, LayoutInflater mInflater, ArrayList<ThemeItemView> themeList) {        this.context = context;        this.mInflater = mInflater;        this.themeList = themeList;    }    public ThemeListViewAdapter(Context context) {        this.mInflater = LayoutInflater.from(context);        notifyDataSetChanged();    }    public ThemeListViewAdapter(Context context, ArrayList<ThemeItemView> themeList) {        this.context = context;        this.mInflater = LayoutInflater.from(context);        this.themeList = themeList;        Log.i("as", themeList.size() + "");        notifyDataSetChanged();    }    @Override    public int getCount() {        if (themeList == null) {            return 0;        }        return themeList.size();    }    @Override    public Object getItem(int position) {        if (themeList == null) {            return null;        }        return position;    }    @Override    public long getItemId(int position) {        return position;    }    @Override    public View getView(final  int position, View convertView, ViewGroup parent) {        ViewHolder holder = null;        if (convertView == null) {            holder = new ViewHolder();            convertView = mInflater.inflate(R.layout.theme_item_listview, null);//布局填充器        }//        rl = (RelativeLayout) convertView.findViewById(R.id.theme_item_listview);        holder.theme_icon = (ImageView) convertView.findViewById(R.id.theme_head_portrait);        holder.tv_theme = (TextView) convertView.findViewById(R.id.theme_tv_name);        holder.tv_detail = (TextView) convertView.findViewById(R.id.theme_tv_content);        convertView.setTag(holder);        String item_theme1 = themeList.get(position).getTv_theme().toString();        String item_detail = themeList.get(position).getTv_detail();        String item_icon = themeList.get(position).getTheme_icon();        holder.tv_theme.setText(item_theme1);        holder.tv_detail.setText(item_detail);        String url = fileName + "/" + item_icon;//获取图片//        Log.i("url", url);        Bitmap bitmap = ReaderFileTool.getImageFromAssetsFile(context, url);//公共类解析图片,可以提出来反复使用,也可以如下面注释的一样写在///当前//        Log.i("123", bitmap.toString());        holder.theme_icon.setImageBitmap(bitmap);        //item适配器中跳转到activity,activity来接收        convertView.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                item_theme = themeList.get(position).getTv_theme().toString();//                String string=tv_theme.getText().toString();//空指针异常                Intent intent = new Intent();                intent.putExtra("title",item_theme);                intent.setClass(context, ThemeWeedingActivity.class);                context.startActivity(intent);            }        });        return convertView;    }//    private Bitmap getImageFromAssetsFile(String url) {////        Bitmap bitmap = null;//        AssetManager assetManager = context.getAssets();//        try {//            InputStream inputStream = assetManager.open(url);//            bitmap = BitmapFactory.decodeStream(inputStream);//            inputStream.close();//        } catch (IOException e) {//            e.printStackTrace();//        }//        Log.i("bitmap", bitmap + "");//        return bitmap;//    }    private class ViewHolder {        public TextView tv_theme;        public TextView tv_detail;        public ImageView theme_icon;    }}
ThemeItemDetailsListViewAdapter.java

package com.ncsyeyy.YeyyAdapterJSON;import android.content.Context;import android.content.Intent;import android.graphics.Bitmap;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.*;import java.util.ArrayList;/** * 婚庆作品列表view adapter,可下载 * Created by yeyy on 7/20/2015. */public class ThemeItemDetailsListViewAdapter extends BaseAdapter {    private LayoutInflater inflater;    private ArrayList<ThemeItemDetailsListView> themeIDListView;    private Context context;    private String fileName = "themeimage";    ImageView ivTHead;    TextView tvTName;    TextView tvTDownloadNum;    CheckBox ivTCollect;    ImageView ivTWorks;    public ThemeItemDetailsListViewAdapter(Context context,                                           ArrayList<ThemeItemDetailsListView> themeIDListView) {        this.context = context;        this.inflater = LayoutInflater.from(context);        this.themeIDListView = themeIDListView;        notifyDataSetChanged();    }    @Override    public int getCount() {        if (themeIDListView == null) {            return 0;        }        return themeIDListView.size();    }    @Override    public Object getItem(int position) {        if (themeIDListView == null) {            return null;        }        return position;    }    @Override    public long getItemId(int position) {        return position;    }    @Override    public View getView(int position, View convertView, ViewGroup parent) {        if (convertView == null) {            convertView = inflater.inflate(                    R.layout.theme_item_details, null);        }        ivTHead = (ImageView) convertView.findViewById(R.id.theme_item_details_head);        tvTName = (TextView) convertView.findViewById(R.id.theme_item_details_name);        tvTDownloadNum = (TextView) convertView.findViewById(R.id.theme_item_details_download_number_a);        ivTCollect = (CheckBox) convertView.findViewById(R.id.theme_item_details_collect);        final CheckBox checkBox = ivTCollect;//注意        ivTCollect.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                if (checkBox.isChecked()) {                    Toast.makeText(context, "收藏成功", Toast.LENGTH_SHORT).show();                } else {                    Toast.makeText(context, "取消收藏", Toast.LENGTH_SHORT).show();                }            }        });        ivTWorks = (ImageView) convertView.findViewById(R.id.theme_item_details_works);        String item_head = themeIDListView.get(position).getIvTHead();        String item_name = themeIDListView.get(position).getTvTName();        String item_works = themeIDListView.get(position).getIvTWorks();        int item_downloadNum = themeIDListView.get(position).getTvTDownloadNum();        tvTName.setText(item_name);        tvTDownloadNum.setText(item_downloadNum + "");//注意要转换成字符串        String url = fileName + "/" + item_head;        String url1 = fileName + "/" + item_works;        Bitmap bitmap = ReaderFileTool.getImageFromAssetsFile(context, url);        Bitmap bitmap1 = ReaderFileTool.getImageFromAssetsFile(context, url1);        ivTHead.setImageBitmap(bitmap);        ivTWorks.setImageBitmap(bitmap1);//点击主题内作品列表时可以分享出去        convertView.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                Intent sendIntent = new Intent();                sendIntent.setAction(Intent.ACTION_SEND);//调用系统软件分享                sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");                sendIntent.setType("text/plain");                context.startActivity(sendIntent);            }        });        return convertView;    }}
关于adapter

(1)获得布局文件中的控件findViewById,注意listview重复使用的问题

(2)找到布局文件的位置get,转换成字符串,String item_head = themeIDListView.get(position).getIvTHead();

(3)set内容进去,ivTHead.setImageBitmap(bitmap);


关于读取文件的json数据公共类,ReaderFileTool类

package com.ncsyeyy.YeyyAdapterJSON;import android.content.Context;import android.content.res.AssetManager;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.util.Log;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;/** * 读取文件的json数据公共类 * Created by yeyy on 7/20/2015. */public class ReaderFileTool { private static AssetManager manager=null;    public static String getLocalJson(Context context,String fileName){        manager = context.getAssets();        StringBuilder sBuilder = new StringBuilder();        try {            InputStream inputStream = manager.open(fileName);            BufferedReader reader = new BufferedReader(new InputStreamReader(                    inputStream));            String line = "";//?            while ((line = reader.readLine()) != null) {                sBuilder.append(line);            }        } catch (IOException e) {            e.printStackTrace();        }        return sBuilder.toString();    }//读取json图片转换成字符串    public static Bitmap getImageFromAssetsFile(Context context,String url){        Bitmap bitmap=null;        AssetManager assetManager=context.getAssets();        try {            InputStream inputStream=assetManager.open(url);            bitmap= BitmapFactory.decodeStream(inputStream);            inputStream.close();        } catch (IOException e) {            e.printStackTrace();        }        Log.i("bitmap",bitmap+"");        return bitmap;    }}
把json数据放进对应控件的公共类JsonTool类

package com.ncsyeyy.YeyyAdapterJSON;import android.content.Context;import android.content.res.AssetManager;import android.util.Log;import android.widget.Toast;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import java.util.ArrayList;/** * Created by yeyy on 7/20/2015. */public class JsonTool {    public static AssetManager manager;    private static ArrayList<ThemeItemView> themeList;    private static ArrayList<ThemeItemDetailsListView> themeIDListView;    public static ArrayList<ThemeItemView> setThemeData(Context context, String json) {        themeList = new ArrayList<ThemeItemView>();        try {            JSONObject jsonObject = new JSONObject(json);            JSONArray array = jsonObject.getJSONArray("theme");            for (int i = 0; i < array.length(); i++) {                JSONObject object = array.getJSONObject(i);                ThemeItemView themeItemView = new ThemeItemView();                themeItemView.setId(object.getInt("id"));                themeItemView.setTheme_icon(object.getString("theme_icon"));                themeItemView.setTv_theme(object.getString("tv_theme"));                themeItemView.setTv_detail(object.getString("tv_detail"));                themeList.add(themeItemView);            }        } catch (JSONException e) {            e.printStackTrace();        }        return themeList;    }    public static ArrayList<ThemeItemDetailsListView> setProData(Context context, String json, String str) {        try {            themeIDListView = new ArrayList<ThemeItemDetailsListView>();            JSONObject jsonObject = new JSONObject(json);            //把解析的json文件名写活            JSONArray array = jsonObject.getJSONArray(str);            for (int i = 0; i < array.length(); i++) {                JSONObject object = array.getJSONObject(i);                ThemeItemDetailsListView themeDetailsListView = new ThemeItemDetailsListView();                themeDetailsListView.setTvTName(object.getString("tvTName"));                themeDetailsListView.setIvTHead(object.getString("ivTHead"));                themeDetailsListView.setIvTWorks(object.getString("ivTWorks"));                themeDetailsListView.setTvTDownloadNum(object.getInt("tvTDownloadNum"));                themeIDListView.add(themeDetailsListView);            }        } catch (JSONException e) {            e.printStackTrace();        }        return themeIDListView;    }    public static ArrayList<ThemeItemDetailsListView> setProPerson(Context context, String json, String str,String name) {        try {            themeIDListView = new ArrayList<ThemeItemDetailsListView>();            JSONObject jsonObject = new JSONObject(json);            //把解析的json文件名写活            JSONArray array = jsonObject.getJSONArray(str);            for (int i = 0; i < array.length(); i++) {                JSONObject object = array.getJSONObject(i);                ThemeItemDetailsListView themeDetailsListView = new ThemeItemDetailsListView();                themeDetailsListView.setTvTName(object.getString("tvTName"));                themeDetailsListView.setIvTHead(object.getString("ivTHead"));                themeDetailsListView.setIvTWorks(object.getString("ivTWorks"));                themeDetailsListView.setTvTDownloadNum(object.getInt("tvTDownloadNum"));                Log.i("themeDetailsListView.getTvTName()",themeDetailsListView.getTvTName());                Log.i("name",name);                if(themeDetailsListView.getTvTName().equals(name)){                    themeIDListView.add(themeDetailsListView);                }else {                    Toast.makeText(context,"没有你要查询的名字!", Toast.LENGTH_LONG).show();                }            }        } catch (JSONException e) {            e.printStackTrace();        }        return themeIDListView;    }
解析对象,上面两种解析数组,注意不同之处//    public static MeView setMeData(Context context,String json){//        MeView meV=new MeView();//        try {//            JSONObject jsonObject=new JSONObject(json);//              JSONObject object=jsonObject.getJSONObject("user");//                meV.setId(object.getInt("id"));//                meV.setMe_head(object.getString("me_head"));//                meV.setMe_point(object.getInt("me_point"));//                meV.setMe_download(object.getInt("me_download"));//                meV.setMe_collect(object.getInt("me_collect"));//        } catch (JSONException e) {//            e.printStackTrace();//        }//        return meV;//    }}


代码仍有不完善的地方,大家互相学习进步了

源码下载地址:http://download.csdn.net/detail/csdnyuandaimaxuexi/8986007



































1 0
原创粉丝点击