Android: Previous page button, without losing data - android

I have need some help to achieve the following:
When I click on my previous-button I want the application to go to the previous page without losing my data. I already added the previous-button to the application, but when I click it my application goes to the main page instead of the previous page.
My code:
Button next,previous;
next = (Button)findViewById(R.id.work_next);
previous = (Button)findViewById(R.id.work_previous);
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentSignUP = new Intent(getApplicationContext(), filldetails.class);
startActivity(intentSignUP);
finish();
}
});
next.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
boolean allValues = true;
String comp="",desg="",fromdate="",todate="",role_d="",technologies_used="";
if(companyName.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
else
{
comp= companyName.getText().toString();
//Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
if(designation.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
else
{
desg = designation.getText().toString();
//Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
if(fromDate.getText().toString().length()<8 || fromDate.getText().toString().length()>10 ||fromDate.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(),"Please enter valid Date",Toast.LENGTH_SHORT).show();
}
else
{
fromdate = fromDate.getText().toString();
}
if(toDate.getText().toString().length()<8 || toDate.getText().toString().length()>10 ||toDate.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(),"Please enter valid Date",Toast.LENGTH_SHORT).show();
}
else
{
todate = toDate.getText().toString();
}
if(role_desc.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
else
{
role_d = role_desc.getText().toString();
}
if(technologiesUsed.getText().toString().equals(""))
{
allValues = false;
Toast.makeText(getApplicationContext(), "Please enter all the fields",Toast.LENGTH_SHORT).show();
}
else
{
technologies_used = technologiesUsed.getText().toString();
}
if(allValues)
{
Intent moveToNext = new Intent(getApplicationContext(),skills.class);
moveToNext.putExtra("comp_name",comp);
moveToNext.putExtra("desc",desg);
moveToNext.putExtra("role_d",role_d);
moveToNext.putExtra("from_date",fromdate);
moveToNext.putExtra("to_date",todate);
moveToNext.putExtra("technologies_used",technologies_used);
moveToNext.putExtra("iscurrent",isCurrent.isChecked());
moveToNext.putExtra("aboutme",getIntent().getStringExtra("aboutme"));
moveToNext.putExtra("address",getIntent().getStringExtra("address"));
startActivity(moveToNext);
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Please provide all values", Toast.LENGTH_SHORT).show();
}
}
});
}

You don't need to start the activity to go to previous activity (if you haven't called finish() on that), just close the current activity and it will go to previous activity and data will be intact.
Change your onClick method of previous button like this
#Override
public void onClick(View v) {
finish();
}
Note: If you have closed the previous activity by calling finish() then remove that code, otherwise data will not be intact without modifying your code in that activity.

Related

how to toast message inside the filtering method?

Interface:-
I want to make a toast message, if user did not choose any subject, it will toast message "Please choose subject". There is no error, the issue was I dont know where to put the coding to display the toast message when needed.
Coding:-
#Override
public void onClick(View v) {
final MediaPlayer mediaPlayer = MediaPlayer.create(FilterTuitionCentreActivity.this, R.raw.soundeffect1);
if (v == filterButton) {
mediaPlayer.start();
filterBtnFlag = true;
if(spLocation.getSelectedItem() == null){
return;
}
/*if(!(spSubject.getSelectedItem().toString().equalsIgnoreCase("Subject")
|| spSubject.getSelectedItem().toString().equalsIgnoreCase("Choose Subject"))){
Toast.makeText(FilterTuitionCentreActivity.this, "Please choose subject.", Toast.LENGTH_SHORT).show();
}*/
else {
loadFilteredInstitutesList("Advertisement");
}
}
}
You need a move that validation logic up and return without go further if any validation fails.
#Override
public void onClick(View v) {
//add your spinner validity checking here
if(!(spSubject.getSelectedItem().toString().equalsIgnoreCase("Subject")
||
spSubject.getSelectedItem().toString().equalsIgnoreCase("Choose Subject"))){
Toast.makeText(FilterTuitionCentreActivity.this, "Please choose subject.", Toast.LENGTH_SHORT).show();
return;
}
final MediaPlayer mediaPlayer = MediaPlayer.create(FilterTuitionCentreActivity.
this, R.raw.soundeffect1);
if (v == filterButton) {
mediaPlayer.start();
filterBtnFlag = true;
if(spLocation.getSelectedItem() == null){
return;
}
loadFilteredInstitutesList("Advertisement");
}
}

login form doesnt send userid at firsttime

hiiii following is my login code
public class Login extends ActionBarActivity {
// flag for Internet connection status
Boolean isInternetPresent = false;
String shareduid;
// Connection detector class
ConnectionDetector cd;
ImageView imgview;
EditText uname;
EditText pass;
Button create,login;
TextView trouble;
public static final String MyPREFERENCES = "MyPrefs";
public static String userid = null;
SharedPreferences sharedpreferences;
private static final String TAG = "myAppSurun";
//private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
//End Drawer
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
String otpkey,vrfy;
// url to get all products list
private static String url_all_login = "http://xxx/xxx/xxxx/xxx";
//Globalstring
String username =null;
String password = null;
//Global Variable for login state checking
public boolean loginflag = false;
// RelativeLayout relativeLayout=new RelativeLayout(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
cd = new ConnectionDetector(getApplicationContext());
imgview=(ImageView)findViewById(R.id.imageView2);
uname=(EditText)findViewById(R.id.edituser);
pass=(EditText)findViewById(R.id.editpassword);
create=(Button)findViewById(R.id.create);
login=(Button)findViewById(R.id.Login);
trouble=(TextView)findViewById(R.id.trouble_login);
getSupportActionBar().setTitle("Surun Support");
ColorDrawable(Color.parseColor("#F58634")));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
ActionBar bar = getSupportActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F58634")));
//Click Text Animation
final Animation myanim, imganim;
myanim = AnimationUtils.loadAnimation(this, R.anim.link_text_anim);
imganim = AnimationUtils.loadAnimation(this, R.anim.rotate);
uname.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
validation.isValid(uname, "^[_a-zA-Z]+(\\.[_a-zA-Z 0-9-]+)*#[a-zA-Z]+(\\.[a-zA-Z]+)*(\\.[a-zA-Z]{2,})$", "Invalid UserName", true);
}
});
pass.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
validation.isValid(pass, "[0-9]{10}", "Invalid Mobile No", true);
}
});
//end of initializing component
create.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Create Click", Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), Registration_user.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
});//End of On click for button
//starting font settings this has prone to error try catch is mandatory while setting font(Overriding native font interface).
try {
Typeface myTypeface = Typeface.createFromAsset(this.getAssets(), "fonts/robotoregular.ttf");
create.setTypeface(myTypeface);
} catch (Exception e) {
Log.v(TAG, "Exception " + e);
}
//End of font settings
//Initializing shared preferences
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
//load preferences if exist
Log.v(TAG,""+sharedpreferences);
Log.v(TAG,"Preference is present loading it");
String shareduser = sharedpreferences.getString("User", "");
String sharedpass = sharedpreferences.getString("Password", "");
shareduid = sharedpreferences.getString("userid", "");
String sharedotp = sharedpreferences.getString("otp", "");
String sharedvrfy = sharedpreferences.getString("verified", "");
Log.v(TAG,"uid"+shareduser);
Log.v(TAG,"otp"+sharedpass);
Log.v(TAG,"vrfy"+sharedvrfy);
if ((shareduser.length() > 0) && (sharedpass.length() > 0)) {
//Navigating to main page
Log.v(TAG,"navigate to main");
Intent i = new Intent(getApplicationContext(), UserLogedIn.class);
i.putExtra("user", shareduser);
i.putExtra("pass", sharedpass);
i.putExtra("userid", shareduid);
i.putExtra("otpkey",sharedotp);
i.putExtra("vrfy", sharedvrfy);
//Starting An Activity
startActivity(i);
finish();
} else {
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
if (uname.getText().length() <= 0 || pass.getText().length() <= 0) {
AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("All Fields Are Mandatory");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "Please Enter Correct User Name And Password", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
if (pass.getText().length() > 10) {
Toast toast1 = Toast.makeText(getApplicationContext(), "Four Characters Only...", Toast.LENGTH_SHORT);
toast1.show();
trouble.setVisibility(View.VISIBLE);
//Log.v(TAG,"Not Valid");
}
} else if (pass.getText().length() > 10) {
AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Mobile no Must be 10 digit only ");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "Please Enter Correct User Name And Password", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
} else if (!(validation.isValid(uname, "^[_a-zA-Z]+(\\.[_a-zA-Z0-9-]+)*#[a-zA-Z]+(\\.[a-zA-Z]+)*(\\.[a-zA-Z]{2,})$", "Invalid UserName", true))) {
AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Email Is Incorrect");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "Email Id Is InCorrect", Toast.LENGTH_SHORT).show();
uname.requestFocus();
}
});
// Showing Alert Message
alertDialog.show();
} else {
//Animate Button load animation from anim/rotate.xml
imgview.startAnimation(imganim);
username = uname.getText().toString().toLowerCase();
password = pass.getText().toString();
//Sending Login Request To Server for validation Using Asynchronus Tasks where username and password as a parameter to method
Log.v(TAG, "Excuting check detail");
new CheckDetail().execute();
//Creating Shared Preferences
}//end of else_if fields are valid
}
else
{
AlertDialog alertDialog = new AlertDialog.Builder(Login.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Internet is not active.Please Check Your NEtwork Setting");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "Internet Is Inactive", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
}
}
});//End of On click for button
}//If no shared preferences found
}//End of onCreate function
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_admin_home, menu);
return true;
}//End of onCreateOptionMenu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
//Remove Following Comment To Enable Drawer Toggling On Login Page
/*// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}*/
return super.onOptionsItemSelected(item);
}//End of onOptionItemSelected
//Alert Dialog when User Click Back Button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if(keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.quit)
.setMessage(R.string.really_quit)
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
Login.this.finish();
}
})
.setNegativeButton("no", null)
.show();
return true;
}
else {
return super.onKeyDown(keyCode, event);
}
}//End of Alert Dialog Box
class CheckDetail extends AsyncTask<String,String, String> {
JSONArray datail=null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Logging in. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
try {
Log.v(TAG, "In Do in Background");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("pwd", password));
// getting JSON string from URL
JSONObject json =jParser.makeHttpRequest(url_all_login, "POST", params);
//Object Parsing Failed here hence by using trail guide using JSONParser.alternateJSONArray to parse user data.
//Hence not using json instance of object using a BACKUP static variable of Parser class for proccessing.
//To use this backup utility theme the process should be standard and return unique or two out put only or ether way use three logical step
if(json != null) {
// As if login fails it returns object handling fail logic here.
//We can make it general by sending array from server side so we can only use alternateJSONArray variable
}
if(JSONParser.alternateJSONArray != null)
{
Log.v(TAG, "USING BACKUP ARRAY");
//Check your log cat for JSON futher details
for (int jsonArrayElementIndex=0; jsonArrayElementIndex < JSONParser.alternateJSONArray.length(); jsonArrayElementIndex++) {
JSONObject jsonObjectAtJsonArrayElementIndex = JSONParser.alternateJSONArray.getJSONObject(jsonArrayElementIndex);
userid=jsonObjectAtJsonArrayElementIndex.getString("u_id");
otpkey=jsonObjectAtJsonArrayElementIndex.getString("OTP");
vrfy=jsonObjectAtJsonArrayElementIndex.getString("is_verified");
Log.v(TAG,"" +userid);
Log.v(TAG,"" +otpkey);
Log.v(TAG,"" +vrfy);
if(jsonObjectAtJsonArrayElementIndex.getString("email").equals(username) && jsonObjectAtJsonArrayElementIndex.getString("mobile").equals(password))
{
Log.v(TAG,"Login Successful Now setting loginflag true");
loginflag = true;
}
}
}
else
{
loginflag=false;
}
} catch (Exception e) {
e.printStackTrace();
Log.v(TAG, "Exception at end :" + e.toString());
//Log.e("TAG", "Error......!RecoverIt");
}
return null ;
}
protected void onPostExecute(String result)
{
// dismiss the dialog after getting all products
//super.onPostExecute();
// pDialog.dismiss();
Log.v(TAG,"verification"+vrfy);
Log.v(TAG,"userid"+userid);
/* if(vrfy==false)
{
Intent i = new Intent(getApplicationContext(), Verifyotp.class);
i.putExtra("userid", userid);
i.putExtra("isverified", vrfy);
startActivity(i);
}else*/
if(loginflag==true) {
Log.v(TAG, "Executing Shared Preferences...");
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("User", uname.getText().toString());
editor.putString("Password", pass.getText().toString());
Log.v(TAG, "Userid==================" + userid);
Log.v(TAG, "otpkey==============" + otpkey);
Log.v(TAG, "is verified " + vrfy);
editor.putString("userid", userid);
editor.putString("otp", otpkey);
editor.putString("vrfy", vrfy);
editor.commit();
Toast.makeText(getApplicationContext(), "Login Succeed", Toast.LENGTH_SHORT).show();
android.util.Log.v(TAG, "Login Succeed");
Intent i = new Intent(getApplicationContext(), UserLogedIn.class);
i.putExtra("user", shareduid);
Log.v(TAG, "" + userid);
startActivity(i);
finish();
}
else
{
Toast.makeText(getApplicationContext(),"Login failed,Invalid Details...!",Toast.LENGTH_LONG).show();
trouble.setVisibility(View.VISIBLE);
}
pDialog.dismiss();
}
}
i send userid from login.java to next activity but in other activity it doesnt receive that userid first time.at first time it display null but at other places it show/print userid correctely
if i restart app userid will be perfect and app will work fine
i dont know why it is happen at first time
code in other activity
Intent iin = getIntent();
Bundle b = iin.getExtras();
if (b != null) {
u_id = (String) b.get("userid");//first time it shows null but after restart it get correct value
Log.v(TAG, "userlogged in" + u_id);
}
because you sending null first time change below in your onpost method
Intent i = new Intent(getApplicationContext(), UserLogedIn.class);
i.putExtra("user", shareduid);
Log.v(TAG, "" + userid);
startActivity(i);
in above shareduid is null first time you setting by shared preference so just put below
Intent i = new Intent(getApplicationContext(), UserLogedIn.class);
i.putExtra("user", userid);
Log.v(TAG, "" + userid);
startActivity(i);
check with this and let me know also i think check with key if you putextra with 'user' key you have to access with the same 'user' key

Program Execution is not in proper way

When I click on button in my program without entering data it shows both errors parallely (I have Highlighted in below prog). here i need to get only one error at a time i mean when it is null it has show appropriate one.vice versa..
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(v==findViewById(R.id.button1)) {
et1 = (EditText) findViewById(R.id.editText1);
if(et1.getText()!=null ) {
try {
radius = Double.valueOf(et1.getText().toString());
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Please enter correct value", Toast.LENGTH_SHORT).show();
}
}
if(radius==0.0) {
Toast.makeText(getApplicationContext(), "Value cannot be 0", Toast.LENGTH_SHORT).show();
}
try {
output = (double) Math.round(Math.PI * radius * radius);
String s = Double.toString(output);
tv1.setText(s);
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Please enter correct value", Toast.LENGTH_SHORT).show();
}
}
}
});
do not make things more complicated as they actually are. You can be sure that a correct value was entered without any try/catch blocks. Possible approach:
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
Pattern p = Pattern.compile("([0-9]*)");
if (et1.getText().toString().trim().length() > 0) {
Matcher m = p.matcher(et1.getText().toString().trim());
if (m.matches()) {
radius = Double.valueOf(et1.getText().toString());
output = (double) Math.round(Math.PI * radius
* radius);
tv1.setText(Double.toString(output));
} else
Toast.makeText(getApplicationContext(),
"incorrect value", Toast.LENGTH_SHORT)
.show();
} else
Toast.makeText(getApplicationContext(),
"input is empty", Toast.LENGTH_SHORT).show();
break;
default:
}
}
});
In the above code you check if there was any text entered. The second if checks whether the input is numeric using a java regex. When both requirements are met you can be sure the output is calculated correctly.
BTW, using switch-case is a better approach for click listeners

Progress dialog is not showing while calling a web service

I am new to android. I want to show progress dialog when user click on login button. I tried this but the dialog is not showing
btn_logIn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
getUserCredentials();
}
}); //end of anonymous class
private void showProgressDialog() {
if (dialog == null) {
dialog = new ProgressDialog(this);
}
dialog.setMessage("Please Wait. Your authentication is in progress");
dialog.setButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
dialog.dismiss();
}
}); //end of anonymous class
dialog.show();
} //end of showProgressDialog()
private void getUserCredentials() {
EditText txt_userName = (EditText) findViewById(R.id.txt_userName);
String userName = txt_userName.getText().toString();
EditText txt_password = (EditText) findViewById(R.id.txt_password);
String password = txt_password.getText().toString();
if (userName != null && !userName.trim().equals("") && password != null && !password.trim().equals("")) {
showProgressDialog();
callWebService(userName, password);
}
} //end of getUserCredentials()
private void callWebService(String userName, String password) {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("userName", userName);
....
Object result = envelope.getResponse();
if (result.equals("true")) {
dialog.dismiss();
Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
} else {
dialog.dismiss();
Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
}
} catch (SocketTimeoutException e) {
dialog.dismiss();
Toast.makeText(this, "Service is not connected, Please make sure your server is running", Toast.LENGTH_LONG).show();
} catch(Exception e) {
e.printStackTrace();
dialog.dismiss();
Toast.makeText(this, "Unable to connect, please try again later. Thank you", Toast.LENGTH_LONG).show();
}
} //end of callWebServide()
Am i doing anything wrong. When i click on login button and service is not running then it shows message that Service is not connected, Please make sure your server is running", but the dialog isn't showing...Why? My logic is when user click on login button and fields have values then start showing progress dialog and if anything happens like when result come or server is not running or if any exception happen , then i remove the dialog and show the appropriate message, but dialog isn't showing...Why? What i am doing wrong? Please help..
Thanks
Try this,
Change your getUserCredentials() like this,
private void getUserCredentials() {
EditText txt_userName = (EditText) findViewById(R.id.txt_userName);
String userName = txt_userName.getText().toString();
EditText txt_password = (EditText) findViewById(R.id.txt_password);
String password = txt_password.getText().toString();
if (userName != null && !userName.trim().equals("") && password != null && !password.trim().equals("")) {
showProgressDialog();
Thread t=new Thread(new Runnable() {
public void run() {
callWebService(userName, password);
}
}); t.start();
}
}
And your callWebService method like this,
private void callWebService(String userName, String password) {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("userName", userName);
....
Object result = envelope.getResponse();
if (result.equals("true")) {
dialog.dismiss();
Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
} else {
ActivityName.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
}
});
}
} catch (SocketTimeoutException e) {
ActivityName.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
Toast.makeText(this, "Service is not connected, Please make sure your server is running", Toast.LENGTH_LONG).show();
}
});
} catch(Exception e) {
e.printStackTrace();
ActivityName.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
Toast.makeText(this, "Unable to connect, please try again later. Thank you", Toast.LENGTH_LONG).show();
}
});
}
}
Update 1
To answer your questions from your comments,
1)Yes Async Task is more efficient. It has its own methods to do the same task what I have described here.
AsyncTask has the following methods,
i)onPreExecute()-which can be used to start your Dialog
ii)doInBackground()-which acts as the background thread.
iii)onPostExecute()-which gets called at the end where you can dismiss the dialog.
The reason why I didn't mention is that, there are possibilities that you might have to change your working code's structure to adapt to Async task.
2)runonUiThread- as the name indicates, anything inside this will be considered as it is running in the main UI thread. So basically to update the screen you have to use this. There are also other methods available, like Handlers which can also do the same task.
Use AsyncTask for it when ever task started at that time initialise your widget and then call your webservice from run method and close your progress bar on stop method.

NullPointerException When Intent is used Android After Checking A boolean Condition?

I have a activity am using a boolean condition to check some thing .if the boolean condition Satisfy i need to Go to The next Page. But When The condition Satisfy the Device get crash With NullPointerException Am giving The Code Below
The Boolean Condition
boolean check()
{
boolean matches=false;
int falseFlag=0;
if(cc.length==picarray.length)
{
for (int i=0;i<cc.length;i++)
{
if(cc[i].equals(picarray[i]))
{
//---The Database Value Stored in Array is modified---
xmin=X[i]-25;
xmax=X[i]+25;
ymin=Y[i]-25;
ymax=Y[i]+25;
//---Check Whether The Selected Password Is Inside The Array Values---
if(xmin<realx[i]&&realx[i]<xmax)
{
System.out.println("TRUE");
}
else
{
falseFlag++;
System.out.println("FALSE");
}
if(ymin<realy[i]&&realy[i]<ymax)
{
System.out.println("TRUE");
}
else
{
falseFlag++;
System.out.println("FALSE");
}
}
else
{
falseFlag++;
}
}
}
else
{
falseFlag++;
}
if(falseFlag==0)
{
matches=true;
}
System.out.println("Authentication returns "+matches);
return matches;
}
in button click
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(check())
{
Intent sa=new Intent(Test.class,Test2.class);
startActivity(sa);
System.out.println("U R AUTHENTICATED");
}
else
{
System.out.println("INVALID USER");
Toast.makeText(getApplicationContext(), "INVALID USER", Toast.LENGTH_LONG).show();
}
}
});
try this,
Intent sa=new Intent(getApplicationContext(),Test2.class);
basically intent needs context and not a class...
i doub't this (Intent sa=new Intent(Test.class,Test2.class);) will compile
The first argument is a Context so when you create the intent, it should be:
Intent sa=new Intent(Test.this,Test2.class);
instead of
Intent sa=new Intent(Test.class,Test2.class);
This should also work:
Intent sa=new Intent(v.getContext(),Test2.class);
Intent sa=new Intent(Test.class,Test2.class);
The first parameter should be Test.this(Context), is it not throwing a Compile-time error ??

Categories

Resources