I'm developing an app and I'm blocked in one simple thing.
In my Activity, I show a dialog (AlertDialog.Builder) that ask a mail address and an activation. These two fields are checked with a Rest API.
If the activation code is wrong I restart the activity (with an Intent) and I show again the dialog.
I don't understand why, if I'm wrong the activation code the first time, the second time appears the dialog correctly, but when I click "submit", the app doesn't run the Rest call and return always "Invalid credentials", like if it would remind the old "state".
Instead, if I run the app and I put the correct credentials, all is ok.
Any idea?
Source code:
public class PinActivity extends Activity {
String mail;
String verification;
JSONObject responseServer;
BluetoothSocket bsocket;
ConnectedThreadBT cdbt;
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
EditText mail_add;
EditText verification_code;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check);
setup();
dialogActivation();
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void setup(){
RestClientManager.initialize(getApplicationContext()).enableDebugLog(true);
bsocket = BluetoothApplication.getBSocket();
//salvo codice attivazione sul pacchetto
cdbt=new ConnectedThreadBT(bsocket,mHandler, "PinActivity");
cdbt.start();
}
private void dialogActivation(){
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(new ContextThemeWrapper(this, R.style.myDialog));
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_dialog_verification, null);
mail_add = (EditText) view.findViewById(R.id.mailAddress);
verification_code = (EditText) view.findViewById(R.id.verification_code);
builder.setView(view).
setPositiveButton(getApplicationContext().getResources().getString(R.string.submit), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//prendo e salvo credenziali
mail = mail_add.getText().toString();
verification = verification_code.getText().toString();
//invio dati al server
activatePPS();
}
});
builder.setCancelable(false);
builder.show();
}
private void activatePPS(){
dialogCheck();
String url = "....";
RestClientManager.getInstance().makeJsonRequest(Request.Method.POST, url, new RequestHandler<>(new RequestCallbacks<JSONObject, Error>()
{
#Override
public void onRequestSuccess(JSONObject response)
{
responseServer = response;
int reply_code = 0;
try {
reply_code = response.getInt("reply_code");
checkReplyCode(reply_code);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onRequestError(Error error)
{
}
}, paramsList()));
}
private void dialogCheck(){
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(new ContextThemeWrapper(this, R.style.myDialog));
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_dialog_load_check, null);
builder.setView(view);
builder.setCancelable(false);
builder.show();
}
private void checkReplyCode(int reply_code) throws JSONException, IOException {
switch(reply_code){
case 0:
successActivation();
break;
case 1001:
//credenziali invalide
Toast.makeText(getApplicationContext(), getResources().getString(R.string.wrong_credentials), Toast.LENGTH_LONG).show();
Intent intent = new Intent(PinActivity.this, PinActivity.class);
startActivity(intent);
break;
}
}
private void successActivation() throws JSONException {
String access_token = responseServer.get("access_token").toString();
String nickname = responseServer.get(".....
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
int value = sharedPref.getInt("step_conf",0);
if(value==0){
Intent intent = new Intent(getApplicationContext(), MethodCurveActivity.class);
intent.putExtra("style", 0);
startActivity(intent);
}
else{
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
},3000);
}
private ArrayMap<String, String> paramsList(){
ArrayMap<String, String> parameters=new ArrayMap<>();
parameters.put("user_mail", mail);
parameters.put(.....
return parameters;
}
private void resetMobileDevice(){
String url = "....";
RestClientManager.getInstance().makeJsonRequest(Request.Method.POST, url, new RequestHandler<>(new RequestCallbacks<JSONObject, Error>()
{
#Override
public void onRequestSuccess(JSONObject response)
{
System.out.println("Risposta:"+response);
responseServer = response;
int reply_code = 0;
try {
reply_code = response.getInt("reply_code");
} catch (JSONException e) {
e.printStackTrace();
}
try {
checkReplyCode(reply_code);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onRequestError(Error error)
{
}
}, paramsList()));
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
}
}
};
}
The important point is in the "case 1001", after error.
I have tried finish() and all the method to delete the old instance of the Activity...
Create Application class in your project and initialize RestClientManager in its onCreate Method like this:
public class MyApp extends Application {
private final static String LOG_TAG = Application.class.getSimpleName();
#Override
public void onCreate() {
Log.d(LOG_TAG, "Application.onCreate - Initializing application...");
super.onCreate();
initializeApplication();
Log.d(LOG_TAG, "Application.onCreate - Application initialized OK");
}
private void initializeApplication() {
RestClientManager.initialize(getApplicationContext()).enableDebugLog(true);
}
}
Add this line in your <Application> tag in androidmanifest.xml file:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:name=".App"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
And Make sure your singleton structure should be something like this:
private static RestClientManager instance;
static void initInstance()
{
if (instance == null)
{
// Create the instance
instance = new RestClientManager();
}
}
public static RestClientManager getInstance()
{
// Return the instance
return instance;
}
Remember to remove
RestClientManager.initialize(getApplicationContext()).enableDebugLog(true);
from your main activity.
Please give it a try and let me know.
Related
I am trying to get some data from a server. User clicks search and another acitivity starts by startActivityForResult().when user clicks the data the data should be put inside intent and setResult() is done with that intent and finish() is called. Now i have tried debugg but when finish() is called the activity does no go back to the one which called this activity. instead the app closes down.
Here is the code;
public class SearchContactActivity extends AppCompatActivity {
ProgressBar pb;
CircleImageView profile_image_search;
TextView name_search,user_name_search;
EditText edit_search_contact;
Button btn_search_contact;
ConstraintLayout cl;
String profile_image,firstName,lastName;
RequestQueue myQueue;
String url = "working url";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_contact);
pb = findViewById(R.id.progressBar);
profile_image_search = findViewById(R.id.profile_image_search);
name_search = findViewById(R.id.name_search);
user_name_search = findViewById(R.id.user_name_search);
btn_search_contact = findViewById(R.id.btn_search_contact);
edit_search_contact = findViewById(R.id.edit_search_contact);
cl = findViewById(R.id.nested_layout);
cl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setResultForPreviousAcitvity();
}
});
btn_search_contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
search_contacts();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
hideVisibility();
}
public void setResultForPreviousAcitvity()
{
Intent data = new Intent();
data.putExtra("first_name",firstName);
data.putExtra("last_name",lastName);
data.putExtra("user_name",user_name_search.getText().toString());
data.putExtra("profile", profile_image);
setResult(RESULT_OK,data);
finish(); // app closes down here
}
private void search_contacts() throws JSONException {
pb.setVisibility(View.VISIBLE);
//send php data in json array format
//JSONObject jsonbody = new JSONObject("{\"search_key\":\"jhonsanders \"}");
HashMap<String, String> params = new HashMap<String, String>();
params.put("search_key", edit_search_contact.getText().toString().trim());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( url,new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("result");
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject myobj = jsonArray.getJSONObject(i);
firstName = myobj.getString("first_name");
lastName = myobj.getString("last_name");
String userName = myobj.getString("user_name");
profile_image = myobj.getString("profile_image");
Bitmap image = NameAndImage.stringToImage(profile_image);
show_visibility();
profile_image_search.setImageBitmap(image);
user_name_search.setText(userName);
name_search.setText(firstName+" "+lastName);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
})/*{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> param = new HashMap<>();
param.put("search_key",edit_search_contact.getText().toString().trim());
return param;
}
}*/;
myQueue = VolleySingleton.getInstance(SearchContactActivity.this).getRequestQueue();
myQueue.add(jsonObjectRequest);
}
private void hideVisibility()
{
pb.setVisibility(View.INVISIBLE);
profile_image_search.setVisibility(View.INVISIBLE);
name_search.setVisibility(View.INVISIBLE);
user_name_search.setVisibility(View.INVISIBLE);
}
private void show_visibility()
{
profile_image_search.setVisibility(View.VISIBLE);
name_search.setVisibility(View.VISIBLE);
user_name_search.setVisibility(View.VISIBLE);
pb.setVisibility(View.INVISIBLE);
}
/* private Bitmap stringToImage(String s)
{
byte[] image = Base64.decode(s,Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(image,0,image.length);
return decodedImage;
}*/
}
The above activity is called by
Intent i = new Intent(ContactsActivity.this,SearchContactActivity.class);
startActivityForResult(i,REQUEST_CONTACT_SEARCH);
This is the manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.privatechat">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/Theme.PrivateChat">
<activity android:name=".SearchContactActivity"></activity>
<activity android:name=".ContactsActivity" />
<activity android:name=".NameAndImage" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
There is no logs that i can print.The log is cleared when onfinish() is called.
The app goes back to this other activity. This one also has onAcitivityResult but its not the one that called the other acitivity.
public class NameAndImage extends AppCompatActivity {
EditText editFirstName,editLastName;
ImageView profile_image;
Button uploadNameImage;
Bitmap image;
RequestQueue myQueue;
SaveSharedPreference sp = new SaveSharedPreference();
private String URL = "working url";
public static final int PICK_IMAGE_REQUEST = 1011;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name_and_image);
editFirstName = findViewById(R.id.edit_first_name);
editLastName = findViewById(R.id.edit_last_name);
profile_image = findViewById(R.id.profile_image_search);
uploadNameImage = findViewById(R.id.upload_name_image);
Log.i("SharedPreference",sp.getUserName(NameAndImage.this).trim());
profile_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pickPhoto();
}
});
uploadNameImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadData();
}
});
}
private void pickPhoto()
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,PICK_IMAGE_REQUEST);
}
private void uploadData()
{
StringRequest upload_data = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.trim().equals("success_data_upload"))
{
Toast.makeText(NameAndImage.this, "upload success", Toast.LENGTH_SHORT).show();
Intent i = new Intent(NameAndImage.this,ContactsActivity.class);
startActivity(i);
}
if(response.trim().equals("Error"))
{
Toast.makeText(NameAndImage.this, "upload error", Toast.LENGTH_SHORT).show();
Log.i("server",response.toString());
}
else
{
Toast.makeText(NameAndImage.this, "Response dont match", Toast.LENGTH_SHORT).show();
Log.i("server",response);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(NameAndImage.this, error.toString(), Toast.LENGTH_SHORT).show();
Log.i("server",error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> param = new HashMap<>();
param.put("image",imageToString(image));
param.put("first_name",editFirstName.getText().toString());
param.put("last_name",editLastName.getText().toString());
param.put("user_name",sp.getUserName(NameAndImage.this).trim());
return param;
}
};
upload_data.setRetryPolicy(new DefaultRetryPolicy(
3000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
));
myQueue = VolleySingleton.getInstance(NameAndImage.this).getRequestQueue();
myQueue.add(upload_data);
}
public static String imageToString(Bitmap pic)
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
pic.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
byte[] imageByte = byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imageByte,Base64.DEFAULT);
}
public static Bitmap stringToImage(String s)
{
byte[] image = Base64.decode(s,Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(image,0,image.length);
return decodedImage;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK)
{
Uri uri = data.getData();
try {
image = MediaStore.Images.Media.getBitmap(getContentResolver(),uri);
profile_image.setImageBitmap(image);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Edit:
The app seems to close but after 2 sec the wrong activity is started.
When setting the result in setResult() i was putting a string profile which contained image as a String. I guess the string was really large but when i debugg the whole string seemed to be there. So when i made profile empty the app operated normally. Looks like i will have to split the string in 2 for more effectiveness.
I have created a login screen.
If I type something on my edit text and rotate my device,
the data gets lost.
How can I make my edit texts, survive these changes?
I have created a loginViewModel in which I am just fetching the data from the api.
Here is my loginActivity
public class LogInActivity extends AppCompatActivity {
private TextInputLayout mLoginUserName, mLoginPassword;
private LoginViewModel loginViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
loginViewModel = new LoginViewModel(getApplication(),
this);
mLoginPassword = findViewById(R.id.logInPassword);
mLoginUserName = findViewById(R.id.logInUserName);
Button mFinalLoginButton =
findViewById(R.id.finalLogInButton);
TextView mForgotPassword =
findViewById(R.id.text_view_forgot_password);
mForgotPassword.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LogInActivity.this,
ForgotPasswordSend.class));
}
});
mFinalLoginButton.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
final String userName =
mLoginUserName.getEditText().getText().toString().trim();
final String userPass =
mLoginPassword.getEditText().getText().toString().trim();
if (userName.isEmpty())
mLoginUserName.setError("Please enter User
Name");
else mLoginUserName.setError(null);
if (userPass.isEmpty()) {
mLoginPassword.setError("Please enter
password");
} else {
mLoginPassword.setError(null);
loginViewModel.logInRequest(userName,
userPass);
}
}
});
}}
This is my loginViewModel. Right now it is not working as a viewmodel. I just have named it but i want to make it work as a viewmodel class
class LoginViewModel extends AndroidViewModel {
private final Context context;
private final SharedPrefs sharedPrefs = new SharedPrefs(getApplication());
public LoginViewModel(#NonNull Application application, Context context) {
super(application);
this.context = context;
}
public void logInRequest(final String userName, String userPassword) {
final JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("identifier", userName);
jsonObject.put("password", userPassword);
} catch (JSONException e) {
e.printStackTrace();
}
APIService apiService = RetrofitClient.getAPIService();
Call<String> logInResponse = apiService.logIn(jsonObject.toString());
logInResponse.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.message().equals("OK")) {
try {
JSONObject jsonObjects = new JSONObject(response.body());
JSONObject token = jsonObjects.getJSONObject("token");
String key = token.getString("token");
String sUserName = jsonObjects.getString("username");
String email = jsonObjects.getString("email");
String firstName = jsonObjects.getString("firstName");
String lastName = jsonObjects.getString("lastName");
sharedPrefs.saveUserName(sUserName);
sharedPrefs.saveEmail(email);
sharedPrefs.saveFullName(firstName, lastName);
sharedPrefs.saveToken(key);
context.startActivity(new Intent(context, HomeActivity.class));
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplication(), "Wrong User Name or Password", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(getApplication(), "Something went wrong
please try again", Toast.LENGTH_SHORT).show();
}
});
}}
In the App i am developing i am trying to use IntentService as shown below in the code. the IntentService is declared as shown below in the manifest file.
the issue i am facing now is, when I run App the onHandleIntent is never get called.
I checked some examples in the internt but non of them was helpful, because the recommended hints to solve the issue did not work.
I started the service as follows:
this.mButtonFetchURL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mServiceIntent = new Intent(getApplicationContext(), TwitterTrendsAPIService.class);
mServiceIntent.putExtra(CONST_KEY_REQUEST_URL, BASE_REQUEST_URL);
startService(mServiceIntent);
clearEditText(mEditTextURLContents);
}
});
please let me know how to solve it.
code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.pc_.twittertrendsnearlocation">
<uses-permission android:name="android.permission.INTERNET" />
<application
....
....
....
<service
android:name=".services.TwitterTrendsAPIService"
android:exported="false"
android:enabled="true"/>
</application>
code
public class TwitterTrendsAPIService extends IntentService {
private static final String TAG = TwitterTrendsAPIService.class.getSimpleName();
private boolean mIsFetching = false;
private String mBaseRequestURL = null;
private RequestQueue mRequestQueue = null;
private JsonArrayRequest mJsonArrayRequest = null;
private final static String CONST_KEY_JSON_ARRAY_TRENDS = "trends";
private JSONObject mEntireJSONObject = null;
private JSONArray mEntireTrendsArray = null;
public TwitterTrendsAPIService() {
super(null);
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* #param name Used to name the worker thread, important only for debugging.
*/
public TwitterTrendsAPIService(String name) {
super(name);
}
#Override
public void onCreate() {
super.onCreate();
Log.w(TAG, "[onCreate]");
this.setupVolley();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w(TAG, "[onStartCommand]");
return Service.START_NOT_STICKY;
}
#Override
public void onHandleIntent(Intent intent) {
Log.w(TAG, "[onHandleIntent]");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.w(TAG, "[onDestroy]");
}
private void setupVolley() {
this.mRequestQueue = Volley.newRequestQueue(this);
}
private class ServiceRunnable implements Runnable {
#Override
public void run() {
fetchJSONData();
stopSelf();
}
}
private void fetchJSONData() {
Log.w(TAG, "#fetchJSONData");
this.mJsonArrayRequest = new JsonArrayRequest(Request.Method.GET, this.mBaseRequestURL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
mEntireJSONObject = response.getJSONObject(0);
mEntireTrendsArray = mEntireJSONObject.getJSONArray(TwitterTrendsAPIService.CONST_KEY_JSON_ARRAY_TRENDS);
Log.i(TAG, "mEntireTrendsArray.length(): " + mEntireTrendsArray.length());
Log.i(TAG, "mEntireTrendsArray.get(0): " + mEntireTrendsArray.get(0));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
}
Delete onStartCommand(), or chain to the superclass' implementation of onStartCommand(). Right now, you are overriding the built-in implementation, and IntentService uses that to set up the background thread and call onHandleIntent().
in my Service I am using http://loopj.com/android-async-http/
within the doInBackground() method of a service. Because it's asynchronous, the method finishes before the callbacks are called, and therefore onPostExecute is being called and shutting the service down... How can I avoid this?
public class LoginService extends AsyncTask<String, Void, LoginService.LoginStatus> {
private static String TAG = "x-LoginService";
private ProgressDialog progressDialog;
private AlertDialog dialog = null;
private final Context context;
public LoginService(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(context, "", context.getString(R.string.waitingLogin), true);
}
#Override
protected void onPostExecute(LoginStatus loginStatus) {
progressDialog.dismiss();
Log.d(TAG, "--STARTONPOSTEXECUTE");
String message;
LocalSettingsService settings = new LocalSettingsService(context);
if (loginStatus == LoginStatus.LOGGED_IN) {
settings.put("loggedIn", "true");
Intent intent = new Intent(context, FragmentTabs.class);
context.startActivity(intent);
//Intent intent = new Intent(context, SummaryPage.class);
//Intent intent = new Intent(context, FeedbackPage.class);
//Intent intent = new Intent(context, NavTab.class);
//context.startActivity(intent);
return;
} else if (loginStatus == LoginStatus.INVALID_CREDENTIALS) {
settings.put("loggedIn", "false");
message = context.getString(R.string.invalidCredentials);
} else {
settings.put("loggedIn", "false");
message = context.getString(R.string.serverError);
}
dialog = new AlertDialog.Builder(context)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(context.getString(R.string.errorTitle))
.setMessage(message)
.setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).create();
dialog.show();
}
#Override
protected LoginStatus doInBackground(String... strings) {
String username = strings[0];
String password = strings[1];
doLogin();
return LoginStatus.LOGGED_IN;
}
private void doLogin() {
{
Log.d(TAG, "--STARTDOLOGIN");
RequestParams params = new RequestParams();
params.put("username", "un");
params.put("password", "pw");
ServicesRestClient.post("ajax/login", params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(String s) {
Log.d(TAG, "--ONSUCCESS");
}
#Override
public void onFailure(Throwable throwable, String s) {
Log.d(TAG, "--ONFAILURE");
}
});
}
}
public void onPause() {
if (dialog != null) {
dialog.dismiss();
}
}
public static enum LoginStatus {
LOGGED_IN, INVALID_CREDENTIALS, SERVER_SIDE_ERROR
}
}
I think you this code too much complicated. In general you should somehow stay in doInBackground() unless you service ends, but not knowing the internals of what you use I can tell how to do it best. But since this library you use announces to be doing asynchronous networking, I'd not use another async task in first place
Main Class:
public class ProgressIndicator {
static ProgressIndicator instance;
Context context;
public static ProgressIndicator getInstance() {
if (instance == null) {
instance = new ProgressIndicator();
}
return instance;
}
private ProgressIndicator() {
}
IndicatorThread sd;
public void showIndicator(Activity activity, String title, String message, boolean flag) {
sd = new IndicatorThread(activity, title, message, flag);
sd.start();
}
public void dismissIndicator(Activity activity) throws InterruptedException{
sd.dismiss();
// sd.join();
}
private static class IndicatorThread extends Thread {
private static final Message listener = null;
private static String mTitle;
private static String mText;
private Activity mActivity;
private boolean mflag;
private ProgressDialog mDialog;
protected boolean dismiss;
IndicatorThread(Activity activity, String title, String text, boolean flag) {
super();
IndicatorThread.mText = text;
IndicatorThread.mTitle = title;
this.mActivity = activity;
this.mflag = flag;
if (mDialog == null) {
mDialog = new ProgressDialog(mActivity);
mDialog.setTitle(mTitle);
mDialog.setMessage(mText);
mDialog.setIndeterminate(true);
mDialog.setCancelable(true);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
if(mflag == true){
mDialog.setButton("Cancel", listener);
mDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
mDialog.dismiss();
interrupt();
}
});
}
}
mDialog.show();
mDialog.getWindow().setLayout(160, 350);
mDialog.getWindow().setGravity(0);
}
public void dismiss() {
dismiss = true;
mDialog.dismiss();
System.out.println("notifying..."+dismiss);
synchronized (this) {
notifyAll();
}
}
#Override
public void run() {
System.out.println("Running..."+dismiss);
while (!dismiss) {
System.out.println("waiting..."+!dismiss);
synchronized (this) {
try {
wait();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
System.out.println("Quitting...");
}
}
}
Call from AppController class:
private ProgressIndicator progressInstance = null;
public void showWaitingAnimation(Activity parent) {
progressInstance.showIndicator(AppController.getInstance().currentActivity, "" , "", false);
}
Test Class:
public class ProgressIndicatorTest extends
ActivityInstrumentationTestCase2<MyTestActivity> {
private Solo solo;
private ProgressIndicator progressIndicatorInstance;
public ProgressIndicatorTest() {
super("com.test.activity",
MyTestActivity.class);
}
protected void setUp() throws Exception {
AppController.getInstance().startApp(getActivity());
solo = new Solo(getInstrumentation(), getActivity());
progressIndicatorInstance = ProgressIndicator.getInstance();
}
protected void tearDown() throws Exception {
try {
solo.finalize();
} catch (Throwable e) {
e.printStackTrace();
}
getActivity().finish();
super.tearDown();
}
public void testGetInstance() {
try {
ProgressIndicator instance = ProgressIndicator.getInstance();
assertNotNull(instance);
} catch (Exception e) {
fail("Creation of ExceptionDetails get instance failed!");
}
}
public void testShowIndicator() {
Log.d("testCase Name:-", "testShowIndicator");
ProgressIndicator progressInstance = ProgressIndicator.getInstance() ;
progressInstance.showIndicator(AppController.getInstance().getCurrentActivity(), "" , "", false);
//AppController.getInstance().showWaitingAnimation(AppController.getInstance().getCurrentActivity());
solo.waitForDialogToClose(8000);
try {
progressInstance.dismissIndicator(AppController.getInstance().getCurrentActivity());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void testDismissIndicator() {
Log.d("testCase Name:-", "testDismissIndicator");
ProgressIndicator progressInstance = ProgressIndicator.getInstance() ;
progressInstance.showIndicator(AppController.getInstance().getCurrentActivity(), "" , "", false);
solo.waitForDialogToClose(2000);
try {
progressInstance.dismissIndicator(AppController.getInstance().getCurrentActivity());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//AppController.getInstance().showAppTerminationDialog("", AppController.getInstance().getCurrentActivity());
}
}
While running the project the dialog is visible & working properly. But while running the test case only a black screen is visible, no dialog is getting displayed (after using solo.waitForDialogToClose(8000); problem is there). No error or exception is getting thrown and the test cases are getting passed in Android Junit test. If anyone has any idea how to display this progress dialog in case of robotium test, Please share.
In my case I can successfully display progress dialogs.
I simply used
boolean showProgressBar = false;
showProgressBar = solo.waitForText("Verifying and Saving Credentials...", 1, 3000);
I hope it should also work for you.. :)