Android Disable any onTouch - java

I have developed an Android App that communicates via HTTP-Request with a server.
Some times it takes more time for a request so the app shows just a black screen and passes some seconds later. Sometimes the black screen appears some seconds later and you can send the request again and again.
Is there any possibility to disable the onTouch-Events or show a layer while the screen is loading?
Thank you.

use an asyncTask and launch your httprequest in the doInBackground() method, and for blocking the user , just display a ProgressDialog :
class YourRequestTask extends AsyncTask<Void, Void, JSONObject> {
ProgressDialog progress;
Context context;
public YourRequestTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(context, null,"Please wait...");
}
#Override
protected JSONObject doInBackground(Void... params) {
//do your work here for your http request
}
#Override
protected void onPostExecute(JSONObject result) {
progress.dismiss();
Log.i(TAG, "result is "+result.toString());
}
}

Related

AsyncTask: doInBackground is not finishing

I'am trying to implement an AsyncTask in Android that will load all my data from the database. Therefore I used the onPreExecute method to start a ProgressDialog
public class DataLoader extends AsyncTask<Void, Void, Void> {
private LoginActivity activity;
private ProgressDialog nDialog;
public DataLoader (LoginActivity act){
this.activity = act;
nDialog = new ProgressDialog(activity);
}
protected void onPreExecute() {
System.out.print("Start AsyncTask");
nDialog.setMessage("Loading data..");
nDialog.setTitle("Starting the application");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected Void doInBackground(Void ... params) {
System.out.println("Starting doInBackground");
loadDashboardData();
return null;
}
protected void onPostExecute() {
nDialog.dismiss();
Intent i = new Intent();
i.setClass(activity.getApplicationContext(), DashboardActivity.class);
activity.startActivity(i);
}
The I use the doInBackground method to load call a function to load the data. This method is called from an visible activity. The task is called with:
public class LoginActivity extends Activity {
public void onClick(View v) {
DataLoader dl = new DataLoader(this);
dl.execute();
}
}
And the code for the doInBackground is:
protected Void doInBackground(Void ... params) {
System.out.println("Starting doInBackground");
loadDashboardData();
return null;
}
Now the problem is that my doInBackground method will not finish. I tried to implement the loadDashboardData() call in the onPreExecute method. This will not show my dialog box but it will load the data correctly. In this case the UI Thread is not responding and will response after all the data has been loaded.
What can hinder the doInBackground method to execute correctly and load the data properly? The called method works (because I can call it and get the correct data). Also I'am not seeing the println in my run console.
In the frontend I can see the progressbar spinning, but in the backend I can see that no data is loaded.
Your problem is that you are overriding the wrong method name : )
It should be
#Override
protected void onPostExecute(Void result) {
// your code
}
as in your case the variable which doInBackground return is Void.
You can check the documentation about AsyncTask .

Loading button in Android Studio

I'm doing a login, I would like when the user put the credentials, the app show a toast or a image saying loading. But this image should be a few seconds in the screen before change the activity. Thanks.
Basically the image is shown during the time when the app is doing authentication task or other works in background. I dont know why you want few seconds. And you can use progress dialog for the loading view.
Do authentication in an AsyncTask and update interface when data finishes loading.
You can start a new activity in your AsyncTask's onPostExecute() method.
You need a new class that extends AsyncTask:
public class MyTask extends AsyncTask<Void, Void, Void> {
public MyTask(ProgressDialog progress) {
this.progress = progress;
}
public void onPreExecute() {
progress.show();
}
public void doInBackground(Void... unused) {
//do your login here
}
public void onPostExecute(Void unused) {
progress.dismiss();
}
}
In activity do:
ProgressDialog progress = new ProgressDialog(this);
progress.setMessage("Loading...");
new MyTask(progress).execute();
In onPostExecute() start activity by Intent
Intent go=new Intent(this.class,target_activity.class);
startActivity(go);

AsyncTask setMessage after some time android java

hi i have AsyncTask in my app but i am unable to change its setMessage
for example :-
private class ProgressTask1 extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask1(MainActivity mainActivity) {
context = mainActivity;
dialog = new ProgressDialog(context);
}
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Checking system...");
this.dialog.setCancelable(false);
this.dialog.setTitle("Please Wait...");
this.dialog.setIcon(R.drawable.ic_launcher);
this.dialog.show();
}
now i want that setmessage to change i tried adding it in doinbackground
protected Boolean doInBackground(final String... args) {
dothis1();
this.dialog.setMessage("one done...");
dothis2();
this.dialog.setMessage("two done...");
but this is making app force close and do not rate it low because i tried my best and searched forum but could able to fix this so asked for hand at this nice community :)
anybody can help ? :)
ERROR
05-13 23:36:34.899: E/AndroidRuntime(2454): Caused by:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the
original thread that created a view hierarchy can touch its views.
ohmm, you should not update UI from background thread. To update UI, you can do by two ways:
1) Using publishProgress (Progress... values) and onProgressUpdate(...). To do that, you must change your AsynTask class:
private class ProgressTask1 extends AsyncTask<String, String, Boolean> {
//.......... //your init
#Override
protected Boolean doInBackground(String... params) {
//your background handle
//publish to change UI
String toShow = "your_string_here";
publishProgress(toShow);
//return ...; //your return value
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
//detect message and show it.
//this.dialog.setMessage(values[0]);
}
}
2) Using onPostExecute(....):
private class ProgressTask1 extends AsyncTask<String, Void, Boolean> {
//.......... //your init
#Override
protected Boolean doInBackground(String... params) {
//your background handle
//return ...;//your return value
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
String toShow = "your_string_here";
//this.dialog.setMessage(toShow);
}
}
You cannot update the UI from the background.
See AsyncTask.onProgressUpdate to update the UI based on your background progress. :D

Android progress dialog for Listview

I have an activity with a listview. When I call this activity the activity takes about 3-5 seconds to appear and display the listview. It looks as if the button has not been pressed to load the activity, i would like to display a progressdialog while this loads but can't figure it out.
ProgressDialog progress;
progress = ProgressDialog.show(this, "Loading maps!",
"Please wait...", true);
// sort out track array
getTracks();
progress.dismiss();
I did the above on the oncreate() of the activity with the listview but the dialog never shows?
What I would like is to show the progress dialog on Activity A when the button is pressed and then dismiss once Activity B is loaded and displayed?
Thanks
You need to implement AsyncTask or simple JAVA threading. Go with AsyncTask right now.
onPreExecute() - display dialog here
doInBackground() - call getTracks()
onPostExecute() - display tracks in ListView and dismiss dialog
For example:
private static class LoadTracksTask extends AsyncTask<Void, Void, Void> {
ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = new ProgressDialog(yourActivity.this);
progress .setMessage("loading");
progress .show();
}
#Override
protected Void doInBackground(Void... params) {
// do tracks loading process here, don't update UI directly here because there is different mechanism for it
return null;
}
#Override
protected void onPostExecute(Void result) {
// write display tracks logic here
progress.dismiss(); // dismiss dialog
}
}
Once you are done with defining your AsyncTask class, just execute the task inside onCreate() by calling execute() method of your AsyncTask.
For example:
new LoadTracksTask().execute();
You can make progress Dialog like this :
onPreExecute(){
progressdialog = new ProgressDialog(MainActivity.this);
progressdialog.setMessage("Please wait while downloading application from the web.....");
progressdialog.setIndeterminate(false);
progressdialog.setMax(100);
progressdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressdialog.setCancelable(false);
progressdialog.show();
}
doInBackground(String... strings){
// here you code for downloading
}
onProgressUpdate(String... progress)
{
// here set progress update
progressdialog.setProgress(Integer.parseInt(progress[0]));
}
onPostExecute(String result)
{
progressdialog.dismiss();
}
Use something like this:
private static class MapLoader extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
progress.setVisibility(View.VISIBLE);
// make your element GONE
}
#Override
protected Void doInBackground(Void... params) {
// Load map processing
return null;
}
#Override
protected void onPostExecute(List<Document> result) {
progress.setVisibility(View.GONE);
adapter.setNewData(new_data);
adapter.notifyDataSetChanged();
}
}
In your onCreate() use:
listView.setAdapter(adapter);
new MapLoader.execute();

Show splash screen until app is done loading

My app loads a lot of stuff on startup and after testing it delays too long at the beginning to not have a splash screen. So, I want to display a splash screen until my app is done loading. I do NOT want to display a screen with a timer for X seconds. I found an example here:
Android SplashScreen
I tried implementing the code in the SO topic above but I just don't understand the code. After integrating it in my code I come up with one error that I commented into the code below. But I don't understand a lot of the code and I have commented in the code below the parts I am confused by.
public class MainMenu extends Activity {
private ProgressDialog pd = null;
private Object data = null; //What is this?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mainmenu);
// show the ProgressDialog on this thread
this.pd = ProgressDialog.show(this, "Working...", "Downloading data...", true, false);
// start a new thread that will download all the data
new DownloadTask().execute("Any parameters to download."); //What is DownloadTask()?
}
private class DownloadTask extends AsyncTask<String, Void, Object> {
protected Object doInBackground(String... args) { //Are these parameters correct?
return "replace this with your object"; //What is this?
}
protected void onPostExecute(Object results) {
// pass the resulting data to the main activity
MainMenu.this.data = result; //Error: "result cannot be resolved to a variable"
if(MainMenu.this.pd != null) {
MainMenu.this.pd.dismiss();
}
}
}
}
Let's start with the error:
MainMenu.this.data = result;
Notice the typo? It should be result*s*:
MainMenu.this.data = results;
Addressing the rest of your questions below:
private class DownloadTask extends AsyncTask<String, Void, Object>
The declaration is for an inline class called DownloadTask, and it states that you'll be taking Strings (via String...) as parameters to your doInBackground(String... params).
The second parameter (Void in your case) indicates the datatype used to "publish" the progress via publishProgress(DATATYPE)/onProgressUpdate(DATATYPE... progress). This method is suitable for notifying the user of changes, for example when you've finished downloading a file but still have a few to go.
The last parameter (Object), indicates what type of data you'll be passing on to onPostExecute(DATATYPE), in this example Object. This could either be to update a ListAdapter somewhere, or trigger any other UI change based on the outcome of the actions done in doInBackground.
Show ProgressDialog in onPreexecute and dismiss it in onPostExcute methods
something like this
private class DownloadTask extends AsyncTask<String, Void, Object> {
#Override
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(activity);
mProgressDialog =ProgressDialog.show(activity, "", "Please Wait",true,false);
super.onPreExecute();
}
protected Object doInBackground(String... args) { //Are these parameters correct?
return "replace this with your object"; //What is this?
}
protected void onPostExecute(Object results) {
// pass the resulting data to the main activity
MainMenu.this.data = results; //it should be results
if (mProgressDialog != null || mProgressDialog.isShowing()){
mProgressDialog.dismiss();
}
if(MainMenu.this.pd != null) {
MainMenu.this.pd.dismiss();
}
}

Categories