簡體   English   中英

Android沒有得到Json結果

[英]Android not getting Json result

這是我的代碼。 這只是整個應用程序的一小段。 它發出HTTP請求並從septa獲取火車數據。 該代碼是正確的,因為它可以在Java項目中使用。 請注意,當我嘗試在單獨的Java類中執行簡單的http請求部分並將其作為Java文件運行時。 在運行中,它給了我一個致命錯誤:java.lang.String的值無效布局。 我試着在這個論壇上查看話題。 什么都沒有。 不知道為什么會這樣。 該代碼之前工作!

package com.cs275.septaassignment;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.HttpURLConnection;

import android.app.Activity;
import android.os.Bundle;
import android.os.AsyncTask;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.*;

import java.util.ArrayList;

public class TrainInfo extends Activity
{
    protected static String startStation;
    protected static String endStation;

    private ListView listView;//ListView for the output
    private ArrayAdapter<String> adapter;//Adapter to interact with the ListView


    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.train_infolayout);

        startStation = this.getIntent().getExtras().getString("fromStation");
        endStation = this.getIntent().getExtras().getString("toStation");

        ArrayList<String> trainInfo = new ArrayList<String>();

        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, trainInfo);//initializing the ArrayAdapter

        listView = (ListView)findViewById(R.id.train_listView);
        listView.setAdapter(adapter);//Linking the adapter      
        adapter.setNotifyOnChange(true);//This ensures that the changes in data so the UI components can refresh themselves     

        TrainData trainSchedule = new TrainData();
        trainSchedule.execute();
    }
    public class TrainData extends AsyncTask<Void,Void,Void>
    {
        ArrayList<String> nextTrains;

        protected void onPostExecute(Void arg0)//This method is called after the background process is complete 
        {
            adapter.clear();
            for(int i = 0;i<nextTrains.size();i++)
            {
                System.out.println(nextTrains.get(i));
                adapter.add(nextTrains.get(i));
            }
            adapter.add("Hello World");
            TextView updateMessage = (TextView) findViewById(R.id.train_list_info);
            updateMessage.setText("Here are the available trains for your trip from " + startStation + " to " + endStation);
            adapter.notifyDataSetChanged();//This send the signal that the data is changes and allows the UI components like the ListView to get updated.           

        }
        @Override
        protected Void doInBackground(Void... params) 
        {
            // TODO Auto-generated method stub
            try
            {
                String sURL = "http://www3.septa.org/hackathon/NextToArrive/"+ startStation + "/" + endStation + "/10"; 
                System.out.println(sURL);
                URL url = new URL(sURL);
                HttpURLConnection request = (HttpURLConnection) url.openConnection();
                request.connect();

                JsonParser jp = new JsonParser();//Json parsing tool
                JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));//Getting content in Json
                System.out.println("root:\n" + root);
                JsonArray rootArray = root.getAsJsonArray();

                nextTrains = new ArrayList<String>();
                if(rootArray.size() > 0)
                {
                    for(int i = 0;i<rootArray.size();i++)
                    {
                        JsonObject train = rootArray.get(i).getAsJsonObject();
                        String departureTime = train.get("orig_departure_time").getAsString();
                        String arrivalTime = train.get("orig_arrival_time").getAsString();
                        String delayTime = train.get("orig_delay").getAsString();
                        String trainNumber = train.get("orig_train").getAsString();

                        String result = "Train " + trainNumber + "\nDeparts from " + startStation + ": " + departureTime
                                        + "\nArrives at " + endStation + ": " + arrivalTime;
                        if(!delayTime.equals("On Time"))
                            result = result + "\nDelayed: " + delayTime;
                        nextTrains.add(result);
                    }
                }else
                {
                    nextTrains.add("No trains available from " + startStation + " to " + endStation);
                }


                }catch(Exception e)
                {
                    System.out.println("Unable to make http request!");
                }
            return null;
        }
        public void retrieveData()
        {

        }
    }
}

您應該通過將AsyncTask定義為<Intent, Void, Void>並調用其execute方法(例如trainSchedule.execute(getIntent());來避免可能的線程問題trainSchedule.execute(getIntent()); doInBackground(Void... params)更改為doInBackground(Intent... params)並在使用以下方法設置URL之前,從該意圖中獲取更多信息

String start = params[0].getExtras().getString("fromStation");
String end = params[0].getExtras().getString("toStation");

使用URLEncoder 編碼方法對您的URL進行編碼,這會將空格更改為%20和其他必要的編碼

更新資料

如前所述,上述方法實際上會將空格編碼為+ ,這在這種情況下是不好的,因為服務器不能很好地處理它們。 您也可以嘗試使用Uri.encode ,它看起來應該可以根據需要將空格編碼為%20。

進一步更新

根據此答案,您將必須在使用URLEncoder之后自己對空格進行編碼,如下所示: URLEncoder.encode(sURL, "UTF-8").replace("+", "%20")

將其作為Java文件運行。 在運行中,它給了我一個致命錯誤:java.lang.String的值無效布局

作為Android應用程序而不是通用Java應用程序運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM