I would like to apologize if this has a trivial answer but I can't seem to come up with a pattern/flow for this scenario.
I am using Android Asynchronous Http Client which provides a callback for when its done with the request. I guess this is where I'm getting confused because I don't know where to use the library.
Here is my setup:
DataClass.java
public class DataClass {
String created_date = null;
String username = null;
String details = null;
private static AsyncHttpClient client;
public DataClass(String id) {
client = new AsyncHttpClient();
GetDataObject(id);
}
public void GetDataObject(String id) {
//...build RequestParams()
client.post(get_data_url, params, new JsonHttpResponseHandler(){
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
String response_string = new String(response);
//...parse JsonObject
created_data = jsonObject.getString("date");
username = jsonObject.getString("username");
details = jsonObject.getString("details");
// all dataClass instance variables accessed here are null.
Log.d("Created: ", created_data); //returns somedate
Log.d("Username: ", username); //returns someusername
}
});
}
}
ShowDataActivity.java
public class ShowDataActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_question);
Intent intent = getIntent();
String id = intent.getStringExtra("id");
DataClass dataClass = new DataClass(id);
// all dataClass instance variables accessed here are null.
Log.d("Created: ", dataClass.created_data); //returns null
Log.d("Username: ", dataClass.username); //returns null
}
}
When I put breakpoints on the instance variables assignment inside the RestClient callback, I can see that they aren't null but have the correct data in them.
I have been searching for a while and see some built-in Android libraries like Loaders, ContentObserver and BoradcastReceivers that might help but I don't know how to use them in conjunction with Android Asynchronous Http Client.
Please not the example above is not complete, but all the relevant information is there.
Let me know if more information is needed. Thank you.
Problem:
When I instantiate the DataClass in ShowDataActivity my dataClass instance variables are null. I'm guessing it's because the variables are being assigned in the callback which is after I instantiate the object. Not really sure how to ask this but how can I make sure that DataClass dataClass = new DataClass(id);
initializes with the data from the internet.