有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java数组json不能用于我的列表视图

我的ListView不显示JSON数组titulo。我在Logcat上收到以下错误

 06-19 14:02:12.750    6497-6518/com.eu.agendamarinhagrande E/JSON Parser﹕ Error parsing data org.json.JSONException: Value  of type java.lang.String cannot be converted to JSONObject

下面是主要的活动类

   package com.eu.agendamarinhagrande;

import 安卓.annotation.TargetApi;
import 安卓.app.ProgressDialog;
import 安卓.content.Intent;
import 安卓.os.AsyncTask;
import 安卓.os.Build;
import 安卓.support.v7.app.ActionBar;
import 安卓.support.v7.app.ActionBarActivity;
import 安卓.os.Bundle;
import 安卓.util.Log;
import 安卓.view.Menu;
import 安卓.view.MenuItem;
import 安卓.view.View;
import 安卓.widget.AdapterView;
import 安卓.widget.ListAdapter;
import 安卓.widget.ListView;
import 安卓.widget.SimpleAdapter;
import 安卓.widget.TextView;

import com.eu.agendamarinhagrande.JSONParser;
import com.eu.agendamarinhagrande.R;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class MainActivity extends ActionBarActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> empresaList;


    // url to get all products list
    private static String url_all_empresas = "http://www.grifin.pt/projectoamg/Conexao.php";

    // JSON Node names


    private static final String TAG_TITULO = "Titulo";


    // products JSONArray
    String resultado = null;

    ListView lista;

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

        // Hashmap para el ListView
        empresaList = new ArrayList<HashMap<String, String>>();
        new LoadAllProducts().execute();
        // Cargar los productos en el Background Thread

        lista = (ListView) findViewById(R.id.listView);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

    }//fin onCreate


    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Antes de empezar el background thread Show Progress Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("A carregar eventos. Por favor espere...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * obteniendo todos los productos
         */
        protected String doInBackground(String... args) {
            // Building Parameters
            List params = new ArrayList();
            // getting JSON string from URL
          JSONObject json = jParser.makeHttpRequest(url_all_empresas, "GET", params);
            StringBuilder sb = new StringBuilder();
            // Check your log cat for JSON reponse
            Log.d("All Products: ", url_all_empresas.toString());
            resultado = sb.toString();
            try {
                // Checking for SUCCESS TAG

                // products found
                // Getting Array of Products

                JSONArray arrayJson = new JSONArray(resultado);
                for (int i = 0; i<arrayJson.length();i++){



                    // Storing each json item in variable
                    JSONObject c = arrayJson.getJSONObject(i);
                    String Titulo = c.getString(TAG_TITULO);


                    // creating new HashMap
                    HashMap map = new HashMap();

                    // adding each child node to HashMap key => value
                    map.put(TAG_TITULO, Titulo);


                    empresaList.add(map);
                }

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

        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            MainActivity.this,
                            empresaList,
                            R.layout.single_post,
                            new String[]{
                                    TAG_TITULO

                            },
                            new int[]{
                                    R.id.single_post_tv_id

                            });
                    // updating listview
                    //setListAdapter(adapter);
                    lista.setAdapter(adapter);
                }
            });

        }
    }
}

请帮助我理解导致我的JSON无法显示在我的ListView上的问题


共 (1) 个答案

  1. # 1 楼答案

    这对我有用。我注释了一些代码以使其工作

    public class test extends ActionBarActivity {
    
        // Progress Dialog
        private ProgressDialog pDialog;
    
        // Creating JSON Parser object
        // JSONParser jParser = new JSONParser();
    
        ArrayList<HashMap<String, String>> empresaList;
    
    
        // url to get all products list
        private static String url_all_empresas = "http://www.grifin.pt/projectoamg/Conexao.php";
    
        // JSON Node names
    
    
        private static final String TAG_TITULO = "Titulo";
    
    
        // products JSONArray
        String resultado = null;
    
        ListView lista;
    
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_test);
    
            // Hashmap para el ListView
            empresaList = new ArrayList<HashMap<String, String>>();
            new Download().execute();
            // Cargar los productos en el Background Thread
    
            lista = (ListView) findViewById(R.id.listView);
    
           // ActionBar actionBar = getSupportActionBar();
           // actionBar.setDisplayHomeAsUpEnabled(true);
    
        }//fin onCreate
    
    
        public class Download extends AsyncTask<Void, Void, String> {
    
            @Override
            protected String doInBackground(Void... params) {
                String out = null;
    
                try {
                    DefaultHttpClient httpClient = new DefaultHttpClient();
    
                    final HttpParams httpParameters = httpClient.getParams();
    
                    HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
                    HttpConnectionParams.setSoTimeout(httpParameters, 15000);
    
                    HttpGet httpPost = new HttpGet(url_all_empresas);
    
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
    
                    out = EntityUtils.toString(httpEntity, HTTP.UTF_8);
    
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
                return out;
            }
    
    
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
    
            ArrayList<String> list = new ArrayList<>();
    
            try {
                JSONArray jsonArray = new JSONArray(result);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsa = jsonArray.getJSONObject(i);
                    String str = jsa.getString("Titulo");
                    Log.e("TAG", str);
    
                    String s1 = Normalizer.normalize(str, Normalizer.Form.NFKD);
                    String regex = Pattern.quote("[\\p{InCombiningDiacriticalMarks}\\p{IsLm}\\p{IsSk}]+");
    
                    str = new String(s1.replaceAll(regex, "").getBytes("ascii"), "ascii");
    
                    list.add(str);
                }
    
                ArrayAdapter adapter = new ArrayAdapter<>(test.this, android.R.layout.simple_list_item_1, list);
    
                // updating listview
                //setListAdapter(adapter);
                lista.setAdapter(adapter);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
          }
        }
    }