Get an Arraylist from an inner class - android

I am seeking help so that I may get an ArrayList<String> in an alternate class. As you can see in the following code I have inner and outer classes. Both work as expected and I am both able to insert values and fetch details from my online database using php scripts (I have commented out these details for code clarity as it was taking up a lot of space).
public class ServerRequests {
ProgressDialog progressDialog;
public static final int CONNECTION_TIMEOUT = 15000;
public static final String SERVER_ADDRESS = "// my url domain";
public ArrayList<String> list1 = new ArrayList<>();
public ServerRequests(Context context)
{
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("Processing");
progressDialog.setMessage("Please wait..");
}
public void storeDataInBackground(MultiChallenge multiChallenge)
{
progressDialog.show();
new StoreDataAsyncTask(multiChallenge).execute();
}
public class StoreDataAsyncTask extends AsyncTask<Void , Void , Void>
{
MultiChallenge multiChallenge;
public StoreDataAsyncTask(MultiChallenge multiChallenge)
{
this.multiChallenge = multiChallenge;
}
#Override
protected Void doInBackground(Void... voids) {
// where I insert values...
#Override
protected void onPostExecute(Void aVoid) {
progressDialog.dismiss();
super.onPostExecute(aVoid);
Log.d("ServerRequests", "Post execute");
}
}
public ArrayList<String> fetchDataInBackground() {
progressDialog.show();
new FetchDataAsyncTask().execute();
return list1;
}
public class FetchDataAsyncTask extends AsyncTask<Void, Void, ArrayList<String>>
{
public FetchDataAsyncTask()
{
}
String text = "";
#Override
protected ArrayList<String> doInBackground(Void... params) {
InputStream is1;
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(// my url domain+ "// php script");
try {
HttpResponse httpResponse = client.execute(post);
is1 = httpResponse.getEntity().getContent();
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(is1, "iso-8859-1"), 8);
String line = null;
while ((line = reader.readLine()) != null) {
text += line + "\n";
}
is1.close();
JSONArray data = new JSONArray(text);
for (int i = 0; i < data.length(); i++) {
Log.d("GetNames", data.getString(i));
JSONObject jsonData = data.getJSONObject(i);
list1.add( // I successfully add details to list1 here, I have commented it out for code clarity);
}
for (int iterate = 0; iterate < list1.size(); iterate++) {
Log.d("list1", list1.get(iterate));
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
// catch (JSONException e) {e.printStackTrace();}
return list1;
}
#Override
protected void onPostExecute(ArrayList<String> myList) {
progressDialog.dismiss();
super.onPostExecute(myList);
}
}
}
Now that I successfully add to the list1 (I can tell values are added to it because of the for loop with the int iterate), I now need to send it to another class whereby I will put items in a listview. This is my code in the class in which I want to display the details of the ArrayList I get from ServerRequests:
ServerRequests serverRequests = new ServerRequests(DisplayInfo.this);
ArrayList<String> myList = new ArrayList<>();
myList = serverRequests.fetchDataInBackground();
for (int iterate = 0; iterate < myList.size(); iterate++) {
Log.d("Display", myList.get(iterate));
However the above for loop is never called, indicating that myList is never given the details that list1 manages to get in the doInBackground method of class FetchDataAsync.
Please note I did spend a number of hours attempting a variety of my own ideas and answers derived from SO before asking this question. Thank you all in advance of your help.

In the onPostExecute method call a function in the calling class
#Override
protected void onPostExecute(ArrayList<String> myList) {
progressDialog.dismiss();
super.onPostExecute(myList);
MainActivity.sendStrings(myList);
}
In the calling function implement a method:
public static void sendStrings(ArrayList<String> strings)
{
//Add for loop here
}
Alternatively you can also use interfaces. Call the interface in onPostExecute and implement the interface in the calling class

Related

httpurl response code is blank in android studio

I am trying to get mysql data from remote server www.kudossoft.in/get_data030518.php. but i am getting nothing when i check httpurl response code that is blank.
i have also add uses permission for internet in mainifest
my code is following please see.
i have also checked my php files permission that is ok.
and i am also inserting some data from another activity in same database that is working properly.
MainActivity code:
public class MainActivity extends AppCompatActivity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
getJSON("http://kudossoft.in/get_data300518.php");
}
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String[] heroes = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
heroes[i] = obj.getString("name");``
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, heroes);
listView.setAdapter(arrayAdapter);
}
}

Empty listView in listFragment

I have a list fragment. When I run the app, I see an empty listView.
I don't know what the problem is. Maybe I should use a library?
public class MyEmployeFragment extends ListFragment {
private static final String ATTRIBUTE_ID = "p_id";
private static final String ATTRIBUTE_NAME = "p_name";
private static final String ATTRIBUTE_LAST_NAME = "p_last_name";
ArrayList<spr_item> ret_data;
MyTask task;
SimpleAdapter sAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
task = new MyTask();
task.execute();
return inflater.inflate(R.layout.my_employe, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ret_data = new ArrayList<spr_item>();
ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>(
ret_data.size());
Map<String, Object> m;
for (int i = 0; i < ret_data.size(); i++) {
m = new HashMap<String, Object>();
m.put(ATTRIBUTE_ID, ret_data.get(i).getId());
m.put(ATTRIBUTE_NAME, ret_data.get(i).getName());
m.put(ATTRIBUTE_LAST_NAME, ret_data.get(i).getLastName());
data.add(m);
}
// массив имен атрибутов, из которых будут читаться данные
String[] from = {ATTRIBUTE_ID, ATTRIBUTE_NAME, ATTRIBUTE_LAST_NAME};
// массив ID View-компонентов, в которые будут вставлять данные
int[] to = {R.id.tw_employe_id, R.id.tw_employe_name, R.id.tw_employe_last_name};
// создаем адаптер
sAdapter = new SimpleAdapter(getActivity(), data, R.layout.list_item_employee,
from, to);
// определяем список и присваиваем ему адаптер
ListView lvSimple = (ListView) getView().findViewById(android.R.id.list);
lvSimple.setAdapter(sAdapter);
}
class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
String s = "5ACACEC6-752B-4EFF-AA50-EEBE58A52113";
// String user_guid = myPrefs.getString("guid", "");
HttpActivity _http = new HttpActivity("192.168.10.11", "80");
_http.set_addr_protocol("/WebSite/P/spr/spr.aspx/");
_http.add_param("query", "spr_employee_get");
// _http.add_param("p_guid", user_guid.toString().trim());
_http.add_param("p_guid", s);
_http.send();
List<spr_item> tempList = _http.getArrayParamValue();
for(int i = 0; i < tempList.size(); i++)
ret_data.add(tempList.get(i));
//employer_name = _http.getArrayParamValue("p_name");
//employer_id = _http.getArrayParamValue("p_id");
//employer_last_name = _http.getArrayParamValue("p_last_name");
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
sAdapter.notifyDataSetChanged();
}
}
}
With the above code apart from the Empty list you may have the null pointer exception too if the task is too quick to load. Here onCreate is called first onCreateView next and onActvityCreated next. So it is better to initialise adapter in onCreate set the adapter to listView in onCreateView and set listView listeners in onActvityCreated using getListView() method.
Apart from this if you are using local database to retrieve data you need to use cursorADapter to fetch the data
The adapter's data references (ArrayList, array, etc.), tend to get lost pretty easily. In that case the notfiyDataSetChanged() method will not work. If you are adamant on using this method I suggest you check the references to the adapter's source again. If that is not the case this is the approach I've used in my project. A small warning in advance, the formatting and the closing of brackets is poorly executed, but the approach is still clear enough.
public class MyFragment extends ListFragment {
// For populating the list view.
SomeAdapter adapter;
public MyFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] parameters = {"url for request"};
new GetRequestTask().execute(parameters);
}
// The async task to make the HTTP GET requests.
class GetRequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
Log.e("GetRequestTask", "Client protocol exception.");
e.printStackTrace();
} catch (IOException e) {
Log.e("GetRequestTask", "IO exception.");
e.printStackTrace();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Update UI with the new response.
new UpdateUITask().execute(result);
}
}
}
// The async task to update the UI.
class UpdateUITask extends AsyncTask<String, String, ArrayList<Something>>{
#Override
protected ArrayList<Something> doInBackground(String... input) {
ArrayList<Something> someArray = new ArrayList<Something>();
try{
// Do some JSON magic to parse the data.
}
catch(JSONException je){
Log.e("UpdateUITask", "JSON parsing error occured.");
je.printStackTrace();
}
return someArray;
}
#Override
protected void onPostExecute(ArrayList<Something> result) {
super.onPostExecute(result);
Log.i("UpdateUITask", "Updating UI.");
adapter = new SomeAdapter(getActivity(), R.layout.some_list_item, restOfTheParameters);
setListAdapter(adapter);
}
}
}
}

Working with cursor objects in android

SplashActivity.java {Updated}
public class SplashActivity extends Activity {
/** Called when the activity is first created. */
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<HashMap<String, String>> arraylist;
private String Content;
DatabaseAdapter db;
TextView txtSplashTitle,txtSplashDesc;
DatabaseAdapter databaseHelper;
Cursor cursor;
//#InjectView(R.id.txtSplashDesc) TextView txtSplashDesc=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
//ButterKnife.inject(this);//using ButterKnife library for viewInjection
txtSplashDesc=(TextView) findViewById(R.id.txtSplashDesc);
String serverURL = "";
db = new DatabaseAdapter(this);
new LongOperation().execute(serverURL);
freeMemory();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
//Setting fonts for textviews
setCustomFontForTextViews();
}
private void setCustomFontForTextViews() {
Typeface typeFace = Typeface.createFromAsset(getAssets(), "royalacid.ttf");
txtSplashDesc.setTypeface(typeFace);
}
// Class with extends AsyncTask class
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(SplashActivity.this);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
Dialog.setMessage("Downloading source..");
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
try {
// NOTE: Don't call UI Element here.
HttpGet httpget = new HttpGet("http://10.0.2.2:3009/findmybuffet/?storedproc=get_app_tables&flag=sudhakar");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
jsonobject = new JSONObject(Content);
jsonobject = jsonobject.getJSONObject("findmybuffet");
jsonarray = jsonobject.getJSONArray("buffets");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("buf_off_id", jsonobject.getString("buf_off_id"));
map.put("from_time", jsonobject.getString("from_time"));
map.put("to_time", jsonobject.getString("to_time"));
map.put("online_price", jsonobject.getString("online_price"));
map.put("reserved_price", jsonobject.getString("reserved_price"));
map.put("buf_image", jsonobject.getString("buf_image"));
map.put("res_name", jsonobject.getString("res_name"));
map.put("rating", jsonobject.getString("rating"));
map.put("latitude", jsonobject.getString("latitude"));
map.put("longitude", jsonobject.getString("longitude"));
map.put("buf_type_name", jsonobject.getString("buf_type_name"));
map.put("from_date", jsonobject.getString("from_date"));
map.put("to_date", jsonobject.getString("to_date"));
map.put("city_id", jsonobject.getString("city_id"));
map.put("city_name", jsonobject.getString("city_name"));
map.put("meal_type_id", jsonobject.getString("meal_type_id"));
map.put("meal_type_name", jsonobject.getString("meal_type_name"));
map.put("buf_desc", jsonobject.getString("buf_desc"));
map.put("distance", jsonobject.getString("distance"));
Log.d("----$$$----", map.toString());
//Calling database
db.addContact(map);
try {
Cursor cursor = (Cursor) databaseHelper.getAllContacts();
cursor.moveToFirst();
if(cursor.moveToFirst()){
do{
String refDestLatitude=cursor.getString(cursor.getColumnIndex(cursor.getColumnName(7)));
Log.d("---#*#*#*#*#*#----", refDestLatitude+"");
}while(cursor.moveToNext());
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("ThrownException", e.toString());
e.printStackTrace();
}
//cursor.close();
}
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
} catch (IOException|JSONException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
// Close progress dialog
Dialog.dismiss();
Intent intent=new Intent(SplashActivity.this,MainActivitySherlock.class);
startActivity(intent);
}
}
private void freeMemory() {
jsonobject=null;
jsonarray=null;
arraylist=null;
Content=null;
}
}
When i debugged the app i found as below
I am having problem in the line ::
String refDestLatitude=cursor.getString(cursor.getColumnIndex(cursor.getColumnName(7)));
Cursor is able to get the value
cursor.getColumnIndex(cursor.getColumnName(7))
But exception popps up when
cursor.getString(cursor.getColumnIndex(cursor.getColumnName(4)));
is evaluated
Note:: This line was working when i was handling in adapter ..... but its not working here. do i need to cast a reference or something ?
try like this :
if(c.moveToFirst()){
do{
String refDestLatitude=cursor.getString(cursor.getColumnIndex(cursor.getColumnName(7)));
}while(c.moveToNext())
}
cursor.getString(cursor.getColumnIndex(cursor.getColumnName(7)));
You get an error because there is no column 7.
I have to ask why all the drama when you could just get the data from the column?
if (getColumnCount() > 11) { // 4+7 = 11 fail
cursor.getString(7);
}

Asynctask wont update array

I am having a problem accessing the arraylists populated by this asynctask from class file A. From Class file B I try to use A a method such as
inStream = new InboxLoader(MainInbox.this,1);
Log.e("JJJ",""+inStream.getMemId().size());
method from a different class file I get a crash in logcat saying indexoutofbounds error
I was looking for an alternative to having this AsyncTask in the same file as class B
public class InboxLoader {
Context ctx;
ArrayListmemName,memAvatar,msgBody,msgTime;
ArrayList msgId,memId;
InboxLoader(Context context,int id){
this.ctx = context;
this.msgBody = new ArrayList<String>();
this.memAvatar = new ArrayList<String>();
this.memId = new ArrayList<Integer>();
this.memName = new ArrayList<String>();
this.msgTime = new ArrayList<String>();
this.msgId = new ArrayList<Integer>();
new LoadStream().execute(id);
}
public ArrayList<String> getMsgBody(){
return msgBody;
}
public ArrayList<String> getMemAvatar(){
return memAvatar;
}
public ArrayList<Integer> getMemId(){
return memId;
}
public ArrayList<String> getMemName(){
return memName;
}
public ArrayList<Integer> getMsgId(){
return msgId;
}
public ArrayList<String> getMsgTime(){
return msgTime;
}
/*
* STARTS GRABBING DATA FOR THE LISTVIEW
*/
public class LoadStream extends AsyncTask<Integer, Integer, JSONObject> {
ProgressDialog progressBar;
#Override
protected void onPreExecute() {
progressBar = new ProgressDialog(ctx, ProgressDialog.STYLE_SPINNER);
progressBar.setMessage("Generating Inbox....");
progressBar.show();
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(Integer... params) {
List<NameValuePair> params2 = new ArrayList<NameValuePair>();
params2.add(new BasicNameValuePair("memberId", String.valueOf(1)));
params2.add(new BasicNameValuePair("type", "get"));
JSONObject json = new jsonParser().makeRequest("url", params2);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
super.onPostExecute(json);
int success = 0;
JSONObject jData;
JSONArray jObj = null;
try{
// successfully received details
jObj = json.getJSONArray("details"); // JSON Array
success = json.getInt("success");
}catch(Exception e){
e.printStackTrace();
}
if(success == 1){
try{
for( int i = 0; i < jObj.length(); i++ ){
//GET OBJECT FROM JSON Array
jData = jObj.getJSONObject(i);
//ASSIGN VALUES
msgId.add(jData.getInt("msg_id"));
memAvatar.add(jData.getString("mem_avatar"));
memName.add(jData.getString("mem_name"));
memId.add(jData.getInt("mem_id"));
msgBody.add(jData.getString("msg_body"));
msgTime.add(jData.getString("msg_time"));
}
}catch(Exception e){
Log.e("STREAM FILE PROBLEM", e.getMessage());
}
}
progressBar.dismiss();
Log.e("STREAM FILE PROBLEM",""+memId.size());//prints 1
}
}
}
You are trying to read the ArrayList immediately after you start the AsyncTask, while the result will not be available until the doInBackground ends.
You should do what you want in onPostExecute to make sure the task executed all right.
Edited:
Define a listener like below:
public interface RequestListener {
public void onComplete(T response);
}
and the add a field requestListener in InboxLoader:
InboxLoader(Context context,int id, RequestListener li){
this.ctx = context;
this.msgBody = new ArrayList<String>();
this.memAvatar = new ArrayList<String>();
this.memId = new ArrayList<Integer>();
this.memName = new ArrayList<String>();
this.msgTime = new ArrayList<String>();
this.msgId = new ArrayList<Integer>();
this.requestListener = li;
new LoadStream().execute(id);
}
in the onPostExecute add this:
protected void onPostExecute(JSONObject json) {
super.onPostExecute(json);
int success = 0;
JSONObject jData;
JSONArray jObj = null;
try{
// successfully received details
jObj = json.getJSONArray("details"); // JSON Array
success = json.getInt("success");
if(requestListener!=null)
requestListener.onComplete();
}catch(Exception e){
e.printStackTrace();
}
Then you could process the result in onComplete define in your class B:
inStream = new InboxLoader(MainInbox.this,1, new RequestListener() {
public void onComplete(){
Log.e("JJJ",""+inStream.getMemId().size());
};
});

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

Categories

Resources