Hide a ProgressDialog once data is loaded - android

In my android application I have a MainActivity. It has an EditText and a Button. User enter his twitter handle and press button. An IntentService is launched which retrieves user's tweets and then return the first tweet to a BroadcastReceiver.
Since loading tweets takes time I want to show a loader until loading tweets is done.
I'm using following code in button click listener to show the loading dialog
ProgressDialog progress = new ProgressDialog(MainActivity.this);
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.show();
But I don't know how to hide this once the loading is done.
Below are the code of the MainActivity , IntentService and BroadcastReceiver
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
analyze = (Button)findViewById(R.id.analyze);
twitter_username = (EditText)findViewById(R.id.twitter_username);
analyze.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
ProgressDialog progress = new ProgressDialog(MainActivity.this);
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.show();
Intent i = new Intent(MainActivity.this , TwitterChecker.class);
i.putExtra("username", twitter_username.getText().toString());
startService(i);
}});
}
IntentService
public class TwitterChecker extends IntentService {
public TwitterChecker(){
super("TwitterChecker");
}
#Override
protected void onHandleIntent(Intent intent) {
String username = intent.getStringExtra("username");
TwitterAuthenticator authenticator = TwitterAuthenticator.getInstance();
String accessToken = null;
try {
accessToken = authenticator.authenticate();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (AuthenticationException e) {
e.printStackTrace();
}
Twitter tweets = FetchTweets.fetch(accessToken , username);
Log.i("Info" , "IntentService started");
Intent tweet = new Intent("com.kaysush.action.TWEET");
tweet.putExtra("tweet", tweets.get(0).getText());
sendBroadcast(tweet); // Once loaded the tweet is sent to the Receiver
}
}
BraodcastReceiver
public class TweetsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("TWEET RECEIVED" , intent.getStringExtra("tweet"));
//Once loading is done a toast is shown
Toast.makeText(context, intent.getStringExtra("tweet"), Toast.LENGTH_LONG).show();
}
}

Hide a ProgressDialog once data is loaded
You are able to do it but you need to use not static but dynamic BroadcastReceiver. So here is solution:
At first, register in your Activity BroadcastReceiver dynamically:
private void registerReceiver() {
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Const.LOADING_COMPLETE_ACTION)) {
if (dlg != null) {
dlg.dismiss();
}
}
}
}
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Const.LOADING_COMPLETE_ACTION);
registerReceiver(receiver, intentFilter);
}
And then in your IntentService, all what you need is to send Broadcast:
sendBroadcast(new Intent(Const.LOADING_COMPLETE_ACTION));
Note: Also define your ProgressDialog variable on Activity scope to have access to it from onReceive() method.

ProgressDialog progress; // Make global
Assign onClick listener
progress = new ProgressDialog(MainActivity.this);
Then in call back method onReceive()
progress.cancel();

Related

How to update edittext from IntentService class?

I'm making a chat app and using intent service for sending messages to firebase database even after activity is destroyed. When the uploading is successful i want to clear text in Edittext in the IntentService class but don't know how to do it.
Acivity class code
Intent sendmsgService = new Intent(getApplicationContext(),SendMessageService.class);
sendmsgService.putExtra("msg",message);
sendmsgService.putExtra("time",time);
sendmsgService.putExtra("cuser",current_user);
sendmsgService.putExtra("otheruser",otherusername);
startService(sendmsgService);
IntentService class code
public class SendMessageService extends IntentService {
DatabaseReference msgDatabase , mDatabase;
String current_user,otherusername,message,time;
public SendMessageService() {
super("SendMessageService");
mDatabase = FirebaseDatabase.getInstance().getReference();
msgDatabase = mDatabase.child("messages").child(current_user).child(otherusername);
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
assert intent!=null;
message = intent.getStringExtra("msg");
time = intent.getStringExtra("time");
current_user = intent.getStringExtra("cuser");
otherusername = intent.getStringExtra("otheruser");
DatabaseReference push_database = msgDatabase.push();
String msg_push = push_database.getKey();
DatabaseReference d = FirebaseDatabase.getInstance().getReference();
String cuser = current_user+"/"+otherusername+"/";
String ouser = otherusername+"/"+current_user+"/";
Map<String,Object> chatitems = new HashMap<>();
chatitems.put("seen",false);
chatitems.put("msg",message);
chatitems.put("from",current_user);
Map<String,Object> msgitemmap = new HashMap<>();
chatitems.put("time", ServerValue.TIMESTAMP);
msgitemmap.put("servertime",ServerValue.TIMESTAMP);
msgitemmap.put("time",time);
msgitemmap.put("msg",message);
msgitemmap.put("from",current_user);
msgitemmap.put("to",otherusername);
msgitemmap.put("seen",false);
msgitemmap.put("key",msg_push);
Map<String,Object> chatmap = new HashMap<>();
chatmap.put("chatlist/"+cuser,chatitems);
chatmap.put("chatlist/"+ouser,chatitems);
chatmap.put("messages/"+cuser+msg_push,msgitemmap);
chatmap.put("messages/"+ouser+msg_push,msgitemmap);
d.updateChildren(chatmap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//Here i want to clear the edittext
}
});
}}
If any other solution please suggest.
Intent service runs on background thread not on main(UI) thread but we can use the Handler mechanism to send/update data to activity.
To send data to activity you need to declare handler in your activity like:
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Bundle reply = msg.getData();
// do whatever with the bundle here
}
};
in the intent service class pass data in this way:
Bundle bundle = intent.getExtras();
if (bundle != null) {
Messenger messenger = (Messenger) bundle.get("messenger");
Message msg = Message.obtain();
msg.setData(data); //put the data here
try {
messenger.send(msg);
} catch (RemoteException e) {
Log.i("error", "error");
}
}
Most Important invoke the intent service from activity to pass handler to it:
Intent intent = new Intent(this, IntentService1.class);
intent.putExtra("messenger", new Messenger(handler));
startService(intent);
Hope this will help you
Simple solution is to use Broadcast Reciever Declare this in your activity class
BroadcastReceiver broadCastNewMessage = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// do your stuff here
edittext.setText("");
}
};
Now in onCreate() register this
registerReceiver(this.broadCastNewMessage, new IntentFilter("uploading_done"));
And in onDestroy()
unregisterReceiver(broadCastNewMessage);
Now Call this method from the service class where u want to update the activity
sendBroadcast(new Intent().setAction("uploading_done"));

directly start Activity if user has already registered

I am new in android development. i want my application to directly launch MainActivity if the User has already registered. how can i do this.
this is my MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
Button btnTip, btnApp, btndos, btnAbout, btnServices;
ConnectionDetector cd;
AsyncTask<Void, Void, Void> mRegisterTask;
public static String name;
public static String email;
public static String contact;
public static String imei;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
toolbar.setTitle("Dental Application");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
btnTip = (Button) findViewById(R.id.tips);
btndos = (Button) findViewById(R.id.dos);
btnApp = (Button) findViewById(R.id.appointments);
btnAbout = (Button) findViewById(R.id.about);
btnServices = (Button) findViewById(R.id.services);
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this,
"Internet Connection Error",
"Please check your Internet connection", false);
// stop executing code by return
return;
}
Intent i = getIntent();
name = i.getStringExtra("name");
email = i.getStringExtra("email");
contact = i.getStringExtra("contact");
imei = i.getStringExtra("imei");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
//lblMessage = (TextView) findViewById(R.id.lblMessage);
registerReceiver(mHandleMessageReceiver, new IntentFilter(
DISPLAY_MESSAGE_ACTION));
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(this);
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(this, SENDER_ID);
} else {
// Device is already registered on GCM
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// Register on our server
// On server creates a new user
ServerUtilities.register(context, name, email, regId, contact, imei);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
btnTip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, TipsActivity.class);
startActivity(intent);
}
});
btndos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DosActivity.class);
startActivity(intent);
}
});
btnApp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, BookAppointmennts.class);
startActivity(intent);
}
});
btnAbout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AboutUsActivity.class);
startActivity(intent);
}
});
btnServices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ServicesActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Receiving push messages
* */
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
/**
* Take appropriate action on this message
* depending upon your app requirement
* For now i am just displaying it on the screen
* */
// Showing received message
//lblMessage.append(newMessage + "\n");
Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
// Releasing wake lock
WakeLocker.release();
}
};
#Override
protected void onDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
try {
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
} catch (Exception e) {
Log.e("UnRegister Receiver", "> " + e.getMessage());
}
super.onDestroy();
}
}
and the RegisterActivity
public class RegisterActivity extends Activity {
// alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Internet detector
ConnectionDetector cd;
// UI elements
EditText txtName;
EditText txtEmail;
EditText txtContact;
// Register button
Button btnRegister;
String imei;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(RegisterActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if GCM configuration is set
if (SERVER_URL == null || SENDER_ID == null || SERVER_URL.length() == 0
|| SENDER_ID.length() == 0) {
// GCM sernder id / server url is missing
alert.showAlertDialog(RegisterActivity.this, "Configuration Error!",
"Please set your Server URL and GCM Sender ID", false);
// stop executing code by return
return;
}
txtName = (EditText) findViewById(R.id.txtName);
txtEmail = (EditText) findViewById(R.id.txtEmail);
txtContact = (EditText) findViewById(R.id.contact);
btnRegister = (Button) findViewById(R.id.btnRegister);
TelephonyManager mngr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
imei = mngr.getDeviceId();
/*
* Click event on Register button
* */
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Read EditText dat
String name = txtName.getText().toString();
String email = txtEmail.getText().toString();
String contact = txtContact.getText().toString();
// Check if user filled the form
if (name.trim().length() > 0 && email.trim().length() > 0 && contact.trim().length()>0) {
// Launch Main Activity
Intent i = new Intent(getApplicationContext(), MainActivity.class);
// Registering user on our server
// Sending registraiton details to MainActivity
i.putExtra("name", name);
i.putExtra("email", email);
i.putExtra("contact", contact);
i.putExtra("imei", imei);
startActivity(i);
finish();
} else {
// user doen't filled that data
// ask him to fill the form
alert.showAlertDialog(RegisterActivity.this, "Registration Error!", "Please enter your details", false);
}
}
});
}
}
i am using GCM. the user is first registered and MainActivity is Displayed. Next time when the user opens the application i want directly MainActivity to be displayed. how can i do this. Can anyone please help me.
You will have to make LauncherActivity like SplashScreen in which check from shared prefrences or sqlite data that user is already registered or not
then by checking this transfer to corresponding activity.
If the user is not registered then show Registration Screen and when user register then save info in Sqlite or sharedpreferences or any other way.
If the user is already registered the show HomeScreen
First of all just post only the code that needs modification, you've posted all of the code in that Java file of yours. We could be more helpful if your code isn't cluttered.

Android:Unable to receive data from Service to Activity through Broadcastreceiver

I have an activity and and a service. I am running my service in background in a time interval through AlaramManager. What I want is to receive periodically data from the service inside activity. For this I'm using broadcastreceiver, but it does not showing any data.
In my service I'm using this method for sending data:
private final void sendServiceActiveBroadcast(final boolean pActivate) {
final Intent _intent = new Intent();
_intent.setAction(BROADCAST_ACTION);
_intent.addCategory("com.monday.worker_android.android.CATEGORY");
_intent.putExtra("isactive", pActivate);
NewService.this.sendBroadcast(_intent);
}
And use it inside an AsyncTask class like:
#Override
protected void onPostExecute(String result) {
Log.d("Post Execute", "Executed");
super.onPostExecute(result);
float[] arr = new float[30];
if (round(distance(LATITUDE, LONGITUDE, lati, longi)) < 200) {
Log.d("OnPostExecute", "In");
sendServiceActiveBroadcast(true);
}
}
And try to receive this in my activity like:
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
boolean value = intent.getBooleanExtra("isactive", false);
if (value == true) {
Toast.makeText(getApplicationContext(), "received",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), " not received",
Toast.LENGTH_SHORT).show();
}
}
};
I resister it in my onResume() and unresister it in my onPause() like:
#Override
protected void onResume() {
IntentFilter filter = new IntentFilter();
filter.addAction(NewService.BROADCAST_ACTION);
registerReceiver(receiver, filter);
super.onResume();
}
#Override
protected void onPause() {
unregisterReceiver(receiver);
super.onPause();
}
I just check some tutorials and code it. My application is working fine with service and also it excutes the onPostExecute() perfectly. But it does't show any broadcast data.
Can any one please suggest me how to receive periodically data from service and why I fail to receive data here and about my mistakes.
Thank You
addCategory
is the problem in your code. Because, in your activity you didn't set the category attribute, so the reference can not be found. Also, without having the category you can send this to multiple receivers at different locations with action attribute.

How to get progress dialog until get the response from service in android?

I am using service for running long background tasks in my application, in the service these functions are running login to XMPP and getting some data from XMPP server. i want to show the progress bar upto login completed. How to get response from service to activity to Update progress bar properly to avoid some exceptions in UI.
I am calling service like this
final Intent gtalk_intent = new Intent(AccountsActivity.this, GtalkService.class);
gtalk_intent.putExtra("user_name", acc.getAcc_Name());
gtalk_intent.putExtra("user_pass", acc.getAcc_Pass());
startService(gtalk_intent);
this is the code from service
public class PmService extends Service {
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class PmBinder extends Binder {
public PmService getService() {
return PmService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
context = this;
app_preferences = new AppPreferences(this);
chat_source = new ChatsDataSource(this);
chat_source.open();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle extras = intent.getExtras();
if(extras == null) {
full_name = extras.getString("user_name");
if(full_name.contains("#")) {
String[] _na = full_name.split("#");
U_name = _na[0];
}
U_pass = extras.getString("user_pass");
}
new PmAsync().execute();
return START_STICKY;
}
private class PmAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
#Override
protected Void doInBackground(Void... params) {
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
ConnectionConfiguration config = new ConnectionConfiguration(server_host, SERVER_PORT, SERVICE_NAME);
configure(ProviderManager.getInstance());
m_connection = new XMPPConnection(config);
try {
m_connection.connect();
Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.manual);
} catch (XMPPException e) {
e.printStackTrace();
}
try {
m_connection.login(U_name, U_pass);
setPacketFilters();
} catch (XMPPException e) {
}
return null;
}
}
i want to show the progress bar upto login completed, how to response from service after login completed?
Via Binder you can send callbacks to your Activity, which means that you can update UI.
Add according method to your Binder (let's name it onProgress)
From your AsyncTask call method of this Binder
In order to know about progress updates consider using Observer pattern (in other words - your Activity should listen for updates of your Binder, or more specifically - of calling Binder.onProgress method)
You can update the progress bar via overriding the onProgress() method
here is a close to your case that you can refer to.link

How to show a ProgressDialog using intent in Android?

I have an Activity which downloads the data from the Database. While the Activity is doing this work, I want to show the progress with ProgressDialog.I use ProgressDialog.STYLE_HORIZONTAL because I want to show the actual values. I use a Handler to start the Activity which displays the ProgressDialog:
Intent intent = new Intent(this, ProgressDialogActivity.class);
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what == SET_PROGRESS){
intent.putExtra("action", "show");
intent.putExtra("progress", msg.arg1);
intent.putExtra("max", msg.arg2);
intent.putExtra("message", syncMessage);
intent.putExtra("title", R.string.please_wait);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else if(msg.what == SHOW_PROGRESS){
intent.putExtra("action", "show");
intent.putExtra("title", syncMessage);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else if(msg.what == HIDE_PROGRESS){
intent.putExtra("action", "hide");
intent.putExtra("message", "");
intent.putExtra("title", "");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
};
Here is the ProgressDialogActivity:
public class ScreenProgressDialog extends Activity {
ProgressDialog pd;
Bundle extras;
String action;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
extras = getIntent().getExtras();
pd = new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(false);
pd.setProgress(extras.getInt("progress"));
pd.setMax(extras.getInt("max"));
pd.setMessage(extras.getCharSequence("message"));
pd.setTitle(extras.getString("title"));
action = extras.getString("action");
if (action.equals("show")){
pd.show();
}
else{
pd.dismiss();
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
When the Main Activity downloads a new table from the Database the Handler starts a new ProgressDialogActivity and a new Activity appears. I would like to avoid this. My aim is to show only ONE Activity which displays the ProgressDialog with the correct values.
(I cannot create a ProgressDialog in the Main Activity, I have to find another way. It's some kind of homework but I need some help).
Thank you!
You can use AsyncTask to fetch data in background and show ProgressDialog
Here is code:
// Get feed!
new ProgressTask().execute();
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(HomeActivity.this);
/** progress dialog to show user that the backup is processing. */
/** application context. */
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
/**
* Fetch the RSS Feeds from URL
*/
Utilities.arrayRSS = objRSSFeed
.FetchRSSFeeds(Constants.Feed_URL);
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
// display UI
UpdateDisplay();
}
}
}
What about using an AsyncTask: How to add ProgressDialog
Where you can do the download part in the doInBackground method and update the progress bar accordingly using onProgressUpdate..

Categories

Resources