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


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

    <?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 "
    ";
        echo json_encode($book2);
        echo "
    ";
        echo json_encode($book3);
        echo "
    ";
        
    ?>
    View Code

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

    listview的一行的样式  one_item.xml  :

    <?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代码:

    //搞了我半天,整个流程应该是这样的
    //因为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

  • 相关阅读:
    确定比赛名次
    What Are You Talking About
    小兔的棋盘
    How Many Answers Are Wrong
    备份当前的ubuntu系统生成iso
    eclipse导入maven项目有时出现web.xml is missing的问题
    eclipse自动添加版权信息
    javac不是内部或外部命令
    linux目录权限
    python import error:no module named yaml
  • 原文地址:https://www.cnblogs.com/sleeptothedeath/p/3699023.html
Copyright © 2020-2023  润新知