I need to get text from a website which is done in a new thread. Then i need to put that text in a list view.
The problem is that i cant set up array adapter for list view until text is put in the lists used in that adapter. Lists are filled in that thread used for connecting to website.
I tried to solve that by setting up adapter in new thread run by first thread. Program starts without errors, but nothing shows up in list view.
I am using List view code from this site http://www.vogella.com/articles/AndroidListView/article.html
Im a newbie in java and android so i hope you understand what im trying to do :)
Heres the code
package com.example.studentservis;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class MainActivity extends Activity {
String s;
List<String> headersList = new ArrayList<String>();
List<String> contentList = new ArrayList<String>();
ListView listview;
StableArrayAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listView1);
threadStart();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void adapterInit()
{
adapter = new StableArrayAdapter(this, android.R.layout.simple_list_item_1, headersList);
listview.setAdapter(adapter);
}
private class StableArrayAdapter extends ArrayAdapter<String>{
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
}
public void threadStart()
{
//txtView.setText(stringHandler.getString());
new Thread(new Runnable() { // thread
public void run(){
try
{
webRequest();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
adapterInit();
}
};
}
}).start();
}
public void webRequest() throws Exception{
String servisURL = "http://www.sczg.unizg.hr/student-servis/";
Document doc = Jsoup.connect(servisURL).get();
Elements jobNode = doc.select("div.jobBox");
Elements headersNode = jobNode.select("h1");
Elements contentNode = jobNode.select("content");
for(int i = 0; i < headersNode.size(); i++){
headersList.add(headersNode.get(i).text());
}
for(int i = 0; i < contentNode.size(); i++){
contentList.add(contentNode.get(i).text());
}
}
}
Hope this may work for you, here i used Asynchronous Task instead of thread
public class MainActivity extends Activity {
String s;
List<String> headersList = new ArrayList<String>();
List<String> contentList = new ArrayList<String>();
ListView listview;
StableArrayAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listView1);
// threadStart();
// Here i implemented Asynchronous Task instead of Thread
new SampleAsyncTask().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public class SampleAsyncTask extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(
MainActivity.this);
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(false);
this.dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
webRequest();
adapter = new StableArrayAdapter(MainActivity.this,
android.R.layout.simple_list_item_1, headersList);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
// Here if you wish to do future process for ex. move to another
// activity do here
listview.setAdapter(adapter);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
private class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
}
public void webRequest() throws Exception {
String servisURL = "http://www.sczg.unizg.hr/student-servis/";
Document doc = Jsoup.connect(servisURL).get();
Elements jobNode = doc.select("div.jobBox");
Elements headersNode = jobNode.select("h1");
Elements contentNode = jobNode.select("content");
for (int i = 0; i < headersNode.size(); i++) {
headersList.add(headersNode.get(i).text());
}
for (int i = 0; i < contentNode.size(); i++) {
contentList.add(contentNode.get(i).text());
}
}
}
At first I propose you to read this guide, especially about Using AsyncTask instead raw Thread.
At second, as I understand, you want to invoke adapterInit from UI thread?
So, you can try this:
runOnUiThread( // <-- method from Activity
new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
adapterInit();
}
}
);
Maybe the problem is that you are not calling the method notifyDataSetChanged() on the adapter to force it to update his informations, it's like notifying the adapter that the underlaying data were updated and that it needs to refresh the associated listview.
You should call it after you fetch the data from the website.
You can use Handler.
In the webRequest thread,When webRequest() finished,you use Handler to notice the main thread to adapterInit().Not use another thread in the webRequest thread.
A simple example.
#Override
public void onClick(DialogInterface dialog,
int which) {
setControlsEnable(false);
new Thread() {
public void run() {
WebserviceMethod wb = new WebserviceMethod();
if (wb.DeleteEmployee(
VerificationUtils
.GetInstance()
.CreateToken(),
personId) == 1) {
Message msg = new Message();
msg.obj = SwitchActivityValue.SWITCH_DELETEPERSON_OK;
mHandler.sendMessage(msg);
}
}.start();
}
#Override
public void handleMessage(Message msg){
super.handleMessage(msg);
SwitchActivityValue value = (SwitchActivityValue)msg.obj;
switch (value) {
case SWITCH_DELETEPERSON_OK:
ManageUtils.EmployeeListDataForAdmin.personInfos.clear();
ManageUtils.EmployeeListDataForAdmin.currentPage = 0;
mActivity.switchActivity(mValue);
break;
case SWITCH_DELETEPERSON_FAILED:
break;
default:
break;
}
mActivity.showMessage(value);
}
Such as the example,you can bind the data in the Handler.When the thread finished,it use hanlder to sendmessage to notice handleMessage handle others.
Related
I downloaded and imported the library [https://github.com/shontauro/android-pulltorefresh-and-loadmore][1]
Everything works fine. but when I try to change the code in my error output.
comment out what works. what appear below my not work. Even the logs are not shown. what am I doing wrong?
public class LoadMoreExampleActivity extends ListActivity {
// list with the data to show in the listview
private LinkedList<String> mListItems;
// The data to be displayed in the ListView
private String[] mNames = { "Fabian", "Carlos", "Alex", "Andrea", "Karla",
"Freddy", "Lazaro", "Hector", "Carolina", "Edwin", "Jhon",
"Edelmira", "Andres" };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loadmore);
mListItems = new LinkedList<String>();
mListItems.addAll(Arrays.asList(mNames));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mListItems);
setListAdapter(adapter);
// set a listener to be invoked when the list reaches the end
((LoadMoreListView) getListView())
.setOnLoadMoreListener(new OnLoadMoreListener() {
public void onLoadMore() {
// Do the work to load more items at the end of list
// here
new LoadDataTask().execute();
}
});
}
private class LoadDataTask extends AsyncTask<String, Void, String> {
String[] mass;
#Override
protected String doInBackground(String... strings) {
Document doc;
if (isCancelled()) {
return null;
}
// Simulates a background task
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// }
// for (int i = 0; i < mNames.length; i++)
// mListItems.add("string"+i);
try {
doc = Jsoup.connect(link).get();
Elements eName = doc.select("name");
for (int i = 0; i < eName.size(); i++) {
mListItems.add(eName.get(i).ownText());
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
mListItems.add("Added after load more");
// We need notify the adapter that the data have been changed
((BaseAdapter) getListAdapter()).notifyDataSetChanged();
// Call onLoadMoreComplete when the LoadMore task, has finished
((LoadMoreListView) getListView()).onLoadMoreComplete();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
((LoadMoreListView) getListView()).onLoadMoreComplete();
}
}
}
And you do not forget to connect to the internet?
<uses-permission android:name="android.permission.INTERNET"/>
I have a problem with implementing searchview showing its results for data coming from a server. I currently use an AsyncTask so that I don't block the UI. Here's how I implemented it:
searchView.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String query) {
if (query.length() > 0) {
new GetSearchByNameResultTask(searchView).execute(query);
} else {
return false;
}
return true;
}
#Override
public boolean onQueryTextSubmit(String arg0) {
// TODO Auto-generated method stub
return false;
}
});
GetSearchByNameResultTask
class GetSearchByNameResultTask extends AsyncTask<String, Void, String> {
private SearchView searchView;
public GetSearchByNameResultTask(SearchView searchView) {
this.searchView = searchView;
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return WebRequestHelper.getInfo(params[0]);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
AppLog.d(TAG, "Result search: " + result);
Gson gson = new Gson();
searchResponseList = gson.fromJson(result, new TypeToken<List<Info>>() {
}.getType());
loadHistory(searchView, searchResponseList);
// TODO: search adapter
}
}
loadHistory() code:
private void loadHistory(SearchView searchView, List<AppInfo> searchResponse) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
searchView.setSuggestionsAdapter(null);
// Cursor
String[] columns = new String[] { "_id", "text" };
Object[] temp = new Object[] { 0, "default" };
MatrixCursor cursor = new MatrixCursor(columns);
final List<Info> items = searchResponse;
for (int i = 0; i < items.size(); i++) {
temp[0] = i;
temp[1] = items.get(i).getName();
cursor.addRow(temp);
}
CursorAdapter ca = new AppListSearchAdapter(this, cursor, items);
new AsyncQueryResult(cursor,ca).executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
// SearchView
searchView.refreshDrawableState();
searchView.setSuggestionsAdapter(ca);
searchView.setOnSuggestionListener(new OnSuggestionListener() {
#Override
public boolean onSuggestionSelect(int position) {
// TODO Auto-generated method stub
return false;
}
});
}
}
Problem
Everything runs alright. I'm getting the search results. But I have a problem updating the views. Probably best explained with an example:
Data:
Hell
Hello
Helicopter
text in search: Hel
Result:
Hello World
Hello
Helicopter
text in search: Hell
Hell
Hello
[extra empty space]
the extra empty space is my problem. The "listview" doesn't get updated to fit the results until I type 'Hello'
I forgot to answer this question.
I managed to fix this issue, although it was a bit of a hack on my part. Here's what I did:
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
searchAdapter = new SearchAdapter(this, cursor, false);
mSearchView.setSuggestionsAdapter(searchAdapter );
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
searchAdapter.notifyDataSetChanged();
}
}, 200);
//Reload fragment to show list
}
This would force to refresh the search view's adapter. The new Handler().postDelayed() was the key here.
Hope this solution helps.
Trying to parse an html pages like http://www.ts.kg/serials/ on android. Tried to do it with htmlcleaner, but it didnot work. Trying to do it with jsoup. In the begining was my code to complex. Here is the shortest code. The same thing works on java Please help. My Logs http://smartpics.kz/imgs/1361209668WW5O.JPG
Here is my class:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] names= {};
String url = "http://www.ts.kg/mults/";
try {
Document doc = Jsoup.connect(url).get();
Element e = doc.body();
Elements ggg = e.getElementsByAttributeValue("class", "categoryblocks");
for (int i =0;i<ggg.size();i++) {
Element linkk = ggg.get(i);
if(linkk.getElementsByTag("a")!=null){
Element atom = linkk.getElementsByTag("a").first();
String n = atom.getElementsByTag("span").first().text();
names[i] = n;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ListView lvMain = (ListView) findViewById(R.id.listViewData);
// создаем адаптер
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, names);
// присваиваем адаптер списку
lvMain.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
posted 20.feb.2013:
tryed to do it as it was proposed by Shoshy (thanks for your answer), but it didn't work (perhaps because of my not-from-right-place-growing hands). Here is my modified code:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = "http://www.ts.kg/mults/";
pd = ProgressDialog.show(MainActivity.this, "Working...", "request to server", true, false);
//Запускаем парсинг
new AsyncExecution().execute();
}
private ProgressDialog pd;
String url;;
String names[];
private class AsyncExecution extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
// here your task will be done in seperate thread from UI thread
// and if you want to use the variables (that will be modifed here)
// from anywhere in MainActivity, then you should declare them as global
// variable in MainActivity. remember you cannot update UI from here , like
// Toast message. if you want to do that you can use OnPostExecute
// method bellow .
try {
ArrayList<String> array = new ArrayList<String>();
Document doc = Jsoup.connect(url).get();
Element e = doc.body();
Elements ggg = e.getElementsByAttributeValue("class", "categoryblocks");
for (int i =0;i<ggg.size();i++) {
Element linkk = ggg.get(i);
if(linkk.getElementsByTag("a")!=null){
Element atom = linkk.getElementsByTag("a").first();
String n = atom.getElementsByTag("span").first().text();
array.add(n);
}
}
for (int i = 0;i<array.size();i++){
names[i]=array.get(i);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
//Убираем диалог загрузки
pd.dismiss();
//Находим ListView
ListView listview = (ListView) findViewById(R.id.listViewData);
//Загружаем в него результат работы doInBackground
listview.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, names));
}
}
}
you have to make the request for getting the page in another thread from UI thread. you can use AsyncTask. i am giving some example by editing your code :
the link about AsyncTask is : about AsynckTask
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//the class is defined bellow
new AsyncExecution().execute();
//other codes.....
.......................
}
/// your other codes .....
// you need to add this class
private class AsyncExecution extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
// here your task will be done in seperate thread from UI thread
// and if you want to use the variables (that will be modifed here)
// from anywhere in MainActivity, then you should declare them as global
// variable in MainActivity. remember you cannot update UI from here , like
// Toast message. if you want to do that you can use OnPostExecute
// method bellow .
try {
Document doc = Jsoup.connect(url).get();
Element e = doc.body();
Elements ggg = e.getElementsByAttributeValue("class", "categoryblocks");
for (int i =0;i<ggg.size();i++) {
Element linkk = ggg.get(i);
if(linkk.getElementsByTag("a")!=null){
Element atom = linkk.getElementsByTag("a").first();
String n = atom.getElementsByTag("span").first().text();
names[i] = n;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPostExecute(Void result) {
}
}
I have an application which load data from json to android as below
public class MainActivity extends Activity {
private final String URL_SERVICE = "http://92.253.101.239:81/sudandoctors/api.aspx?op=5&GovernorateId=&SpecializationId=&DoctorName=&LastDoctorId=0";
private final String URL_IMAGE_BASE = "http://92.253.101.239:81/sudandoctors/UploadedFiles/";
TextView tv;
DoctorInfo doctorObj = new DoctorInfo();
ArrayList<DoctorInfo> doctorsInfoList = new ArrayList<DoctorInfo>();
ListView lv = (ListView)findViewById(R.id.mylist);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AsyncHttpClient client = new AsyncHttpClient();
client.get(URL_SERVICE, new AsyncHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
// show loading bar
Log.d("onStart", "onStart");
}
#Override
public void onSuccess(String response) {
super.onSuccess(response);
Log.d("onSuccess", "onSuccess");
DoctorsModel doctorModel = new DoctorsModel();
ArrayList<DoctorInfo> doctorsInfoList = new ArrayList<DoctorInfo>();
try {
// convert response to JSON
JSONObject json = new JSONObject(response);
// get JSON Items
doctorModel.setDoctorCnt(json.getInt("DoctorsCount"));
doctorModel.setOp(json.getString("op"));
JSONArray doctorsArray = json.getJSONArray("Doctors");
Log.d("dr arrat", doctorsArray.toString());
for (int i = 0; i < doctorsArray.length(); i++) {
JSONObject doctorJSON = doctorsArray.getJSONObject(i);
doctorObj .setId(doctorJSON.getString("Id"));
Log.d("id", doctorJSON.getString("Id"));
doctorObj.setName(doctorJSON.getString("DoctorName"));
doctorObj.setGovernorateId(doctorJSON.getString("GovernorateId"));
doctorObj.setGovernorateName(doctorJSON.getString("GovernorateName"));
doctorObj.setSpecializationName(doctorJSON.getString("SpecializationName"));
doctorObj.setHospitalId(doctorJSON.getString("HospitalId"));
doctorObj.setHospitalName(doctorJSON.getString("HospitalName"));
doctorObj.setImageName(URL_IMAGE_BASE + doctorJSON.getString("ImageName"));
doctorObj.setMobile(doctorJSON.getString("Mobile"));
doctorObj.setSpecializationId(doctorJSON.getString("SpecializationId"));
doctorObj.setWeekendDays(doctorJSON.getString("WeekendDays"));
doctorObj.setWorkingDays(doctorJSON.getString("WorkingDays"));
doctorObj.setWorkingTime(doctorJSON.getString("WorkingTime"));
doctorsInfoList.add(doctorObj);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable e, String message) {
super.onFailure(e, message);
// show error message
}
#Override
public void onFinish() {
super.onFinish();
// remove loading bar
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.activity_list_item);
// Assign adapter to ListView
lv.setAdapter(adapter);
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
And I want to show the data in list view, how can I do that ?
Use an Adapter - http://developer.android.com/reference/android/widget/Adapter.html
Create an adapter with your data, then set that adapter as the ListView's adapter.
Hello I am trying to create an ASyncTask that will parse data from an XML file in the background and then display that String array data in a ListView. I am not understanding what I am doing wrong so far, or how to return the String Array values back to my GUI. Here is the code for what I have so far with it if you need anything else let me know please. Thank you for looking and giving any suggestions or places to turn to to find out more.
package com.lvlup.kikurself.scotttest;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import java.io.IOException;
import org.xml.sax.SAXException;
//import com.lvlup.kikurself.scotttest.WikiParser.Cm;
public class scottPlayers extends ListActivity {
public class PlayerGet extends AsyncTask<Void, Void, Void>{
#Override
protected void onPostExecute(Void result){
WikiParser p = new WikiParser();
ArrayList<String> titles = new ArrayList<String>();
try {
p.parseInto(new URL("http://scottlandminecraft.wikia.com/api.php?action=query&list=categorymembers&cmtitle=Category:Players&cmlimit=500&format=xml"), titles);
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (SAXException e) {}
//String[] values = new String[50];
//values = res;
ArrayAdapter<String> adapter = new ArrayAdapter<String>(scottPlayers.this, R.layout.main, titles);
setListAdapter(adapter);
//final ListView playersList = getListView();
/*playersList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long thisID)
{
Object o = (playersList.getItemAtPosition(position));
String playerName_temp = (o.toString());
Intent newIntent = new Intent(v.getContext(), playerDisp.class);
newIntent.putExtra("tempN", playerName_temp);
startActivity(newIntent);
}
});*/
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Toast.makeText(scottPlayers.this,
"onPreExecute \n: preload bitmap in AsyncTask",
Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
new PlayerGet().execute();
}
//get your data back again with: String fName = getIntent().getExtras().getInt("fname");
}
EDIT: I added new code after looking at other examples this is what I have come up with but now when I run this in the Emulator it just shows the background of my Main.xml the list doesn't populate, and if I import this to my phone running ICS it says that there was an error and force closes...I couldn't get this to happen in the emulator for some reason, and there were no errors in the LogCat for the emulator.
public class scottPlayers extends ListActivity {
private ArrayAdapter<String> mAdapter;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, new ArrayList<String>());
setListAdapter(mAdapter);
new PlayerGet().execute();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Object o = l.getItemAtPosition(position);
String playerName_temp = o.toString();
Intent newIntent = new Intent(v.getContext(), playerDisp.class);
newIntent.putExtra("tempN", playerName_temp);
startActivity(newIntent);
}
private class PlayerGet extends AsyncTask<Void, Void, ArrayList<String>> {
WikiParser p = new WikiParser();
ArrayList<String> titles = new ArrayList<String>();
#Override
protected ArrayList<String> doInBackground(Void... urls) {
try {
p.parseInto(new URL("http://scottlandminecraft.wikia.com/api.php?action=query&list=categorymembers&cmtitle=Category:Players&cmlimit=500&format=xml"), titles);
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (SAXException e) {}
return titles;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
for (String item : result) {
mAdapter.add(item);
}
}
}
}
Too much code to change, read AsyncTask docs. Especially execute() and onPostExecute().
Please get into the habit of reading the documentation before you ask for help. Everything you need is here.
Specifically, you need to implement onPostExecute in your PlayerGet class. It will be called when the background task has finished and will return the ArrayList to you as an argument to the callback.
A couple of helpful tips also. Always follow the standard Java naming conventions. Your class name "scottPlayers" should start with an uppercase letter. Also try to avoid using Object unless absolutely necessary. Type casting and type checking will save you a world of pain later on.