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

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

概述我试图从JSONurl链接显示JSON结果.目前,当我加载时,它什么都不显示,只是空白页面.ThisisthesourcewhereIgotinformationaboutJSON.这是我的代码:publicclassDVLAresultextendsAppCompatActivity{publicclassDVLAlistextendsListActivity{@

我试图从JSON url链接显示JSON结果.目前,当我加载时,它什么都不显示,只是空白页面. This is the source where I got information about JSON.

这是我的代码:

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" />

解决方法:

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

activity_main.xml中

<?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

参考文献:

> How to send HTTP request GET/POST in Java
> Java HttpURLConnection Example to send HTTP GET/POST Requests
> Android POST and GET Request using HttpURLConnection Tutorial

总结

以上是内存溢出为你收集整理的ANDROID,从Web服务器解析JSON数据并在ListView上显示全部内容,希望文章能够帮你解决ANDROID,从Web服务器解析JSON数据并在ListView上显示所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1102746.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存