I have a custom DialogFragment. I want to show this dialog while switching my activities.
Scenario:-
1) In actvity1 I start the dialog.
2) Start a asynctask class.
3) Do some authentication in doInBackground().
4) Start new actvity from onPostExecute().
Issue:-
The dialog stops before the asynctask.
Here is my code:-
myWebView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageStarted(WebView view, String url,
Bitmap favicon)
{
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
redirected =view.getUrl();
redirected= Uri.decode(redirected);
if(redirected!=null && redirected.contains(string1))
{
myprogressDialog.show(getFragmentManager(), "Wait");
}
}
#Override
public void onPageFinished(WebView view, String url)
{
// TODO Auto-generated method stub
super.onPageFinished(view, url);
if(redirected!=null && redirected.contains(mystring) )
{
myWebView.stopLoading();
String authorizationContentString = myurl
new Authentication(Activity2.this, myprogressDialog, url).execute(authorizationString);
}
private static class ProgressDialogFragment extends DialogFragment
{
public static ProgressDialogFragment newInstance()
{
return new ProgressDialogFragment();
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_FRAME, android.R.style.Theme_Translucent);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_dialog_progress, container, false);
}
}
Authentication.java
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
/* progDia.show(man, "wait");
progDia= new Utility.ProgressDialogFragment().newInstance();*/
}
public AuthenticateDevice(Details1 myContext, ProgressDialogFragment myprogressDialog, String Url)
{
// TODO Auto-generated constructor stub
mContext = myContext;
this.progDia = myprogressDialog;
this.Url = Url;
this.mActivity = myContext;
}
#Override
protected Void doInBackground(String... params)
{
// TODO Auto-generated method stub
//Some authentication
return null;
}
#Override
protected void onPostExecute(Void result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
if(progDia!=null&&progDia.isVisible())
{
progDia.dismiss();
}
Intent myIntent = new Intent(mContext, Activity2.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(myIntent);
mActivity.finish();
}
Try following code to show progress dialog in async
ProgressDialog pd;
class MYAsync extends AsyncTask<Void , Void, String>{
#Override
protected void onPreExecute() {
// pd.setTitle("Please Wait");
pd.setMessage("Working...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String sResponse) {
pd.dismiss();
pd.cancel();
}
}
}
I tried to recreate it, it appears to be working fine. this below method has comments explaining your actions.
private void myWOrk() {
try {
final ProgressDialog Dialog = new ProgressDialog(this);
Dialog.setMessage("Loading route...");
Dialog.show();
Thread.sleep(2000);// load url and redirect
//Toast.makeText(LoginActivity.this, "redirect caught", Toast.LENGTH_SHORT).show();
new AsyncTask<Object, Object, Object>() {
protected String doInBackground(Object... params) {
try {
Thread.sleep(2000);// authenticate
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Object result) {
Toast.makeText(LoginActivity.this, "onPostExecute", Toast.LENGTH_SHORT).show();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Dialog.dismiss();// start your new activity here
};
}.execute(null, null, null);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}`
Related
I have an asynTask to get all the events from server. This data from asyncTask I want to show as a list in a dialog. How can I do this?
getEventsAsyncTask
public class GetEventsAsyncTask extends AsyncTask<Void, Void, JSONObject> {
String api;
private Context context;
public GetEventsAsyncTask(Context context) {
this.context = context;
}
#Override
protected JSONObject doInBackground(Void... params) {
try {
api = context.getResources().getString(R.string.server_url) + "api/event/getEvents.php";
ServerRequest request = new ServerRequest(api);
return request.sendGetRequest();
} catch(Exception e) {
return Excpetion2JSON.getJSON(e);
}
} //end of doInBackground
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
Log.e("ServerResponse", response.toString());
try {
int result = response.getInt("result");
String message = response.getString("message");
if (result == 1 ) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//code after getting profile details goes here
} else {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//code after failed getting profile details goes here
}
} catch(JSONException je) {
je.printStackTrace();
Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
}
} //end of onPostExecute
}
dialog:
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
String[] listContent = {"Wedding",
"Anniversary",
"Naming Ceremony/Baptism",
"Thread Ceremony",
"Engagement",
"Birthday",
"Friends and Family Meet",
"Funeral",
"Movie",
"Play"};
switch(id) {
case CUSTOM_DIALOG_ID:
dialog = new Dialog(PlanEventActivity.this);
// dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.choose_event_dialog);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
// Toast.makeText(PlanEventActivity.this,
// "OnCancelListener",
// Toast.LENGTH_LONG).show();
}});
dialog.setOnDismissListener(new DialogInterface.OnDismissListener(){
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
// Toast.makeText(PlanEventActivity.this,
// "OnDismissListener",
// Toast.LENGTH_LONG).show();
}});
//Prepare ListView in dialog
dialog_ListView = (ListView)dialog.findViewById(R.id.dialoglist);
ArrayAdapter<String> adapter
= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listContent);
dialog_ListView.setAdapter(adapter);
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// Toast.makeText(PlanEventActivity.this,
// parent.getItemAtPosition(position).toString() + " clicked",
// Toast.LENGTH_LONG).show();
chooseEventText.setText(parent.getItemAtPosition(position).toString());
dismissDialog(CUSTOM_DIALOG_ID);
}});
break;
}
return dialog;
}
In this dialog the list I am showing as a string. How can I show list of data from asyncTask? Thank you..
This is my library project .
public class myads extends Activity implements AdListener {
public static int num;
public static InterstitialAd interstitialAds;
static AdRequest adr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
interstitialAds = new InterstitialAd(this, "ca-app-pub-*************/**********");
interstitialAds.setAdListener(this);
adr=new AdRequest();
interstitialAds.loadAd(adr);
interstitialAds.show();
}
public static void intenr(Context c){
interstitialAds.loadAd(adr);
interstitialAds.show();
Toast.makeText(c, "Sample", Toast.LENGTH_LONG).show();
num=3;
}
#Override
public void onDismissScreen(Ad arg0) {
// TODO Auto-generated method stub
}
#Override
public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLeaveApplication(Ad arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPresentScreen(Ad arg0) {
// TODO Auto-generated method stub
}
#Override
public void onReceiveAd(Ad arg0) {
// TODO Auto-generated method stub
interstitialAds.show();
}
}
It has unfortunately stopped Error and not working when I call it(this library project) from another project.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myads.intenr(this);
}
If I remove int.load and int.show from library project , It is working and toasting , got passed int. I also added internet permission and google activity tag properly. Thank you for interesting my problem.
It may be useful-
private InterstitialAd interstitial;
private AdRequest adRequestFullScreen;
private LocalBroadcastManager localBroadcastManager;
private NotificationReciever notificationReciever;
private Dialog answerDialog, chatReqDialog, questionDialog;
private boolean isShowAd = true, isRecieverRegistered = false,
isNetDialogShowing = false, isGpsDialogShowing = false;
private String notificationData = "", notificationType;
// Ad
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(getString(R.string.admob_fullscreen_ad));
// live
// adRequestFullScreen = new AdRequest.Builder().build();
// test
adRequestFullScreen = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("").build();
loadAd();
public void loadAd() {
interstitial.loadAd(adRequestFullScreen);
}
public void showAd() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
#Override
public void onDestroy() {
if (isRecieverRegistered) {
unregisterReceiver(internetConnectionReciever);
unregisterReceiver(GpsChangeReceiver);
}
AndyUtils.removeSimpleProgressDialog();
if (isShowAd) {
showAd();
}
Mint.closeSession(getApplicationContext());
stopLocationUpdate();
super.onDestroy();
}
I have the current under my MainActivity class and i cannot see why s and post are returning errors?
public class MainActivity extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTask<String, Integer, String> (){
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
OkHttpClient client = new OkHttpClient();
s = post("https://raw.github.com/square/okhttp/master/README.md","");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e("ANSWER", "" + s);
I am not sure why its not working
I know that have a lot of answers about this, but I can't find exactly what I need:
1) When users click on the button, shows a progress Dialog;
2) Executes a class AsyncTask and wait for the answer (it's a response using HTTPUrlConnection);
3) Dismiss Progress Dialog;
I tried a lot of things, but the progress dialog is not "appearing". My code:
public class MainActivity extends Activity implements OnTaskCompleted{
..
private ProgressDialog progressDialog;
private Button btnLogin;
..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
progressDialog = ProgressDialog.show(MainActivity.this,
"", "Scanning Please Wait", true);
try {
String param1 = "testParam1";
String param2 = "testParam2";
String response = new SyncHelper(MainActivity.this).execute("http://server.example.com/api", param1, param2).get(); //this way, my activity waits of the answer
Log.d(TAG, "Finished: " + response);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
// user didn't entered username or password
Toast.makeText(getApplicationContext(),
"Done",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
});
}
public void onTaskCompleted()
{
progressDialog.dismiss();
}
public class SyncHelper extends AsyncTask<Object, Void, String>
{
..
private OnTaskCompleted listener;
..
protected String doInBackground(Object... url) {
String response = "";
try {
response = getRequest((String) url[0],(String) url[1], (String) url[2]); //Here I make a HttpURLConnection
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPreExecute() {
}
protected void onPostExecute(String result) {
listener.onTaskCompleted();
}
}
public interface OnTaskCompleted{
void onTaskCompleted();
}
public class MainActivity extends Activity{
..
private Button btnLogin;
..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
String param1 = "testParam1";
String param2 = "testParam2";
new SyncHelper(MainActivity.this).execute("http://server.example.com/api", param1, param2); //this way, my activity waits of the answer
Log.d(TAG, "Finished: " + response);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
// user didn't entered username or password
Toast.makeText(getApplicationContext(),
"Done",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
});
}
public class SyncHelper extends AsyncTask<String, Void, String>
{
..
Context context;
private ProgressDialog pd;
..
public SyncHelper (Context c)
{
context = c;
}
#Override
protected void onPreExecute() {
pd = new ProgressDialog(context);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
protected String doInBackground(String... url) {
String response = "";
try {
response = getRequest(url[0], url[1], url[2]); //Here I make a HttpURLConnection
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
protected void onPostExecute(String result) {
// here you will be getting the response in String result.
if (pd.isShowing())
pd.dismiss();
}
}
When you are using get, using AsyncTask doesn't make any sense. Because get() will block the UI Thread, maybe thats why are not able to see the progress dialog. If you want to send the response back to the MainActivity then use the callback interface as you were using beofre.
I have this problem. I need to send a call to my SAX Parser (every time user tries enter name of the student) to get the names. What I am doing right now is sending a token-string to my HttpHandler which is returning 10 records every time because total no of students are about 40K so I can't parse them all at once. I am calling my AsyncTask for ParsingXML in onTextChanged event of AutoCompletetextview. but still I am not able to set the adapter to Autocomplete.
public ArrayList<AutoCompleteUserDataGetterSetter> parsexml(String token)
{
try {
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();
URL url = new URL(xyz.com/xyz.ashx?token=+"token"); // URL of the XML
AutoCompleteUserDataXMLHandler myXMLHandler = new AutoCompleteUserDataXMLHandler();
xmlR.setContentHandler(myXMLHandler);
xmlR.parse(new InputSource(url.openStream()));
} catch (Exception e) {
System.out.println(e);
}
return data=AutoCompleteUserDataXMLHandler.getArrayData();
}
Here is my AutoCompleteTextViewAdapter Code
ArrayList<AutoCompleteUserDataGetterSetter> data=new ArrayList<AutoCompleteUserDataGetterSetter>();
public UserNewMessageAutoCompleteAdapater(Context context,
int textViewResourceId,
ArrayList<AutoCompleteUserDataGetterSetter>data) {
super(context, textViewResourceId, data);
// TODO Auto-generated constructor stub
this.context = context;
this.data=data;
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final AutoCompleteUserDataGetterSetter i = this.data.get(position);
if (i != null) {
Log.d("adapter", "in here");
AutoCompleteUserDataGetterSetter si = (AutoCompleteUserDataGetterSetter) i;
v = vi.inflate(R.layout.autocompletetext_layout, null);
final TextView title = (TextView) v
.findViewById(R.id.autocomplete_name);
TextView userid = (TextView) v
.findViewById(R.id.autocompleteuserid);
if (title != null)
title.setText(si.GetFullName());
userid.setText(si.GetUserId());
}
return v;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public AutoCompleteUserDataGetterSetter getItem(int arg0) {
// TODO Auto-generated method stub
return data.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
and here is my AsyncTask Class
class SomeTask extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(UserMessagesComposeNewActivity.this);
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... voids) {
UserMessagesComposeNewActivity.this.data=parsexml(users.getText().toString());
for(int i=0;i<data.size();i++)
{
nameadapter.add(data.get(i).GetFullName());
useridadapter.add(data.get(i).GetUserId());
}
if(data==null)
{
AutoCompleteUserDataGetterSetter umsgs=new AutoCompleteUserDataGetterSetter();
umsgs.SetFullName(" ");
umsgs.SetUserID("");
data.add(umsgs);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
users.setAdapter(nameadapter);
}
}
Finally after some head-desking finally sorted the issue Finally!
I gave up the custom adapter approach and used the ArrayAdapter approach. so here is the complete code for my Sending Messages to users via selecting their names.
public class UserMessagesComposeNewActivity extends Activity implements TextWatcher{
ArrayList<AutoCompleteUserDataGetterSetter> data=new
ArrayList<AutoCompleteUserDataGetterSetter>();
Long login;
Boolean shouldAutoComplete;
UserNewMessageAutoCompleteAdapater cdapater;
String TO,FROM;
Button btn;
AutoCompleteTextView users;
EditText edTextSubject,edTextMessage;
AutoCompleteWidget myAutoComplete;
List<String> nameadapter=new ArrayList<String>();
ArrayAdapter<String> dataAdapter ;
UserNewMessageAutoCompleteAdapater atAdapter;
String ResultEmail;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent=getIntent();
setContentView(R.layout.user_messages_compose_new);
login=intent.getLongExtra("EmployeedId", 0);
btn=(Button)findViewById(R.id.userNewmessageSendButton);
edTextSubject=(EditText)findViewById(R.id.userNewmessageSubject);
edTextMessage=(EditText)findViewById(R.id.userNewmessageMessage);
users=(AutoCompleteTextView)findViewById(R.id.userNewmessageAutoCT);
users.addTextChangedListener(this);
users.setThreshold(4);
//Here we get the selected value from autocompletetextview dropdown
users.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
for(int i=0;i<data.size();i++)
{
if(data.get(i).GetFullName().equals(users.getText().toString()))
{
TO=data.get(i).GetUserId();
}
else
{
TO="0";
}
}
}
});
//here we call the Send Email method.
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new DomParserEmail().execute();
}
});
}
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.length()>=4)
{
new SomeTask().execute();
}
}
class SomeTask extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(UserMessagesComposeNewActivity.this);
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... voids) {
//Here we are parsing the xml
UserMessagesComposeNewActivity.this.data=parsexml(users.getText().toString());
if(data==null)
{
AutoCompleteUserDataGetterSetter umsgs=new AutoCompleteUserDataGetterSetter();
umsgs.SetFullName(" ");
umsgs.SetUserID("");
data.add(umsgs);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
UserMessagesComposeNewActivity.this.nameadapter.clear();
for(int i=0;i<data.size();i++)
{
UserMessagesComposeNewActivity.this.nameadapter.add(UserMessagesComposeNewActivity.this.data.get(i).GetFullName());
}
dataAdapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_dropdown_item_1line, nameadapter);
dataAdapter.notifyDataSetChanged();
users.setAdapter(dataAdapter);
users.showDropDown();
}
}
public ArrayList<AutoCompleteUserDataGetterSetter> parsexml(String token)
{
try {
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();
URL url = new URL("blah blah"); // URL of the XML
/**
* Create the Handler to handle each of the XML tags.
**/
AutoCompleteUserDataXMLHandler myXMLHandler = new AutoCompleteUserDataXMLHandler();
xmlR.setContentHandler(myXMLHandler);
xmlR.parse(new InputSource(url.openStream()));
} catch (Exception e) {
System.out.println(e);
}
return data=AutoCompleteUserDataXMLHandler.getArrayData();
}
class DomParserEmail extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(UserMessagesComposeNewActivity.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Sending your message");
this.dialog.setTitle("Please Wait");
this.dialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
// download and parse
UserMessagesComposeNewActivity.this.ResultEmail=EmailSuccessMessage(UserMessagesComposeNewActivity.this.edTextSubject.getText().toString(),UserMessagesComposeNewActivity.this.edTextMessage.getText().toString(),UserMessagesComposeNewActivity.this.TO,UserMessagesComposeNewActivity.this.login.toString());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
Toast toast=Toast.makeText(getApplicationContext(),UserMessagesComposeNewActivity.this.ResultEmail,Toast.LENGTH_LONG );
toast.show();
}
}
}
public String EmailSuccessMessage(String subject,String content,String To, String From) throws FactoryConfigurationError
{
try {
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();
URL url = new URL("abc.com/abc.asahx?blah blah");
/**
* Create the Handler to handle each of the XML tags.
**/
UserReplyMessageXMLParsing myXMLHandler = new UserReplyMessageXMLParsing();
xmlR.setContentHandler(myXMLHandler);
xmlR.parse(new InputSource(url.openStream()));
}
catch (Exception e)
{
System.out.println(e);
UserMessagesComposeNewActivity.this.ResultEmail="Email Not Sent";
}
UserReplyMessageXMLParsing usmx=new UserReplyMessageXMLParsing();
UserMessagesComposeNewActivity.this.ResultEmail=usmx.GetEmailStatus();
return UserMessagesComposeNewActivity.this.ResultEmail;
}
}