【问题标题】:JSON Parsing Into TextView Android APIJSON 解析成 TextView Android API
【发布时间】:2017-01-03 00:46:58
【问题描述】:

这是我的 API json

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

我创建了这个布局,我想在活动启动时用这些数据(“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 文件中使用了我需要的所有权限(网络、互联网等)。

我使用 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)

【问题讨论】:

  • 你能用调试或日志语句检查 t a c e 和 p 的值吗?
  • 好的,我该怎么做?
  • 请阅读这篇关于如何开始调试的文章:developer.android.com/studio/debug/index.html。但在此之前,您是否尝试过查看 JSON URL 是否适用于您正在测试 Android 应用程序的 Android 设备(使用网络浏览器)?
  • 好的,所以我调试了我的应用程序并通过 A.S Emulator 启动。在地址 10.0.2.2 。它说“Titre”没有价值。我将编辑我的帖子,以便您查看完整的错误日志。
  • 你没有发布错误 :) 顺便说一句,我为你找到了。立即发布

标签: java android json api symfony


【解决方案1】:

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

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"); 而不是“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运行它

【讨论】:

  • 谢谢先生!我会测试的。确实我的钥匙没有大写,而且你的代码似乎比我的要好得多。我希望它会起作用。否则,当我用 Postman 测试它时,我的 Api 可以工作,并且我在 Manifest 中使用了 Internet 权限。
  • 您看到org.json.JSONException 异常对吗?因此,除了 jsonObject.getString 调用之外,您无需重写任何内容 :) 你是金子。
  • 谢谢大哥!!!!!!你救了我的命 !问题只是大写字母,我应该只写“titre”而不是“Titre”哈哈。上帝保佑你,这是我项目的最后一部分!
猜你喜欢
  • 2012-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多