Json数据显示不起作用

时间:2017-05-02 13:08:16

标签: android json database android-studio

当我启动我的应用程序时,没有崩溃但是json中的数据没有显示,并且在日志中有这些消息:

package com.example.nicol.etablissement43;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by nicol on 25/04/2017.
 */

public class recherche_2 extends AppCompatActivity {
    private static final String LOG_TAG = "Selection Ville";
    private ListView Ville;
    private ArrayAdapter<String> listAdapter ;
    private AdapterClient adapterClient ;
    private TextView SQLData;

    @Override/*
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recherche_2);
    }*/

    protected void onCreate(Bundle savedInstanceState) {
        {

            if (Build.VERSION.SDK_INT > 8) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }

            super.onCreate(savedInstanceState);
            String page = this.getPage("http://appec43.890m.com/connectionbddandroid/config.inc.php");

            Log.i("ContenuPost", page);

            setContentView(R.layout.recherche_2);
            SQLData = (TextView)findViewById(R.id.SQLData);
            Ville = (ListView) findViewById(R.id.Ville);
            SQLData.setText("Les villes");
            SQLData.setText("Les villes");

            //String[] planets = new String[] {""};


            // ArrayList<String> planetList = new ArrayList<String>();
            // planetList.addAll( Arrays.asList(planets) );

            //listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, planetList);
            adapterClient = new AdapterClient(this, R.layout.recherche_2);
            try {
                JSONArray jsonArray = new JSONArray(page);

                for (int i = 0; i < jsonArray.length(); i++) {

                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    client clientobj = new client();
                    clientobj.setVille(jsonObject.getString("Ville"));
                    clientobj.setCodepostal(jsonObject.getString("codepostal"));

                    adapterClient.add(clientobj);
                }

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


        /*
        String[] split = page.split(",");
        for (int i = 0; i < split.length; i++) {
            listAdapter.add( split[i] );
            if (i != split.length - 1) {
                listAdapter.add(" ");
            }
        }
        */


           Ville.setAdapter(adapterClient);

        }
    }

    public String getPage(String adresse){

        StringBuffer stringBuffer = new StringBuffer("");
        BufferedReader bufferedReader = null;

        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 15000);

            HttpPost httpPost = new HttpPost();

            URI uri = new URI(adresse);

            httpPost.setURI(uri);
            List<NameValuePair> parametres = new ArrayList<NameValuePair>();
            parametres.add(new BasicNameValuePair("login", "u265740438_root2"));
            parametres.add(new BasicNameValuePair("pass", "nicolas"));
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parametres);
            httpPost.setEntity(formEntity);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            InputStream inputStream = httpResponse.getEntity().getContent();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            String ligneLue = bufferedReader.readLine();

            while (ligneLue != null) {
                Log.i("Valeur", ligneLue);
                stringBuffer.append(ligneLue);
                stringBuffer.append("\n");
                ligneLue = bufferedReader.readLine();

            }
        }
        catch(Exception e) {
            Log.e("Erreur", e.getMessage());
        }

        finally{
            if(bufferedReader != null){
                try{
                    bufferedReader.close();
                }
                catch (IOException e){

                }
            }

        }

        return stringBuffer.toString();

    }


    }

我的主程序(recherche_2.java):

package com.example.nicol.etablissement43;



public class client {

    private String ville;
    private String codepostal;


    public void setVille(String ville){ this.ville = ville ;}

    public void setCodepostal(String codepostal){this.codepostal = codepostal;}

    public String getVille(){return this.ville;}

    public String getcodepostal(){return this.codepostal;}

}

我项目的另一部分:

client.java:

package com.example.nicol.etablissement43;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;



public class AdapterClient extends ArrayAdapter<client>
{

    public AdapterClient(Context context, int textViewRessourceId)
    {
        super(context, textViewRessourceId);
    }


    public View getView(int position, View convertView, ViewGroup parent)
    {
        View result = convertView;
        if (convertView == null)
        {
            result = LayoutInflater.from(getContext()).inflate(R.layout.ligne, parent, false);
        }
        client Ville = getItem(position);

        //Assigner aux textView les valeurs obtenues par les get de la classe client
        TextView ville = (TextView)result.findViewById(R.id.idv);
        ville.setText(Ville.getVille());

        TextView nom = (TextView)result.findViewById(R.id.villes);
        nom.setText(Ville.getcodepostal());

        return result;
    }


}

适配器client.java:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">


        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <TextView
        android:text="Villes"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/SQLData"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="52dp"
        android:layout_marginStart="52dp" />

    <ListView
        android:id="@+id/Ville"
        style="@style/Widget.AppCompat.Light.ListView.DropDown"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView"
        android:layout_marginTop="24dp" />
</RelativeLayout>

我的布局:

recherche_2.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:text="TextView"
        android:layout_width="45dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:id="@+id/idv"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:text="TextView"
    android:layout_width="330dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="0dp"
    android:layout_alignTop="@+id/villes"
    android:layout_toEndOf="@+id/villes"
    android:id="@+id/villes"
    android:layout_toRightOf="@+id/villes" />

</LinearLayout>

    <!--
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rowTextView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:textSize="16sp" >
    </TextView>

    -->

ligne.xml:

"[{\"id\":\"1\",\"ville\":\"ARAULES\"},{\"id\":\"2\",\"ville\":\"AUREC SUR LOIRE\"},{\"id\":\"3\",\"ville\":\"AUREC SUR LOIRE\"},{\"id\":\"4\",\"ville\":\"BAINS\"},{\"id\":\"5\",\"ville\":\" BAS EN BASSET\"},{\"id\":\"6\",\"ville\":\"BEAULIEU\"},{\"id\":\"7\",\"ville\":\"BEAUZAC\"},{\"id\":\"8\",\"ville\":\"BRIOUDE\"},{\"id\":\"9\",\"ville\":\" BRIOUDE\"},{\"id\":\"10\",\"ville\":\"BRIOUDE\"},{\"id\":\"11\",\"ville\":\" BRIVES CHARENSAC\"},{\"id\":\"12\",\"ville\":\" BRIVES CHARENSAC\"},{\"id\":\"13\",\"ville\":\" BRIVES CHARENSAC\"},{\"id\":\"14\",\"ville\":\" BRIVES CHARENSAC\"},{\"id\":\"15\",\"ville\":\"BRIVES CHARENSAC\"},{\"id\":\"16\",\"ville\":\"COUBON\"},{\"id\":\"17\",\"ville\":\"CRAPONNE\"},{\"id\":\"18\",\"ville\":\"DUNI\\u00c8RES\"},{\"id\":\"19\",\"ville\":\"CRAPONNE\"},{\"id\":\"20\",\"ville\":\"DUNI\\u00c8RES\"},{\"id\":\"21\",\"ville\":\"ESPALY\"},{\"id\":\"22\",\"ville\":\"GRAZAC\"},{\"id\":\"23\",\"ville\":\"LANGEAC\"},{\"id\":\"24\",\"ville\":\"LANGEAC\"},{\"id\":\"25\",\"ville\":\" LANTRIAC\"},{\"id\":\"26\",\"ville\":\"LAPTE\"},{\"id\":\"27\",\"ville\":\"LAUSSONNE\"},{\"id\":\"28\",\"ville\":\" LAVOUTE CHILHAC\"},{\"id\":\"29\",\"ville\":\"LE MONASTIER\"},{\"id\":\"30\",\"ville\":\"LE MONASTIER\"},{\"id\":\"31\",\"ville\":\"MONISTROL\\\/LOIRE\"},{\"id\":\"32\",\"ville\":\"MONISTROL\\\/LOIRE\"},{\"id\":\"33\",\"ville\":\"MONISTROL\\\/LOIRE\"},{\"id\":\"34\",\"ville\":\"MONTFAUCON\"},{\"id\":\"35\",\"ville\":\" MONTREGARD\"},{\"id\":\"36\",\"ville\":\"POLIGNAC\"},{\"id\":\"37\",\"ville\":\"PRADELLES\"},{\"id\":\"38\",\"ville\":\"LE PUY EN VELAY\"},{\"id\":\"39\",\"ville\":\"LE PUY EN VELAY\"},{\"id\":\"40\",\"ville\":\"LE PUY EN VELAY\"},{\"id\":\"41\",\"ville\":\"LE PUY EN VELAY\"},{\"id\":\"42\",\"ville\":\"LE PUY EN VELAY\"},{\"id\":\"43\",\"ville\":\"LE PUY EN VELAY\"},{\"id\":\"44\",\"ville\":\"VALS PRES LE PUY\"},{\"id\":\"45\",\"ville\":\"LE PUY EN VELAY\"},{\"id\":\"46\",\"ville\":\"LE PUY EN VELAY\"},{\"id\":\"47\",\"ville\":\"LE PUY EN VELAY\"},{\"id\":\"48\",\"ville\":\"LE PUY EN VELAY\"},{\"id\":\"49\",\"ville\":\"RAUCOULES\"},{\"id\":\"50\",\"ville\":\"LE PUY EN VELAY\"},{\"id\":\"51\",\"ville\":\"RETOURNAC\"},{\"id\":\"52\",\"ville\":\"RIOTORD\"},{\"id\":\"53\",\"ville\":\"ROSIERES\"},{\"id\":\"54\",\"ville\":\"ST BONNET LE FROID\"},{\"id\":\"55\",\"ville\":\"ST DIDIER EN VELAY\"},{\"id\":\"56\",\"ville\":\"ST DIDIER EN VELAY\"},{\"id\":\"57\",\"ville\":\"ST FERREOL D\\u2019AUROURE\"},{\"id\":\"58\",\"ville\":\"SAINT FRONT\"},{\"id\":\"59\",\"ville\":\"ST GERMAIN LAPRADE\"},{\"id\":\"60\",\"ville\":\"STE FLORINE\"},{\"id\":\"61\",\"ville\":\"STE FLORINE\"},{\"id\":\"62\",\"ville\":\"ST JULIEN CHAPTEUIL\"},{\"id\":\"63\",\"ville\":\"ST JULIEN CHAPTEUIL\"},{\"id\":\"64\",\"ville\":\"ST JUST MALMONT\"},{\"id\":\"65\",\"ville\":\"ST MAURICE DE LIGNON\"},{\"id\":\"66\",\"ville\":\"ST PAL\\\/CHALENCON\"},{\"id\":\"67\",\"ville\":\"ST PAL DE MONS\"},{\"id\":\"68\",\"ville\":\"SAINT PAULIEN\"},{\"id\":\"69\",\"ville\":\"ST PIERRE D\\\/CHAMP\"},{\"id\":\"70\",\"ville\":\"ST ROMAIN LACHALM\"},{\"id\":\"71\",\"ville\":\"STE SIGOL\\u00c8NE\"},{\"id\":\"72\",\"ville\":\"STE SIGOL\\u00c8NE\"},{\"id\":\"73\",\"ville\":\"ST VICTOR MALESCOURS\"},{\"id\":\"74\",\"ville\":\"SAUGUES\"},{\"id\":\"75\",\"ville\":\"SAUGUES\"},{\"id\":\"76\",\"ville\":\"LA SEAUVE S\\\/SEM\\u00c8NE\"},{\"id\":\"77\",\"ville\":\"SOLIGNAC\\\/LOIRE\"},{\"id\":\"78\",\"ville\":\"TENCE\"},{\"id\":\"79\",\"ville\":\"TENCE\"},{\"id\":\"80\",\"ville\":\"TIRANGES\"},{\"id\":\"81\",\"ville\":\"VERGEZAC\"},{\"id\":\"82\",\"ville\":\"LES VILLETTES\"},{\"id\":\"83\",\"ville\":\"VOREY\"},{\"id\":\"84\",\"ville\":\"YSSINGEAUX\"},{\"id\":\"85\",\"ville\":\"YSSINGEAUX \"},{\"id\":\"86\",\"ville\":\"YSSINGEAUX \"},{\"id\":\"87\",\"ville\":\"YSSINGEAUX\"}]"

和Json:

match(x,y)           #If no match is found, it returns (by default) NA
#[1] NA  1  2  3

is.na(match(x,y))    #Thus, is.na will create a logical vector for NA values
#[1]  TRUE FALSE FALSE FALSE

x[is.na(match(x,y))]    #Using the above logical vector as index for x
#[1] 1

这个问题有解决方法吗?因为我有很多需要寻找的东西,我还没有找到 提前谢谢你

3 个答案:

答案 0 :(得分:0)

您正在将字符串转换为jsonArray,其中您的响应是jsonObject:

    JSONObject jsnobject = new JSONObject(result);

JSONArray jsonArray = jsnobject.getJSONArray("data");


    for (int i = 0; i < jsonArray.length(); i++)
    {
        JSONObject data= jsonArray.getJSONObject(i);
        dataList.add(data.getString("name"));
    }

答案 1 :(得分:0)

首先,您要在主线程上发送您不应该的请求。 其次,考虑使用HttpURLConnection

,不推荐使用HttpClient

下面的代码应该可以使用AsyncTask

private class DownloadTask extends AsyncTask<String, Void, String> {


    public DownloadTask() {
    }

    @Override
    protected String doInBackground(String... urls) {
        StringBuffer stringBuffer = new StringBuffer("");
        BufferedReader bufferedReader = null;
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        int serverResponseCode = 0;
        try {

            URL url = new URL("" + urls[0]);
            // Open a HTTP  connection to  the URL

            conn = (HttpURLConnection) url.openConnection();

            conn.setDoInput(true); // Allow Inputs

            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("GET");

            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            if(serverResponseCode == 200) {
                StringBuffer sb = new StringBuffer();
                InputStream is = new BufferedInputStream(conn.getInputStream());
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String inputLine = "";
                while ((inputLine = br.readLine()) != null) {
                    sb.append(inputLine);
                }
                return sb.toString();
            } else {
                return "";
            }

        }
        catch(Exception e) {
            e.printStackTrace();
            Log.e("Erreur", e.getMessage());
        }

        finally{
            if(bufferedReader != null){
                try{
                    bufferedReader.close();
                }
                catch (IOException e){

                }
            }

        }

        return stringBuffer.toString();
    }

    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        boolean error = false;
        // This can be done in the main activity UI Thread
        try {
            JSONArray arr = new JSONArray(result);
             // Output just to validate that it work
            for (int i = 0; i < arr.length(); i++) {
                JSONObject jsonObject = arr.getJSONObject(i);
                System.out.println(jsonObject.toString());
            }
            showData(arr) // This can be a function in your activity

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

在onCreate方法中,您可以像这样调用它

new DownloadTask().execute("http://appec43.890m.com/connectionbddandroid/config.inc.php");

我希望这会有所帮助。

答案 2 :(得分:-1)

这是一个已知的android bug,你不应该在4.1之前覆盖那个方法。有关详细信息,请查看此answer