Answer the question
In order to leave comments, you need to log in
How to populate a ListView?
I can not put the cells of the parsed page in the ListView.
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import static android.R.layout.simple_list_item_1;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
private Context mContext;
private TextView myTextView;
class MyTask extends AsyncTask<Void, Void, Void> {
String title;
@Override
protected Void doInBackground(Void... params) {
ListView listView = (ListView) findViewById(R.id.listView);
// Создаём пустой массив для хранения имен котов
final ArrayList<String> catnames = new ArrayList<String>();
// Создаём адаптер ArrayAdapter, чтобы привязать массив к ListView
final ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(mContext,android.R.layout.simple_list_item_1, catnames);
// Привяжем массив через адаптер к ListView
listView.setAdapter(adapter);
try {
Connection.Response res= Jsoup
.connect("https://site.ru")
.method(Connection.Method.GET)
.execute();
res= Jsoup
.connect("https://www.site.ru/login/")
.data("login","123")
.cookies(res.cookies())
.data("password","321")
.method(Connection.Method.POST)
.execute();
Elements ele = doc.select("font[face=arial]");
title = ele.text();
String text;
for( Element element : doc.select("td#ele_id") )
{
text = element.text(); // Get the Text of the Link
catnames.add(0,text);
adapter.notifyDataSetChanged();
}
// Iterator<Element> iterator = ele.listIterator();
// Element element = iterator.next();
} catch (IOException e) {
// e.printStackTrace();
myTextView.setText("error");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
myTextView.setText(title);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = this;
myTextView = (TextView) findViewById(R.id.textView);
MyTask mt = new MyTask();
mt.execute();
}
}
Answer the question
In order to leave comments, you need to log in
You cannot communicate with UI elements not from MainThread. You do this in doInBackground(). Give catnames as the result of doInBackground, and loop through the array into the adapter once in onPostExecute. This is at least.
In general, asynctasks for network interaction are not good to use. There are normal libraries for this, for example - Retrofit.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question