Michał Szydłowski
Michał Szydłowski

Reputation: 3409

Why do I get a null pointer exception while issuing a HTTP request using AsyncTask in Android?

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); 


}



}

Upvotes: 0

Views: 337

Answers (1)

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132972

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

Upvotes: 1

Related Questions