I'm using AsyncTask with Viewpager and so far everything is working properly. When I run my application everything works fine and displays the data by sliding from one column to another. But when you start the app the data in that first column does not appear. I have tried in the onCreate insert the following code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = "1";
layout = R.id.lista;
empty = R.id.empty;
DownloadJSON newTask = new DownloadJSON(url,layout,empty);
newTask.execute();
...
It does not work. The app is closed. How do I can load this data when the app starts?
My code:
public class MainActivity extends Activity {
ViewPager vp;
private vpAdapter myAdapter;
ListViewAdapter adapter;
ListView listview;
String url;
int layout;
int empty;
ArrayList<HashMap<String, String>> arraylist;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctx = this;
setContentView(R.layout.activity_main);
vp = (ViewPager) findViewById(R.id.pager);
myAdapter = new vpAdapter();
vp.setAdapter(myAdapter);
vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int i) {
//CASE 0 = FIRST PAGE
switch (i) {
case 0:
url = "1";
layout = R.id.lista;
empty = R.id.empty;
DownloadJSON newTask = new DownloadJSON(url,layout,empty);
newTask.execute();
break;
default:
break;
case 1:
url = "2";
layout = R.id.lista2;
empty = R.id.empty2;
DownloadJSON newTask2 = new DownloadJSON(url,layout,empty);
newTask2.execute();
break;
case 2:
url = "3";
layout = R.id.lista3;
empty = R.id.empty3;
DownloadJSON newTask3 = new DownloadJSON(url,layout,empty);
newTask3.execute();
break;
case 3:
url = "4";
layout = R.id.lista4;
empty = R.id.empty4;
DownloadJSON newTask4 = new DownloadJSON(url,layout,empty);
newTask4.execute();
break;
case 4:
url = "5";
layout = R.id.lista5;
empty = R.id.empty5;
DownloadJSON newTask5 = new DownloadJSON(url,layout,empty);
newTask5.execute();
break;
case 5:
url = "6";
layout = R.id.lista6;
empty = R.id.empty6;
DownloadJSON newTask6 = new DownloadJSON(url,layout,empty);
newTask6.execute();
break;
}
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
String givemeurl;
int givemelayout;
int givemeempty;
public DownloadJSON(String url, int layout, int empty) {
this.givemeurl = url;
this.givemelayout = layout;
this.givemeempty = empty;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
ListView listview = (ListView) findViewById(layout);
if(listview.getCount()==0){
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Cargando...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}else{
cancel(true);
Log.e("CANCELADO","CANCELADO");
}
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("URL");
if(jsonobject != null){
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("productos");
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("imagen", jsonobject.getString("imagen"));
map.put("nombre", jsonobject.getString("nombre"));
map.put("total", jsonobject.getString("total"));
map.put("empresa", jsonobject.getString("empresa"));
map.put("unidades", jsonobject.getString("unidades"));
map.put("precionuevo", jsonobject.getString("precionuevo")+" €");
map.put("precioantiguo", jsonobject.getString("precioantiguo")+" €");
map.put("descripcion", jsonobject.getString("descripcion"));
map.put("direccion", jsonobject.getString("direccion"));
map.put("telefono", jsonobject.getString("telefono"));
map.put("latitud", jsonobject.getString("latitud"));
map.put("longitud", jsonobject.getString("longitud"));
map.put("codeqr", jsonobject.getString("codeqr"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
//e.printStackTrace();
} catch (Exception e) {
Log.e("Error", e.getMessage());
}
}else{
//Log.e("Response","No data");
}
return null;
}
#Override
protected void onPostExecute(Void args) {
listview = (ListView) findViewById(givemelayout);
listview.setEmptyView(findViewById(givemeempty));
adapter = new ListViewAdapter(MainActivity.this, arraylist);
listview.setAdapter(adapter);
mProgressDialog.dismiss();
//Log.e("",""+listview.getCount());
}
}
For a better performance, You should download all of the data, before showing the view pager. Currently you're downloading the same data again and again, whenever the user swipes the view pager. And not seeing any data on the first page initially is an expected result, because you download data only in onPageChangeListener. My suggestion is:
Create a dummy activity and make it launcher. It will be for downloading data. You can also do some configurations initially.
In onCreate method of that activity, download all of the necessary data your app needs using an AsyncTask.
In onPostExecute method of that AsyncTask start your main intent.
And finish the dummy activity to remove it from the stack so that when the user clicks back, your dummy activity won't be seen.
You can either pass the data you got to your main intent with:
Setting them as extras to your intent, using putExtra
Or you can store them in Application class, this is the only class that won't be destroyed by Android OS, so it's safe to store data there.
Related
This is my first time to write Android code and I am stark with a problem.
In the MainActivity, I use AsyncTask to request "Category" list to create buttons. The MainActivity buttons can be clicked and it redirects to GetProductsActivity with an extras String "Category(e.g.drink)". In the GetProductsActivity, I request server again using "Category" to get "Products" list to create product button.
Here is the problem: the code create button first, then AsyncTask request server to get "Products" list, I want to get the "Products" list before creating the button. What should I do?
"orga.getAttributes" is the function to request server.
Here is MainActivity
public class MainActivity extends AppCompatActivity {
private ArrayList<String> data = new ArrayList<String>();
List<String> attributes = new ArrayList<String>();
List<String> categoryList = new ArrayList<String>();
final Organisation orga = Organisation.getInstance();
private class CallSocketTask extends AsyncTask<Integer, Integer, String> {
protected String doInBackground(Integer... nochnix) {
orga.SetInit();
categoryList = orga.getAttributes(orga.GET_CATEGORIES,null,true);
return null;
}
protected void onPostExecute(String string) {
//attributes = orga.getAttributes(orga.GET_PRODUCTS_BY_CATEGORY,null,true);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new CallSocketTask().execute();//orga.stop();
//requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_main);
LinearLayout layer = (LinearLayout) findViewById(R.id.layer);
//getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.activity_main);
for(int i=0; i < categoryList.size(); i++)
{
Button button = new Button(this);
button.setId(i);
final String category = categoryList.get(i);
button.setText(category);
//click action
View.OnClickListener productHandler = new View.OnClickListener(){
public void onClick(View v) {
// doStuff
Intent intentMain = new Intent(MainActivity.this ,
GetProductsActivity.class);
intentMain.putExtra("categroy",category);
MainActivity.this.startActivity(intentMain);
Log.i("Content "," Main layout Click to Get Products by Category");
}
};
button.setOnClickListener(productHandler);
layer.addView(button);
}
}
}
Here is the GetProductsActivity
public class GetProductsActivity extends AppCompatActivity{
private ArrayList<String> data = new ArrayList<String>();
List<String> attributes = new ArrayList<String>();
final Organisation orga = Organisation.getInstance();
String category;
private class CallSocketTask extends AsyncTask<Integer, Integer, String> {
protected String doInBackground(Integer... nochnix) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
category = extras.getString("categroy");
Log.i("Category Selected",category);
}
//orga.SetInit();
attributes = orga.getAttributes(orga.GET_PRODUCTS_BY_CATEGORY,category);
Log.i("Product number ",attributes.size()+"");
//attributes = orga.getAttributes("getProducts","getCategories","Orangensaft");
return null;
}
protected void onPostExecute(String string) {
//Log.i("Result ","");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this.notifyAll();
CallSocketTask myTask = new CallSocketTask();
myTask.execute();//orga.stop();
setContentView(R.layout.get_products);
LinearLayout layer = (LinearLayout) findViewById(R.id.productsLayer);
//getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.activity_main);
//Bundle extras = getIntent().getExtras();
//data= extras.getStringArrayList("products");
Log.i("Product number OnCreate",attributes.size()+"");
for(int i=0; i < attributes.size(); i++)
{
Log.i("Product",attributes.get(i));
Button button = new Button(this);
button.setId(i);
button.setText(attributes.get(i));
layer.addView(button);
}
}
}
Move your code for setting up the buttons into onPostExecute.
Solve the problem quite easy: use Thread.sleep() in onCreate() function, so loop button can wait for the AsyncTask running.
Non-static inner AsyncTask may lead to memory leaks, check some gotchas.
Thread.sleep() is a bad way. What if the request "Category" runs longer because of network issues?
Buttons can be created in a method YourActivity.createButtons() which should be called in onPostExecute().
Here is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
setContentView(R.layout.startpage);
rowItems = new ArrayList<RowItem>();
//... Filling this array.
}
Later, from another activity StartPage.rowItems.size() throw NullPointerException
It can be 0 (failed to retrieve data or I did .clear()), but how, the hell, it became null? I definitely never set it to null.
One more point - this array variable is public static and I use it from another activity. Can it be possible android unloads parent activity (what contains all global variables for the whole app)?
P.S. I cannot check it more thoroughly, because this error is not appears in my emulator/devices, but I got reported it on Google Play. So I can't check what was before and when the array became null...
Thank you
More exact code:
public class StartPage extends Activity implements View.OnTouchListener {
public static List<RowItem> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
setContentView(R.layout.startpage);
rowItems = new ArrayList<RowItem>();
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading data...");
pDialog.setCancelable(false);
pDialog.show();
gc=new GetData();gc.execute();
}
public class GetData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
rowItems.clear();
inProgress=true;
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
items = jsonObj.getJSONArray(TAG_COINS);
for (int i = 0; i < itemss.length(); i++) {
JSONObject c = items.getJSONObject(i);
String id = c.getString(TAG_ID).toUpperCase();
String price = c.getString(TAG_PRICE);
String name = c.getString(TAG_NAME);
RowItem item = new RowItem(id, name, price);
rowItems.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
inProgress=false;
pDialog.dismiss();
}
}
Then call another activity:
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_UP:
int x = (int) event.getX();
int y = (int) event.getY();
int w=view.getWidth()-20;
int h=view.getHeight()-20;
if (x<w*0.05 || x>w*0.95 || y<h*0.13 ) return false; // Misclicked
if (x<w*0.5 && y<h*0.38) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
return true;
}
On another activity (MainActivity), try to refresh the listview with the data from main activity:
public class MainActivity extends ListActivity implements View.OnClickListener {
void refresh_list() {
if (StartPage.rowItems.size()>0) { <-- Here is NPE
ListAdapter adapter = new CustomListAdapter(MainActivity.this,R.layout.list_item,StartPage.rowItems);
setListAdapter(adapter);
((BaseAdapter) getListAdapter()).notifyDataSetChanged();
}
}
Google play report:
Caused by: java.lang.NullPointerException
at halfprice.coinmanager.MainActivity.refresh_list(MainActivity.java:116)
at halfprice.coinmanager.MainActivity.onCreate(MainActivity.java:105)
at android.app.Activity.performCreate(Activity.java)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java)
Hope this helps...
you are loading your data in static ArrayList and Acessing it to different activity. its not good practice to do.
Let me first tell your answer as you have created this object in Oncreate(). Its better you make create it Globally than this problem will not occure.
Example :
public class StartPage extends Activity implements View.OnTouchListener {
public static List<RowItem> rowItems = new ArrayList<RowItem>();
OnCreate(){
//and perform the action you want to do.
}
//Hope this will help you definately.
Now Another Method which is the good Practice in Programming language
Passing data object from one Activity to another is simple, If you want to pass Array object than the object should be serialized. Eg;
ArrayList rowItems = new ArrayList();
for Passing array object you have to use intent PutExtra, Eg:
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
intent.putExtra("key",array); startActivity(intent);
//intent.putExtra("key",array); will show error if your Model class is not implements Serializable eg: public class Model implements Serializable{
String id;
String price;
String name;
//generate your getter setter and set data in to this.
}
//For getting data in to another class just use
ArrayList<Model> data = (ArrayList<Model>)getIntent().getSerializable("key");
Now you can play arround with this data object. You should always try to play around with private or protected object.
Hope this will help you.
If i'm not mistaken:
When your activity is launched, the onCreate() method is called.
But when you come back to the same activity from another activity, then the onCreate method is skipped and onResume() method is called..so my suggestion is to initialize in the onResume() method
#Override
protected void onResume(Bundle savedInstanceState) {
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
setContentView(R.layout.startpage);
rowItems = new ArrayList<RowItem>();
//... Filling this array.
}
This answer might not solve your current problem ( not enough code to give a suggestion) but will help you head in the right direction.
Do provide a central data store for your objects, you should consider using singleton design pattern. Also, since the data will be accessed from multiple threads, you should make the arraylist (in your case) thread safe.
Note: if you are using synchronized list, you should lock the object to prevent access when it is iterated.
in my app im using gridview
when in portrait mode it shows one column.
in landscape mode new layout defined to show 2 column.
this is how the app works..
when app is launched, progress dialog is called to load website name from sqlite database and async is used to load website from sqlite db. the progress dialog is dismissed after the gridview is inflated.
now after loading the website name into gridview the screen orientation changes, it restarts the progress dialog.
i know that on screen orientation change the ondestroy() and then oncreate() are called.
this is my app's src code.
public class RSSReaderActivity extends Activity {
private ProgressDialog pDialog;
ArrayList<HashMap<String, String>> rssFeedList;
RSSParser rssParser = new RSSParser();
RSSFeed rssFeed;
Button add_rss;
// array to trace sqlite ids
String[] sqliteIds;
public static String TAG_ID = "id";
public static String TAG_TITLE = "title";
public static String TAG_LINK = "link";
GridView gridview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.site_list);
add_rss = (Button) findViewById(R.id.add_rss);
gridview = (GridView) findViewById(R.id.gridview);
rssFeedList = new ArrayList<HashMap<String, String>>();
new loadStoreSites().execute();
gridview.setOnItemClickListener(new OnItemClickListener() {
...
...
);
add_rss.setOnClickListener(new View.OnClickListener() {
...
...
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class loadStoreSites extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
...
...
}
#Override
protected String doInBackground(String... args) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
RSSDatabaseHandler rssDb = new RSSDatabaseHandler(getApplicationContext());
// listing all websites from SQLite
List<WebSite> siteList = rssDb.getAllSites();
sqliteIds = new String[siteList.size()];
// loop through each website
for (int i = 0; i < siteList.size(); i++) {
WebSite s = siteList.get(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, s.getId().toString());
map.put(TAG_TITLE, s.getTitle());
map.put(TAG_LINK, s.getLink());
// adding HashList to ArrayList
rssFeedList.add(map);
// add sqlite id to array
// used when deleting a website from sqlite
sqliteIds[i] = s.getId().toString();
}
gridview.setAdapter(new SimpleAdapter(RSSReaderActivity.this,rssFeedList, R.layout.site_list_row,new String[] { TAG_ID, TAG_TITLE, TAG_LINK },new int[] { R.id.sqlite_id, R.id.title, R.id.link }));
registerForContextMenu(gridview);
}
});
return null;
}
protected void onPostExecute(String args) {
// dismiss the dialog after getting all products
pDialog.dismiss();
}
}
}
SO how do we use onsavedinstance() over here.. please can anyone guide me.
add this in menifest file
android:configChanges="keyboardHidden|orientation|screenSize"
I am trying to pass the data from this main activity to another activity
I am successful in sending data between activities .... Like the data from Edit-text to next activity through putExtra and GetExtra methods and passing as intents
But i am facing challenge in this particular task where it involves
sending data from listview to an ordinary activity
data is populated in the list view from JSON so when on click of a
row how can i send the data from that row to a new activity
Any Ideas,
ativity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listViewID"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center">
</ListView>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
// url to make request
private static String url = "http://54.218.73.244:7002/";
List<Item> yourData = new ArrayList<Item>();
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Instantiating ProgressDialog with onCreate method
progressDialog=new ProgressDialog(MainActivity.this);
new ParsingAsync().execute();
}
private class ParsingAsync extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog=ProgressDialog.show(MainActivity.this, "", "Please Wait", true, false);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Creating JSON Parser instance
JSONObjParser jParser = new JSONObjParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
try {
for (int i = 0; i < json.length(); i++) {
JSONObject c = json.getJSONObject(i);
// Storing each json item in variable
String NAME=c.getString("restaurantNAME");
yourData.add(new Item(NAME));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressDialog.dismiss();
ListView yourListView = (ListView) findViewById(R.id.listViewID);
ListAdapter customAdapter = new ListAdapter(MainActivity.this, R.layout.itemlistrow, yourData);
yourListView.setAdapter(customAdapter);
yourListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
if(position == 0)
{
//code specific to first list item
Intent myIntent = new Intent(MainActivity.this,CopperChimneyDesc.class);
startActivity(myIntent);
}else if(position == 1)
{
//Intent myIntent = new Intent(MainActivity.this,AroyDesc.class);
//startActivity(myIntent);
}
}
});
}
}
}
item.java
public class Item{
private String Name;
public Item(String name){
this.Name = name;
}
public String getName(){
return Name;
}
}
Thanks,
Ok so you would do
String item = yourData.get(position).getName();
Then you can add the string to intent using:
intent.putExtra("restaurent", item);
On the other end if its textview you would do
textView.setText(getIntent().getExtras().getString("restaurent"));
intent.putExtra("City Name", String.valueOf(lvCity.getSelectedItem()));
try this one to cast.
you can parcle data and send it to other activity with putxtera method.please see How to store values in onSaveInstanceState() and retrive?
Since you have the index of the item in the listview the user has clicked you can get the item value from the adapter:
String value = (String)customAdapter.getItem(position);
Intent myIntent = new Intent(MainActivity.this,CopperChimneyDesc.class);
intent.putExtra("restaurant_name", value);
startActivity(myIntent);
You can save the data in sharedPreferences and can access it from other activity. Just an idea :)
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) {
}
}