android create ProgressDialog in constructor - java

I created Activity that includes ProgressDialog and its methods.
public class ProgressActivity extends AppCompatActivity implements Thread.UncaughtExceptionHandler {
public final ProgressDialog progressDialog;
public void dismissPD() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
public void setPDMessage(String msg) {
progressDialog.setMessage(msg);
}
public void showPD(String msg) {
ProgressDialog.show(this, "", msg);
}
#Override
public void uncaughtException(Thread thread, Throwable ex) {
ex.printStackTrace();
}
public ProgressActivity() {
progressDialog = new ProgressDialog(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
dismissPD();
}
}
Now I extend my new activity from it, but I get NullpointerException inside constructur on progressDialog = new ProgressDialog(this)
As I see, I have a wrong context when constructor runs. Is there a right approach to realize it in my way?

I solved the problem by overriding oncreate mothod of the main Activity:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progressDialog = new ProgressDialog(this);
}

Related

moving the code to the activity java class (making two java classes into one)

I have codes in two classes
First class is ExampleBroadcastReceiver:
public class ExampleBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false
);
if (noConnectivity) {
Toast.makeText(context, "Disconnected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Connected", Toast.LENGTH_SHORT).show();
}
}
}
}
Second class is MainActivity:
public class MainActivity extends AppCompatActivity {
ExampleBroadcastReceiver exampleBroadcastReceiver = new ExampleBroadcastReceiver();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(exampleBroadcastReceiver, filter);
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(exampleBroadcastReceiver);
}
}
How can I make the two classes into one by passing the code from the ExampleBroadcastReceiver class to MainActivity? Is it possible? Please don't ask why. Thanks.
Use java interface to handle an event in MainActivity that occurs in ExampleBroadcastReceiver. This way you don't have to merge classes to share an event based data.
public class ExampleBroadcastReceiver extends BroadcastReceiver {
public interface ConnectivityMonitorCallback {
void onConnectivityChanged(boolean connectivity);
}
public ConnectivityMonitorCallback callback;
public ExampleBroadcastReceiver(#NonNull ConnectivityMonitorCallback eventCallback) {
callback = eventCallback;
}
#Override
public void onReceive(Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false
);
callback.onConnectivityChanged(noConnectivity);
}
}
}
Finally in the MainActivity you handle the event.
public class MainActivity extends AppCompatActivity {
ExampleBroadcastReceiver exampleBroadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Define event handling code here which occurs in ExampleBroadcastReceiver
exampleBroadcastReceiver = new ExampleBroadcastReceiver(new ExampleBroadcastReceiver.ConnectivityMonitorCallback {
#Override
void onConnectivityChanged(boolean connectivity) {
// Handle the event that occured in ExampleBroadcastReceiver
}
});
}
#Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(exampleBroadcastReceiver, filter);
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(exampleBroadcastReceiver);
}
}

java.lang.IllegalStateException: Fragment not attached to Activity issue in android

I am facing strange issue during call of my activity with Fragment usage. I am getting error like,
java.lang.IllegalStateException: Fragment ScoreFragment{ee2b833
id=0x7f0e0198} not attached to Activity
On line 146. My Fragment code which have error is line like below
if(mPageFlag.equalsIgnoreCase(getString(R.string.winners))){
And My full code for same is below,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mPageFlag = getArguments().getString(ARG_PAGE_FLAG);
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser && !mIsPageLoaded){
mContext = getActivity();
mIsPageLoaded = true;
if(mPageFlag.equalsIgnoreCase(getString(R.string.winners))){
new getcontestscorewinners(mContext).execute();
}else{ //
new getcontestscorewinnersNew(mContext).execute();
}
}
}
public class getcontestscorewinners extends AsyncTask<String, Void, String> {
boolean response = false;
private Context mContext;
public getcontestscorewinners(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(mContext, "Processing...",
"Please wait....");
}
#Override
protected String doInBackground(String... params) {
NetworkTask.getContestScoreWinners(winnerHandler);
return "";
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
Let me know if someone can help me for get out of it. Thanks.
Try using isAdded():
Return true if the fragment is currently added to its activity.
So your code should be like this :
if(isAdded() && mPageFlag.equalsIgnoreCase(getString(R.string.winners))){

start an activity through a method of the class that will be responsible for the running starActivity

good afternoon I have two classes, one that implement one progressBar this class I intend to create a public method that will run startActivity(). the main class would have a button that would call the method. However this giving error null reference.
ProgressBarUtil:
public class ProgressBarUtil extends BaseActionBarActivity {
private ProgressBar progressBar;
private Handler handler;
private int progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progress_bar_util);
inicializaComponentes();
}
public void inicializaComponentes() {
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setIndeterminate(true);
handler = new Handler();
executaProgressbar();
}
public void startProgressBar(){
startActivity(new Intent(getBaseContext(),ProgressBarUtil.class));
}
private void executaProgressbar() {
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
class that will call the method starProgressBar
The other class
#Override
public void onClick(View view) {
int id = view.getId();
if (btnDownload.getId() == id){
new ProgressBarUtil().startProgressBar();
}
}

How to add ProgressDialog while loading content from web view

This is my program to load a webpage into a web view. My problem is how to add ProgressDialog while loading content from web view.
public class Openpage extends Activity {
WebView wb=null;
String s1=null;
#SuppressLint({ "SetJavaScriptEnabled", "HandlerLeak" })
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsfeed);
Intent i=getIntent();
s1=i.getStringExtra("link");
Toast.makeText(this, s1, Toast.LENGTH_LONG).show();
Log.d(s1, "hai");
ProgressDialog progress = new ProgressDialog(this);
progress.setMessage("Loading...");
new MyTask(progress).execute();
}
public class MyTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress;
public MyTask(ProgressDialog progress) {
this.progress = progress;
}
public void onPreExecute() {
progress.show();
}
public Void doInBackground(Void...voids) {
wb=(WebView)findViewById(R.id.webView1);
wb.loadUrl(s1);
return null;
}
public void onPostExecute(Void void1) {
progress.dismiss();
}
}
You can get to know how much the page has loaded from
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if(progress == 100){
// Page has fully loaded. Cancel the progress dialog here
}
}
});
You can read it from here

External AsyncTask class with ProgressDialog [Update: and returning back?]

**Updated: (See below)**I have been looking around for couple of days and can't find a straight answer to this.
Some say it possible to some say to accomplish some say it's not. I am getting crazy on this.
What I want is just to have the AsyncTaskTask showing a progressbar an external class. To do this I am passing the context as you can see in the main class. But whatever I try I get NullPointerException.
Working code examples is appreciated. Thank you
Using Android 2.2 by the way.
main:
import android.app.Activity;
import android.os.Bundle;
public class AsyncDemo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new AsyncClass(this).execute();
}
}
AsyncClass.java
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.SystemClock;
public class AsyncClass extends AsyncTask<Void, String, Void> {
private Context context;
ProgressDialog dialog = new ProgressDialog(context);
public AsyncClass(Context cxt) {
context = cxt;
}
#Override
protected void onPreExecute() {
dialog.setTitle("Please wait");
dialog.show();
}
#Override
protected Void doInBackground(Void... unused) {
SystemClock.sleep(2000);
return (null);
}
#Override
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
}
Update:
I have a follow up question: Using the above code, is it possible to return a value from the onPostExecute method back to the main class, somehow? (Sorry about beeing noobish)
I have tried something like this:
String result = new AsyncClass(this).execute();
and then a method that return back a string. But I can't do that because i got:
Type mismatch: cannot convert from AsyncTask<String,Void,Void> to String
What can I do to tackle this problem? Thanks.
You were creating the ProgressDialog with a null context. The following code worked for me.
public class AsyncClass extends AsyncTask<Void, String, Void> {
private Context context;
ProgressDialog dialog;
public AsyncClass(Context cxt) {
context = cxt;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
dialog.setTitle("Please wait");
dialog.show();
}
#Override
protected Void doInBackground(Void... unused) {
SystemClock.sleep(2000);
return (null);
}
#Override
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
}
ok this is what I did as i was using fragments. This is how you call the AsyncTask inside a fragment:
String result=new AsyncClass(getActivity()).execute();
and this is how my AsyncTask outer class looks like:
public class AsyncClass extends AsyncTask<Void, Void, String> {
ProgressDialog pdialog;
public AsyncClass(Context context) {
pdialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
pdialog.setIndeterminate(true);
pdialog.setCancelable(false);
pdialog.setTitle("Loading Feed..");
pdialog.setMessage("Please wait.");pdialog.show();
}
#Override
protected String doInBackground(Void... params) {
String result=null;
//do your task here and generate result String
return result;
}
#Override
protected void onPostExecute(String result) {
if(pdialog.isShowing())
pdialog.dismiss();
}
}
#SSZero thanks great answer, helped a lot.
I would like to answer that follow up question i.e.
I have a follow up question: Using the above code, is it possible to return a value from the onPostExecute method back to the main class, somehow? (Sorry about beeing noobish) I have tried something like this:
String result = new AsyncClass(this).execute();
I did this in my code it worked.
AsyncClass ac=new AsyncClass();
ac.execute("");
String rslt=ac.get();
Call this code wherever you want to.
public class AsynchClass extends AsyncTask <String,Integer,String>
{
public String result=null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
protected String doInBackground(String... params)
{
// Do all your background task here
return result;
}
#Override
protected void onProgressUpdate(Integer... values) {
}
protected void onPostExecute(String result) {
}
}

Categories