`
zhengdl126
  • 浏览: 2543244 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类

收藏列表实例【ViewSwitcher+Thread+JSONObject ++handler+Adapter】

 
阅读更多

 

 

layout_favorite_list.xml

 



 

 


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:background="@color/listcolor"

    android:orientation="vertical" >

   

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

   

    <FrameLayout

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:orientation="vertical" >

 

        <ViewSwitcher

            android:id="@+id/viewswitcher_news_top"

            android:layout_width="match_parent"

            android:layout_height="match_parent"

            android:layout_gravity="center" >

        </ViewSwitcher>

 

        <ListView

            android:id="@+id/favorite_list"

            android:layout_width="match_parent"

            android:layout_height="match_parent"

            android:cacheColorHint="@color/transparent"

            android:divider="@drawable/tip_line" />

    </FrameLayout>

 

</LinearLayout>

 

 

 

 

FavoriteActivityList.java

 

 

 

package com.cps.media.ui.favorite;

 

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.List;

 

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

import org.json.JSONArray;

import org.json.JSONObject;

 

import com.cps.media.R;

import com.cps.media.model.ExhibitorItem;

import com.cps.media.model.FavoriteItem;

import com.cps.media.model.NewsItem;

import com.cps.media.ui.PopupWindowImageButton;

import com.cps.media.ui.account.AccountManager;

import com.cps.media.ui.exhibitors.ExhibitorActivity;

import com.cps.media.ui.news.NewsContainerActivity;

import com.cps.media.util.CONST;

import com.cps.media.util.Util;

 

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.os.Handler;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.ViewGroup;

import android.widget.AdapterView;

import android.widget.BaseAdapter;

import android.widget.ImageButton;

import android.widget.ListView;

import android.widget.TextView;

import android.widget.ViewSwitcher;

import android.widget.AdapterView.OnItemClickListener;

 

publicclass FavoriteActivityList extends Activity implements OnClickListener{

   

    publicstatic String NEWS_TITLE = "title";

    publicstatic String NEWS_TYPE = "type";

   

    private ListView mList;

   

    private List<FavoriteItem> mFavoriteList;

   

    private ItemAdapter mAdapter;

 

    private ViewSwitcher viewSwitcher;

 

    private ImageButton mBackImageButton;

 

    private TextView mTitleTextView;

   

    privateintmMode;

   

    private PopupWindowImageButton mMenuImageButton;

 

    @Override

    protectedvoid onCreate(Bundle savedInstanceState) {

       // TODO Auto-generated method stub

       super.onCreate(savedInstanceState);

       setContentView(R.layout.layout_favorite_list);

      

       mList = (ListView) findViewById(R.id.favorite_list);

      

       viewSwitcher = (ViewSwitcher) findViewById(R.id.viewswitcher_news_top);

       viewSwitcher.addView(getLayoutInflater().inflate(

              R.layout.layout_progress_page, null));

 

       mBackImageButton = (ImageButton) findViewById(R.id.btn_newscontent_back);

       mBackImageButton.setOnClickListener(this);

 

       mMenuImageButton = (PopupWindowImageButton) findViewById(R.id.header_menu);

 

       mTitleTextView = (TextView) findViewById(R.id.new_header_title);

        mTitleTextView.setText(getIntent().getIntExtra(NEWS_TITLE, R.string.news_top_left_text));

       mMode = getIntent().getIntExtra(NEWS_TYPE, Util.FAVORITE_NEWS);

       requestData();

    }

   

    @Override

    protectedvoid onResume() {

       // TODO Auto-generated method stub

       super.onResume();

       mMenuImageButton.reload(Util.SHOW_FAVORITE);

    }

   

    privateOnItemClickListenerlistener = new OnItemClickListener() {

 

       @Override

       public void onItemClick(AdapterView<?> parent, View view, int position,

              long id) {

           Intent intent = null;

           if(mMode == Util.FAVORITE_NEWS){

              intent = new Intent(FavoriteActivityList.this,

                     NewsContainerActivity.class);

              NewsItem item = new NewsItem();

              item.setId(mFavoriteList.get(position).getCid());

              item.setNewsType(mFavoriteList.get(position).getSrc_type());

              item.setTitle(mFavoriteList.get(position).getTitle());

              intent.putExtra("news_item", item);

              startActivityForResult(intent, 0);

           }elseif(mMode == Util.FAVORITE_EXHIBITOR){

              intent = new Intent(FavoriteActivityList.this,

                     ExhibitorActivity.class);

              ExhibitorItem item = new ExhibitorItem();

              item.setId(mFavoriteList.get(position).getCid());

              item.setName(mFavoriteList.get(position).getTitle());

              intent.putExtra("exhibitor_item", item);

              startActivityForResult(intent,0);

           }

       }

    };

   

    protectedvoid onActivityResult(int requestCode, int resultCode, Intent data) {

       switch (requestCode) {

       case 0:

           requestData();

           break;

 

       default:

           break;

       }

    }

   

    privatevoid requestData() {

       viewSwitcher.setVisibility(View.VISIBLE);

       viewSwitcher.showNext();

       Thread t = new Thread() {

           @Override

           publicvoid run() {

              super.run();

              HttpClient client = new DefaultHttpClient();

              StringBuilder builder = new StringBuilder();

              int error = 1;

              JSONArray array = null;

              HttpGet myget = null;

              if (getIntent().getIntExtra(NEWS_TYPE, Util.FAVORITE_NEWS) == Util.FAVORITE_NEWS) {

                  myget = new HttpGet(CONST.URL_FAVORIT_LIST

                         .replace("{0}", "english")

                         .replace("{1}", "favorList")

                         .replace("{2}", Util.FAVORITE_NEWS+"")

                         .replace(

                                "{3}",

                                AccountManager.getInstance().getAccount()

                                       .getId()

                                       + ""));

              } else {

                  myget = new HttpGet(CONST.URL_FAVORIT_LIST

                         .replace("{0}", "english")

                         .replace("{1}", "favorList")

                         .replace("{2}", Util.FAVORITE_EXHIBITOR+"")

                         .replace(

                                "{3}",

                                AccountManager.getInstance().getAccount()

                                       .getId()

                                       + ""));

              }

              try {

                  HttpResponse response = client.execute(myget);

                  BufferedReader reader = new BufferedReader(

                         new InputStreamReader(response.getEntity()

                                .getContent()));

                  for (String s = reader.readLine(); s != null; s = reader

                         .readLine()) {

                     builder.append(s);

                  }

                  JSONObject jsonObject = new JSONObject(builder.toString());

                  error = jsonObject.getInt("errno");

                  String errormsg = jsonObject.getString("errmsg");

                  Log.v("wgp",myget.getURI().toString());

                  Log.v("wgp", "error=" + error);

                  Log.v("wgp", "errormsg=" + errormsg);

                  if (error == 0) {

                     array = jsonObject.getJSONArray("data");

                     mFavoriteList = new ArrayList<FavoriteItem>();

                     FavoriteItem item = null;

                     String srcType;

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

                         item = new FavoriteItem();

                         item.setId(array.getJSONObject(i).getInt("id"));

                         item.setUserId(array.getJSONObject(i).getInt("userid"));

                         item.setUsername(array.getJSONObject(i).getString("username"));

                         item.setType(array.getJSONObject(i).getInt("type"));

                         item.setCid(array.getJSONObject(i).getInt("cid"));

                         item.setTitle(array.getJSONObject(i).getString("title"));

                         item.setUrl(array.getJSONObject(i).getString("url"));

                         item.setTag(array.getJSONObject(i).getString("tag"));

                         item.setSrc(array.getJSONObject(i).getString("src"));

                         item.setCreateDate(array.getJSONObject(i).getString("created"));

                         item.setModifiedDate(array.getJSONObject(i).getString("modified"));

                         srcType = array.getJSONObject(i).getString("src_type");

                         if(srcType != null && srcType.equals("cps")){

                            item.setSrc_type("industry");

                         }else{

                            item.setSrc_type(srcType);

                         }

                         mFavoriteList.add(item);

                     }

                     if (mFavoriteList.size() == 0) {

                         handler.sendEmptyMessage(-1);

                     } else {

                         handler.sendEmptyMessage(1);

                     }

                  }

              } catch (Exception e) {

                  e.printStackTrace();

                  handler.sendEmptyMessage(-1);

              } finally {

              }

           }

       };

        t.start();

    }

   

    Handler handler = new Handler() {

       publicvoid handleMessage(android.os.Message msg) {

           if (msg.what == 1) {

              mAdapter = new ItemAdapter();

              mList.setAdapter(mAdapter);

              mList.setOnItemClickListener(listener);

           }

           viewSwitcher.setVisibility(View.INVISIBLE);

       };

    };

   

    class ItemAdapter extends BaseAdapter {

 

       private ViewHolder holder;

 

       @Override

       publicint getCount() {

           return mFavoriteList.size();

       }

 

       @Override

       public Object getItem(int location) {

           returnmFavoriteList.get(location);

       }

 

       @Override

       publiclong getItemId(int location) {

           returnmFavoriteList.get(location).getId();

       }

 

       @Override

       public View getView(int position, View convertView, ViewGroup parent) {

 

           try {

              if (convertView == null) {

                  holder = new ViewHolder();

                  convertView = getLayoutInflater().inflate(

                         R.layout.layout_favorite_list_item, null);

                  holder.title = (TextView) convertView

                         .findViewById(R.id.favorite_title);

                  convertView.setTag(holder);

              } else {

                  holder = (ViewHolder) convertView.getTag();

              }

              holder.title.setText(mFavoriteList.get(position).getTitle());

           } catch (Exception e) {

              e.printStackTrace();

           }

           return convertView;

 

       }

 

       class ViewHolder {

           TextView title;

       }

    }

 

    @Override

    publicvoid onClick(View v) {

       int id = v.getId();

       switch (id) {

       case R.id.btn_newscontent_back:

           backKey();

           break;

 

       default:

           break;

       }

    }

   

    privatevoid backKey() {

       setResult(RESULT_OK);

       finish();

       getParent().overridePendingTransition(R.anim.news_dync_in_from_left,

              R.anim.news_dync_out_to_right);

    }

 

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 大小: 15.5 KB
分享到:
评论

相关推荐

    用Delphi XE7 Indy写的微信公众平台示例

    temp := JSONObject.Values['subscribe'].ToString; Memo1.Lines.Add('subscribe:' + temp); temp := JSONObject.Values['openid'].ToString; Memo1.Lines.Add('openid:' + temp); temp := JSONObject.Values['...

    jsonobject

    `JSONObject`是Java中处理JSON的一种常见工具,它允许我们创建、解析和操作JSON对象。在Java中,`JSONObject`是org.json库的一部分,这个库提供了处理JSON的各种功能。 `JSONObject`类是用于表示JSON对象的Java类。...

    JsonObject

    `JsonObject`是一个在Java开发中常用的JSON处理库,主要用于创建、解析和操作JSON对象。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它易于人阅读和编写,同时也易于机器解析和生成。在Java中,...

    JSONObject对象依赖的jar包

    JSONObject jsonObject = new JSONObject(); jsonObject.put("name", "John"); jsonObject.put("age", 30); String jsonString = jsonObject.toString(); ``` 此外,`JSONObject`还支持从JSON字符串反序列化到Java...

    org.json.JSONObject引用依赖包

    在Java编程中,`org.json.JSONObject` 是一个广泛使用的库,用于处理JSON...例如,你可以使用`new JSONObject(new FileReader("56c8c605946e4cb1a6f53f16fe7a7f9e"))`来读取并转换文件内容为一个JSONObject实例。

    jsonobject.zip

    这个“jsonobject.zip”压缩包很可能包含了使用JSONObject所需的全部依赖库,确保你能在Java项目中正确地导入和使用JSONObject类。 为了在Java中使用JSONObject,首先你需要了解JSON的基本结构。JSON数据由键值对...

    JAVA JSONObject Jar包

    在Java中,处理JSON数据时,一个常用的库是`JSONObject`,它来自于org.json包。这个`JAVA JSONObject Jar包`包含了处理JSON对象所需的类和方法。 JSONObject是org.json库中的核心类,它允许我们创建、读取和修改...

    JSONObject所必须的jar包

    在Java编程环境中,JSONObject是一个非常常用的库,它用于处理JSON(JavaScript Object Notation)数据格式。JSON是一种轻量级的数据交换格式,易于人阅读和编写,同时也方便机器解析和生成。当你在Java项目中需要与...

    JSONObject相关依赖架包

    在Java开发中,JSON(JavaScript Object Notation)是一种轻量级的数据交换...这样,你就可以在代码中调用如`JSONArray.parseArray(String json)`、`JSONObject.fromObject(Object obj)`等方法,轻松地进行JSON操作了。

    创建JSONObject的四个常用方法

    通过调用`JSONObject`的构造器来创建一个新的`JSONObject`实例,并使用`element`方法添加键值对到该对象中。 **示例1**: ```java JSONObject jsonObject = new JSONObject(); jsonObject.element("name", ""); ...

    json.jar(JSONObject)

    4. 从JSON字符串解析:使用`JSONObject(String)`构造函数或`JSONObject.parseObject(String)`静态方法将JSON字符串转换为`JSONObject`。例如: ```java String jsonString = "{\"name\":\"John\",\"age\":30}"; ...

    JsonObject(免分)

    JsonObject是Java语言中的一种数据处理类,主要用于处理JSON(JavaScript Object Notation)格式的数据。JSON是一种轻量级的数据交换格式,它易于人阅读和编写,同时也易于机器解析和生成。在Java中,JsonObject通常...

    JSONOBJECT+SERVLET-API所需架包

    JSONOBJECT和SERVLET-API是Java开发中两个关键的组件,它们在构建Web应用程序时起着至关重要的作用。本文将详细介绍这两个概念以及相关的知识点。 **JSONOBJECT** JSON(JavaScript Object Notation)是一种轻量级...

    JSONObject及依赖的jar包

    在Java中,`JSONObject`是JSON-P(Java API for JSON Processing)规范的一个实现,由org.json库提供,它允许开发者将Java对象转换为JSON格式,以及将JSON数据转换回Java对象。 `JSONObject`类是处理JSON对象的核心...

    解决net.sf.json.JSONObject

    可以通过构造函数创建一个空的JSONObject,或者直接从一个Map实例转换而来。例如: ```java Map, Object&gt; map = new HashMap(); map.put("name", "John"); map.put("age", 30); JSONObject jsonObject = ...

    org.json.JSONObject 包下载

    `org.json.JSONObject`是Java编程语言中用于处理JSON(JavaScript Object Notation)数据的一个轻量级库。这个库由Mozilla Public License提供,广泛应用于需要在Java应用中进行JSON解析、生成和操作的场景。JSON是...

    使用JsonObject所需要的jar包

    在Java编程环境中, JsonObject是Java JSON处理库Gson的一个关键组件。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,广泛用于Web服务和应用程序之间的数据传输。Gson库由Google开发,允许我们将...

Global site tag (gtag.js) - Google Analytics