从 JSON 响应填充 Gridview 我在 logcat 中收到 NullPointerException

Populating Gridview from JSON response I am getting NullPointerException in logcat

我在 logcat 中遇到空点异常,因为我正在尝试从 JSON 响应中获取 GridView 任何人都可以解决这个问题。我是 android

的新手
public class MainActivity extends Activity {
    GridView mListView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //view = inflater.inflate(R.layout.activity_main, null);

        String strUrl = "http://globalringtools.com/android/categories.php";
        DownloadTask downloadTask = new DownloadTask();
        downloadTask.execute(strUrl);
        mListView = (GridView) findViewById(R.id.gridView1);
    }   
    private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        try{
            URL url = new URL(strUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            iStream = urlConnection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
            StringBuffer sb  = new StringBuffer();
            String line = "";
            while( ( line = br.readLine())  != null){
                sb.append(line);
            }
            data = sb.toString();
            br.close();
        }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
        }finally{
            iStream.close();
        }       
        return data;        
    }
    private class DownloadTask extends AsyncTask<String, Integer, String>{
        String data = null;
        @Override
        protected String doInBackground(String... url){
            try{
                data = downloadUrl(url[0]);
            }catch(Exception e){
                Log.d("Background Task",e.toString());
            }
            return data;
        }
        @Override
        protected void onPostExecute(String result){
            ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
            listViewLoaderTask.execute(result);
        }
    }   
    private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
        JSONObject jObject;
        @Override
        protected SimpleAdapter doInBackground(String... strJson){
            try{
                jObject = new JSONObject(strJson[0]);
                CountryJSONParser countryJsonParser = new CountryJSONParser();
                countryJsonParser.parse(jObject);
            }catch(Exception e){
                Log.d("JSON Exception1",e.toString());
            }       
            CountryJSONParser countryJsonParser = new CountryJSONParser();
            List<HashMap<String, Object>> countries = null;
            try{
                countries = countryJsonParser.parse(jObject); 
            }catch(Exception e){
                Log.d("Exception",e.toString());
            }
            String[] from = { "flag","country"};
            int[] to = { R.id.picture,R.id.text};
            SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.grid_layout, from, to);
             return adapter;
        }
        @Override
        protected void onPostExecute(SimpleAdapter adapter){
            mListView.setAdapter(adapter);
            for(int i=0;i<adapter.getCount();i++){
                HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
                String imgUrl = (String) hm.get("flag_path");
                ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
                HashMap<String, Object> hmDownload = new HashMap<String, Object>();
                hm.put("flag_path",imgUrl);
                hm.put("position", i);
                imageLoaderTask.execute(hm);
            }
        }
    }
    private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
        @Override
        protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm){
            InputStream iStream=null;
            String im;
            String imgUrl = (String) hm[0].get("flag_path");
            int position = (Integer) hm[0].get("position");
            URL url;
            try{
                url = new URL(imgUrl);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.connect();
                iStream = urlConnection.getInputStream();
                File cacheDirectory = getBaseContext().getCacheDir();
                File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");
                FileOutputStream fOutStream = new FileOutputStream(tmpFile);
                Bitmap b = BitmapFactory.decodeStream(iStream);
                b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
                fOutStream.flush();
                fOutStream.close();
                HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
                hmBitmap.put("flag",tmpFile.getPath());
                hmBitmap.put("position",position);
                return hmBitmap;
            }catch(Exception e){
                e.printStackTrace();
            }
            return null;
        }
        protected void onPostExecute(HashMap<String, Object> result){
            String path = (String) result.get("flag");
            int position = (Integer) result.get("position");
            SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();
            HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
            hm.put("flag",path);
            adapter.notifyDataSetChanged();
        }
    }
}

Json 解析器 class

    package com.ambilobes.cust_grid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/** A class to parse json data */
public class CountryJSONParser {

    // Receives a JSONObject and returns a list
    public List<HashMap<String,Object>> parse(JSONObject jObject){

        JSONArray jCountries = null;
        try {
            // Retrieves all the elements in the 'countries' array
            jCountries = jObject.getJSONArray("categories");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // Invoking getCountries with the array of json object
        // where each json object represent a country
        return getCountries(jCountries);
    }

    private List<HashMap<String, Object>> getCountries(JSONArray jCountries){
        int countryCount = jCountries.length();
        List<HashMap<String, Object>> countryList = new ArrayList<HashMap<String,Object>>();
        HashMap<String, Object> country = null;

        // Taking each country, parses and adds to list object
        for(int i=0; i<countryCount;i++){
            try {
                // Call getCountry with country JSON object to parse the country
                country = getCountry((JSONObject)jCountries.get(i));
                countryList.add(country);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } 
        return countryList;
    }

    // Parsing the Country JSON object
    private HashMap<String, Object> getCountry(JSONObject jCountry){

        HashMap<String, Object> country = new HashMap<String, Object>();
        String countryName = "";
        String flag="";
        StringBuilder strBuilder = new StringBuilder();
        strBuilder.append("http://globalringtools.com/flowborn/template/resources/images/client_categories");

        try {
            strBuilder.append(jCountry.getString("image"));
            flag = strBuilder.toString();
            countryName = jCountry.getString("category");
            country.put("country", countryName);
            country.put("flag", R.drawable.blank);
            country.put("flag_path", flag);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return country;
    }
}

我正在尝试从 json 获取 Gridview,但出现空点异常。 谁能帮帮我

您的 ImageLoaderTask 中第 145 行的任何内容都是问题所在。响应不为空吗?您尝试访问的网站可能是空的。

protected void onPostExecute(HashMap<String, Object> result){
  if (result != null) {
  ...
  }
}

以下代码失败。

try{
                url = new URL(imgUrl);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.connect();
                iStream = urlConnection.getInputStream();
                File cacheDirectory = getBaseContext().getCacheDir();
                File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");
                FileOutputStream fOutStream = new FileOutputStream(tmpFile);
                Bitmap b = BitmapFactory.decodeStream(iStream);
                b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
                fOutStream.flush();
                fOutStream.close();
                HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
                hmBitmap.put("flag",tmpFile.getPath());
                hmBitmap.put("position",position);
                return hmBitmap;
            }catch(Exception e){
                e.printStackTrace();
            }

某事抛出异常,您应该单步执行代码或至少使用 Log.e("Exception",e);

记录异常

问题就在这里。

 DownloadTask downloadTask = new DownloadTask();
 downloadTask.execute(strUrl);
 mListView = (GridView) findViewById(R.id.gridView1);

此处您的 DownloadTask 在初始化 GridView 之前执行。所以你的错误将是这一行。因此需要在执行 DownloadTask 之前移动此行 mListView = (GridView) findViewById(R.id.gridView1);。所以它将是

mListView = (GridView) findViewById(R.id.gridView1);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(strUrl);