3

我创建了一个 AsyncTask,它在执行时从网站加载数据。目前我收到一个空指针异常,我认为这是因为我试图过早地填充 UI,所以我希望创建某种 if 语句来说明 AsyncTask 是否未完成显示加载图形以及何时填充数据。但我不知道该怎么做,有人知道我怎么能做到这一点,或者至少为我指明了正确的方向。

到目前为止,这是我的代码

public void checkPreferences(){

    SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
    ChosenMethod = preferences.getString("ChosenMethod", ChosenMethod);
    ChosenLeagueID = preferences.getString("ChosenLeagueId", ChosenLeagueID);
    ChosenTeamId = preferences.getString("ChosenTeamId", ChosenTeamId);

    Log.v("lc", "newsurl" + newsFeedURL);


    Log.v("myapp", "ChosenMethod Home = " + ChosenMethod);
    Log.v("myapp", "ChosenLeagueID Home = " + ChosenLeagueID);
    Log.v("myapp", "ChosenTeamID Home = " + ChosenTeamId);

    if (ChosenMethod.equals("Team")) {
        setContentView(R.layout.homeactteam2);
        newsAmount = 5;

    } else {
        newsAmount = 10;
        setContentView(R.layout.homeactteam);
    }

}


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    //Check Preferences which sets UI

    checkPreferences();
   PostTask posttask;
   posttask = new PostTask();
   posttask.execute();

   FillData();


    Button backbtn = (Button) findViewById(R.id.backbtn);

    //Listening to button event
    backbtn.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            //Starting a new Intent
            Intent previousScreen = new Intent(getApplicationContext(), ChooseTeamActivity.class);
            ChosenMethod = "null";
            SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("ChosenMethod", ChosenMethod);            
            editor.commit();
            previousScreen.putExtra("FullData", fulldata);
            startActivity(previousScreen);


        }
    });

//((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
//   
//    public void onRefresh() {
//        // Do work to refresh the list here.
//        loadData();
//    }
//});
//


}



public void loadNewsFeed(){

     newsFeedRequest = "website/" + chosenLeagueId + "/news?timestamp=" + unixTimeStamp;
     newsFeedURL = "https://www.website.com" + newsFeedRequest; 

        String myhash = buildHmacSignature(apiKey, newsFeedURL);
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(newsFeedURL);

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("requestToken", myhash));
        pairs.add(new BasicNameValuePair("apiUser", apiUser));

            try {
                post.setEntity (new UrlEncodedFormEntity(pairs));
                HttpResponse response = client.execute(post);
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                String json = reader.readLine();
                fulldata = String.valueOf(json);
                Log.v("myApp","newsdata" + fulldata);

                newsList = new ArrayList<String>();
                newsList2 = new ArrayList<String>();
                newsList3 = new ArrayList<String>();
                imageList = new ArrayList<String>();


                JSONObject obj = new JSONObject(json);    
                JSONObject objData = obj.getJSONObject("data");
                JSONArray jArray = objData.getJSONArray("news");
                Log.v("lc","newsAmount= " + newsAmount);

                   for(int t = 0; t < newsAmount; t++){
                       JSONObject newsTitleDict = jArray.getJSONObject(t);
                       imageList.add(newsTitleDict.getString("image_small"));
                     newsList3.add(newsTitleDict.getString("title"));

                   }

                   for(int t = 0; t < 1; t++){
                       JSONObject newsTitleDict = jArray.getJSONObject(t);

                 newsList.add(newsTitleDict.getString("title"));
            //       newsList2.add(newsTitleDict.getString("title"));

                   }



    } catch (ClientProtocolException 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();
    }


}           


public void loadResultsFeed(){


    resultsFeedRequest = "website/" + chosenLeagueId + "/results?&team_id=" + ChosenTeamId + "&limit=31&timestamp=" + unixTimeStamp;
    resultsFeedURL = "https://www.website.com" + resultsFeedRequest;    

    String myhash = buildHmacSignature(apiKey, resultsFeedURL);

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(resultsFeedURL);

    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("requestToken", myhash));
    pairs.add(new BasicNameValuePair("apiUser", apiUser));

    try {
        post.setEntity (new UrlEncodedFormEntity(pairs));
        HttpResponse response = client.execute(post);
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String json = reader.readLine();
        fulldata = String.valueOf(json);
        Log.v("myApp","resultsdata" + fulldata);

        newsList = new ArrayList<String>();
        newsList2 = new ArrayList<String>();
        newsList3 = new ArrayList<String>();
        imageList = new ArrayList<String>();


        JSONObject obj = new JSONObject(json);    
        JSONObject objData = obj.getJSONObject("data");
        JSONArray jArray = objData.getJSONArray("results");


        if(jArray.length() < 1) loadLastResults();



    } catch (ClientProtocolException 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();
    }   


}


public void loadLastResults(){

    resultsFeedRequest = "website/" + chosenLeagueId + "/results?month=04&team_id=" + ChosenTeamId + "&limit=31&timestamp=" + unixTimeStamp;
    resultsFeedURL = "https://www.website.com" + resultsFeedRequest;    

     String myhash = buildHmacSignature(apiKey, resultsFeedURL);

    Date anotherCurDate = new Date();  
    SimpleDateFormat formatter = new SimpleDateFormat("MM");  
    String CurMonth = formatter.format(anotherCurDate);  

    int Int = Integer.parseInt(CurMonth);

    int MonthInt = Int -1;


    CurMonth = (String) (String.valueOf(MonthInt));



    if (CurMonth.equals("1")){

        lastMonth = "12";

    }    
     else {
        if(CurMonth.length() < 2){
            lastMonth = "0" + CurMonth;
        } else {
            lastMonth = CurMonth;
        }
    }

    Log.v("lc","month= " + CurMonth);
    Log.v("lc","LastMonth= " + lastMonth);


        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(resultsFeedURL);

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("requestToken", myhash));
        pairs.add(new BasicNameValuePair("apiUser", apiUser));

        try {
            post.setEntity (new UrlEncodedFormEntity(pairs));
            HttpResponse response = client.execute(post);
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
            String json = reader.readLine();
            fulldata = String.valueOf(json);
            Log.v("myApp","resultsdata" + fulldata);

            newsList = new ArrayList<String>();
            newsList2 = new ArrayList<String>();
            newsList3 = new ArrayList<String>();
            imageList = new ArrayList<String>();


            JSONObject obj = new JSONObject(json);    
            JSONObject objData = obj.getJSONObject("data");
            JSONArray jArray = objData.getJSONArray("results");


               for(int t = 0; t < 1; t++){

                   resultsDict = jArray.getJSONObject(t);
                  HomeTeam = resultsDict.getString("hometeam");
                  AwayTeam = resultsDict.getString("awayteam");
                  HomeScore = resultsDict.getString("homescore");
                  AwayScore = resultsDict.getString("awayscore");
                  Attendance = resultsDict.getString("attendance");
                  Division = resultsDict.getString("division");

                  Log.v("lc","hometeam" + HomeTeam);
                  Log.v("lc","awayteam" + AwayTeam);


               }


        } catch (ClientProtocolException 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();
        }


    }   


public class PostTask extends AsyncTask<Void, String, Boolean> {

    @Override
    protected Boolean doInBackground(Void... params) {
        boolean result = false;
        loadNewsFeed();
        loadResultsFeed();
        loadLastResults();
        publishProgress("progress");
        return result;
    }

    protected void onProgressUpdate(String... progress) {
        StringBuilder str = new StringBuilder();
            for (int i = 1; i < progress.length; i++) {
                str.append(progress[i] + " ");
            }
    }

}

public void FillData(){ 


     if (ChosenMethod.equals("Team")) {


         resultsView = LayoutInflater.from(getBaseContext()).inflate(R.layout.resultscell,
                 null);

       TextView homeTeam = (TextView) resultsView.findViewById(R.id.HomeTeam);
       homeTeam.setText(HomeTeam);

       TextView awayTeam = (TextView) resultsView.findViewById(R.id.AwayTeam);
       awayTeam.setText(AwayTeam);

       TextView homeScore = (TextView) resultsView.findViewById(R.id.HomeScore);
       homeScore.setText(HomeScore);

       TextView awayScore = (TextView) resultsView.findViewById(R.id.AwayScore);
       awayScore.setText(AwayScore);

       TextView attendance = (TextView) resultsView.findViewById(R.id.Attendence);
       attendance.setText("Att:" + Attendance);

       TextView division = (TextView) resultsView.findViewById(R.id.Division);
       division.setText(Division);

        arrayAdapter = new ArrayAdapter<String>(this, R.layout.single_item, newsList);

         String[] mStrings = (String[]) imageList.toArray(new String[imageList.size()]);
         String[] news = (String[]) newsList3.toArray(new String[newsList3.size()]);

         arrayAdapter3 = new LazyAdapter(this, mStrings, news);


            ListView list = getListView();
               list.setTextFilterEnabled(true);

               LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
                View header = inflater.inflate( R.layout.homeheader, list, false);
                View header2 = inflater.inflate( R.layout.homeheader2, list, false);
                View header3 = inflater.inflate( R.layout.homeheader3, list, false);


        //setListAdapter (arrayAdapter);


            adapter = new MergeAdapter();
            adapter.addView(header);
            adapter.addAdapter(arrayAdapter);
            adapter.addView(header2);
            adapter.addView(resultsView);
            adapter.addView(header3);
            adapter.addAdapter(arrayAdapter3);
            setListAdapter(adapter);



     } else {

         arrayAdapter = new ArrayAdapter<String>(this, R.layout.single_item, newsList);
            arrayAdapter2 = new ArrayAdapter<String>(this, R.layout.single_item, newsList2);
            //arrayAdapter3 = new ArrayAdapter(this, R.layout.complex_item, newsList3);

             String[] mStrings = (String[]) imageList.toArray(new String[imageList.size()]);
             String[] news = (String[]) newsList3.toArray(new String[newsList3.size()]);


             arrayAdapter3 = new LazyAdapter(this, mStrings, news);


                ListView list = getListView();
                   list.setTextFilterEnabled(true);

                   LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
                    View header3 = inflater.inflate( R.layout.homeheader3, list, false);


            //setListAdapter (arrayAdapter);


                adapter = new MergeAdapter();
                adapter.addView(header3);
                adapter.addAdapter(arrayAdapter3);
                setListAdapter(adapter);
         } 
}
4

5 回答 5

4

盲目假设...!(没有 StackTrace 报告)

onPostExecute()在你的实现AsyncTask并在其中放置FillData()方法..当你的doInBackground()..完成控制onPostExecute()自动进入..然后填充你的 UI 部分..

于 2012-06-08T09:48:30.383 回答
4

在里面调用你的FillData()方法onPostExecute Method of AsyncTask

它应该是::

public class PostTask extends AsyncTask<Void, String, Boolean> {

    @Override
    protected Boolean doInBackground(Void... params) {
        boolean result = false;
        loadNewsFeed();
        loadResultsFeed();
        loadLastResults();
        publishProgress("progress");
        return result;
    }


    protected void onProgressUpdate(String... progress) {
        StringBuilder str = new StringBuilder();
            for (int i = 1; i < progress.length; i++) {
                str.append(progress[i] + " ");
            }
    }

        @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

         fillData();
    }
}
于 2012-06-08T09:48:35.750 回答
1

您应该使用另一种方法AsyncTask来更新 UI。

protected void onPostExecute(Long result) {
    showDialog("Downloaded " + result + " bytes");
}
于 2012-06-08T09:47:57.140 回答
1

asynctask在ie 中添加一个方法

public void onPostExecute(Void result){} 

并在其中关闭对话并致电您的fillData()

于 2012-06-08T10:03:26.913 回答
0

您可以使用 ProgressDialog 直到来自服务器的完整数据到达您的末尾并填写数据...

请阅读

让我知道是否有任何问题。

谢谢,

哈普斯。

于 2012-06-08T09:50:32.087 回答