I am accessing .net web services through my Android Application. If the user is successfully registered then log cat will show 1 as the response. If not it will show 0 and If some field is missing then it will show -1 as response. so is it possible to show a dialog box according to the log cat response?
If response is 1 then "successfully registered"
If response is 0 then "Try Again"
How can we do this?
Log.v("TAG", String.valueOf(resultsRequestSOAP)); with this I am getting the response in logcat
Help is always appreciated....Thanks!
In this piece of code,I want to add the required code to show the dialog box.
Button signin = (Button) findViewById(R.id.regsubmitbtn);
signin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(0);
t = new Thread() {
public void run() {
register();
try {
Thread.sleep(5000);
removeDialog(0);
// I want to show the dialog box like registered successfully after removing this dialog//
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t.start();
}
});
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 0: {
dialog = new ProgressDialog(this);
dialog.setMessage("Registering...");
dialog.setIndeterminate(true);
dialog.setCancelable(true);
return dialog;
}
}
return null;
}
Write a method that will create dialogs according to a parameter. Then you just have to call this method with a right parameter to create a right dialog depending on the server's response.
Related
I have an app in which user authentication is done sending a request and if response is successful the app navigated to next activity.If username password is correct it navigates but if it is incorrect the dialog box pops up and does not close and in my logs I get
java.io.IOException: HTTP/1.1 401 The username or password you entered is incorrect.
I have handled it in my code that if response is not successful display a toast message Login failed and dismiss dialog box.if I enter incorrect credentials it is not showing it.That part of the code is unreachable I checked using breakpoint.
My code:
buttonlogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(etemail.getText().toString().equals("") && etpass.getText().toString().equals(""))
{
Toast.makeText(getApplicationContext(),"Enter your username and Password",Toast.LENGTH_LONG).show();
}
else
{
final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Logging in..Please wait");
progressDialog.setIndeterminate(true);
progressDialog.show();
new Thread(new Runnable()
{
public void run()
{
try
{
restApi = new RallyRestApi(new URI("https://rally1.rallydev.com"),etemail.getText().toString(),etpass.getText().toString());
restApi.setApplicationName("BMC-AndroidforRally");
qtestset = new QueryRequest("Users");
qtestset.setLimit(1);
response=restApi.query(qtestset);
if(!response.wasSuccessful())
{
parent.runOnUiThread(new Runnable() {
#Override
public void run()
{
Toast.makeText(getApplicationContext(),"Login Failed..incorrect Username/Password",Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
});
}
else
{
progressDialog.dismiss();
//Toast.makeText(getApplicationContext(),"Login Successful.....Logged in as :"+etemail.getText().toString(),Toast.LENGTH_LONG).show();
Intent mainintent = new Intent(MainActivity.this,FirstPage.class);
mainintent.putExtra("username",etemail.getText().toString());
mainintent.putExtra("password",etpass.getText().toString());
startActivity(mainintent);
}
}
catch (URISyntaxException | IOException e)
{
e.printStackTrace();
}
}
}).start();
}
}
});
Also i have created a new thread for faster execution.
In this concepts no need to implement runnable thread.
Remove Thread in OnClickListener it will work correctly.Because of thread only its showing old message(still that running). Best remove thread in OnClickListener or stop thread when condition going to false statement.
In my application I am creating a sign up activity using parse database and I used the signUpInBackground() but when I run the code on the emulator the parse is giving me a message that says "unauthorised.
Join.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog dialog = new ProgressDialog(SignUp.this);
dialog.setTitle("Please Wait");
dialog.setMessage("Please Wait While Signing Up");
dialog.show();
final ParseUser user =new ParseUser();
user.setUsername(Username.getText().toString().trim());
user.setPassword(Password.getText().toString().trim());
user.setEmail(Email.getText().toString().trim());
user.put("firstName", FirstName.getText().toString().trim());
user.put("lastName", LastName.getText().toString().trim());
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
dialog.dismiss();
if(e!=null){
Toast.makeText(SignUp.this,e.getMessage(),Toast.LENGTH_LONG).show();
}else {
Intent i = new Intent(SignUp.this,LogIn.class);
startActivity(i);
}
}
});
}
});
When you initialise Parse in your Application class, are you setting your ACL?
Also are your keys correct when you initialise?
Make sure you follow the Quick Start Guide.
Hi In my Application I'm sending one request to server to validate the user,after sending the request I'm storing that value in database and making the status as 1, after some time I'm changing the status to 2 in database.Now my android app should wait till the status becomes 2. For this I'm showing the user in mobile progress bar.But my problem is as soon as I send the request progress bar stops displaying in the mobile.
Here is what I have tried.
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.show();
progressDialog.setTitle("Please Wait");
progressDialog.setMax(100);
e1 = edittext.getText().toString();
//Toast.makeText(MainActivity.this, "" + e1, Toast.LENGTH_SHORT).show();
AsyncHttpClient client = new AsyncHttpClient();
final RequestParams params = new RequestParams();
params.put("sendingJSON", composeJSON());
client.post("http://192.168.43.137/gpstracker/check_user.php", params, new AsyncHttpResponseHandler() {
public void onSuccess(String response) {
Gson gson = new GsonBuilder().create();
try {
progressDialog.dismiss();
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = (JSONObject) arr.get(i);
String general = obj.get("success").toString();
Toast.makeText(getApplicationContext(), ""+general, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onFailure(int statusCode, Throwable error, String content) {
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]",Toast.LENGTH_LONG).show();
}
}
});
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton) {
// what ever you want to do with No option.
}
}
);
alert.show();
}
A good solution in this cases is to work with events. Using events you can notify everywhere that something is happening. In your case, you can send an event when "the status changes to 2 in the database" and dismiss the progress dialog. There is a powerful and easy-to-use library to work with events called eventbus:
https://github.com/greenrobot/EventBus
I hope this helps to clarify!
I would recomend you to use an AsynkTask to do it. You can create the progress dialog in the onPreExecute() method, do what you are trying to do (post action or database update) in doInBackground() and once you have everything you want, in the onPostExecute() you can dismiss the dialog and send the result/data, if you need to, to your activity.
public class yourAsyncTask extends AsynkTask<Params, Params, Params>
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Charging...");
pDialog.setCancelable(true);
pDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
errorMesaje = "Process cancelled";
cancel(true);
}
});
pDialog.show();
}
#Override
protected Void doInBackground(Params... params) {
//Do your things here...
#Override
protected void onPostExecute(Void void) {
super.onPostExecute(void);
//Use an interface to call your activity and pass the data, you will have to change the attribute of the method in order to do it.
// Dismiss your dialog when your requests have finished
pDialog.dismiss();
}
I donĀ“t understand what are you trying to do exactly, if you just want to be sure that the post action is completed before the progress bar goes off, this solution will be fine. You can also call in the doInBackground() to your database and update it.
Hope it's clear enough!
I want to log in as a ParseUser. Everything works but after second click on button Log in.
private void openMainActivity(boolean loggedIn) {
if (loggedIn){
startActivity(new Intent(ParseStarterProjectActivity.this, MainPage.class));
finish();
}else{
initialize();
logInBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (logIn(username.getText().toString(),pwd.getText().toString())){
startActivity(new Intent(ParseStarterProjectActivity.this, MainPage.class));
finish();
}else{
Toast.makeText(getApplicationContext(),
"Failed to log in, try again.", Toast.LENGTH_LONG).show();
}
}
});
}
}
Log in method:
private boolean logIn(String username, String pwd) {
ParseUser.logInInBackground(username, pwd, new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
loggedIn=true;
} else {
loggedIn=false;
}
}
});
return loggedIn;
}
Is it an issue of time? That it doesn't get values from EditText immediately, maybe callback delay? Or any idea?
The issue is that ParseUser.logInInBackground() is an async call.
You're telling it to start the log-in process, it will finish some time later after the code talks to the Parse server and gets a response.
You're then trying to use the value of loggedIn before that value has been set.
With async code you get to tell it what to do later when the code finishes (that public void done() block). Your startActivity() etc code should be inside the callback block.
I have a file that is supposed to pull a list of products from my MySQL database, encode them into a JSON array then I need to make the Android application display those.
Ideally I want it to display icons but that's something I can tinker with later for now I just want to get it to work
Using the current code below when I click the button it doesn't do anything. My LogCat shows my JSON perfectly fine but the app doesn't display anything, or crash.
public class GetProducts extends Activity {
//Delcare Variables
// JSON Response node names
private static String KEY_SUCCESS = "success";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.view_products);
Functions userFunctions = new Functions();
if(!userFunctions.isConnected(getApplicationContext()))
{
displayDialogue("Connection Error","Your network settings are invalid - please turn on network settings ", "Open Network Settings");
}
if(!userFunctions.isUserLoggedIn(getApplicationContext())){
Intent i = new Intent(GetProducts.this, FirstScreen.class);
startActivity(i);
}
Button btnLogin;
btnLogin = (Button)findViewById(R.id.btnGetProducts);
//When our login button is pressed
btnLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new LoginTask().execute();
}
});
//Assign the variables our layout buttons
}
//We are using an AsyncTask so that this function runs on a seperate thread of the processor
//Since 4.2 + Android requires any web or HTTP activity to be ran seperate thread to the GUI
class LoginTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
//Run the login function
Login();
return null;
}
}
public void displayDialogue(String title, String Message, String Button){
final AlertDialog.Builder myDialogue = new AlertDialog.Builder(this);
myDialogue.setTitle(title);
myDialogue.setMessage(Message);
TextView messageView = new TextView(this);
messageView.setGravity(Gravity.CENTER);
myDialogue.setView(messageView);
myDialogue.setCancelable(false);
myDialogue.setPositiveButton(Button, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = myDialogue.create();
dialog.show();
}
public void Login(){
try{
Functions userFunctions = new Functions();
final JSONObject json = userFunctions.getProducts();
JSONObject json_user = json.getJSONObject("products");
JSONArray jArray;
jArray = json.getJSONArray("products");
if (json.getString("success") != null) {
String res = json.getString("success");
if(Integer.parseInt(res) == 1){
try{
// user successfully logged in
// Store user details in SQLite Database
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
displayDialogue("Error",json.getString("name"), "Try Again");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// Clear all previous data in database
// Close Login Screen
finish();
}
catch(final Exception e){
runOnUiThread(new Runnable() {
#Override
public void run() {
displayDialogue("Error",e.toString(), "Try Again");
}
});
}
}
else{
runOnUiThread(new Runnable() {
#Override
public void run() {
displayDialogue("Error", "Error. \nWrong username / password combination please re-enter the details", "Try Again");
}
});
}
}else{
runOnUiThread(new Runnable() {
#Override
public void run() {
displayDialogue("Error", "Error. \nGeneric Error", "Try Again");
}
});
}
}
catch(JSONException e){
e.printStackTrace();
}
}
}
JSON result:- (Printed to Logcat)
12-27 16:53:45.011: E/JSON(23028): {"tag":"getProducts","success":1,"error":0,"products":{"name":"Coffee1","price":"4.00","image":"http:\/\/test.com"}}{"tag":"getProducts","success":1,"error":0,"products":{"name":"Coffee2","price":"5.00","image":"http:\/\/test2.com"}}
Any help would be great, thanks!