0

I'm trying to get scoreboards from FB, and to achieve this I issue a HTTP request to the API. It has to be done on a separate thread, here is my async task class:

public class AsyncBuildScoreboard extends AsyncTask<Void, Void,String> {
ProgressBar pb;

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

}

@Override
protected String doInBackground(Void... voids) {

    String token = Session.getActiveSession().getAccessToken();     
    try{            
        HttpClient client = new DefaultHttpClient();                
        HttpGet get = new HttpGet("https://graph.facebook.com/"+GameStatic.app_id+"?fields=scores&access_token=" + token);
        HttpResponse resp = client.execute(get);                    
        HttpEntity responseEntity = resp.getEntity();
        String response = EntityUtils.toString(responseEntity);     
        return response;

    }
    catch (IOException e) 
    {

    }   
    return "";

}


protected void onPostExecute(String response) {
    try{    
        JSONObject res = new JSONObject(response);                          
        JSONObject scores = res.getJSONObject("scores");
        JSONArray data = scores.getJSONArray("data");                       
        int len = data.length();                        
        String[] values = new String[len];
        for(int i=0;i<len;i++)
        {
            JSONObject obj = data.getJSONObject(i);                         
            JSONObject user = obj.getJSONObject("user");
            String name = user.getString("name");
            String score = obj.getString("score");          
            values[i] = name + "  " + score;
            GameStatic.scoreboard.add(values[i]);
        }
    }       
    catch (JSONException e)
    {

    }



}

}

GameStatic is an external variable to store what I get from thread. And yet, when doing this:

AsyncBuildScoreboard board = new AsyncBuildScoreboard ();
    board.execute();        
    final ListView listview = (ListView) findViewById(R.id.scorelist);            
    final StableArrayAdapter adapter = new StableArrayAdapter(this,
                android.R.layout.simple_list_item_1, GameStatic.scoreboard);        
    listview.setAdapter(adapter); 

a null pointer exception occurs, which means, that the GameStatic.scoreboard has NOT been filled with the entries I wanted.

What am I doing wrong, any ideas?

I'd be obliged, since I am REALLY pressed on time...

public class AsyncBuildScoreboard extends AsyncTask<Void, Void, Void> 
{
public ListView list;
public Context ctx;
public ArrayList<String> scoreboard = new ArrayList <String> ();


public AsyncBuildScoreboard(ListView list, Context context)
{
    this.list = list;
    this.ctx = context;
}

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

}

@Override
protected Void doInBackground(Void... voids) 
{
    Void nothing = null;
    String token = Session.getActiveSession().getAccessToken();     
    try{            
        HttpClient client = new DefaultHttpClient();                
        HttpGet get = new HttpGet("https://graph.facebook.com/"+GameStatic.app_id+"?fields=scores&access_token=" + token);
        HttpResponse resp = client.execute(get);                    
        HttpEntity responseEntity = resp.getEntity();
        String response = EntityUtils.toString(responseEntity); 


    }
    catch (IOException e) 
    {

    }   
    return nothing;     
}


protected void onPostExecute(String response) {
    try{    
        JSONObject res = new JSONObject(response);                          
        JSONObject scores = res.getJSONObject("scores");
        JSONArray data = scores.getJSONArray("data");                       
        int len = data.length();                        
        String[] values = new String[len];
        for(int i=0;i<len;i++)
        {
            JSONObject obj = data.getJSONObject(i);                         
            JSONObject user = obj.getJSONObject("user");
            String name = user.getString("name");
            String score = obj.getString("score");          
            values[i] = name + "  " + score;
            scoreboard.add(values[i]);
        }
    }       
    catch (JSONException e)
    {

    }
    final ArrayAdapter adapter = new ArrayAdapter(ctx,
            android.R.layout.simple_list_item_1, scoreboard);       
    list.setAdapter(adapter); 


}



}
3
  • 1
    Can you copy your response string? Commented Jun 4, 2013 at 20:20
  • 1
    return response; after catch block. remove return ""; and try the suggested answer by @ρяσѕρєя K Commented Jun 4, 2013 at 20:22
  • 1
    you need to notifyDatasetChanged when you modify the array backing your listview Commented Jun 4, 2013 at 20:31

1 Answer 1

1

you will need to use onPostExecute for showing the score when doInBackground execution complete instead of passing GameStatic.scoreboard just after AsyncTask.execute() because doInBackground always execute in separate thread so it.

you can use AsyncBuildScoreboard class constructor for passing ListView instance and Context from Activity as:

ListView listview;
Context context;
public AsyncBuildScoreboard(ListView listview,Context context){
 this.context=context;
 this.listview=listview;
}
....
protected void onPostExecute(String response) {
   //...your code here..

  StableArrayAdapter adapter = new StableArrayAdapter(context,
             android.R.layout.simple_list_item_1, GameStatic.scoreboard);        
    listview.setAdapter(adapter); 
}

and change your Activity code as for passing Context :

ListView listview = (ListView) findViewById(R.id.scorelist);
AsyncBuildScoreboard board = new AsyncBuildScoreboard (listview,
                                                     Your_Activity.this);
board.execute(); 

or you can also create callbacks methods using interface which fire when on UI Thread when doInBackground execution complete.see following post for more details:

android asynctask sending callbacks to ui

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, that looks very reasonable, though I get an error of undefined constructor, even though I did define it in the asynctask class...
@MichałSzydłowski : ok plz show your latest updated code to get more help
there you go. now there is no error, but my array remains empty
ok... I'll try, but why did you put the ArrayAdapter instance inside the for loop?
@MichałSzydłowski : bez if any error occur in json parsing then ArrayAdapter code not execute and you can change it according to your need
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.