码迷,mamicode.com
首页 > 移动开发 > 详细

[Android学习系列16]Android把php输出的json加载到listview

时间:2014-04-30 20:19:42      阅读:684      评论:0      收藏:0      [点我收藏+]

标签:android   com   http   blog   style   class   div   img   code   java   c   

首先写个php脚本输出json,注意,还要输出回车,方便android的bufferreader读取一行 

bubuko.com,布布扣
<?php

    class Book {
        public $bookid;
        public $bookname;
        public $bookinfo;
        
        function __construct($id,$name,$info ){
            $this->bookid = $id;
            $this->bookname = $name;
            $this->bookinfo = $info;
        }
    }
    
    $book1 = new Book("1","高等数学","一本好书");
    $book2 = new Book("2","呵呵呵呵","一本好书");
    $book3 = new Book("3","哈哈哈哈","一本好书");
    
    
    
    //把对象转成json 输出
    echo json_encode($book1);
    echo "\r\n";
    echo json_encode($book2);
    echo "\r\n";
    echo json_encode($book3);
    echo "\r\n";
    
?>
View Code

 

然后在android的客户端,用子线程发送http请求获取数据,然后发消息给主线程的handler更新listview

listview的一行的样式  one_item.xml  :

bubuko.com,布布扣
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <TextView 
        android:id="@+id/textview"
        android:gravity="center"
        android:textColor="#000000"
        android:layout_width="fill_parent"
        android:layout_height="30dp"/>

</LinearLayout>
View Code

 

activity的java代码:

bubuko.com,布布扣
//搞了我半天,整个流程应该是这样的
//因为http获取json的数据 写到一个新线程里  new thread ( runnableUi )
//在新线程runnableUi里,有一个initDataAndAdapter() 用来获得网络数据 放进listbook,获取完后发消息给 主线程的handler
//handler收到消息后, 把数据源listbook 传给  listview 的adapter (即更新主线程界面)

public class MainActivity extends Activity {
    
    List<Book> listBook;
    ListView listView;
    
    
    // 构建Runnable对象,在runnable中更新界面  
    Runnable runnableUi = new Runnable(){  
        @Override  
        public void run() {  
            
            initDataAndAdapter();
        }  
          
    };  
    
    //主线程的handler,  http请求获得数据后 会调用这个主线程的handler  来修改主线程界面(绑定listview的adapter)
    Handler handler = new Handler(){
        
        public void handleMessage(Message msg) {
            
            //在主线程的handler里    修改listview的适配器
            listView.setAdapter(new MyListAdapter(getApplicationContext(), listBook ));
            
        };
        
    };
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        listView = (ListView)findViewById(R.id.listView1);
        listBook = new ArrayList<Book>();
        
        
        new Thread( runnableUi ).start();
    
        
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    
    
    public void initDataAndAdapter() {
        
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("http://taobibi.kuphp.net/");
        Book book;
        
        try {
            
            HttpResponse httpResponse = httpClient.execute(httpGet);
            BufferedReader bufferReader = new BufferedReader( new InputStreamReader( httpResponse.getEntity().getContent() ) );
            
            for(String s = bufferReader.readLine(); s != null; s = bufferReader.readLine())
            {
                //每行为一个json对象
                JSONObject jsonObject = new JSONObject( s );
                Log.v("mytag", s);
                
                //然后放进book对象
                book = new Book();
                book.bookId = jsonObject.getString("bookid");
                book.bookName = jsonObject.getString("bookname");
                book.bookInfo = jsonObject.getString("bookinfo");
                
                //然后把book放进list
                listBook.add(book);

            }
            
            
            
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
        //数据全都接收到listView以后,发消息给主线程里面的handler,让他去修改listview 的  setadapter
        handler.sendEmptyMessage(0);
        
    }
    
    
    

    
    class Book {
        String bookId;
        String bookName;
        String bookInfo;
    }
    
    
    class MyListAdapter extends BaseAdapter {
        
        Context context;
        List<Book> listBook;

        MyListAdapter(Context con , List<Book> list ) {
            this.context = con;
            listBook = (ArrayList<Book>)list;
            
        }
        
        @Override
        public int getCount() {
            return listBook.size();
        }

        @Override
        public Object getItem(int arg0) {
            return arg0;
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            
            LayoutInflater inflator = LayoutInflater.from(context);
            View oneView = inflator.inflate(R.layout.one_item, null);
            TextView textView = (TextView)oneView.findViewById(R.id.textview);
            
            String str = listBook.get(position).bookId  + " " + listBook.get(position).bookName + " " +  listBook.get(position).bookInfo; 
            textView.setText( str );
            
            return oneView;
        }
        
    }

}
View Code

 

 

 

 

参考:

解决NetworkOnMainThreadException    

http://www.aitinan.com/4387.html

Android访问php取回json数据       

http://www.oschina.net/code/snippet_12_1122

http://blog.csdn.net/djx123456/article/details/6325983

 

[Android学习系列16]Android把php输出的json加载到listview,布布扣,bubuko.com

[Android学习系列16]Android把php输出的json加载到listview

标签:android   com   http   blog   style   class   div   img   code   java   c   

原文地址:http://www.cnblogs.com/sleeptothedeath/p/3699023.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有
迷上了代码!