ANDROID,从Web服务器解析JSON数据并显示在ListView上

2024-01-12

我正在尝试显示 JSON url 链接的 JSON 结果。目前,当我加载时,它什么也不显示,只是空白页面。这是我获取有关 JSON 信息的来源 http://adblogcat.com/parse-json-data-from-a-web-server-and-display-on-listview/.

这是我的代码:

public class DVLAresult extends AppCompatActivity {


    public class DVLAlist extends ListActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.content_dvlaresult);


            setListAdapter(new ArrayAdapter(
                    this,android.R.layout.simple_list_item_2,
                    this.populate()));
        }


        private ArrayList<String> populate() {
            ArrayList<String> items = new ArrayList<String>();

            TextView newtext = (TextView) findViewById(R.id.view_number);

            try {
                URL url = new URL
                        ("https://dvlasearch.appspot.com/DvlaSearch?licencePlate=mt09nks&apikey=DvlaSearchDemoAccount");
                HttpURLConnection urlConnection =
                        (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();
                // gets the server json data
                BufferedReader bufferedReader =
                        new BufferedReader(new InputStreamReader(
                                urlConnection.getInputStream()));
                String next;
                while ((next = bufferedReader.readLine()) != null) {
                    JSONArray ja = new JSONArray(next);

                    for (int i = 0; i < ja.length(); i++) {
                        JSONObject jo = (JSONObject) ja.get(i);
                        items.add(jo.getString("text"));
                    }
                }
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return items;
        }
    }
}

这是我的 XML 文件 simple_list_2.xml

<?xml version="1.0" encoding="utf-8"?>

<TwoLineListItem xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/listPreferredItemHeight"
    android:mode="twoLine"
    android:paddingStart="?attr/listPreferredItemPaddingStart"
    android:paddingEnd="?attr/listPreferredItemPaddingEnd">

    <TextView android:id="@id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:textAppearance="?attr/textAppearanceListItem" />

    <TextView android:id="@id/text2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/text1"
        android:layout_alignStart="@id/text1"
        android:textAppearance="?attr/textAppearanceListItemSecondary" />

    <TextView android:id="@id/text3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/text2"
        android:layout_alignStart="@id/text2"
        android:textAppearance="?attr/textAppearanceListItemSecondary" />

... Continue up to text18, because I have 18 fields.

</TwoLineListItem>

这是主要的 XML ListView

 <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/list"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_above="@+id/button2"
        android:layout_below="@+id/view_number" />

我碰巧遇到类似的问题。这是帮助我找到解决方案的代码。希望对你有帮助。

活动主文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SEND GET REQUEST"
        android:id="@+id/sendGet"
        android:onClick="sendGetRequest"
        android:layout_alignParentStart="true" />

    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/scrollView"
        android:layout_below="@+id/sendGet"
        android:layout_centerHorizontal="true">

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Response ....."
            android:id="@+id/showOutput"
            android:layout_alignEnd="@+id/scrollView"
            android:layout_marginEnd="34dp" />

    </ScrollView>

</RelativeLayout>

MainActivity.java

import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.google.android.gms.appindexing.Action;

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

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private ProgressDialog progress;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
 //   private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
  //      client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    public void sendGetRequest(View View) {
        new GetClass(this).execute();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
 //       client.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://com.example.gunawardena.get_post_demo/http/host/path")
        );
 //       AppIndex.AppIndexApi.start(client, viewAction);
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://com.example.gunawardena.get_post_demo/http/host/path")
        );
      //  AppIndex.AppIndexApi.end(client, viewAction);
      // client.disconnect();
    }

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

        private final Context context;

        public GetClass(Context c) {
            this.context = c;
        }

        protected void onPreExecute() {
            progress = new ProgressDialog(this.context);
            progress.setMessage("Loading Get Method.....");
            progress.show();
        }

        @Override
        protected Void doInBackground(String... params) {
            try {

                final TextView outputView = (TextView) findViewById(R.id.showOutput);
                URL url = new URL("https://dvlasearch.appspot.com/DvlaSearch?licencePlate=mt09nks&apikey=DvlaSearchDemoAccount");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                connection.setRequestMethod("GET");
                connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
                connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");

                int responseCode = connection.getResponseCode();

                final StringBuilder output = new StringBuilder("Request URL " + url);
                output.append(System.getProperty("line.separator") + "Response Code " + responseCode);
                output.append(System.getProperty("line.separator") + "Type " + "GET");
                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line = "";
                StringBuilder responseOutput = new StringBuilder();
                System.out.println("output===============" + br);
                while ((line = br.readLine()) != null) {
                    responseOutput.append(line);
                }
                br.close();

                output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());

                MainActivity.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        outputView.setText(output);
                        progress.dismiss();

                    }
                });

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }
    }
}

模拟器上的输出

HTH


参考:

  • 如何在Java中发送HTTP请求GET/POST http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/
  • Java HttpURLConnection 发送 HTTP GET/POST 请求的示例 http://www.journaldev.com/7148/java-httpurlconnection-example-to-send-http-getpost-requests
  • Android POST 和 GET 请求使用 HttpURLConnection 教程 https://www.numetriclabz.com/android-post-and-get-request-using-httpurlconnection/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ANDROID,从Web服务器解析JSON数据并显示在ListView上 的相关文章

  • InflateException:二进制 XML 文件行 #8:膨胀类 ImageView 时出错

    我知道还有其他问题也问同样的事情 我已经看过其中的大部分了 大多数答案都涉及内存错误 我看不出如何ImageView只加载一个小图标 24x24 像素 可以做出类似这样的东西 但我想在这里发布堆栈跟踪 也许其他人可以识别我无法识别的东西并帮
  • 如果我使用单例,在哪里关闭 SQLiteOpenHelper

    我有以下课程允许用户获得SQLiteOpenHelper object import android content Context public class DBUtils private DBUtils private static D
  • Android 中的 JDBC 连接

    有没有人在 android 中尝试过 JDBC 连接 因为在 Android 2 3 中支持 JDBC 我必须在没有 Web 服务的情况下连接 Mysql 我已经提出申请 但它给了我错误 public class MysqlConnect
  • Onclick 不会在 CardView 上触发

    我有一个OnClickListener on a CardView 仅当我点击内容之外的区域 TextViews ImageViews 时 侦听器才起作用 我的内部也有一个线性布局CardView 我希望当我点击屏幕上的任意位置时它就能工作
  • Google Games API 需要 games_lite 函数

    我使用 Google Play 游戏服务 我从官方示例中获取了代码 尝试使用 API 27 和 API 17 所有功能仅在一个帐户 所有者 Google 开发者控制台 下有效 在任何其他帐户下均有效 不行 我明白了 E AndroidRun
  • 推送通知需要很长时间才能到达

    我在适用于 iOS 和 Android 的 Adob e Air 应用程序中遇到推送通知的奇怪问题 我正在使用 Milkman Games 的 Easy Push ANE 以及 One Signal 服务 问题是通知确实会到达 但有时 随机
  • Oreo(API 26)-drawOverlay + 在状态栏上绘制

    在android oreo中 我无法使用WindowManager LayoutParams TYPE SYSTEM ERROR不再需要并且必须使用WindowManager LayoutParams TYPE APPLICATION OV
  • 使用MockWebServer暂停功能测试

    我正在测试使用 MockWebServer 的挂起函数返回结果的 api 但它不适用于 runBlockingTest testCoroutineDispatcher testCorounieScope 除非launch使用builder
  • 更改弹出对话框的背景颜色

    我编写了显示弹出对话框的 android 代码 但我想将背景颜色从黑色更改为白色 然后更改文字颜色 这是对话框的代码 mPrefs PreferenceManager getDefaultSharedPreferences this Boo
  • 替换 JSON 中的转义字符

    我想用空格替换 JSON 字符串中的 字符 我怎样才能做到这一点 我发现从 JSON 字符串中删除所有转义字符的最简单 最好的方法是将字符串传递到正则表达式 Unescape 方法 此方法返回一个没有转义字符的新字符串 甚至删除了 n t
  • 使用 PHP 和 jSON 从 MySQL 获取 UIImage

    我正在开发一个小型新闻阅读器 它通过对 URL 执行 POST 请求来从网站检索信息 响应是一个带有未读新闻的 JSON 对象 例如 应用程序上的最新新闻的时间戳为 2013 03 01 当用户刷新表时 它会发布 domain com ap
  • setKeyListener 将覆盖 setInputType 并更改键盘

    大家好 我在两个设备之间遇到问题 在实践中使用InputType和KeyListener我正在操纵一个EditText让它从数字键盘接收逗号和数字 有关更多背景信息 请检查我之前的question https stackoverflow c
  • 有效的 URL 分隔符

    我有一个很长的 URL 其中包含多个值 示例1 http www domain com list seach type 0 search period 1 search min 3000 search max 21000 search ar
  • 将 JSON 数组转换为 bash 数组并保留空格

    我想将 JSON 文件转换为 bash 字符串数组 稍后我可以对其进行迭代 我的JSON结构如下 USERID TMCCP CREATED DATE 31 01 2020 17 52 USERID TMCCP CREATED DATE 31
  • Android 和 iPhone 应用程序可以使用同一个 Facebook 应用程序 ID 吗?

    我有两个具有相同名称和相同功能的应用程序 一款在安卓市场 一款在应用商店 目前仅通过 iPhone 应用程序 您可以使用我创建的 Facebook 应用程序将您的分数发布到 Facebook 墙上 我的问题是我可以使用相同的 Android
  • 在运行时用Dagger添加Retrofit RequestInterceptor

    我正在使用匕首和改装 我用 Dagger 注入我的 Retrofit 服务 现在我想做一个授权请求来获取 accessToken 之后 我想使用请求拦截器来增强我的 api 模块 以便将此访问令牌用于将来的请求 我的想法是在收到访问令牌后使
  • 将文件读取为 JSON

    我想读取几个文件 index html style css main js 来创建用于上传的 JSON 有效负载 我知道使用 Nodejs 我可以开始创建我想要的东西 如下所示 var fs require fs fs readFile i
  • Android 键盘清单未显示在设置中

    我正在制作我的第一个 Android 应用程序 我需要它作为键盘服务 据我所知 清单看起来不错 并且我有一个文件 WifiJoy java 在 com zwad3 wifijoy 包中 以及所有其他文件
  • Android 方向传感器的替代品是什么?

    大家好 我正在为 Android 构建 3D 游戏 我目前正在尝试在我的游戏中添加一个传感器 允许玩家倾斜机器人作为其控制 理想情况下 我想使用方向传感器 但我注意到它已被弃用 有谁知道如何检测 Android 中的倾斜并且不使用这个传感器
  • 如何为 Android Q 打开具有特定专辑或文件夹的默认图库应用程序?

    我尝试打开图库中的特定文件夹 如下代码所示 但它对我不起作用 并且出现错误无法找到物品 fun openDirectoryInGallery context Context directory String val intent Inten

随机推荐

  • 在express js路由中调用异步函数的正确方法

    我现在就是这样做的 但试图看看是否有正确的或其他的方法可以做到这一点 async function getmanual vars req res ajax var return data let db await mongo client
  • vim:添加注释宏

    Vim 对我来说几乎是完美的 但我仍然想要行注释和块注释功能 我想知道如何编写 vimrc 来在 python 和 javascript 中执行此操作 没有插件 http www vim org scripts script php scr
  • 为什么苹果的闭包声明缺少参数标签

    当我读完UIKit 大多数时候我看到的是闭包 作为函数参数 缺少这样的参数标签 func fooClosure fooClosure Bool gt Swift Void 在某些情况下我可以猜出它代表什么 而在其他情况下我不能 Exampl
  • 从数据文件 VB 脚本中读取下一行

    我正在尝试获取数据标记文件的下一行 但是因为有多行具有相同的标记 所以它正在经历并获取最后一行 但我需要第一行 下面的示例标记文件 Summary SA2100 7775555 Summary SUM100 9674555 Summary
  • 使用 Jquery 附加多个 html 元素

    我对 jQuery 很陌生 想知道是否有人可以建议我最佳实践 我希望将一个 div 元素附加到页面 其中包含大量 html 并且不确定实现此目的的最佳方法是什么 或者是否建议使用 jquery 例如 如果我想使用 jquery 将以下代码附
  • 函数模板的多个定义

    假设头文件定义了一个函数模板 现在假设有两个实现文件 include这个头 并且每个都调用了函数模板 在两个实现文件中 函数模板都使用相同的类型进行实例化 header hh template
  • 加载页面时显示加载动画微调器

    我想在 JQueryMobile 页面中显示加载动画微调器 该页面是通过 ajax 关闭加载的 页面已加载data ajax false or rel external 我试穿了pagebeforecreate and pageshow事件
  • Javascript样式对象将复杂的颜色名称转换为rgb

    当将复杂的 CSS 颜色名称应用于 DOM 元素时 有没有一种方法可以覆盖 javascript 将复杂的 CSS 颜色名称转换为 RGB 值的方式document getElementById xxx style object 例如 设置
  • php imagemagick 创建平铺金字塔 TIFF

    好吧 正如标题所说 我遇到了一个问题 我的测试函数是这样的 imagePath tmp 511a3874a0da1 pngName imagePath png tifName imagePath tif tempImg new Imagic
  • 具有多个子类型的 Scala 泛型(元组)类型

    我正在 Scala 中编写一个数据结构 基本上是一个哈希图 它将采用一个元组 每次可能有不同数量的参数 并用它做一些事情 为了一般地实现这一点 我定义了一个类型 type T lt Tuple1 with Tuple2 with Tuple
  • 更改应用程序中的 Cocoa 显示名称?

    如何更改 OS X 上 Dock 中应用程序上方显示的名称 我尝试过重命名目标并重命名我的项目 而且 我已经用 Google 搜索过它 经过进一步谷歌搜索后 我发现了这一点 项目 gt 编辑活动目标 gt 打包 gt 产品名称 虽然我第一次
  • Paytm sdk ios集成打开Paytm付款表格?

    在 iOS Xcode 7 中集成 Paytm sdk 2 1 并配置为进行支付 我有一个表格 其中需要填写金额和其他字段 然后有一个 Payment 按钮 这是我正在使用的代码 Step 1 Create a default mercha
  • jqGrid 卡在加载中?

    我正在尝试使用 JQuery 插件jqGrid http www trirand com blog 使用 asp net mvc 应用程序 我在下面向网格传递一个 JSON 对象format http www secondpersonplu
  • 创建 UIImageView 时上下文无效

    当我尝试创建 UIImageView 时出现错误 看看这段代码 UIImage backgroundPanel UIImage imageNamed loginPanelBackground png resizableImageWithCa
  • Azure API 管理:验证 jwt 令牌范围

    我们希望使用 validate jwt 策略保护 API 操作调用 但当我使用 required claims 检查范围时遇到问题 示例 我有一个令牌 其范围包括多个值 例如 xxx READ xxx WRITE yyy READ yyy
  • 如何解析 Excel 文件以提供与视觉上显示的数据完全相同的数据?

    我使用的是 Rails 5 Ruby 2 4 我想阅读 xls 文档 并且希望将数据转换为 CSV 格式 就像在 Excel 文件中显示的那样 有人推荐我使用 Roo 所以我就这么做了 book Roo Spreadsheet open f
  • 将标题行写入 csv python

    如何将标题添加到 csv 的第一行 我的解决方案目前附加了所有内容 就像是 writer writerow DataA DataB DataC DATA D 0 我觉得有一种简单的方法可以做到这一点 但我忽略了显而易见的事情 我在网上查看了
  • 为什么 JSLint 更喜欢点表示法而不是方括号?

    我一直在检查我的一些代码 并收到一些错误 说最好使用点表示法 我发现我使用的是方括号符号 从这篇精彩的文章中可以清楚地看出 https stackoverflow com questions 2001360 javascript dot n
  • 实体框架-存储过程返回值

    我正在尝试获取存储过程的返回值 以下是此类存储过程的示例 select Name IsEnabled from dbo something where ID ID if rowcount 0 return 1 return 这是一个简单的选
  • ANDROID,从Web服务器解析JSON数据并显示在ListView上

    我正在尝试显示 JSON url 链接的 JSON 结果 目前 当我加载时 它什么也不显示 只是空白页面 这是我获取有关 JSON 信息的来源 http adblogcat com parse json data from a web se