lagfvu lagfvu - 3 months ago 12
Android Question

how to get progress bar to display

Its my first time using a progress bar, i have a http request being made. I want an indeterminate progress bar to show when the user clicks the login button and then to disappear when the response is received. Below is what i have already, but the progress bar does not display.

below is the login.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myCoordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
tools:context=".app.LoginActivity">

<android.support.v7.widget.Toolbar
android:id="@+id/toolBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary">

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:contentDescription="logo"
android:src="@drawable/bar" />

</android.support.v7.widget.Toolbar>


<ScrollView
android:id="@+id/login_form"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
android:id="@+id/icons_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="40dp">
<!-- Login progress -->
<ProgressBar
android:id="@+id/login_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:indeterminate="true"
android:visibility="invisible" />

<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email here"
android:maxLines="1"
android:singleLine="true" />


<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:imeActionId="@+id/login"
android:imeActionLabel="Password here"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true" />

<Button
android:id="@+id/email_sign_in_button"
style="?android:textAppearanceSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:text="Login"
android:textStyle="bold" />

</LinearLayout>
</ScrollView>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>


Below is the login activity

public class loginActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "solutions.orbs.com.myapplication.app";
EditText email, password;
Button login;
String emailCred, passwordCred;
ProgressBar progressBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);

email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.login_progress);

ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
final boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

login = (Button) findViewById(R.id.email_sign_in_button);


login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

progressBar.setVisibility(ProgressBar.VISIBLE);

emailCred = email.getText().toString();
passwordCred = password.getText().toString();

if (emailCred.isEmpty()) {
email.setError("Enter your Email");
} else if (passwordCred.isEmpty()) {
password.setError("Enter your Password");
} else if (!isConnected) {
Snackbar.make(findViewById(R.id.myCoordinatorLayout), "Sorry,Please connect to a network", Snackbar.LENGTH_SHORT).show();
} else {
makeRequest(emailCred, passwordCred);
}
}
});
}

public void makeRequest(final String user, final String cred) {
//the url we are posting the request to
String url = "http://mobile.map.education/api/login";


//the post request function
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
progressBar.setVisibility(ProgressBar.INVISIBLE);
try {
//the json object represents the response we are expecting and status is the status of the request
//which will either be a success or an error and will be sent to us from the server
JSONObject jsonResponse = new JSONObject(response);
String status = jsonResponse.getString("status");

//handler for if the response is an error
if (status.equalsIgnoreCase("error")) {
progressBar.setVisibility(ProgressBar.INVISIBLE);
//display and error message to the user using the snackbar notifier
Snackbar.make(findViewById(R.id.myCoordinatorLayout), jsonResponse.getString("message"), Snackbar.LENGTH_LONG).show();
}
//handler for is the login is successful
else if (status.equalsIgnoreCase("success")) {
//this is the token granted to us by the server
String token = jsonResponse.getString("token");

progressBar.setVisibility(ProgressBar.INVISIBLE);

//this starts an intent that sends us to the dashboard page of the application
Intent loader = new Intent(loginActivity.this, MainActivity.class);
loader.putExtra(EXTRA_MESSAGE, token);
startActivity(loader);
}

} catch (JSONException e) {
e.printStackTrace();
}
}
},
//this handles any errors the volley package gets
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
) {
//this is a method to set the parameters we are sending to be in the proper format
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();

//the proper format of the login parameters is portal[parameter name goes here]
params.put("portal[username]", user);
params.put("portal[password]", cred);
params.put("portal[From]", "web");
return params;
}
};

//this is a retry policy that has been set to deal with timeout errors
postRequest.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

Volley.newRequestQueue(getApplicationContext()).add(postRequest);

}
}

Answer

Try this . Make a custom dialog class which can be reused all over the application

public class CShowProgress {
    public static CShowProgress s_m_oCShowProgress;
    public static Context m_Context;
    public Dialog m_Dialog;

    public CShowProgress(Context m_Context) {
        this.m_Context = m_Context;
    }

    public static CShowProgress getInstance() {
        if (s_m_oCShowProgress == null) {
            s_m_oCShowProgress = new CShowProgress(m_Context);
        }
        return s_m_oCShowProgress;
    }

    public void showProgress(Context m_Context) {
        m_Dialog = new Dialog(m_Context);
        m_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        m_Dialog.setContentView(R.layout.custom_progress_layout);
        m_Dialog.findViewById(R.id.progress_bar).setVisibility(View.VISIBLE);
        m_Dialog.setCancelable(true);
        m_Dialog.setCanceledOnTouchOutside(true);
        m_Dialog.show();
    }

    public void hideProgress() {
        if (m_Dialog != null) {
            m_Dialog.dismiss();
            m_Dialog = null;
        }
    }
}

Corresponding XML custom_progress_layout.xml

   <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       xmlns:app="http://schemas.android.com/apk/res-auto"
       android:background="@android:color/transparent"
       android:orientation="vertical">

       <ProgressBar
            android:id="@+id/progress_bar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:indeterminate="true"/>
   </RelativeLayout>

And the Activity

  CShowProgress cShowProgress = CShowProgress.getInstance();
  cShowProgress.showProgress(Activity.this);

and hide by calling

  cShowProgress.hideProgress();

Hope this will help.