首页 > 解决方案 > 尝试从我的大学停车场 API 在 Android 中导入数据

问题描述

我正在尝试从我的大学提供的 API 获取实时停车信息。我可以在运行 java 代码时获取数据。但是当我把这段代码放在android studio中时,它给了我一个例外。这是我的清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.parth.p4">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Check"></activity>
    </application>

</manifest>

这是我运行 java 代码的文件:

package com.example.parth.p4;

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

import java.net.URL;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Check extends AppCompatActivity {


    public TextView t;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check);

        try {
            chk();
        }catch (Exception  e)
        {
           t.setText("Error");
        }


    }
    private static Document loadTestDocument(String url) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        return factory.newDocumentBuilder().parse(new URL(url).openStream());
    }
    public void chk() throws Exception {
        t = (TextView)findViewById(R.id.textView2);
       String carPoolSpacesAvailable;
        Document doc = loadTestDocument("https://api.uow.edu.au/parking/data/?format=xml");



        NodeList nodes1 = doc.getElementsByTagName("parks");



        carPoolSpacesAvailable = nodes1.item(6).getFirstChild().getNodeValue();

         t.setText(carPoolSpacesAvailable);

    }
}

这是我试图在文本视图中显示数据的 xml 文件。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Check">



    <TextView
        android:id="@+id/textView2"
        android:layout_width="44dp"
        android:layout_height="23dp"
        tools:layout_editor_absoluteX="331dp"
        tools:layout_editor_absoluteY="16dp" />
</android.support.constraint.ConstraintLayout>

我得到的输出是我在 oncreate() 方法的 catch 块中放入的错误消息。请帮助。

标签: javaandroid

解决方案


确保您没有在 MAIN UI 线程上进行网络调用。

尝试从后台线程调用 chk()。

 TextView t;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    t = (TextView)findViewById(R.id.textView2);

    new DownloadFilesTask().execute();



}
// doInBackground is called from the background thread while the onPostExecute is called on the Main Thread.

private class DownloadFilesTask extends AsyncTask<Void, Void, String> {
    String carPoolSpacesAvailable = null;
    @Override
    protected String doInBackground(Void... voids) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
         try {
        Document
            doc = factory.newDocumentBuilder().parse(new URL("https://api.uow.edu.au/parking/data/?format=xml").openStream());
             NodeList nodes1 = doc.getElementsByTagName("parks");

             carPoolSpacesAvailable = nodes1.item(6).getFirstChild().getNodeValue();

         } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }



        return carPoolSpacesAvailable;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if(s!=null){
            t.setText(s);
        }
    }
}

在你的第二个活动中试试这个。


推荐阅读