Android DialogFragment - android

I use a class which extends DialogFragment, and in this class I use an AsyncTask for loading the content of my AlertDialog.
My question is: how I can create an AlertDialog which shows: "Loading..." and then shows the content in my onPostExecute method?
public class MyDialog extends DialogFragment {
public MyDialog(){
super();
}
#Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
....
return builder.create();
}
public class myTask extends Asynctask<Void, Void, Void> {
#Override
protected Void onPreExecute(){
Show loading... in AlertDialog
}
#Override
protected Void doInBackground(Void... voids) {
Load content...
}
#Override
protected Void onPostExecute(){
Show content in AlertDialog
}
}

For that purpose, my suggestion is that don't use AlertDialog. Use a progress dialog, Here is your complete dialog,
public class MyDialog extends DialogFragment {
public MyDialog(){
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.your_dialog_id, container, false);
new myTask().execute();
return view;
}
private void afterContentLoad (Object content)
{
//Update your UI with respect of your content :)
}
public class myTask extends Asynctask<Void, Void, Void> {
private ProgressDialog mDialog;
#Override
protected Void onPreExecute(){
try{
mDialog = ProgressDialog.show(getActivity(), "", "Loading...!");
}
catch(Exception e)
{
//BadTokenException
e.printStackTrace();
}
}
#Override
protected Void doInBackground(Void... voids) {
Load content...
}
#Override
protected Void onPostExecute(){
if (mDialog != null && mDialog.isShowing()){
mDialog.dismiss();
}
//Put your code after content loaded
afterContentLoad(Object);
}
}
}

Related

Get a TextView in an AsyncTask - Android

I want to publish the result of my AsyncTask (a string) in a textView.
Here is my Main:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ReadRss readRss=new ReadRss(this);
readRss.execute();
......
}
Here is my AsyncTask:
public class ReadRss extends AsyncTask<Void,Void,Void> {
public ReadRss(Context context){
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(Void aVoid) {
}
#Override
protected Void doInBackground(Void... params) {
ProcessXml();
return null;
}
private void ProcessXml() {
//HERE CREATE MY STRING
String myresult="example";
TextView txt_ris = (TextView)findViewById(R.id.txt_ris); <---HOW CAN I DO THIS?
txt_ris.setText(myresult);
}
}
}
}
FindViewById don't work in the AsyncTask so how can i get the TextView in here?
Maybe i can pass it as a paramiter in the AsyncTask, What is the syntax?
You need to place UI work in onPostExecute method, since doInBackground executes in not UI thread
public class ReadRss extends AsyncTask<Void,Void,String> {
public ReadRss(Context context){
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String string) {
TextView txt_ris = (TextView)findViewById(R.id.txt_ris);
txt_ris.setText(myresult);
}
#Override
protected String doInBackground(Void... params) {
return ProcessXml();
}
private String ProcessXml() {
//HERE CREATE MY STRING
return "example";
}
}
For your TextView to be correctly referenced you need a context and you already have a reference to your starting Activity in your AsyncTask constructor, so you can do something like:
public class ReadRss extends AsyncTask<Void,Void,Void> {
private TextView tv;
private YourStartingActivity activity;
public ReadRss(Context context){
activity = (YourStartingActivity)context;
tv = (TextView)activity.findViewById(R.id.txt_ris)
}
#Override
protected void onPreExecute() {
...
}
#Override
protected void onPostExecute(Void aVoid) {
(follow Michael Spitsin instructions here)
}
#Override
protected Void doInBackground(Void... params) {
...
}
}

Android how to pass value from async task to fragment

In My Android Project I am using TabLayout,I have
Fragment1 --> Fragment2(AlertDialog)
|
button1--- name:
listview Id:
okButton--->AsyncTask
Here,In Fragment1 after pressing button1 calls another fragment(Fragment2), there after fillup the form pressing okbutton calls AsyncTask to receive data from server.then the data needs to display in Fragment1's
listview
My classes:
interface
public interface TaskCompleted {
// Define data you like to return from AysncTask
public void onTaskComplete(Integer result);
}
Fragment1
public class Fragment1 extends Fragment implements TaskCompleted {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
btn1 = (Button) view.findViewById(R.id.button1);
listview = (ListView) view.findViewById(R.id.listview);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment picker = new SearchFragment();
picker.show(getActivity().getFragmentManager(), "dialog");
}
});
return view;
}
public static void submit(final String serverResponse) {
#SuppressWarnings("unused")
final class DownloadJSON extends AsyncTask<String, String, Void> {
#Override
protected Void doInBackground(String... params) {
try {
//code to process response
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
//display into adapter
}
}
}
}
Fragment2
public class Fragment2 extends DialogFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View content = inflater.inflate(R.layout.dialog_fragment, null);
builder.setView(content);
builder.setMessage("form")
// Positive button
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new JSONfunctions(getActivity()).execute();
}
});
// Create the AlertDialog object and return it
return builder.create();
}
#Override
public void onTaskComplete(String serverResponse) {
// TODO Auto-generated method stub
}}
AsyncTask
public class JSONfunctions extends AsyncTask<String, String, String> {
private TaskCompleted mCallback;
public JSONfunctions(Context context){
this.mContext = context;
this.mCallback = (TaskCompleted) context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(mContext);
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String serverResponse="";
try {
====code to connect to server===
return serverResponse; (return result)
}
} catch (Exception e) {
e.printStackTrace();
}
return serverResponse;
}
#Override
protected void onPostExecute(String result) {
mProgressDialog.dismiss();
mCallback.onTaskComplete(result);
}
}
and in MainActivity I also have
#Override
public void onTaskComplete(String serverResponse) {
Fragment2.submit(serverResponse);
}
With this code from fragment2 after pressing okbutton it calls asyncTask
and gets successfull response from server..but not displaying into listview..Why?????
Such a complex scenario implemented for such a simple task.
All you need to do is let the Fragment1 implement TaskCompleted interface and create AsyncTask in a separate class and make an attribute of TaskCompleted in this task.
When in onPostExecute just call the listener function and one thing more you have to pass the fragment reference to your async task while creating its object in constructor.
final class DownloadJSON extends AsyncTask<String, String, Void> {
//your attributes
TaskCompleted listener;
public DownloadJSON(TaskCompleted listener){
this.listener = listener;
}
#Override
protected Void doInBackground(String... params) {
try {
jsonarray = new JSONArray(serverResponse);
Gson gson = new Gson();
User[] user = gson.fromJson(jsonarray.toString(), User[].class);
// Contact con = new Contact();
for (int i = 0; i < user.length; i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", user[i].getFullname());
map.put("id", user[i].getId());
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
listener.onTaskCompleted(arraylist);
}
}
public class Fragment1 extends Fragment implements TaskCompleted {
#Override
public void onTaskComplete(ArraList<YourListModel> data) {
adapter = new ListViewAdapter(activity, data);
// Set the adapter to the ListView
listview.setAdapter(adapter);
}
}
Also apply null checks where necessary.

How to show ProgressDialog In Android Fragments?

I have some tabpages and fragments. And these fragments contain a GridView element. My program is going to webservice and reading JSON data, after getting images caching and populating gridviews custom grid.
Now, how can show ProgressDialog only not completed fragments? And how can I dismiss progressDialog GridView populating will complete?
My Fragment OnCreate Method;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_b, container, false);
context = getActivity();
final ProgressDialog dialog = ProgressDialog.show(context, "", "Please wait, Loading Page...", true);
GridView gridView = (GridView) v.findViewById(R.id.gridview);
if (isConnected()) {
try {
new ProgressTask(context).execute();
gridView.setAdapter(new AdapterB(context, WallPaperList));
} catch (NullPointerException e) {
e.printStackTrace();
return v;
}
} else {
Toast.makeText(v.getContext(), "Please check your internet connection..!", Toast.LENGTH_LONG).show();
}
return v;
}
its the short example for showing progress may this help you
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(DownloadImageActivity.this, "Wait", "Downloading...");
}
#Override
protected Bitmap doInBackground(String... params) {
//your downloading code
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(Bitmap bitmap) {
progressDialog.dismiss();
}
}
Check this...........
public interface AsyncTaskListener<Boolean> {
public void onCompletingTask(Boolean result);
}
public class AsyncTaskGetApiKey extends AsyncTask<Void, Void, Boolean>{
ArrayList<AsyncTaskListener<Boolean>> listeners;
public AsyncTaskLoadingInSplash() {
listeners = new ArrayList<AsyncTaskListener<Boolean>>();
}
public void addListener(AsyncTaskListener<Boolean> listener){
listeners.add(listener);
}
public void removeListener(AsyncTaskListener<Boolean> listener){
listeners.remove(listener);
}
#Override
protected Boolean doInBackground(Void... params) {
//do your activities here
return true; // If everything is fine
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
for (AsyncTaskListener<Boolean> listener:listeners) {
listener.onReceivingApiKey(result);
}
}
}
public class MyFagemnt extends Fragment
implements AsyncTaskListener<Boolean>{
AsyncTaskGetApiKey task;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//......
task = new AsyncTaskGetApiKey();
task.addListener(this);
//........
}
#Override
public void onCompletingTask(Boolean result) {
// your asyntask finished
// now close the progress bar
}
}
In AsyncTask, create progress dialog in onPreExecute() and dismiss that progress dialog in onPostExecute().
updated:
add this code in your viewpager activity.
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//You can get Call back to show the progress dialog when swipping.
boolean isLoading = true;//Check if the fragment is still loading or not at given position.
if (isLoading) {
//Show progress dialog.
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});

Progress Dialog for AsyncTask - Android

I'm trying to show a progress dialog while the twitter feed is loading up...However the progress dialog remains on screen when the twitter feed appears. Any help is much appreciated.
public class MainActivity extends ListActivity {
final static String twitterScreenName = "CFABUK";
final static String TAG = "MainActivity";
private AsyncTask<Object, Void, ArrayList<TwitterTweet>> tat;
boolean done;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
done=false;
AndroidNetworkUtility androidNetworkUtility = new AndroidNetworkUtility();
if (androidNetworkUtility.isConnected(this)) {
TwitterAsyncTask syn=new TwitterAsyncTask();
syn.execute(twitterScreenName,this);
ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setMessage("loading");
pd.show();
do {
if(!(syn.getStatus()==AsyncTask.Status.RUNNING)) {
pd.dismiss();
pd.cancel();
done=true;
}
} while(done=false);
} else {
Log.v(TAG, "Network not Available!");
}
}
}
You must call ProgressDialog show() method on AsyncTasks onPreExecute(). For example:
class MyTask extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("loading");
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
// Do your request
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pd != null)
{
pd.dismiss();
}
}
}
You must use a onPreExecute and onPostExecute of AsyncTask class. For example:
class AsyncData extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
// init progressdialog
}
#Override
protected Void doInBackground(Void... arg0) {
// get data
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// dismiss dialog
}
}
The methods onPreExecute(), doInBackground() and onPostExecute() of AsyncTask are used for purpose that you mentioned -
public class MainActivity extends ListActivity {
final static String twitterScreenName = "CFABUK";
final static String TAG = "MainActivity";
private AsyncTask<Object, Void, ArrayList<TwitterTweet>> tat;
boolean done;
Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
done=false;
context = this;
new NetworkTask().execute();
}
}
class NetworkTask extends AsyncTask<String, String, String>
{
Context ctx = context ;
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Working ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args)
{
//Do your background work here and pass the value to onPostExecute
AndroidNetworkUtility androidNetworkUtility = new AndroidNetworkUtility();
if (androidNetworkUtility.isConnected(ctx)) {
TwitterAsyncTask syn=new TwitterAsyncTask();
syn.execute(twitterScreenName,this);
while(done)
{
if(!(syn.getStatus()==AsyncTask.Status.RUNNING))
{
done=true;
}
else
{
Log.v(TAG, "Network not Available!");
}
}
return done + "";
}
protected void onPostExecute(String result)
{
//Do something with result and close the progress dialog
pDialog.dismiss();
}
ProgressBar is best alternative for ProgressDialog. A user interface element that indicates the progress of an operation.
ProgressDialog is deprecated in latest versions.
For more info see android developer official site: https://developer.android.com/reference/android/widget/ProgressBar.html

ProgressDialog does not disappear in android app

I have an android application which in its main activity, data are adapted from sqlite db and shown in list view. I tried to use Progress dialog to show 'loading' message to user during fetching data from db. But the dialog does not disappear.
Here is the code :
public class BirthdayAlarmActivity extends ListActivity {
List<BirthdayContact> listofAvailableBirthdays;
ProgressDialog pDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.birthday_list);
listofAvailableBirthdays=new ArrayList<BirthdayContact>();
ReinitializeList();
}
#Override
protected void onResume() {
ReinitializeList();
}
void ReinitializeList()
{
new LoadListView().execute();
if(listofAvailableBirthdays.size()>0)
{
//get ready the adapter
ArrayAdapter<BirthdayContact> ara=
new MyArrayAdapter(BirthdayAlarmActivity.this,listofAvailableBirthdays);
//set the adapter
setListAdapter(ara);
}
}
public class LoadListView extends AsyncTask<Void, Void, Void>
{
//ProgressDialog pDialog;
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(
BirthdayAlarmActivity.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(Void... unused) {
runOnUiThread(new Runnable() {
public void run() {
// increment current page
listofAvailableBirthdays.clear();
listofAvailableBirthdays=BirthdayHandler.GetTenBirthDays(BirthdayAlarmActivity.this);
}
});
return (null);
}
protected void onPostExecute(Void unused) {
// closing progress dialog
pDialog.dismiss();
}
}
I'm not familiar with the technique you're using, but I'll share what works for me:
final ProgressDialog progress = ProgressDialog.show(activity, "",
activity.getString(R.string.please_wait), true);
new Thread(new Runnable() {
#Override
public void run()
{
try {
--- network activity to retrieve information ---
}
finally {
activity.runOnUiThread(new Runnable() {
#Override
public void run()
{
if ((progress != null) && progress.isShowing())
progress.dismiss();
}
});
}
}
}).start();
I think the problem here is that you're referring to your pDialog and trying to create it in a different class than the one you've declared it in.
You should try using showDialog, dismissDialog and onCreateDialog methods to add a layer of abstraction and that the dialog is being called in the correct class/thread. You can use a Handler aswell as an alternative.
try something like this:
public class BirthdayAlarmActivity extends ListActivity {
List<BirthdayContact> listofAvailableBirthdays;
ProgressDialog pDialog;
static final int LOADING_DIALOG = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.birthday_list);
listofAvailableBirthdays=new ArrayList<BirthdayContact>();
ReinitializeList();
}
#Override
protected void onResume() {
ReinitializeList();
}
void ReinitializeList()
{
new LoadListView().execute();
if(listofAvailableBirthdays.size()>0)
{
//get ready the adapter
ArrayAdapter<BirthdayContact> ara=
new MyArrayAdapter(BirthdayAlarmActivity.this,listofAvailableBirthdays);
//set the adapter
setListAdapter(ara);
}
}
#Override
protected Dialog onCreateDialog(int id)
{
switch(id)
{
case LOADING_DIALOG:
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(
BirthdayAlarmActivity.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
return pDialog;
}
}
public class LoadListView extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
showDialog(LOADING_DIALOG);
}
protected Void doInBackground(Void... unused) {
runOnUiThread(new Runnable() {
public void run() {
// increment current page
listofAvailableBirthdays.clear();
listofAvailableBirthdays=BirthdayHandler.GetTenBirthDays(BirthdayAlarmActivity.this);
}
});
return (null);
}
protected void onPostExecute(Void unused) {
dismissDialog(LOADING_DIALOG);
}
}
If this fails, you should look int using messaging via the Handler class.

Categories

Resources