解决方案 »

  1.   

    这个得看异常啊,代码的话看看这块:
    for(int i=0; i<channelList.length();i++){
                                JSONObject channel = (JSONObject)channelList.opt(i); 
                                HashMap<String, Category> hash = new HashMap<String, Category>();
                                Category c = new Category();
                                c.setCid(Integer.parseInt(channel.getString("ID")));
                                c.setTitle(channel.getString("name"));
                                hash.put("category_title", c);
                                categories.add(hash);
                                System.out.println("-->ID:"+channel.getString("ID")+"|NAME:"+channel.getString("name"));
                            }其中Category  能不能在doInBackground()里边set...?还有就是那个Integer.parseInt会不会有异常,是否需要处理。
      

  2.   

    133行,CustomSimpleAdapter categoryAdapter =new CustomSimpleAdapter(MainActivity.this, sb, R.layout.category_title, new String[]{"category_title"}, new int[]{R.id.category_title});
    这句代码你看看有没问题,得到的是否为空
      

  3.   

    doInBackground ()是耗时操作,onPostExecute()是绑定数据的吧。我页面加载数据就过来。 不要单击事件。怎么弄好?
      

  4.   

    调试下看看categoryAdapter是否为空
      

  5.   

    如上面所说,应该是Adapter里调用layout出了问题,也许与你传入的context有关。
    如果是我写这样的功能,我会写一个service里开线程(或加入线程池管理)来进行http request下载图片,然后通过handler或发广播的方法通知UI更新,这样不会在下载逻辑中过多的有UI相关的东西。个人感觉AsyncTask适用于简单的一来一往http request。 
      

  6.   


    package com.example;import java.io.BufferedReader;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;import org.json.JSONArray;
    import org.json.JSONObject;import android.app.Activity;
    import android.graphics.Color;
    import android.graphics.drawable.ColorDrawable;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Gravity;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.ViewGroup.LayoutParams;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.Button;
    import android.widget.GridView;
    import android.widget.LinearLayout;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.TextView;import com.example.entity.Category;
    import com.example.util.StringUtil;
    import com.example.widget.CustomSimpleAdapter;public class MainActivity extends Activity {
        private HttpURLConnection conn; 
        private URL url;
        private InputStream is;
        private static final String TAG = "ASYNC_TASK";
        private GridView category ;
    private final int COLUNMN_WIDTH_PX = 55;
    private  List<HashMap<String, Category>> categories;
    private int CHANNELID;
    private int ARTICLEID;
    private int columnWidth;
    private ListView  orderlistview;
    //private Category category; 
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            columnWidth = StringUtil.px2dip(this, 55);
            setContentView(R.layout.activity_main);
            final List<HashMap<String, Category>> categories = new ArrayList<HashMap<String,Category>>();
            category = new GridView(this);
    category.setNumColumns(GridView.AUTO_FIT);
    int width = categories.size()*columnWidth;
    category.setGravity(Gravity.CENTER);
    //重绘按钮背景色
    category.setSelector(new ColorDrawable(Color.TRANSPARENT));
    //设置gridView单元格的width
    category.setColumnWidth(columnWidth);
    //根据栏目或类型个数计算gridView的width

    /**创建GridView 的布局参数*/
      LayoutParams params = new LayoutParams(width,LayoutParams.MATCH_PARENT);
    //设置GridView布局参数 
    category.setLayoutParams(params);
    //重绘按钮背景色
    category.setSelector(new ColorDrawable(Color.TRANSPARENT));
    LinearLayout categoryLayout = (LinearLayout)findViewById(R.id.category_layout);
         categoryLayout.addView(category);
      new DownloadImageTask().execute();

        }
         private class DownloadImageTask extends AsyncTask<String, Void, List<HashMap<String, Category>> >{
             //将在onPreExecute 方法执行后马上执行,该方法运行在后台线程中。这里将主要负责执行那些很耗时的后台计算工作
                protected List<HashMap<String, Category>> doInBackground(String...  urls) {
                 Log.i("TAG", "doInbackGround 执行了。 ");
         String  urlDate="http://192.168.1.135:8080/cms/test/NewFile.jsp";
         System.out.println("3333333222");
         List<HashMap<String, Category>> dd=null;
         try {
         url=new URL(urlDate);
         try {
         conn=(HttpURLConnection) url.openConnection();
         conn.connect();
         conn.setConnectTimeout(6*1000);
         if (conn.getResponseCode() != 200)
         throw new RuntimeException("请求url失败");
         is=conn.getInputStream();
          JSONObject jsonArray=parseJSON(is);
          JSONArray channelList= jsonArray.getJSONArray("channelList");
         for(int i=0; i<channelList.length();i++){
         JSONObject channel = (JSONObject)channelList.opt(i); 
         HashMap<String, Category> hash = new HashMap<String, Category>();
         Category c = new Category();
         c.setCid(Integer.parseInt(channel.getString("ID")));
         c.setTitle(channel.getString("name"));
         hash.put("category_title", c);
         categories.add(hash);
         System.out.println("-->ID:"+channel.getString("ID")+"|NAME:"+channel.getString("name"));
         }
         dd=categories;
         } catch (Exception e) {
         e.printStackTrace();
         }
         } catch (Exception e) {
         e.printStackTrace();
         }
                   return dd;
                }
                //在doInBackground 执行完成后,onPostExecute 方法将被UI thread调用,后台的计算结果将通过该方法传递到UI thread.
            protected void onPostExecute(List<HashMap<String, Category>> sb) {
                 Log.i(TAG, "onPostExecute 执行了。");
                 //CustomSimpleAdapter categoryAdapter = new CustomSimpleAdapter(this, categories, R.layout.category_title , new String[]{"category_title"}, new int[]{R.id.category_title});
                 CustomSimpleAdapter categoryAdapter =new CustomSimpleAdapter(MainActivity.this, sb, R.layout.category_title, new String[]{"category_title"}, new int[]{R.id.category_title});
                 // List<HashMap<String, Category>> sb = new ArrayList<HashMap<String,Category>>();
              //为gridView填充数据
                 category.setAdapter(categoryAdapter);
                }
        }
       // 将服务器返回的字节数组转换为字符串   将字符串数据转换为JSON数组——JSONArray jsonArray=new JSONArray(stringVideosData);遍历JSON数组,取出数组里的每个元素,其类型JSONObject为——
            //将每个JSONObject对象的对应值取出来,再填充到对应的JavaBean里面  
       private JSONObject  parseJSON(InputStream inputStream) throws Exception{          
             JSONObject jsons=new JSONObject();
         GetResource getresource=new GetResource();
         byte [] byteVideosData= getresource.readResource(inputStream);//readResource(InputStream inputStream)方法见下  
                String  stringVideosData=new String(byteVideosData);          
                JSONArray jsonArray=new JSONArray(stringVideosData);  
                for(int i=0;i<jsonArray.length();i++){  
                   jsons=jsonArray.getJSONObject(i);  
                    //Video video=new Video(jsonObject.getInt("id"),jsonObject.getString("title"),jsonObject.getInt("timelength"));  
                    //videos.add(video);  
                }
    return jsons;  
            }
            
       public class GetResource {  
                public  byte[] readResource(InputStream inputStream) throws Exception{  
                    ByteArrayOutputStream outputStream=new ByteArrayOutputStream();  
                    byte [] array=new byte[1024];  
                    int len=0;  
                    while( (len=inputStream.read(array))!=-1){  
                           outputStream.write(array,0,len);  
                    }  
                    inputStream.close();  
                    outputStream.close();       
                    return outputStream.toByteArray();  
                }  
            }  
        
        
    } 这段代码没有报任何异常,就是不能渲染出值出来。 问题应该出在
      

  7.   

    代码太多,我也看眼花了,你看下我的博客吧,简单的例子http://blog.csdn.net/aimncy/article/details/21101023
      

  8.   

    自己弄好了,我把代码贴出来,希望能帮助到其他人。 
    package com.example;import java.io.BufferedReader;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;import org.json.JSONArray;
    import org.json.JSONObject;import android.app.Activity;
    import android.graphics.Color;
    import android.graphics.drawable.ColorDrawable;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Gravity;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.ViewGroup.LayoutParams;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.Button;
    import android.widget.GridView;
    import android.widget.LinearLayout;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.TextView;import com.example.entity.Category;
    import com.example.util.StringUtil;
    import com.example.widget.CustomSimpleAdapter;public class MainActivity extends Activity {
        private HttpURLConnection conn; 
        private URL url;
        private InputStream is;
        private static final String TAG = "ASYNC_TASK";
        private GridView category ;
    private final int COLUNMN_WIDTH_PX = 55;
    private  List<HashMap<String, Category>> categories;
    private int CHANNELID;
    private int ARTICLEID;
    private int columnWidth;
    private int mFlingVelocityDip;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            categories = new ArrayList<HashMap<String,Category>>();
            category = new GridView(this);
            new DownloadImageTask().execute();

        }
         private class DownloadImageTask extends AsyncTask<String, Void, List<HashMap<String, Category>> >{
             //将在onPreExecute 方法执行后马上执行,该方法运行在后台线程中。这里将主要负责执行那些很耗时的后台计算工作
                protected List<HashMap<String, Category>> doInBackground(String...  urls) {
                 Log.i("TAG", "doInbackGround 执行了。 ");
                 categories =new ArrayList<HashMap<String, Category>>();
         String  urlDate="http://192.168.1.135:8080/cms/test/NewFile.jsp";
         try {
         url=new URL(urlDate);
         try {
         conn=(HttpURLConnection) url.openConnection();
         conn.connect();
         if (conn.getResponseCode() != 200)
         throw new RuntimeException("请求url失败");
         is=conn.getInputStream();
          JSONObject jsonArray=parseJSON(is);
          JSONArray channelList= jsonArray.getJSONArray("channelList");
         for(int i=0; i<channelList.length();i++){
         JSONObject channel = (JSONObject)channelList.opt(i); 
         HashMap<String, Category> hash = new HashMap<String, Category>();
         Category c = new Category();
         c.setCid(Integer.parseInt(channel.getString("ID")));
         c.setTitle(channel.getString("name"));
         hash.put("category_title", c);
         categories.add(hash);
         } 
         } catch (Exception e) {
         e.printStackTrace();
         }
         } catch (Exception e) {
         e.printStackTrace();
         }
                   return categories;
                }
                //在doInBackground 执行完成后,onPostExecute 方法将被UI thread调用,后台的计算结果将通过该方法传递到UI thread.
            protected void onPostExecute(List<HashMap<String, Category>> sb) {
                 Log.i(TAG, "onPostExecute 执行了。");
                 //CustomSimpleAdapter categoryAdapter = new CustomSimpleAdapter(this, categories, R.layout.category_title , new String[]{"category_title"}, new int[]{R.id.category_title});
                 CustomSimpleAdapter categoryAdapter =new CustomSimpleAdapter(MainActivity.this, sb, R.layout.category_title, new String[]{"category_title"}, new int[]{R.id.category_title});
              //为gridView填充数据
                 category.setAdapter(categoryAdapter);
                 mFlingVelocityDip = StringUtil.px2dip(MainActivity.this, 600);
                    columnWidth = StringUtil.px2dip(MainActivity.this, 200);
                 category.setNumColumns(GridView.AUTO_FIT);
             int width = categories.size()*columnWidth;
             category.setNumColumns(GridView.AUTO_FIT);
             category.setGravity(Gravity.CENTER);
             //重绘按钮背景色
             category.setSelector(new ColorDrawable(Color.TRANSPARENT));
             //设置gridView单元格的width
             category.setColumnWidth(columnWidth);
             /**创建GridView 的布局参数*/
                LayoutParams params = new LayoutParams(width,LayoutParams.MATCH_PARENT);
             //设置GridView布局参数 
             category.setLayoutParams(params);
             //重绘按钮背景色
             category.setSelector(new ColorDrawable(Color.TRANSPARENT));
                 //在onPostExecute方法用于在执行完后台任务后更新UI,显示结果  
                 LinearLayout categoryLayout = (LinearLayout)findViewById(R.id.category_layout);
                 categoryLayout.addView(category);
                }
        }
       private JSONObject  parseJSON(InputStream inputStream) throws Exception{          
         GetResource getresource=new GetResource();
         byte [] byteVideosData= getresource.readResource(inputStream);//readResource(InputStream inputStream)方法见下  
                String  stringVideosData=new String(byteVideosData);          
                JSONObject jsonObject=new JSONObject(stringVideosData);  
    return jsonObject;  
            }
            
       public class GetResource {  
                public  byte[] readResource(InputStream inputStream) throws Exception{  
                    ByteArrayOutputStream outputStream=new ByteArrayOutputStream();  
                    byte [] array=new byte[1024];  
                    int len=0;  
                    while( (len=inputStream.read(array))!=-1){  
                           outputStream.write(array,0,len);  
                    }  
                    inputStream.close();  
                    outputStream.close();       
                    return outputStream.toByteArray();  
                }  
            }  
        
        
    }