zoukankan      html  css  js  c++  java
  • android:通过url向网络端获取json格式数据并解析显示

    第一步:通过httpclient向网络端获取到数据 返回jsonobject格式的数据

    用到的对象:httpClient联网 httpget or httppost通过地址发出请求

     httpresponse 接收idao返回数据 response.getEntity() EntityUtils进行字符串的处理

    jsonobject进行数据的封装

    第二部:定义方法进行相应的解析 

    解析数据 一般如果不只是一组数据 要用到jsonArray 通过jsonobject的getJSONArray()得到

    通过对array的遍历 根据元素名称取出各组相应的数据

    第三部:得到数据 并且进行填充

    得到各个需要填充的空间 根据各自的方法进行数据的填充

    布局文件:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <TableLayout
            android:id="@+id/info"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:padding="10dip"
            android:shrinkColumns="2"
            android:stretchColumns="2" >

            <TableRow android:background="@drawable/xx" >

                <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="40dp"
                    android:layout_marginLeft="5dip"
                    android:gravity="center_vertical"
                    android:text="姓名"
                    android:textColor="#424242"
                    android:textSize="18dp" />

                <EditText
                    android:id="@+id/name"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="25dip"
                    android:layout_marginLeft="20dip"
                    android:layout_marginRight="10dip"
                    android:background="@android:color/white"
                    android:gravity="top|left"
                    android:hint="点击输入"
                    android:textColor="#5c5c5c"
                    android:textSize="16dp" />
            </TableRow>

            <TableRow android:background="@drawable/xx" >

                <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="40dp"
                    android:layout_marginLeft="5dip"
                    android:gravity="center_vertical"
                    android:text="电话"
                    android:textColor="#424242"
                    android:textSize="18dp" />

                <EditText
                    android:id="@+id/usermobile"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="25dip"
                    android:layout_marginLeft="20dip"
                    android:layout_marginRight="10dip"
                    android:background="@android:color/white"
                    android:gravity="top|left"
                    android:hint="点击输入"
                    android:textColor="#5c5c5c"
                    android:textSize="16dp" >

                    <requestFocus />
                </EditText>
            </TableRow>

            <TableRow android:background="@drawable/xx" >

                <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="40dp"
                    android:layout_marginLeft="5dip"
                    android:gravity="center_vertical"
                    android:text="手机"
                    android:textColor="#424242"
                    android:textSize="18dp" />

                <EditText
                    android:id="@+id/userphone"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="25dip"
                    android:layout_marginLeft="20dip"
                    android:layout_marginRight="10dip"
                    android:background="@android:color/white"
                    android:gravity="top|left"
                    android:hint="点击输入"
                    android:textColor="#5c5c5c"
                    android:textSize="16dp" />
            </TableRow>
        </TableLayout>

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="填充数据" />

    </LinearLayout>

    主类:

    public class HttpActivity extends Activity {
     EditText username;
     EditText userorder;
     EditText userphone;

     public static String name;
     public static String phone;
     public static String ordernum;

     Button get;
     String url;

     @Override
     public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      username = (EditText) findViewById(R.id.name);
      userorder = (EditText) findViewById(R.id.usermobile);
      userphone = (EditText) findViewById(R.id.userphone);
      get = (Button) findViewById(R.id.button);
      url = "http://192.168.1.80:9090/ME3/jsp/token/sellexit.jsp";
      get.setOnClickListener(new OnClickListener() {

       @Override
       public void onClick(View v) {
        try {
         JSONObject jsonObject=doGet(url);
         Log.i("HttpActivity001", jsonObject.toString());
         JSONArray array = jsonObject.getJSONArray("data");
         for (int i = 0; i < array.length(); i++) {
          
          JSONObject jsonItem = array.getJSONObject(i);
          name=(String) jsonItem.get("username");
          ordernum=(String) jsonItem.get("ordernum");
          phone=(String) jsonItem.get("phonenum");
          Log.i("HttpActivity", name);
         }
         username.setText(name);
         userorder.setText(ordernum);
         userphone.setText(phone);
        } catch (Exception e) {
         // TODO: handle exception
        }
        // TODO Auto-generated method stub
        
       }
      });

     }

    网络连接获取数据:

     public static JSONObject doGet(String url) {
      try {
       String result = null;
       DefaultHttpClient httpClient = new DefaultHttpClient();

       HttpGet request = new HttpGet(url);
       HttpResponse response = httpClient.execute(request);
       result = EntityUtils.toString(response.getEntity());
       JSONObject object = new JSONObject(result);
       Log.i("HttpActivity", result);
       return object;
                   
      } catch (Exception e) {
       // TODO: handle exception
      }
      return null;

     }

    }

    得到数据,解析:

    public class JsonParser {

    public static ListVideoEntity parse(String returnData) {

    // String returnData = returnData();

    ListVideoEntity lve = new ListVideoEntity();

    try {

    JSONObject jsonObject = new JSONObject(returnData);

    String next = jsonObject.optString("next");

    if (next == null || "".equals(next)) {

    lve.setNext("0");

    }

    lve.setNext(next);

    JSONArray jsonArray = new JSONArray(jsonObject.optString("videos"));

    List<VideoEntity> feList = new ArrayList<VideoEntity>();

    for (int i = 0; i < jsonArray.length(); i++) {

    JSONObject itemObject = (JSONObject) jsonArray.opt(i);

    VideoEntity fe = new VideoEntity();

    //Log.d("D", "解析第:" + i + "条记录");

    fe.setId(itemObject.getString("id"));

    fe.setTitle(itemObject.getString("title"));

    fe.setPlayurl(itemObject.getString("playurl"));

    fe.setPlaytimes(itemObject.getString("playtimes"));

    fe.setDescription(itemObject.getString("description"));

    fe.setDuration(itemObject.getString("duration"));

    fe.setChannel(itemObject.getString("channel"));

    fe.setThumbnail(itemObject.getString("thumbnail"));

    feList.add(fe);

    }

    lve.setVeList(feList);

    } catch (Exception e) {

    e.printStackTrace();

    }

    return lve;

    }

    }

    解析完成就可以进行展示
     
    public void showData(List<VideoEntity> returnData) {
    if (returnData != null && returnData.size() > 0) {
    Log.d("D", "returnData:" + returnData.size());
    listData.addAll(returnData);
    if (init) {
    init = false;
    adapter = new MyAdapter(getApplicationContext(), listview,
    R.layout.loading, listData);
    listview.setAdapter(adapter);
    } else {
    adapter.notifyDataSetChanged();
    listview.moreDataloadComplete();
    }
    } else {
    Toast.makeText(getApplicationContext(), "没有请求到数据",
    Toast.LENGTH_SHORT).show();
    }
    bntSwitch = true;
    moreSwitch = true;
    }
     
     
    public class MyAdapter extends ArrayAdapter<VideoEntity> {
    private BaseListView solpListView;
    // 所有的要加载的数据数量
    public Context context; 
    private List<VideoEntity> datas;
    private AsyncImageLoader imageloader;
     
    public MyAdapter(Context context, BaseListView listView, int ResourceId,
    List<VideoEntity> datas) {
    super(context, 0, datas);
    this.context = context;
    solpListView = listView;
    this.datas = datas;
    imageloader = new AsyncImageLoader();
    }
     
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;
    VideoEntity video = datas.get(position);
    if (convertView == null) {
    holder = new ViewHolder();
    convertView = LayoutInflater.from(context).inflate(
    R.layout.videoitem, null);
    holder.title = (TextView) convertView.findViewById(R.id.title);
    holder.nailImageView = (ImageView) convertView
    .findViewById(R.id.image);
     
    holder.playtimes = (TextView) convertView
    .findViewById(R.id.playtimes);
    holder.duration = (TextView) convertView
    .findViewById(R.id.durationnum);
    convertView.setTag(holder);
    } else {
    holder = (ViewHolder) convertView.getTag();
    }
    VideoEntity ve = getItem(position);
    // 获取图片的URL
    String imageUrl = ve.getThumbnail();
    // 获取图片的VIEW
    ImageView imageView = holder.nailImageView;
    imageView.setTag(imageUrl);
     
    // 利用接口回调加载图片
    Drawable cachedImage = imageloader.loadDrawable(imageUrl,
    new AsyncImageLoader.ImageCallback() {
    public void imageLoaded(Drawable drawable, String imageUrl) {
    ImageView imageViewByTag = (ImageView) solpListView
    .findViewWithTag(imageUrl);
    if (imageViewByTag != null && drawable != null) {
    imageViewByTag.setImageDrawable(drawable);
    }
    }
    });
    if (cachedImage == null) {
    // 添加默认图片
    imageView.setImageResource(R.drawable.aa);
    } else {
    imageView.setImageDrawable(cachedImage);
    }
    holder.title.setText(video.getTitle());
    holder.playtimes.setText(video.getPlaytimes());
    String Duration = video.getDuration();
    holder.duration.setText(Utils.formatDuration(Duration));
     
    return convertView;
    }
    public class ViewHolder {
    TextView title;
    ImageView nailImageView;
    TextView playtimes;
    TextView duration;
    }
  • 相关阅读:
    7.29随堂笔记
    LeetCode77. 组合
    347. 前 K 个高频元素
    LeetCode239. 滑动窗口最大值
    C++_数字字符串互相转换
    LeetCode150. 逆波兰表达式求值
    LeetCode1047. 删除字符串中的所有相邻重复项
    LeetCode20. 有效的括号
    Leetcode225. 用队列实现栈 && LeetCode232. 用栈实现队列
    leetCode5663. 找出第 K 大的异或坐标值
  • 原文地址:https://www.cnblogs.com/qingblog/p/2528687.html
Copyright © 2011-2022 走看看