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);
Related
In my Android app, I have an activity which executes an AsyncTask<Void, Void, Void> named Scan using this code: new Scan().execute();.
In the onPreExecute() method, it starts a progress dialog, on the doInBackground(Void... voids) method it scans a table from DynamoDB, and on the onPostExecute(Void aVoid) method, it dismisses the progress dialog, and views the results of the DB scan in a ListView using a custom BaseAdapter class.
When I open the activity, everything runs great, but when I press the back button, and enter the activity again, then only the onPreExecute() and the onPostExecute(Void aVoid) methods are being executed, while doInBackground(Void... voids) isn't being executed, so it just shows and dismisses the progress dialog, and nothing else is being viewed on the screen.
How can I fix this?
Code:
MessagesListAdapter messages;
ListView messagesLv;
public static ArrayList<Message> arrayList;
public static ProgressDialog progressDialog;
public static DynamoDBScanExpression dbScanExpression;
public static List<Message> messageList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messages);
new Scan().execute();
}
private class Scan extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(TestActivity.this);
progressDialog.setTitle(name);
progressDialog.setMessage("Searching for messages...");
progressDialog.setIndeterminate(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
dbScanExpression = new DynamoDBScanExpression();
Condition condition = new Condition()
.withComparisonOperator(ComparisonOperator.EQ)
.withAttributeValueList(new AttributeValue().withS(MainActivity.msgId));
dbScanExpression.addFilterCondition("msgId", condition);
messageList = MainActivity.mapper.scan(Message.class, dbScanExpression);
arrayList = new ArrayList<Message>();
for (Message msg : messageList) {
if (msg.getUserId() == null || msg.getUserId().equals(MainActivity.userId)) {
msg.setMsgId(msg.getMsgId());
msg.setDate(msg.getDate());
msg.setTime(msg.getTime());
msg.setMessage(msg.getMessage());
msg.setUserId(msg.getUserId());
arrayList.add(msg);
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (!messageList.isEmpty()) {
messagesLv = (ListView) findViewById(R.id.messagesListView);
messages = new MessagesListAdapter(MinaActivity.this, arrayList);
messagesLv.setAdapter(messages);
progressDialog.dismiss();
} else {
TextView tv = (TextView) findViewById(R.id.noMessages);
tv.setVisibility(View.VISIBLE);
progressDialog.dismiss();
}
}
}
The reason that it couldn't find any messages, was that I checked if the user ID of the message equals to the user ID of the registered user. The problem was that it was taken from MainActivity.java which got it from an Intent extra, therefore, when I have left the activity, the variable has been erased.
What I did is to refer to the user ID from the SharedPreferences and suddenly it worked.
try to add messages.notifyDataSetChanged(); in onPostExecute() method.
or use below code
MessagesListAdapter messages;
ListView messagesLv;
public static ArrayList<Message> arrayList;
public static ProgressDialog progressDialog;
public static DynamoDBScanExpression dbScanExpression;
public static List<Message> messageList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messages);
messagesLv = (ListView) findViewById(R.id.messagesListView);
messages = new MessagesListAdapter(MinaActivity.this, arrayList);
messagesLv.setAdapter(messages);
new Scan().execute();
}
private class Scan extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(TestActivity.this);
progressDialog.setTitle(name);
progressDialog.setMessage("Searching for messages...");
progressDialog.setIndeterminate(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
dbScanExpression = new DynamoDBScanExpression();
Condition condition = new Condition()
.withComparisonOperator(ComparisonOperator.EQ)
.withAttributeValueList(new AttributeValue().withS(MainActivity.msgId));
dbScanExpression.addFilterCondition("msgId", condition);
messageList = MainActivity.mapper.scan(Message.class, dbScanExpression);
arrayList = new ArrayList<Message>();
for (Message msg : messageList) {
if (msg.getUserId() == null || msg.getUserId().equals(MainActivity.userId)) {
msg.setMsgId(msg.getMsgId());
msg.setDate(msg.getDate());
msg.setTime(msg.getTime());
msg.setMessage(msg.getMessage());
msg.setUserId(msg.getUserId());
arrayList.add(msg);
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (!messageList.isEmpty()) {
messages.notifyDataSetChanged();
progressDialog.dismiss();
} else {
TextView tv = (TextView) findViewById(R.id.noMessages);
tv.setVisibility(View.VISIBLE);
progressDialog.dismiss();
}
}
}
Trying to populate data to a RecyclerView from cloud, though I get output in Main Thread, it takes time, so decided to add an AsyncTask to load items with ease and also to insert a ProgressDialog, however now it seems like code has no effect, getting an empty screen.
But the AsyncTask is getting executed, as I am able to log items in the logcat, no idea why I don't get a RecyclerView. Here is the code I use and looking for help:
public class BigBoard extends ActionBarActivity {
private List<Person> persons;
private RecyclerView rv;
private RVAdapter adapter;
private String a,b;
private ProgressDialog pr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Parse.initialize(this, "app-id", "client-key");
setContentView(R.layout.activity_big_board);
Loader abc = new Loader();
abc.execute();
adapter = new RVAdapter(persons);
rv=(RecyclerView)findViewById(R.id.rv);
LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
}
private class Loader extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pr = new ProgressDialog(BigBoard.this);
pr.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pr.setIndeterminate(true);
pr.setCancelable(false);
pr.setMessage("Loading Board");
pr.show();
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... urls) {
initializeData();
initializeAdapter();
return null;
}
#Override
protected void onPostExecute(String result) {
pr.dismiss();
}
private void initializeData(){
persons = new ArrayList<>();
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("BigBoard");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> credentialList, ParseException e) {
if (e == null) {
for(int i=0;i<credentialList.size();i++)
{
a=credentialList.get(i).getString("Location");
b=credentialList.get(i).getString("Feed");
persons.add(new Person(a,b));
Log.d("OUT", "So the Val::------> " +a +b);
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
adapter.notifyDataSetChanged();
}
});
}
private void initializeAdapter(){
rv.setAdapter(adapter);
}
}
}
place the adapter.notifyDataSetChanged(); or rv.setAdapter(adapter);
to onPostExecute..
since onOPostExecute works on UI Thread.
Edit :
create a function inside the Adapter
public void updatePersons(List<Person> persons) {
this.persons = persons;
notifyDataSetChanged();
}
after filling the list in onPostExecute call this function the List.
I'm making an android app with a rss feed in android studio. I got a rss feed reader library(https://github.com/ShirwaM/Simplistic-RSS), put it in my project and created my MainActivity and now I get and and exception: V/Error Parsing Data﹕ java.io.IOException: Couldn't open http://feeds.bbci.co.uk/news/rss.xml
MainActivity:
public class MainActivity extends Activity {
private ListView mList;
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = (ListView) findViewById(R.id.list);
adapter = new ArrayAdapter<String>(this, R.layout.basic_list_item);
new GetRssFeed().execute("http://feeds.bbci.co.uk/news/rss.xml");
}
private class GetRssFeed extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
try {
RssReader rssReader = new RssReader(params[0]);
for (RssItem item : rssReader.getItems())
adapter.add(item.getTitle());
} catch (Exception e) {
Log.v("Error Parsing Data", e + "");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter.notifyDataSetChanged();
mList.setAdapter(adapter);
}
}
Add the proper permissions to use internet in your manifest will solve the problem.
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);
}
The progress dialog in AsyncTask does not dismiss, even though progressDialog.dismiss is run in onPostExecute().
I have tried implementing many answers to related questions on SO, with no success so far.
I am sure that I must be overlooking something very basic, but I am stuck.
Any pointers to an explanation and code snippet would be great, Thanks.
Main
public class Main extends Activity {
String result;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
asyncTask task = new asyncTask("Loading ...", this);
try {
result = task.execute("Question").get();
}
catch (Exception e) {
Log.e("Error: ", e.toString());
}
}
}
asyncTask
public class asyncTask extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
private String message;
private Context context;
public asyncTask(String msg, Context ctx) {
this.context = ctx;
message = msg;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.show(context, "", message, true, false);
}
#Override
protected String doInBackground(String... params) {
int count = 100000;
for (int i = 0; i < count; i++) {
// waste time
}
return "Answer";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}
Actually your are doing :
progressDialog.show(context, "", message, true, false);
instead it should be like :
progressDialog = ProgressDialog.show(context, "", message, true, false);
You have to statically call show method and assign it to your progressDialog
Make this changes in your onPostExecute
#Override
protected void onPostExecute(String result) {
try{
if(progrssDialog.isShowing()){
progressDialog.dismiss();
}
}
catch(Exception e){
e.printStackTrace();
}
finally
{
progressDialog.dismiss();
}
}
A common issue i have found is the Variable Scope.
Most times , the ProgressDialog will be defined inside a Method , which wont be accessable outside that method.
You need to Declare it like so ,
Public Class MainActivity extends Activity {
ProgressDialog progressDialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private class asyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}
replace
task.execute("Question").get();
with
task.execute("Question");
by calling .get() you forcing main thread to wait. It will/can hang your UI.
progressDialog.dismiss();
put this in doInBackground() method before Return Statement.