繁体   English   中英

JSON解析为TextView Android API

[英]JSON Parsing Into TextView Android API

这是我的API json

[
{
"titre": "Le Parachutage",
"auteur": "Norbert Zongo",
"categorie": "Litterature",
"editeur": "Harmattan",
"prix": "400 UM"
}
]

我创建了此Layout,并希望在启动活动时用这些数据(“ Le Parachutage”等)替换“ Textview”。

布局

顺便说一句,此活动由预览活动通过按钮和Intent启动。

这是我的代码:

package com.example.kane.bibliokane;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.io.IOException;
import android.util.Log;
import android.widget.TextView;

import java.net.HttpURLConnection;

import static android.R.attr.data;


public class ListesLivres extends AppCompatActivity {

TextView Titre, Auteur, Categorie , Editeur , Prix;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listeslivres);

    Titre = (TextView) findViewById(R.id.textView16);
    Auteur = (TextView) findViewById(R.id.textView17);
    Categorie = (TextView) findViewById(R.id.textView18);
    Editeur = (TextView) findViewById(R.id.textView19);
    Prix = (TextView) findViewById(R.id.textView20);
    new getData().execute();
}

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

    HttpURLConnection urlConnection;

    @Override
    protected String doInBackground(String... args) {

        StringBuilder result = new StringBuilder();

        try {
            URL url = new URL("http://192.168.43.13:8000/api/liste.json");
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            urlConnection.disconnect();
        }


        return result.toString();
    }

    @Override
    protected void onPostExecute(String result) {
        try {
            JSONArray jsonArray = new JSONArray(result);
            JSONObject jsonObject = jsonArray.getJSONObject(0);
            String t = jsonObject.getString("Titre");
            String a = jsonObject.getString("Auteur");
            String c = jsonObject.getString("Categorie");
            String e = jsonObject.getString("Editeur");
            String p = jsonObject.getString("Prix");
            Titre.setText(t);
            Auteur.setText(a);
            Categorie.setText(c);
            Editeur.setText(e);
            Prix.setText(p);

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

    }
    }

我在AndroidManifest文件中使用了我需要的所有权限(网络,Internet等)。

我使用的是Symfony 3,我以0.0.0.0:8000激活了内部服务器,因此任何设备都可以使用API​​。

但是问题是,当我启动活动时,什么都没有发生。 我仍然具有相同的布局,并且TextView并未更改。

请问该如何解决?

谢谢,对不起,我的英语不好,这不是我母亲的语言。

编辑

在尝试通过仿真器调试并启动应用程序之后。

这是我得到的:

W/System.err: org.json.JSONException: No value for Titre
W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
W/System.err:     at org.json.JSONObject.getString(JSONObject.java:550)
W/System.err:     at    com.example.kane.bibliokane.ListesLivres$getData.onPostExecute(ListesLivres.java:75)
W/System.err:     at com.example.kane.bibliokane.ListesLivres$getData.onPostExecute(ListesLivres.java:39)
W/System.err:     at android.os.AsyncTask.finish(AsyncTask.java:636)
W/System.err:     at android.os.AsyncTask.access$500(AsyncTask.java:177)
W/System.err:     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err:     at android.os.Looper.loop(Looper.java:135)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5254)
W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

这是我在日志中发现的错误:

I/System.out: JSON: [{"titre":"Le Parachutage","auteur":"Norbert Zongo","categorie":"Litterature","editeur":"Harmattan","prix":"400 UM"}]

              [ 01-02 21:52:56.868  5158: 5176 D/         ]
              HostConnection::get() New Host Connection established 0x79a60fcff600, tid 5176
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
E/EGL_emulation: tid 5176: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH)
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x79a605fe2ec0, error=EGL_BAD_MATCH
W/System.err: org.json.JSONException: No value for Titre
W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
W/System.err:     at org.json.JSONObject.getString(JSONObject.java:550)
W/System.err:     at xyz.selfenrichment.robertotomas.jsonparsing_stackoverflow.MainActivity$getData.onPostExecute(MainActivity.java:78)

因此,您看到Json对象中的键没有大写。 您想要String t = jsonObject.getString("titre"); 而不是“滴度”等

公平地说,这实际上可能是几件事。

我最终重写了您的代码,直到意识到防火墙被阻止。 因此,如果有问题,请将其关闭。

经过全部修改后,我使用的代码是:

package xyz.selfenrichment.robertotomas.jsonparsing_stackoverflow;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    TextView Titre, Auteur, Categorie , Editeur , Prix;

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

        Titre = (TextView) findViewById(R.id.titreTextView);
        Auteur = (TextView) findViewById(R.id.auteurTextView);
        Categorie = (TextView) findViewById(R.id.categorieTextView);
        Editeur = (TextView) findViewById(R.id.editeurTextView);
        Prix = (TextView) findViewById(R.id.prixTextView);
        new getData().execute();
    }

    class getData extends AsyncTask<String, String, String> {
        private String LOCALHOST = "192.168.1.9";
        HttpURLConnection urlConnection = null;

        @Override
        protected String doInBackground(String... args) {
            StringBuilder result = new StringBuilder();
            try {
                URL url = new URL("http://"+LOCALHOST+":8000/api/liste.json");

                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");

                urlConnection.setDoOutput(true);

                urlConnection.connect();

                BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream()));

                char[] buffer = new char[1024];

                String line;
                while ((line = br.readLine()) != null) {
                    result.append(line+"\n");
                }
                br.close();

                String jsonString = result.toString();

                System.out.println("JSON: " + jsonString);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                urlConnection.disconnect();
            }

            return result.toString();
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                JSONArray jsonArray = new JSONArray(result);
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                String t = jsonObject.getString("Titre");
                String a = jsonObject.getString("Auteur");
                String c = jsonObject.getString("Categorie");
                String e = jsonObject.getString("Editeur");
                String p = jsonObject.getString("Prix");
                Titre.setText(t);
                Auteur.setText(a);
                Categorie.setText(c);
                Editeur.setText(e);
                Prix.setText(p);

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

它也可能是清单。 确保你有

<uses-permission android:name="android.permission.INTERNET"/>

在那里。

也有可能是您的REST服务器。

这是一个正常工作的休息服务器(在节点中):

index.js

'use strict';

var express = require('express');
var app = express(); 

var router = express.Router();  

router.get('/liste.json', function (req, res) {
  res.json([
    {
      "titre": "Le Parachutage",
      "auteur": "Norbert Zongo",
      "categorie": "Litterature",
      "editeur": "Harmattan",
      "prix": "400 UM"
    }
  ])
})

app.use('/api', router)

app.listen(8000)

要使用它,请创建一个空目录,安装节点,然后在服务器目录中运行npm init只需在各字段中按Enter。 然后: npm install --save express 最后,您可以使用node index.js运行它

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM