简体   繁体   English

如何在两个不同的时间传递两个不同的JSON对象进行processFinish

[英]How to pass two different JSON Objects to processFinish at two different times

I have this MainActivity which does two HTTP calls and return the JSON object back to the MainActivity class. 我有这个MainActivity ,它执行两个HTTP调用,并将JSON对象返回给MainActivity类。 I have seperately implemented the AsyncTask class and used the AsyncResponse interface to get the JSON object to the MainActivity by using the processFinish function call. 我已经单独实现了AsyncTask类,并使用AsyncResponse接口通过使用processFinish函数调用将JSON对象获取到MainActivity

At first I came up with one HTTP call which worked perfectly. 最初,我提出了一个HTTP调用,该调用非常有效。 Secondly I wanted to do another HTTP call in the same activity class. 其次,我想在同一活动类中进行另一个HTTP调用。 So I edit the code to cater the second HTTP call. 因此,我编辑代码以适应第二个HTTP调用。

When I run the application, only the first HTTP call is working. 当我运行该应用程序时,只有第一个HTTP调用正在工作。 When I call the second HTTP call it throws an exception saying reference to a null object 当我调用第二个HTTP调用时,它将引发exception指出reference to a null object

Then I checked by logging the onPostExecute method which calls the processFinish function. 然后,我通过记录调用processFinish函数的onPostExecute方法进行检查。 There I could see the JSON Object. 在那里,我可以看到JSON对象。 So, that means the second JSON object doesn't get to the processFinish 因此,这意味着第二个JSON对象不会进入processFinish

How do I manage the second HTTP call? 如何管理第二个HTTP调用? Please help me! 请帮我! I am new to Android. 我是Android新手。

Following is my AsyncTask class... 以下是我的AsyncTask类...

public class ServiceHandler extends AsyncTask<String, Void, JSONObject> {

    String startStationID;
    String endStationID;
    String searchDate;
    String startTime;
    String endTime;

    public ServiceHandler(String startStationID, String endStationID, String searchDate, String startTime, String endTime) {
        this.startStationID = startStationID;
        this.endStationID = endStationID;
        this.searchDate = searchDate;
        this.startTime = startTime;
        this.endTime = endTime;
    }

    public interface AsyncResponse {
        void processFinish(JSONObject output);
    }

    public AsyncResponse delegate=null;

    public ServiceHandler(AsyncResponse delegate) {
        this.delegate = delegate;
    }

    @Override
    protected JSONObject doInBackground(String... params) {

        String method = params[0];
        JSONObject JSON_Object = null;


        if (method.equals("getStations")) {

            JSON_Object = Constants.apiCall("http://api.lankagate.gov.lk:8280/railway/1.0/station/getAll?lang=en");

        } else if (method.equals("searchTrains")) {
            JSON_Object = Constants.apiCall("http://api.lankagate.gov.lk:8280/railway/1.0/train/searchTrain?" +
                    "startStationID="+this.startStationID+"&" +
                    "endStationID="+this.endStationID+"&" +
                    "searchDate="+this.searchDate+"&" +
                    "startTime="+this.startTime+"&" +
                    "endTime="+this.endTime+"&" +
                    "lang=en");
        }
        return JSON_Object;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(JSONObject obj) {
        try{
Log.d("onPostExecute",obj.toString());
            delegate.processFinish(obj);

        }catch (Exception e){
            Log.e("onPostExecute",e.getMessage());
        }

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
}

Following is my processFinish function... 以下是我的processFinish功能...

    @Override
    public void processFinish(JSONObject output) {
        Log.d("processFinish",output.toString());

        if(!isSearchClicked) {
            //Get all the stations...
            if (output != null) {
                Toast.makeText(MainActivity.this, "Successfully Connected!", Toast.LENGTH_SHORT).show();
                try {
                    JSONObject obj = output.getJSONObject("RESULTS");
                    output = null;
                    JSONArray dataArray = obj.getJSONArray("stationList");

                    for (int i = 0; i < dataArray.length(); i++) {
                        JSONObject object1 = dataArray.getJSONObject(i);

                        String stationID = object1.getString("stationID");
                        String stationName = object1.getString("stationName");

                        stationNames.add(stationName);
                        stationIDs.add(stationID);
//                    stations.put(stationID,stationName);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(MainActivity.this, " Connection Failed!", Toast.LENGTH_SHORT).show();
            }
        }else {
            //search click action...
            if (output != null) {
                Toast.makeText(MainActivity.this, "Successfully Searched!", Toast.LENGTH_SHORT).show();


                try {
                    JSONObject obj = output.getJSONObject("RESULTS");
                    JSONArray directTrains = obj.getJSONArray("directTrains");


//                    Log.d("array size",String.valueOf(directTrains.length()));
//                    for (int i = 0; i < directTrains.length(); i++) {
//                        JSONObject object1 = directTrains.getJSONObject(i);
//
//                        String stationID = object1.getString("stationID");
//                        String stationName = object1.getString("stationName");
//                        Log.d("JArr", stationID + " : " + stationName);
//
//                        stationNames.add(stationName);
//                        stationIDs.add(stationID);
////                    stations.put(stationID,stationName);
//                    }
//                    Log.d("stationNames", stationNames.toString());

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(MainActivity.this, " Connection Failed!", Toast.LENGTH_SHORT).show();
                Log.d("output",output.toString());
            }
        }
    }

Following is my first HTTP call... 以下是我的第一个HTTP呼叫...

ServiceHandler sh = new ServiceHandler(this);

String method = "getStations";
sh.execute(method);

Following is my second HTTP call... 以下是我的第二个HTTP呼叫...

String method = "searchTrains"
        ServiceHandler sh = new ServiceHandler(startStationID,endStationID,searchDate,startTime,endTime);
        sh.execute(method);

Although I don't understand exactly what your problem is. 尽管我不太清楚您的问题是什么。 There are few things I suggest you to do. 我建议您做的事情很少。

Here I go. 我来啦。

  1. Don't use AsyncTask to make your http calls , use an intent services instead. 不要使用AsyncTask进行http调用,而应使用意图服务。
  2. Use a OkHTTP library for your networking source 使用OkHTTP库作为您的网络来源
  3. On your intent service send local broadcast with LocalBroadcastManager to broadcast your results from the http call. 在您的意向服务上,使用LocalBroadcastManager发送本地广播以广播来自http调用的结果。
  4. Register broadcastsReceivers within your activities or fragments that will listen for those broadcasts that comes from the intent service 在您的活动或片段中注册广播接收者,这些接收者将侦听来自Intent服务的广播

Why not to use AsyncTask: Because of configuration change - if you rotate your device you will lose that network calls- 为什么不使用AsyncTask:由于配置更改-如果旋转设备,您将失去网络通话-

Read about intent services here 在此处阅读有关意图服务的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM