0

我正在尝试在 asynctask 中使用 json 解析加载数据,但加载不正确,有时无法获得完整的数据,有时说 android.os.main 线程我尝试了很多次但我仍然遇到问题我把我的代码和 logcat 放在这里

这是我的主要课程

HomeActivity.java

class HomeACtivity extends Activity 
 {
  @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
 {
            new FlightListBack.execute("");
   }
 }


 public class FlightListBack extends AsyncTask<String, Integer, ArrayList<HashMap<String,String>>>

{

ArrayList<String> airportList = new ArrayList<String>();
final  JsonParser jparser= new JsonParser();
final  ArrayList<HashMap<String, String>> spinnerAirportList = new ArrayList<HashMap<String, String>>();

String airporturl="http://api.flightstats.com/flex/airports/rest/v1/json/withinRadius/-74.0063/40.7141/100?appId=4dde11f5&appKey=6b80a6ed5d82c8f0b28dadb14e81bfcd";
String spinnerstringfunction;


List<String> spinnercityList= new ArrayList<String>();
final List<String> spinnerAirportNameList= new ArrayList<String>();
JSONArray  sjairport;



@Override
protected ArrayList<HashMap<String,String>> doInBackground(
        String... params) {

    spinnerstringfunction=jparser.getJSONFromUrl(airporturl);

    Log.e("SpinnerstringFunction", "size"+spinnerstringfunction);

    try
    {
    // Getting Array of Contacts
    JSONObject jobject= new JSONObject(spinnerstringfunction);          //  Log.e("JOBJECT ","ACTIVITY-->"+jobject.length());

    // Airlines Array For Getting Airlines Name
    sjairport=jobject.getJSONArray(TAG_AIRPORT);            //  Log.e("JSONARRAY","AIRLINES"+jairlines.length());



    for(int a=0;a<sjairport.length()-30;a++)
    {

        HashMap<String, String> spinnermap = new HashMap<String, String>();

        String spinnerfs=sjairport.getJSONObject(a).get(TAG_SPINNERFS).toString(); 
        String spinnername=sjairport.getJSONObject(a).get(TAG_SPINNERNAME).toString();
        String  spinnercity=sjairport.getJSONObject(a).get(TAG_SPINNERCITY).toString();

        spinnermap.put(TAG_SPINNERFS, spinnerfs);
        spinnermap.put(TAG_SPINNERNAME,spinnername);
        spinnermap.put(TAG_SPINNERCITY,spinnercity);


        if(!spinnercityList.contains(spinnercity))
        {
            spinnercityList.add(spinnercity);  // spinner city list
        }

        spinnerAirportList.add(spinnermap); // Array List For all hash map list 
    }
    Log.e("Spinner Airport List","Complete"+spinnercityList.size()); //
//  Log.e("Airport List","Complete"+spinnerAirportList); //

    Log.e("Spinner Airport List","Complete"+spinnercityList);

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }


    return spinnerAirportList;
}


protected void onPostExecute(String...result)
{

    try
    {



    cityspinner=(Spinner)findViewById(R.id.spinnercity);
    namespinner=(Spinner)findViewById(R.id.spinnername);
    timespinner=(Spinner)findViewById(R.id.spinnertime);
    buttontime=(Button)findViewById(R.id.buttontime);

        ArrayAdapter<String> spinneradapter= new ArrayAdapter<String>(HomeActivity.this, android.R.layout.simple_spinner_item,spinnercityList);
        spinneradapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        cityspinner.setAdapter(spinneradapter);


        // country spinner onclick start

        cityspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {

                String cityselected=cityspinner.getSelectedItem().toString();
                Log.e("city, selected", "Work"+cityselected);
                spinnerAirportNameList.clear();
                for(int b=0;b<spinnerAirportList.size();b++)
                {

                    if(cityselected.equals(spinnerAirportList.get(b).get(TAG_SPINNERCITY).toString()))
                    {
                        clear();
                        String airportname=spinnerAirportList.get(b).get(TAG_SPINNERNAME).toString();
                        Log.e("country, selected", "Work"+cityselected);
                        Log.e("country Selected Airport","work"+airportname);
                        spinnerAirportNameList.add(airportname);
                    }
                }
                Log.e("Spinner Airport NAme list","Work"+spinnerAirportNameList);

                ArrayAdapter<String> spinnerairportnameadapter= new ArrayAdapter<String>(HomeActivity.this, android.R.layout.simple_spinner_item,spinnerAirportNameList);
                spinnerairportnameadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                namespinner.setAdapter(spinnerairportnameadapter);

            }

            public void onNothingSelected(AdapterView<?> arg0) {

            }

        });

        // country spinner onclick finish



        // name spinner onclick start

        namespinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {


                String nameselected=namespinner.getSelectedItem().toString();

                Log.e("Name, selected", "Work"+nameselected);

                for(int c=0;c<spinnerAirportList.size();c++)
                {   
                    if(nameselected.equals(spinnerAirportList.get(c).get(TAG_SPINNERNAME).toString()))
                    {
                        spinnerairportfs=spinnerAirportList.get(c).get(TAG_SPINNERFS).toString();
                        Log.e("Name, selected", "Work"+nameselected);
                        Log.e("fs Selected Airport","work"+spinnerairportfs);

                    }
                }

            }
            public void onNothingSelected(AdapterView<?> arg0) {

            }
        });



        //name spinner onclick finish

        // time spinner
     String[] flighttime={"12:00AM To 1:00AM"   ,   "1:00AM To 2:00AM"   ,  "2:00AM To 3:00AM",
                          "3:00AM To 4:00AM"    ,   "4:00AM To 5:00AM"   ,  "5:00AM To 6:00AM",
                          "6:00AM To 7:00AM"    ,   "7:00PM To 8:00AM"   ,  "8:00AM To 9:00AM",
                          "9:00AM To 10:00AM"   ,   "10:00PM To 11:00AM" ,  "11:00AM To 12:00PM",
                          "12:00PM To 1:00PM"   ,   "1:00PM To 2:00PM"   ,  "2:00PM To 3:00PM",
                          "3:00PM To 4:00PM"    ,   "4:00PM To 5:00PM"   ,  "5:00PM To 6:00PM",
                          "6:00PM To 7:00PM"    ,   "7:00PM To 8:00PM"   ,  "8:00PM To 9:00PM",
                          "9:00PM To 10:00PM"   ,   "10:00PM To 11:00PM" ,  "11:00PM To 12:00PM"};

        ArrayAdapter<String>spinnertimeadapter= new ArrayAdapter<String>(HomeActivity.this, android.R.layout.simple_spinner_item,flighttime);
        spinnertimeadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        timespinner.setAdapter(spinnertimeadapter);

        timespinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {

                String timeselected=timespinner.getSelectedItem().toString();

                if(timeselected.equals("12:00AM To 1:00AM"))
                {

                    time="0";
                }
                else if(timeselected.equals("1:00AM To 2:00AM"))
                {
                    time="1";
                }
                else if(timeselected.equals("2:00AM To 3:00AM"))
                {
                    time="2";
                }
                else if(timeselected.equals("3:00AM To 4:00AM"))
                {
                    time="3";
                }
                else if(timeselected.equals("4:00AM To 5:00AM"))
                {
                    time="4";
                }
                else if(timeselected.equals("5:00AM To 6:00AM"))
                {
                    time="5";
                }
                else if(timeselected.equals("6:00AM To 7:00AM"))
                {
                    time="6";
                }
                else if(timeselected.equals("7:00AM To 8:00AM"))
                {
                    time="7";
                }
                else if(timeselected.equals("8:00AM To 9:00AM"))
                {
                    time="8";
                }
                else if(timeselected.equals("9:00AM To 10:00AM"))
                {
                    time="9";
                }
                else if(timeselected.equals("10:00AM To 11:00AM"))
                {
                    time="10";
                }
                else if(timeselected.equals("11:00AM To 12:00PM"))
                {
                    time="11";
                }
                else if(timeselected.equals("12:00PM To 1:00PM"))
                {
                    time="12";
                }
                else if(timeselected.equals("1:00PM To 2:00PM"))
                {
                    time="13";
                }
                else if(timeselected.equals("2:00PM To 3:00PM"))
                {
                    time="14";
                }
                else if(timeselected.equals("3:00PM To 4:00PM"))
                {
                    time="15";
                }
                else if(timeselected.equals("4:00PM To 5:00PM"))
                {
                    time="16";
                }
                else if(timeselected.equals("5:00PM To 6:00PM"))
                {
                    time="17";
                }
                else if(timeselected.equals("6:00PM To 7:00PM"))
                {
                    time="18";
                }
                else if(timeselected.equals("7:00PM To 8:00PM"))
                {
                    time="19";
                }
                else if(timeselected.equals("8:00PM To 9:00PM"))
                {
                    time="20";
                }
                else if(timeselected.equals("9:00PM To 10:00PM"))
                {
                    time="21";
                }
                else if(timeselected.equals("10:00PM To 11:00PM"))
                {
                    time="22";
                }
                else if(timeselected.equals("11:00PM To 12:00PM"))
                {
                    time="23";
                }
            }
            public void onNothingSelected(AdapterView<?> arg0) {

            }
        });




    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    buttontime.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {


             ArrayList<HashMap<String, String>> flightList = new ArrayList<HashMap<String, String>>();




              Calendar now = Calendar.getInstance();
              int year = now.get(Calendar.YEAR);
              Log.e("Year","ss"+year);
              int month = now.get(Calendar.MONTH); // Note: zero based!
              Log.e("Month","ss"+month);

              int day = now.get(Calendar.DAY_OF_MONTH);
              Log.e("day","ss"+day);

              Log.e("Time is Selected","time"+time);

                Log.e("Spinner airoort fs","fs"+spinnerairportfs);
                String flighturl = "http://api.flightstats.com/flex/flightstatus/rest/v2/json/airport/status/"+spinnerairportfs+"/dep/"+year+"/"+month+"/"+day+"/"+time+"?appId=4dde11f5&appKey=6b80a6ed5d82c8f0b28dadb14e81bfcd&utc=false&numHours=1";

                Log.e("Flight url","Work"+flighturl);
                String jsonstringfunction=jparser.getJSONFromUrl(flighturl);


                try
                {

                        JSONObject jobject= new JSONObject(jsonstringfunction); 
                        JSONObject appendix = jobject.getJSONObject(TAG_APPENDIX);              Log.e("JOBJECT ","APPENDIX-->"+appendix.length());

                        // Airlines Array For Getting Airlines Name
                        JSONArray  jairlines=appendix.getJSONArray(TAG_AIRLINES);               Log.e("JSONARRAY","AIRLINES"+jairlines.length());

                        // Airport Array For Getting Airport Name
                        JSONArray  jairport=appendix.getJSONArray(TAG_AIRPORT);                 Log.e("JSONARRAY","AIRPORT"+jairport.length());

                        // Flightstatuses Array For Getting INFO
                        JSONArray jflightstatuses=jobject.getJSONArray(TAG_FLIGHTSTATUSES);     Log.e("JSONARRAY","FLIGHTSTATUSES"+jflightstatuses.length());

                        int i;
                        int j;
                        int k;
                        int m;
                        int n;


                        //****************************** Flightstatuses Array *****************************
                        for(i=0;i<jflightstatuses.length();i++)
                        {
                            clear();
                            // creating new HashMap
                            HashMap<String, String> map = new HashMap<String, String>();


                            arrivalairportfscode=jflightstatuses.getJSONObject(i).get(TAG_ARRIVALAIRPORTFSCODE).toString();     //  Log.e("ArrivalAirportFsCode","AirportFSCode"+arrivalairportfscode);
                            carrierfscode=jflightstatuses.getJSONObject(i).get(TAG_CARRIERFSCODE).toString(); 
                            flightnumber=jflightstatuses.getJSONObject(i).get(TAG_FLIGHTNUMBER).toString();


                            //****************************** Airport Array *****************************
                            // Comparing ArrivalAirportFsCode For Finding The City Name
                            for(j=0;j<jairport.length();j++)
                            {
                                // Airport Fs Code from AirportArray
                                airportfs=jairport.getJSONObject(j).get(TAG_AIRPORTFS).toString(); //   Log.e("AIRPORT","FS"+airportfs);

                                // Compare ArrivalAirport FsCode and Airport Fs Code For Finding City Name
                                if(arrivalairportfscode.equalsIgnoreCase(airportfs))
                                {   
                                    // City Name From Airport Array
                                    city=jairport.getJSONObject(j).get(TAG_AIRPORTCITY).toString();     //Log.e("Airport City","City-->"+city);
                                    destination="( "+arrivalairportfscode+" ) "+city;       //Log.e("Destination City","city"+destination);
                                    flight=carrierfscode+" "+flightnumber;

                                }
                            }   // airport for loop complete

                            map.put(TAG_MDESTINATION, destination);
                            map.put(TAG_MFLIGHT,flight);


                            for(k=0;k<jairlines.length();k++)
                            {

                                // Airport Fs Code from AirportArray
                                airlinesfs=jairlines.getJSONObject(k).get(TAG_AIRLINESFS).toString();   //Log.e("AIRLINES","FS"+airlinesfs);

                                // Compare ArrivalAirport FsCode and Airport Fs Code For Finding City Name
                                if(carrierfscode.equalsIgnoreCase(airlinesfs))
                                {   
                                    // Airlines Name From Airlines Array
                                    airlinesname=jairlines.getJSONObject(k).get(TAG_AIRLINENAME).toString();        //Log.e("AIRLINES NAME","NAME"+airlinesname);
                                    Log.e("--"+flight,"--"+airlinesname);

                                }

                            } // airlines for loop complete
                            map.put(TAG_MAIRLINE,airlinesname);

                            JSONObject joperationaltimes=jflightstatuses.getJSONObject(i).getJSONObject(TAG_OPERATIONALTIMES);
                            Log.e("Operational times","-->"+joperationaltimes);

                            // Schedule Time 

                            JSONObject jschedulegatedeparture =new JSONObject();
                            JSONObject jestimateddeparture =new JSONObject();

                            for(m=0;m<joperationaltimes.length();m++)
                            {   
                                if(joperationaltimes.has(TAG_SCHEDULEDGATEDEPARTURE))
                                {   

                                       jschedulegatedeparture=joperationaltimes.getJSONObject(TAG_SCHEDULEDGATEDEPARTURE);
                                       schedule=jschedulegatedeparture.getString(TAG_SCHEDULEDATELOCAL).toString();
                                       schedule=schedule.substring(11);

                                       Log.e("Before convert","Time"+schedule);

                                       DateFormat f1 = new SimpleDateFormat("hh:mm:ss");
                                       Date d = f1.parse(schedule);
                                       DateFormat f2 = new SimpleDateFormat("h:mm a");
                                       schedule=f2.format(d).toLowerCase(); // "12:18am"

                                       Log.e("After convert","Time"+schedule);
                                     //  jestimateddeparture=joperationaltimes.getJSONObject(TAG_ACTUALGATEDEPARTURE);
                                     //  actual=jestimateddeparture.getString(TAG_ACTUALDATELOCAL).toString();
                                     //  actual=actual.substring(11);
                                }
                                else
                                {
                                     schedule="Not Available";
                                }

                            }
                            map.put(TAG_MSCHEDULE, schedule);

                            //Log.e("ScheduleGatedtime",""+jschedulegatedeparture);
                            //Log.e("Schedule Time","Work"+schedule);
                            //Log.e("ActualGatedtime",""+jestimateddeparture);
                            //Log.e("Actual Time","Work"+actual);

                            //------------------------------------------------------------------------------------

                            // AIRPORT RESOURCES OBJECT fOR getting departure terminal and departure gate

                            if(jflightstatuses.getJSONObject(i).has(TAG_AIRPORTRESOURCES))
                            {   

                            JSONObject airportresources=jflightstatuses.getJSONObject(i).getJSONObject(TAG_AIRPORTRESOURCES);
                            Log.e("airportresources","--->"+airportresources);

                                if(airportresources.has(TAG_DEPARTURETERMINAL))
                                {
                                    departureterminal=airportresources.get(TAG_DEPARTURETERMINAL).toString();
                                }
                                else
                                {
                                    departureterminal=""; 

                                }

                                if(airportresources.has(TAG_DEPARTUREGATE))
                                {
                                    departuregate=airportresources.get(TAG_DEPARTUREGATE).toString();

                                }
                                else
                                {
                                    departuregate="";
                                }
                                terminal="T-"+departureterminal+" ";
                                gate=departuregate;
                                terminalgate=terminal+gate;
                                Log.e("Terminal Gate","-->"+terminal+gate);

                                map.put(TAG_MTERMINALGATE,terminalgate);
                            }
                            else
                            {
                                terminalgate="Not Available";
                                map.put(TAG_MTERMINALGATE,terminalgate);
                            }
                            //--------------------------------Aiport Resources Complete---------------------------------------------------


                            //--------------------------------Aiport Flight Status Start--------------------------------------------------- 

                                status=jflightstatuses.getJSONObject(i).getString(TAG_STATUS).toString();
                                if(status.equalsIgnoreCase("S"))
                                {
                                    status="Scheduled";
                                }
                                if(status.equalsIgnoreCase("L"))
                                {
                                    status="Landed";
                                }
                                map.put(TAG_MFSTATUS, status);
                                Log.e("Status","--"+status);
                            //--------------------------------Aiport Flight Status Complete---------------------------------------------------  

                        flightList.add(map);

                        Log.e("FlightList","work"+flightList);

                        int displaymode=getResources().getConfiguration().orientation;
                        if(displaymode==1)
                        {

                                ListAdapter adapter = new SimpleAdapter(HomeActivity.this, flightList,
                                        R.layout.listportrait,
                                        new String[] { TAG_MDESTINATION, TAG_MFLIGHT, TAG_MAIRLINE,TAG_MSCHEDULE,TAG_MTERMINALGATE,TAG_MFSTATUS  }, new int[] {
                                                R.id.textdestination, R.id.textflight, R.id.textairline,R.id.textschedule,R.id.texttermgate,R.id.textstatus });
                                setListAdapter(adapter);
                        }
                        else
                        {
                            ListAdapter adapter = new SimpleAdapter(HomeActivity.this, flightList,
                                    R.layout.list,
                                    new String[] { TAG_MDESTINATION, TAG_MFLIGHT, TAG_MAIRLINE,TAG_MSCHEDULE,TAG_MTERMINALGATE,TAG_MFSTATUS  }, new int[] {
                                            R.id.textdestination, R.id.textflight, R.id.textairline,R.id.textschedule,R.id.texttermgate,R.id.textstatus });
                            setListAdapter(adapter);

                        }

                        }   




                }           
                catch (Exception e)
                {
                    e.printStackTrace();
                }

        }
    });

    }


}

JsonParser.java

public class JsonParser {

    static InputStream is = null;
    //static JSONObject jObj = null;
    static String json;
    StringBuilder sb;



    public String getJSONFromUrl(String url) {



        // Making HTTP request
        try {
            is = null;
            //static JSONObject jObj = null;
            json="";
            sb=null;


            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            Log.e("HTTPPOST","WORK-->"+httpPost);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            Log.e("HTTPRESPONSE","WORK-->"+httpResponse);

            StatusLine statusLine=httpResponse.getStatusLine();
            int statusCode= statusLine.getStatusCode();
            Log.e("status", "code"+statusCode);

            HttpEntity httpEntity = httpResponse.getEntity();
            Log.e("HTTPENTITY","WORK-->"+httpEntity);
            is = httpEntity.getContent();   
        }   
            catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try{
        //  Log.e("HTTENTITY is","WORK"+is);


            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            Log.e("BUFFER READER","WORK-->"+reader);


            sb = new StringBuilder();
            Log.e("STRINGBUILDER","WORK");

            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            //is.close();
            json = sb.toString();
            Log.e("STRINGBUILDER","WORK"+sb.toString());
        //  Log.e("HTTPPOST SB TO STRING","WORK-->"+sb.toString());
        //  Log.e("JSON STRING HTTPPOST","WORK-->"+json);

        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // return JSON String
        //return json;

        return sb.toString();

    }


}   

I/Process(1873):发送信号。PID:1873 SIG:9

4

2 回答 2

0

您从 FlightListBack$4.onClick 调用 JsonParser.getJSONFromUrl (您在此处添加的匿名点击监听器:buttontime.setOnClickListener(new OnClickListener(){..})

在这个 JsonParser.getJSONFromUrl 中,您执行一个 http 请求,然后在主线程(或 UI 线程)上运行,因为它是从 onClick() 启动的。您应该重组代码以在工作线程(例如,使用 AsyncTask)上执行 http 请求,就像您在调用 JsonParser.getJSONFromUrl 的另一种情况下所做的那样。

于 2013-01-03T09:16:16.513 回答
-1

在 onCreate() 中添加此代码;执行 AsynckTask 之前的方法

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                 .detectDiskReads()
                 .detectDiskWrites()
                 .detectNetwork()   // or .detectAll() for all detectable problems
                 .penaltyLog()
                 .build());
         StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                 .detectLeakedSqlLiteObjects()
                 .detectLeakedClosableObjects()
                 .penaltyLog()
                 .penaltyDeath()
                 .build());

但请记住,此代码对开发阶段很有帮助,您必须将其删除,并且不要在生产阶段使用任何网络操作。

于 2012-12-08T10:34:59.780 回答