Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/199.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 从JSON响应填充Gridview我在logcat中得到NullPointerException_Android_Json_Gridview - Fatal编程技术网

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

Android 从JSON响应填充Gridview我在logcat中得到NullPointerException,android,json,gridview,Android,Json,Gridview,当我试图从JSON响应中获取GridView时,logcat中出现了空点异常,任何人都可以解决这个问题。我不熟悉安卓系统 public class MainActivity extends Activity { GridView mListView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

当我试图从JSON响应中获取GridView时,logcat中出现了空点异常,任何人都可以解决这个问题。我不熟悉安卓系统

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解析器类

    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,但得到了空点异常。。
有人能帮我吗。

无论您的图像加载程序第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.eException,e

问题就在这里

 DownloadTask downloadTask = new DownloadTask();
 downloadTask.execute(strUrl);
 mListView = (GridView) findViewById(R.id.gridView1);
这里,您的下载任务在初始化GridView之前执行。所以你的错误是这一行。所以需要移动这一行mListView=GridView findviewbydr.id.gridView1;在下载任务执行之前。就这样吧

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

请输入您的日志详细信息。01-23 10:07:59.358:E/AndroidRuntime28335:致命异常:main 01-23 10:07:59.358:E/AndroidRuntime28335:java.lang.NullPointerException 01-23 10:07:59.358:E/AndroidRuntime28335:at com.ambilobes.cust\u grid.main活动$ImageLoaderTask.onPostExecuteMainActivity.java:145无人知道!!!!!!!!!!!!!!!!!!!!!!!!!你能在你的代码中显示空指针的确切位置吗?com.ambilobes.cust_grid.MainActivity$ImageLoaderTask.onPostExecuteMainActivity.java:145你能告诉我该怎么做吗?你的代码很好地工作了…谢谢。。。事实上,我不知道如何在堆栈中提升你。告诉我你应该点击我答案旁边的复选标记使它变成绿色。这将向人们表明你接受答案,这将使人们在未来更愿意提供帮助。这里有完整的说明:那么你还是有同样的问题吗???向我显示您获取错误的行?图像未显示在GridView中,但应用程序正在崩溃?如果它崩溃了,告诉我lineNow我的应用程序没有崩溃。。图像未显示!!要显示图像,请使用通用图像加载器类。在使用我的代码后,应用程序没有崩溃?