Android loading listview with progress dialog - android

this is my code to load listview items
#SuppressLint("DefaultLocale")
public class SearchList extends Activity {
private ArrayList<String> founded = new ArrayList<String>();
private OrderAdapter m_adapter;
ListView lv;
/** Called when the activity is first created. */
#SuppressLint("DefaultLocale")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchlist);
lv = (ListView) findViewById(R.id.listView1);
new Load().execute();
m_adapter = new OrderAdapter(this, R.layout.itemview, founded);
lv.setAdapter(m_adapter);
lv.setTextFilterEnabled(true);
}
private class Load extends AsyncTask<Void, Void, Void> {
ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = new ProgressDialog(SearchList.this);
progress.setMessage("loading....");
progress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
for (int i = 0; i <500000; i++) {
founded.add("String "+i);
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// write display tracks logic here
progress.dismiss(); // dismiss dialog
}
}
when i run the code the progress dialog already appear but after its dismiss i found that the list is empty no items added to it i do not know what is the problem and why the list is empty after the dialog loading .Pls need help
thanks in advance.

Set listadapter in onPostExecute Because you Are using AsyncTask to get adapter data and setting ListAdapter before Completing AsyncTask So Try to Set ListAdapter after Completing AsyncTask
So add these
m_adapter = new OrderAdapter(this, R.layout.itemview, founded);
lv.setAdapter(m_adapter);
lv.setTextFilterEnabled(true);
lines in onPostExecute method instead of onCreate Method
#Override
protected void onPostExecute(Void result) {
// write display tracks logic here
progress.dismiss(); // dismiss dialog
m_adapter = new OrderAdapter(YourActivity.this, R.layout.itemview, founded);
lv.setAdapter(m_adapter);
lv.setTextFilterEnabled(true);
}

Related

ProgressBar not showing in AsyncTask

I am loading list in ListView using AsyncTask by showing ProgressBar. But in my code the ProgressBar is now showing. Cant understand the problem.
I used the same code as in slidenerd but in the video code works but my code doesn't seem to work.
Video Link
public class MainActivity extends AppCompatActivity {
ListView listView;
String[] items = {"Ankush", "Kapoor", "Amit", "Kumar", "Shirshak", "Tillu", "Mishra", "Sudeep", "Dey", "Ayon",
"Ankush", "Kapoor", "Amit", "Kumar", "Shirshak", "Tillu", "Mishra", "Sudeep", "Dey", "Ayon",
"Ankush", "Kapoor", "Amit", "Kumar", "Shirshak", "Tillu", "Mishra", "Sudeep", "Dey", "Ayon",
"Ankush", "Kapoor", "Amit", "Kumar", "Shirshak", "Tillu", "Mishra", "Sudeep", "Dey", "Ayon"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
requestWindowFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
listView.setAdapter(adapter);
new JSONTask().execute();
}
public class JSONTask extends AsyncTask<Void, String, Void> {
private ArrayAdapter<String> adapter;
private int count = 0;
#Override
protected void onPreExecute() {
adapter = (ArrayAdapter<String>) listView.getAdapter();
setProgressBarIndeterminateVisibility(true);
setProgressBarVisibility(true);
}
#Override
protected Void doInBackground(Void... params) {
for (String i : items) {
publishProgress(i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
adapter.add(values[0]);
count++;
setProgress((int) (((double) count / items.length) * 10000));
}
#Override
protected void onPostExecute(Void aVoid) {
setProgressBarIndeterminateVisibility(false);
setProgressBarVisibility(false);
Toast.makeText(getApplicationContext(), "Done!", Toast.LENGTH_SHORT).show();
}
}
}
From the documentation of setProgressBarVisibility() and setProgressBarIndeterminateVisibility():
This method was deprecated in API level 24.
No longer supported
starting in API 21.
You should use a ProgressDialog instead.
you should use simple ProgressDialog
for example :
ProgressDialog myPd = ProgressDialog.show(context, "Please wait", "Uploading Database to Cloud...", true);
myPd.setCancelable(false);

How to declare ArrayList in android?

I want to declare arrayList into this line:
public class tlcity extends Activity {
//ArrayList<String> idArray = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
and into the other method,for example this method:
protected void onPostExecute(String result) {
//fill the arraylist
...
and into the other method for example this method read arraylist data:
public void readlist(){
//read the arraylist data and show
}
How can i do this?
You can declare ArrayList like this
ArrayList<String> list;
list = new ArrayList<String>();
You can add, remove items in ArrayList Like this
list.add("A");
list.remove(0);
ArrayList<String> abc=new ArrayList<String>();
You can initialize or create an instance of your array list like this
idArray = new ArrayList();
You can perform any operations to it using idArray object.
For example you can add items like this
idArray.add("item1");//In you case its a list of strings.
In the same way you would do that in another Java app / class:
public class tlcity extends Activity {
List<String> idArray;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
idArray = new ArrayList<String>();
}
protected void onPostExecute(String result) {
idArray.add("One");
idArray.add("Two");
idArray.add("Three");
...
}
public void readlist(){
for (final String element : idArray) {
// Use the nth string
}
}
I want to declare arrayList into this line:
ArrayList<String> myList;
and into the other method,for example this method:
myList = new ArrayList<String>;
and into the other method for example this method read arraylist data:
for(int i=0; i<myList.size(); i++)
System.out.println(myList.get(i).toString());
If you want to use ArrayList locally then declare it locally. if you want to use it in all methods then declare it globally in class.
public class tlcity extends Activity {
ArrayList<String> idArray = new ArrayList<>(); // to Use this arraylist globally.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> localaraaylist = new ArrayList<>(); //to use arraylist in only in oncreate method.
....
According to your post, telling how to declae ArrayList will not enough as you have some methods like onPreExecute() which is a method ofAsyncTask Interface.
Look at this,
public class MainActivity extends ActionBarActivity {
ArrayList<String> arrayList; // declaring ArrayList here
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrayList = new ArrayList<String>(); // Initializing arrayList
arrayList.add("initial text"); // adding a data to arrayList
ListView listView = (ListView)findViewById(R.id.listView);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arrayList); // setting the arrayList in ArrayAdapter
listView.setAdapter(adapter);
new LongOperation().execute(); // async Task
}
private class LongOperation extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
// progress dialog starts here
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
// for understanding purpose, i made a thread to sleep for 5 sec and later it will add A,B & C to ArrayList.
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// adding few more items to arrayList
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss(); // dismissing the progress Dialog
adapter.notifyDataSetChanged(); // refreshing listview
readA(); // read the arrayList
}
}
public void readA()
{
for (int i = 0; i<arrayList.size(); i++)
{
Log.d("key",arrayList.get(i));
}
}
}
Output :
If you run the above code, Initially your list view will only contain only one item & after 5 sec loading it will add another 3 items. The below information will print in logcat that reads the ArrayList.
04-13 14:07:32.395 1123-1123/? D/key﹕ initial text
04-13 14:07:32.395 1123-1123/? D/key﹕ A
04-13 14:07:32.395 1123-1123/? D/key﹕ B
04-13 14:07:32.395 1123-1123/? D/key﹕ C

What is wrong with progress dialog in AsyncTask

Am using Async Task in my application to get response from web service using restful web service. My code
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json_page);
_mContext = this;
new JSONParserTask().execute();
}
asynctask class
private class JSONParserTask extends AsyncTask<Void, Void, ListAdapter >{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
// dialog = new ProgressDialog(_mContext);
// dialog.setMessage("Loading...");
// dialog.show();
super.onPreExecute();
}
#Override
protected ListAdapter doInBackground(Void... arg0) {
ListAdapter adapter = null;
itemsList = new ArrayList<HashMap<String, String>>();
jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(Constants.JsonURL);
if(json == null){
Log.v(TAG, "----------- null");
return null;
}
try {
// Getting Array of Items
items = json.getJSONArray(TAG_ITEMS);
// looping through All items
for(int i = 0; i < items.length(); i++) {
JSONObject itemsObj = items.getJSONObject(i);
JSONObject products = null;
products = itemsObj.getJSONObject(TAG_PRODUCT);
Log.d(TAG,"product array "+products.toString());
JSONArray images = products.getJSONArray(TAG_IMAGES);
JSONObject imagesObj = images.getJSONObject(0);
Log.d(TAG, "......."+ imagesObj.getString(TAG_LINK));
String imageUrl = imagesObj.getString(TAG_LINK);
// Storing each json item in variable
String kind = itemsObj.getString(TAG_KIND);
String id = itemsObj.getString(TAG_KID);
String selfLink = itemsObj.getString(TAG_SELFLINK);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_KIND, kind);
map.put(TAG_KID, id);
map.put(TAG_SELFLINK, selfLink);
// adding HashList to ArrayList
itemsList.add(map);
}
/**
* Updating parsed JSON data into ListView
* */
adapter = new SimpleAdapter(_mContext, itemsList,
R.layout.list_item_row,
new String[] { TAG_KIND, TAG_SELFLINK }, new int[] {
R.id.name, R.id.mobile });
} catch(JSONException e){
e.printStackTrace();
}
return adapter;
}
#Override
protected void onPostExecute(ListAdapter adapter) {
lv.setAdapter(adapter);
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// some action
}
});
//dialog.dismiss();
}
}
with this code every thing working fine without using progress dialog. If u found, the code related to progress dialog is commented in above class.
If i uncomment progress dialog code, am not getting any response from server. I have tried with debugging also but never get any idea to remove this error.
Can some one tell what wrong am doing here.
ok the reason for that is you are updating you are adapter in your doInBackground() method
adapter = new SimpleAdapter(_mContext, itemsList,
R.layout.list_item_row,
new String[] { TAG_KIND, TAG_SELFLINK }, new int[] {
R.id.name, R.id.mobile });
This code is related to the MAIN THREAD and shouldn't be called here in the background thread, remove it from here, and add it to the onPostExecute() , just pass an array list from the Background thread and do other UI related stuff in the onPostExecute()
Try this
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
mProgressDialog= ProgressDialog.show(getApplicationContext(),"", getString(R.string.dialog_wait_message));
super.onPreExecute();
}
protected void onPostExecute(Void result) {
if(mProgressDialog!=null){
mProgressDialog.dismiss();
}
}
Try this one, rather
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
mProgressDialog= ProgressDialog.show(getApplicationContext(),"", getString(R.string.dialog_wait_message));
super.onPreExecute();
}
#Override
protected ListAdapter doInBackground(Void... arg0){
//do your stuff here
}
#Override
protected void onPostExecute(Void result) {
if(mProgressDialog!=null && mProgressDialog.isShowing()){
mProgressDialog.dismiss();
}
}
Try this
#Override
protected void onPreExecute() {
pd=new ProgressDialog(m_context);
pd.setTitle("Authenticating");
pd.show();
}
#Override
protected Void doInBackground(Void... args) {
//your stuff
}
#Override
protected void onPostExecute(Void result) {
pd.dismiss();
}

can't update list adapter in list view while posting in onPostExecute adapter.notifyDataSetChanged();

Basically i have been try to do the damn this for over 40 hours - read all threads about it and still no result!!! So I can't update list adapter in list view while posting in onPostExecute adapter.notifyDataSetChanged();
ArrayAdapter<String> adapter;
private ProgressDialog dialog;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setListAdapter(adapter);
dialog = new ProgressDialog(
Table.this);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Загружаю. Подождите...");
AsyncTask<Void, Void, Void> loadingTask = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
........ adapter = new ArrayAdapter<String>(Table.this, android.R.layout.simple_list_item_1,CreateStringArray
.getString(myData, null, null, null, null));
return null;
}
#Override
protected void onPostExecute(Void result) {
adapter.notifyDataSetChanged();
Table.this.
dialog.dismiss();
}
};
loadingTask.execute();
getListView().setOnItemClickListener(this);
}
So it shows me the spinner and successfully load and deletes it. After a while of debugging i noticed that it successfully changes data in the adapter. Still it dent display it. Am working with listvew
By instantiating a new Adapter in doInBackGround you lose the reference to the adapter you set doing setListAdapter(adapter); Therefore, the adapter you notify in OnPostExecute is not the one in your ListView.

Having problems trying to set an adapter inside an AsyncTask

I need to retrieve some huge data from one database when an activity is started. To prevent a user with a frozen window, I decided to run a ProgressDialog while data is being processed.
From OnCreate I call my initDb Class:
new initDb().execute();
And then to do this I have one class inside my activity's class:
public class initDb extends AsyncTask<Void, Void, Void> {
ProgressDialog mDialog = new ProgressDialog(ClientsReg.this);
#Override
protected void onPreExecute() {
mDialog.setMessage("Please wait...");
mDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
opendb();
listCities();
return null;
}
#Override
protected void onPostExecute(Void unused) {
// Pass the result data back to the main activity
mDialog.dismiss();
}
}
The real problem happens while setting the adapter:
private void listCities() {
mRedrawHandler.sleep(100000);
c = db.executeSQL("SELECT * FROM RegDB WHERE Reg_Type = 1 AND cad_uzkow = 0 ORDER BY _id DESC");
//add some list items
ArrayList<String> finalList = new ArrayList<String>();
c.moveToFirst();
while (!c.isAfterLast()){
finalList.add(c.getString(0) + ")"+ c.getString(5));
c.moveToNext();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.row, R.id.itemShow, finalList);
sp.setAdapter(adapter);
}
It always happen to crash on sp.setAdapter(adapter);
Any ideas?
Thank you!
Try taking the finalList as an attribute of your initDb class this way you can populate it on the doInBackground method and then us it on the onPostExecute, like this:
public class initDb extends AsyncTask<Void, Void, Void> {
ProgressDialog mDialog = new ProgressDialog(ClientsReg.this);
ArrayList<String> finalList;
#Override
protected void onPreExecute() {
mDialog.setMessage("Please wait...");
mDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
opendb();
listCities();
return null;
}
#Override
protected void onPostExecute(Void unused) {
// Pass the result data back to the main activity
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.row, R.id.itemShow, finalList);
sp.setAdapter(adapter);
mDialog.dismiss();
}
private void listCities() {
mRedrawHandler.sleep(100000);
c = db.executeSQL("SELECT * FROM RegDB WHERE Reg_Type = 1 AND cad_uzkow = 0 ORDER BY _id DESC");
//add some list items
finalList = new ArrayList<String>();
c.moveToFirst();
while (!c.isAfterLast()){
finalList.add(c.getString(0) + ")"+ c.getString(5));
c.moveToNext();
}
}
You should call:
sp.setAdapter(adapter);
in main UI thread. For example in onPostExecute() function. Always keep in mind that views (such as ListView) should only be accessed from main thread.
You can't access the UI from other thread than the thread that created the UI. So in AsyncTask, you can't use doInBackground() for this purpose.

Categories

Resources