OnItemClickListner在android的json解析器中不起作用

OnItemClickListner在android的json解析器中不起作用,android,json,Android,Json,我在android中使用listview和JSON解析器listview成功运行,这是我的问题,McClickListner在listview中不工作 这是我的密码 主要活动代码 public class MainActivity extends Activity { private static final String TAG_NAME = "name"; private static final String TAG_EMAIL = "email"; priva

我在android中使用listview和JSON解析器listview成功运行,这是我的问题,McClickListner在listview中不工作

这是我的密码

主要活动代码

 public class MainActivity extends Activity {

    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_PHONE_MOBILE = "mobile";
    ListView mListView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // URL to the JSON data
        String strUrl = "http://192.168.0.200/android/count.php";

        // Creating a new non-ui thread task to download json data
        DownloadTask downloadTask = new DownloadTask();

        // Starting the download process
        downloadTask.execute(strUrl);

        // Getting a reference to ListView of activity_main
        mListView = (ListView) findViewById(R.id.lv_countries);

    }

    /** A method to download json data from url */
    private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        try{
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            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;
    }

    /** AsyncTask to download json 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) {

            // The parsing of the xml data is done in a non-ui thread
            ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();

            // Start parsing xml data
            listViewLoaderTask.execute(result);

        }
    }

    /** AsyncTask to parse json data and load ListView */
    private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{

        JSONObject jObject;
        // Doing the parsing of xml data in a non-ui thread
        @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());
            }

            // Instantiating json parser class
            CountryJSONParser countryJsonParser = new CountryJSONParser();

            // A list object to store the parsed countries list
            List<HashMap<String, Object>> countries = null;

            try{
                // Getting the parsed data as a List construct
                countries = countryJsonParser.parse(jObject);
            }catch(Exception e){
                Log.d("Exception",e.toString());
            }

            // Keys used in Hashmap
            String[] from = { "flag","details"};

            // Ids of views in listview_layout
            int[] to = { R.id.iv_flag,R.id.tv_country_details};

            // Instantiating an adapter to store each items
            // R.layout.listview_layout defines the layout of each item
            SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to);

            return adapter;
        }

        /** Invoked by the Android on "doInBackground" is executed */
        @Override
        protected void onPostExecute(SimpleAdapter adapter) {

            // Setting adapter for the listview
            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);

                // Starting ImageLoaderTask to download and populate image in the listview
                imageLoaderTask.execute(hm);
            }


        }



    }

    /** AsyncTask to download and load an image in ListView */
    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,gUrl;
            gUrl = (String) hm[0].get("flag_path");
            int position = (Integer) hm[0].get("position");

            URL url;
            try {
                url = new URL(gUrl);

                // Creating an http connection to communicate with url
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                // Connecting to url
                urlConnection.connect();

                // Reading data from url
                iStream = urlConnection.getInputStream();

                // Getting Caching directory
                File cacheDirectory = getBaseContext().getCacheDir();

                // Temporary file to store the downloaded image
                File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");

                // The FileOutputStream to the temporary file
                FileOutputStream fOutStream = new FileOutputStream(tmpFile);

                // Creating a bitmap from the downloaded inputstream
                Bitmap b = BitmapFactory.decodeStream(iStream);

                // Writing the bitmap to the temporary file as png file
                b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);

                // Flush the FileOutputStream
                fOutStream.flush();

               //Close the FileOutputStream
               fOutStream.close();

                // Create a hashmap object to store image path and its position in the listview
                HashMap<String, Object> hmBitmap = new HashMap<String, Object>();

                // Storing the path to the temporary image file
                hmBitmap.put("flag",tmpFile.getPath());

                // Storing the position of the image in the listview
                hmBitmap.put("position",position);

                // Returning the HashMap object containing the image path and position
                return hmBitmap;

            }catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(HashMap<String, Object> result) {
            // Getting the path to the downloaded image
            String path = (String) result.get("flag");

            // Getting the position of the downloaded image
            int position = (Integer) result.get("position");

            // Getting adapter of the listview
            SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();

            // Getting the hashmap object at the specified position of the listview
            HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);

            // Overwriting the existing path in the adapter
            hm.put("flag",path);

            // Noticing listview about the dataset changes
            adapter.notifyDataSetChanged();
            mListView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                    Activity view = null;
                    // TODO Auto-generated method stub
                    // getting values from selected ListItem
                    String type = ((TextView) view.findViewById(R.id.tv_country_details)).getText().toString();



                    // Starting new intent
              Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
                in.putExtra(type, type);
                startActivity(in);

            }


               });
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    }
Json解析器代码

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("countries");
    } 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 flag="";
    String currencyName = "";

    try {

        flag = jCountry.getString("flag");
        currencyName = jCountry.getJSONObject("currency").getString("currencyname");

        String details = currencyName ;


        country.put("flag", R.drawable.blank);
        country.put("flag_path", flag);
        country.put("details", details);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return country;
}

public static Object optJSONObject(int arg2) {
    // TODO Auto-generated method stub
    return null;
}


public static boolean isNull(int arg2) {
    // TODO Auto-generated method stub
    return false;
}
公共类CountryJSONParser{
//接收JSONObject并返回列表
公共列表解析(JSONObject jObject){
JSONArray jCountries=null;
试一试{
//检索“国家”数组中的所有元素
jCountries=jObject.getJSONArray(“国家”);
}捕获(JSONException e){
e、 printStackTrace();
}
//使用json对象数组调用getCountries
//其中每个json对象代表一个国家
返回国家(jCountries);
}
私人名单国家(JSONArray JCcountries){
int countryCount=jCountries.length();
List countryList=new ArrayList();
HashMap country=null;
//获取每个国家,解析并添加到列表对象

对于(inti=0;i将这些代码添加到Dewnladurl方法中

    String jsonString = null;

    HttpURLConnection linkConnection = null;
    try{
        URL linkur1 = new URL(url);
        linkConnection = (HttpURLConnection) linkur1.openConnection();
        int responseCode = linkConnection.getResponseCode();
        if(responseCode == HttpURLConnection.HTTP_OK){
            InputStream linkingStream = linkConnection.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int j = 0;
            while ((j = linkingStream.read()) != -1) {
                baos.write(j);
            }
            byte[] data = baos.toByteArray();

            jsonString = new String(data);
        }
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        if(linkConnection != null){
            linkConnection.disconnect();
        }
    }

    return jsonString;
而不是使用它来获取单个项目

public void onItemClick(AdapterView<?> arg0, View arg1, int position,
        long id) {
          View item = arg0.getChildAt(position);
}
public void onItemClick(适配器视图arg0,视图arg1,内部位置,
长id){
视图项=arg0.getChildAt(位置);
}

将这些代码添加到Dewnladurl方法中

    String jsonString = null;

    HttpURLConnection linkConnection = null;
    try{
        URL linkur1 = new URL(url);
        linkConnection = (HttpURLConnection) linkur1.openConnection();
        int responseCode = linkConnection.getResponseCode();
        if(responseCode == HttpURLConnection.HTTP_OK){
            InputStream linkingStream = linkConnection.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int j = 0;
            while ((j = linkingStream.read()) != -1) {
                baos.write(j);
            }
            byte[] data = baos.toByteArray();

            jsonString = new String(data);
        }
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        if(linkConnection != null){
            linkConnection.disconnect();
        }
    }

    return jsonString;
而不是使用它来获取单个项目

public void onItemClick(AdapterView<?> arg0, View arg1, int position,
        long id) {
          View item = arg0.getChildAt(position);
}
public void onItemClick(适配器视图arg0,视图arg1,内部位置,
长id){
视图项=arg0.getChildAt(位置);
}

是否签入了“调试”中指定onItemClickListener的行是可访问的?可能是因为出现问题而未指定您的侦听器?您正在onPost方法中设置listview onclicklistener它将不起作用,因为json Onclick正在起作用,但内容显示不起作用请举例说明。是否签入调试中的ed是指您分配onItemClickListener的行是可访问的吗?可能是您的侦听器由于出现问题而未分配?您正在onPost方法中设置listview onclicklistener它将不起作用,因为json Onclick正在起作用,但内容显示不起作用。请举例说明。同样的问题也会发生,先生,很遗憾ly应用程序已停止。如何解决此问题?请帮助我。在json中,Onclick正在工作,但内容显示不工作。请用示例说明在您的OnItemClick()中使用适配器。getChildAt(位置)获取listview项。它不起作用。先生,相同的问题内容无法显示。请帮助我,我是初学者android Designner,因此我无法解决此问题,因此我需要您的帮助,如何通过示例解决此问题。先生,同样的问题发生,先生,不幸的是,应用程序已停止。如何解决此问题?请帮助我。在json中,Onclick正在工作内容显示不工作请用示例说明在您的OnItemClick()中使用adapter.getChildAt(位置)获取listview项。它不工作,先生相同的问题内容无法显示请帮助我我是初学者android设计人员,因此我无法修复此问题,因此我需要您的帮助如何用示例修复此问题,先生。