I have to develop a login form android application.Here, i have to enter the username and password. If it is correct, fetch the email belonging to the username and display it in the textview and if the username and password is wrong, display login failed message.
This is my webservice code:
public class Login {
public String authentication(String username,String password) {
String retrievedUserName = "";
String retrievedPassword = "";
String retrievedEmail = "";
String status = "";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xcart-432pro","root","");
PreparedStatement statement = con.prepareStatement("SELECT * FROM xcart_customers WHERE login = '"+username+"'");
ResultSet result = statement.executeQuery();
while(result.next()){
retrievedUserName = result.getString("login");
retrievedPassword = result.getString("password");
retrievedEmail = result.getString("email");
}
if(retrievedUserName.equals(username)&&retrievedPassword.equals(password)&&!(retrievedUserName.equals("") && retrievedPassword.equals(""))){
status = "Success";
}
else {
status = "Login fail!!!";
}
}
catch(Exception e){
e.printStackTrace();
}
return status;
}
};
This is my android code:
public class CustomerLogin extends Activity {
private static final String SPF_NAME = "vidslogin";
private static final String USERNAME = "login";
private static final String PASSWORD = "password";
private static final String PREFS_NAME = null;
CheckBox chkRememberMe;
private String login;
String mGrandTotal,total,mTitle;
EditText username,userPassword;
private final String NAMESPACE = "http://xcart.com";
private final String URL = "http://10.0.0.75:8085/XcartLogin/services/Login?wsdl";
private final String SOAP_ACTION = "http://xcart.com/authentication";
private final String METHOD_NAME = "authentication";
private String uName;
/**Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customer_login);
Bundle b = getIntent().getExtras();
total = b.getString("GrandTotal");
mTitle = b.getString("Title");
TextView grandtotal = (TextView) findViewById(R.id.grand_total);
grandtotal.setText("Welcome ," + mTitle );
chkRememberMe = (CheckBox) findViewById(R.id.rempasswordcheckbox);
username = (EditText) findViewById(R.id.tf_userName);
userPassword = (EditText) findViewById(R.id.tf_password);
SharedPreferences loginPreferences = getSharedPreferences(SPF_NAME, Context.MODE_PRIVATE);
username.setText(loginPreferences.getString(USERNAME, ""));
userPassword.setText(loginPreferences.getString(PASSWORD, ""));
Button login = (Button) findViewById(R.id.btn_login);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
loginAction();
}
});
}
private void loginAction(){
boolean isUserValidated = true;
boolean isPasswordValidated = true;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
EditText username = (EditText) findViewById(R.id.tf_userName);
String user_Name = username.getText().toString();
EditText userPassword = (EditText) findViewById(R.id.tf_password);
String user_Password = userPassword.getText().toString();
//Pass value for userName variable of the web service
PropertyInfo unameProp =new PropertyInfo();
unameProp.setName("username");//Define the variable name in the web service method
unameProp.setValue(user_Name);//set value for userName variable
unameProp.setType(String.class);//Define the type of the variable
request.addProperty(unameProp);//Pass properties to the variable
//Pass value for Password variable of the web service
PropertyInfo passwordProp =new PropertyInfo();
passwordProp.setName("password");
passwordProp.setValue(user_Password);
passwordProp.setType(String.class);
request.addProperty(passwordProp);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try{
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
String status = response.toString();
TextView result = (TextView) findViewById(R.id.tv_status);
result.setText(response.toString());
if(status.equals("Success")) {
// ADD to save and read next time
String strUserName = username.getText().toString().trim();
String strPassword = userPassword.getText().toString().trim();
if (null == strUserName || strUserName.length() == 0) {
// showToast("Enter Your Name");
username.setError( "username is required!" );
isUserValidated = false;
}
if (null == strPassword || strPassword.length() == 0) {
// showToast("Enter Your Password");
isPasswordValidated = false;
userPassword.setError( "password is required!" );
}
if (isUserValidated = true && isPasswordValidated == true) {
if (chkRememberMe.isChecked()) {
SharedPreferences loginPreferences = getSharedPreferences(SPF_NAME, Context.MODE_PRIVATE);
loginPreferences.edit().putString(USERNAME, strUserName).putString(PASSWORD, strPassword).commit();
}
else {
SharedPreferences loginPreferences = getSharedPreferences(SPF_NAME, Context.MODE_PRIVATE);
loginPreferences.edit().clear().commit();
}
}
if (isUserValidated && isPasswordValidated) {
Intent intent = new Intent(CustomerLogin.this,PayPalIntegrationActivity.class);
intent.putExtra("GrandTotal", total);
intent.putExtra("Title", mTitle);
intent.putExtra("login",username.getText().toString());
startActivity(intent);
}
}
else {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_custom_layout,
(ViewGroup) findViewById(R.id.toast_layout_root));
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.TOP, 0, 30);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
}
catch(Exception e){
}
}
}
If the login is success, it will have to display the email on textview. How can i do that?
You can use asy task to do this,
in doInBackground
Do your login operations. Asyctask makes this operation in another task.
when complated in onPostExecute
show the success message. But you need to use runOnUiThread because you cant reach ui controls from non ui thread.
private class loginTask extends AsyncTask<URL, Integer, int> {
protected Long doInBackground(URL... urls) {
// start login process
return 1;
}
protected void onPostExecute(int result) {
_activity.runOnUiThread(new Runnable() {
#Override
public void run() {
textview.setText("login success");
}
});
}
}
Related
Ok so I am trying to pass a list object from ASP to Android using KSOAP2. I am fully able to connect to the Web Service, I have tested that service does return a basic bool to start with, however I need the service to return a list object filled with log in variables. I am getting this error: Error on soapPrimitiveData() org.ksoap2.SoapFault cannot be cast to org.ksoap2.serialization.SoapObject
Java:
public class MainActivity extends ActionBarActivity {
private final String NAMESPACE = "http://tempuri.org/";
private final String URL = "http://www.mycompanysURL.net/CompanyService/ReportingService.asmx";
String user_id;
String password;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button signin = (Button) findViewById(R.id.btnLogin);
text = (TextView) findViewById(R.id.txtOut);
signin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText etxt_user = (EditText) findViewById(R.id.txtUser);
user_id = etxt_user.getText().toString();
EditText etxt_password = (EditText) findViewById(R.id.txtPass);
password = etxt_password.getText().toString();
new LoginTask().execute();
}
});
}
private boolean doLogin(String user_id, String password) {
String ip = Utils.getIPAddress(true);
boolean result = false;
final String SOAP_ACTION = "http://tempuri.org/GetLogin";
final String METHOD_NAME = "GetLogin";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("User", user_id);
request.addProperty("Pass", password);
request.addProperty("ip",ip);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
// Make the soap call.
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
// Get the SoapResult from the envelope body.
//Error seems to happen here.
SoapObject resultRequestSOAP = (SoapObject) envelope.bodyIn;
SoapObject root = (SoapObject) resultRequestSOAP.getProperty(0);
SoapObject s_deals = (SoapObject) root.getProperty("FOO_DEALS");
for (int i = 0; i < s_deals.getPropertyCount(); i++)
{
Object property = s_deals.getProperty(i);
if (property instanceof SoapObject)
{
SoapObject category_list = (SoapObject) property;
String LoginID = category_list.getProperty("Login_ID").toString();
String UserID = category_list.getProperty("UserID").toString();
String Login_Access = category_list.getProperty("Login_Access").toString();
String Login_CompID = category_list.getProperty("Login_CompID").toString();
String Login_ProfileID = category_list.getProperty("Login_ProfileID").toString();
String Login_DisplayName = category_list.getProperty("Login_DisplayName").toString();
String Login_CustomerType = category_list.getProperty("Login_CustomerType").toString();
String active = category_list.getProperty("active").toString();
if (active == "1") {
result = true;
text.setText("Logged In");
} else {
text.setText("Not Logged In");
}
}
}
} catch (SocketException ex) {
Log.e("Error : ", "Error on soapPrimitiveData() " + ex.getMessage());
ex.printStackTrace();
} catch (Exception e) {
Log.e("Error : ", "Error on soapPrimitiveData() " + e.getMessage());
e.printStackTrace();
}
return result;
}
private class LoginTask extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(
MainActivity.this);
protected void onPreExecute() {
this.dialog.setMessage("Logging in...");
this.dialog.show();
}
protected Void doInBackground(final Void... unused) {
boolean auth = doLogin(user_id, password);
System.out.println(auth);
return null;
}
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
}
ASP:
[WebMethod]
public List<LoginObject> GetLogin(string User, string Pass, string ip)
{
SqlConnection conn = new SqlConnection(my_db.credentials);
SqlDataReader rdr = null;
List<LoginObject> LoginList = new List<LoginObject>();
bool login_in_ok = false;
string date = DateTime.Now.ToString();
string UserID1 = "";
string Login_ID1 = "";
string Login_Access1 = "";
string Login_CompID1 = "";
string Login_ProfileID1 = "";
string Login_DisplayName1 = "";
string Login_CustomerType1 = "";
string active1 = "";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("usp_user_login", conn);
cmd.Parameters.Add(new SqlParameter("#login", User));
cmd.Parameters.Add(new SqlParameter("#pwd", Pass));
cmd.Parameters.Add(new SqlParameter("#ip_addr", ip));
cmd.Parameters.Add(new SqlParameter("#local_datetime", date));
cmd.CommandType = CommandType.StoredProcedure;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
UserID1 = rdr["UserID"].ToString();
Login_ID1 = rdr["ID"].ToString();
Login_Access1 = rdr["Access"].ToString();
Login_CompID1 = rdr["CompanyID"].ToString();
Login_ProfileID1 = rdr["ProfileID"].ToString();
Login_DisplayName1 = rdr["Lname"].ToString() + " " + rdr["FName"].ToString();
Login_CustomerType1 = rdr["login_customer_type"].ToString();
active1 = rdr["Active"].ToString();
}
}
finally
{
if (rdr != null)
{
rdr.Close();
}
if (conn != null)
{
conn.Close();
}
}
login_in_ok = active1 == "1" || active1 == "True" ? true : false;
if (login_in_ok)
{
//Dataset for Andriod Login.
LoginList.Add(new LoginObject
{
Login_ID = Login_ID1,
UserID = UserID1,
Login_Access = Login_Access1,
Login_CompID = Login_CompID1,
Login_ProfileID = Login_ProfileID1,
Login_DisplayName = Login_DisplayName1,
Login_CustomerType = Login_CustomerType1,
active = active1
});
}
else
{
//Empty Set for Android to register
LoginList.Add(new LoginObject
{
Login_ID = "",
UserID = "",
Login_Access = "0",
Login_CompID = "",
Login_ProfileID = "",
Login_DisplayName = "",
Login_CustomerType = "",
active = active1
});
}
return LoginList;
}
Any help would be great.
Actually this works, I had an issue with my stored procedure... have to love it when other developers change things and do not inform anyone.
This is done based on selvin's coding, but it doesnt work for me, that is message is not getting posted on the linked wall in android. after login stays in the same page.
This is the code `public class LITestActivity extends Activity {
// /change keysssssssssssssssssssssssssssss!!!!!!!!!!
static final String CONSUMER_KEY = "key";
static final String CONSUMER_SECRET = "secret";
static final String APP_NAME = "abc";
static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-linkedin";
static final String OAUTH_CALLBACK_HOST = "litestcalback";
static final String OAUTH_CALLBACK_URL = String.format("%s://%s",
OAUTH_CALLBACK_SCHEME, OAUTH_CALLBACK_HOST);
static final String OAUTH_QUERY_TOKEN = "oauth_token";
static final String OAUTH_QUERY_VERIFIER = "oauth_verifier";
static final String OAUTH_QUERY_PROBLEM = "oauth_problem";
final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
.getInstance().createLinkedInOAuthService(CONSUMER_KEY,
CONSUMER_SECRET);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory
.newInstance(CONSUMER_KEY, CONSUMER_SECRET);
static final String OAUTH_PREF = "LIKEDIN_OAUTH";
static final String PREF_TOKEN = "token";
static final String PREF_TOKENSECRET = "token secret";
static final String PREF_REQTOKENSECRET = "requestTokenSecret";
TextView tv = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
setContentView(tv);
final SharedPreferences pref = getSharedPreferences(OAUTH_PREF,
MODE_PRIVATE);
final String token = pref.getString(PREF_TOKEN, null);
final String tokenSecret = pref.getString(PREF_TOKENSECRET, null);
if (token == null || tokenSecret == null) {
startAutheniticate();
} else {
showCurrentUser(new LinkedInAccessToken(token, tokenSecret));
}
}
void startAutheniticate() {
final LinkedInRequestToken liToken = oAuthService
.getOAuthRequestToken(OAUTH_CALLBACK_URL);
final String uri = liToken.getAuthorizationUrl();
getSharedPreferences(OAUTH_PREF, MODE_PRIVATE).edit()
.putString(PREF_REQTOKENSECRET, liToken.getTokenSecret())
.commit();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
i.putExtra("sms_body", "Welcome to Rebuix, http://www.rebuix.com");
startActivity(i);
Toast.makeText(this,
"Successfuly posted: " ,
Toast.LENGTH_LONG).show();
}
void finishAuthenticate(final Uri uri) {
if (uri != null && uri.getScheme().equals(OAUTH_CALLBACK_SCHEME)) {
final String problem = uri.getQueryParameter(OAUTH_QUERY_PROBLEM);
if (problem == null) {
final SharedPreferences pref = getSharedPreferences(OAUTH_PREF,
MODE_PRIVATE);
final LinkedInAccessToken accessToken = oAuthService
.getOAuthAccessToken(
new LinkedInRequestToken(uri
.getQueryParameter(OAUTH_QUERY_TOKEN),
pref.getString(PREF_REQTOKENSECRET,
null)),
uri.getQueryParameter(OAUTH_QUERY_VERIFIER));
pref.edit()
.putString(PREF_TOKEN, accessToken.getToken())
.putString(PREF_TOKENSECRET,
accessToken.getTokenSecret())
.remove(PREF_REQTOKENSECRET).commit();
showCurrentUser(accessToken);
} else {
Toast.makeText(this,
"Appliaction down due OAuth problem: " + problem,
Toast.LENGTH_LONG).show();
finish();
}
}
}
void clearTokens() {
getSharedPreferences(OAUTH_PREF, MODE_PRIVATE).edit()
.remove(PREF_TOKEN).remove(PREF_TOKENSECRET)
.remove(PREF_REQTOKENSECRET).commit();
}
void showCurrentUser(final LinkedInAccessToken accessToken) {
final LinkedInApiClient client = factory
.createLinkedInApiClient(accessToken);
try {
final Person p = client.getProfileForCurrentUser();
// /////////////////////////////////////////////////////////
// here you can do client API calls ...
// client.postComment(arg0, arg1);
// client.updateCurrentStatus(arg0);
// or any other API call (this sample only check for current user
// and shows it in TextView)
// /////////////////////////////////////////////////////////
tv.setText(p.getLastName() + ", " + p.getFirstName());
} catch (LinkedInApiClientException ex) {
clearTokens();
Toast.makeText(
this,
"Appliaction down due LinkedInApiClientException: "
+ ex.getMessage()
+ " Authokens cleared - try run application again.",
Toast.LENGTH_LONG).show();
finish();
}
}
#Override
protected void onNewIntent(Intent intent) {
finishAuthenticate(intent.getData());
}
}`
Try the below URL to integration of social network like facebook, Twitter & LinkedIn
I have to develop one android application.
Here i have to fetch the email for beloning user and display that email on android textview.how can i develop these.please give me any idea.
This is my webservice code:
public class Login {
public String authentication(String username,String password){
String retrievedUserName = "";
String retrievedPassword = "";
String retrievedEmail = "";
String status = "";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xcart-432pro","root","");
PreparedStatement statement = con.prepareStatement("SELECT * FROM xcart_customers WHERE login = '"+username+"'");
ResultSet result = statement.executeQuery();
while(result.next()){
retrievedUserName = result.getString("login");
retrievedPassword = result.getString("password");
retrievedEmail = result.getString("email");
}
if(retrievedUserName.equals(username)&&retrievedPassword.equals(password)&&!(retrievedUserName.equals("") && retrievedPassword.equals(""))){
status = retrievedEmail;
}
else {
status = "Login fail!!!";
}
}
catch(Exception e){
e.printStackTrace();
}
return status;
}
}
Here i have to run these webservice code means if login is success means have displayed email id successfully.if my login is incorrect means have displayed login failed message.so my webservice code is correct.
If my login is success means have to display email on android textview.otherwise have to display login failed message.
But here i have faced one problem:
If i have enter correct login detail means thats time also have displayed login failed message.but i have to need the o/p like if my login sucess means display email otherwise login failed message.
Whats wrong in my code.please give me solution for these.
This is my android side code:
public class CustomerLogin extends Activity {
private static final String SPF_NAME = "vidslogin";
private static final String USERNAME = "login";
private static final String PASSWORD = "password";
private static final String PREFS_NAME = null;
private String login;
String mGrandTotal,total,mTitle,mTotal,mQty,mCost;
EditText username,userPassword;
private final String NAMESPACE = "http://xcart.com";
private final String URL = "http://10.0.0.75:8085/XcartLogin/services/Login?wsdl";
private final String SOAP_ACTION = "http://xcart.com/authentication";
private final String METHOD_NAME = "authentication";
private String uName;
/**Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customer_login);
username = (EditText) findViewById(R.id.tf_userName);
userPassword = (EditText) findViewById(R.id.tf_password);
Button login = (Button) findViewById(R.id.btn_login);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
loginAction();
}
});
}
private void loginAction(){
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
EditText username = (EditText) findViewById(R.id.tf_userName);
String user_Name = username.getText().toString();
EditText userPassword = (EditText) findViewById(R.id.tf_password);
String user_Password = userPassword.getText().toString();
//Pass value for userName variable of the web service
PropertyInfo unameProp =new PropertyInfo();
unameProp.setName("username");//Define the variable name in the web service method
unameProp.setValue(user_Name);//set value for userName variable
unameProp.setType(String.class);//Define the type of the variable
request.addProperty(unameProp);//Pass properties to the variable
//Pass value for Password variable of the web service
PropertyInfo passwordProp =new PropertyInfo();
passwordProp.setName("password");
passwordProp.setValue(user_Password);
passwordProp.setType(String.class);
request.addProperty(passwordProp);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try{
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
String status = response.toString();
TextView email = (TextView) findViewById(R.id.tv_status);
email.setText(response.toString());
if(status.equals(email))
{
if(isUserValidated && isPasswordValidated)
{
Intent intent = new Intent(CustomerLogin.this,PayPalIntegrationActivity.class);
startActivity(intent);
}
}
else
{
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_custom_layout,
(ViewGroup) findViewById(R.id.toast_layout_root));
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.TOP, 0, 30);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
}
catch(Exception e){
}
}
}
EDIT:
Here i have wrote the code like means
if(status.equals("krishnaveniveeman#gmail.com"))
am getting the email in textview after enter the correct login deatils.
Here how can i fetch the email from webservice and also set the email on textview.
I have to writhe code like
if(status.equals(email))
means the login failed message only displayed.but my login detail is correct only.
please anyone give me solution for these.
I am sending details to be stored in a database using a web service using KSOAP. I have used visual studio to create the web service. The web service works fine. A string will be returned when the details have been inserted into the database. The problem is that this string is empty, maybe something is wrong in the way that i am getting the response. I have been trying to find out whats wrong for a long time. please help
public class Registration extends Activity{
private static final String SOAP_ACTION = "http://tempuri.org/register";
private static final String OPERATION_NAME = "register";
private static final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
private static final String SOAP_ADDRESS = "http://10.0.2.2:58076/WebSite1/Service.asmx";
Button sqlRegister, sqlView;
EditText sqlFirstName,sqlLastName,sqlEmail,sqlMobileNumber,sqlCurrentLocation,sqlUsername,sqlPassword;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.registration);
sqlFirstName = (EditText) findViewById(R.id.etFname);
sqlLastName = (EditText) findViewById(R.id.etLname);
sqlEmail = (EditText) findViewById(R.id.etEmail);
sqlMobileNumber = (EditText) findViewById(R.id.etPhone);
sqlCurrentLocation = (EditText) findViewById(R.id.etCurrentLoc);
sqlUsername = (EditText) findViewById(R.id.etUsername);
sqlPassword = (EditText) findViewById(R.id.etPwd);
sqlRegister = (Button) findViewById(R.id.bRegister);
sqlRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()){
case R.id.bRegister:
new LongOperation().execute("");
break;
}
}
});
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String firstname = sqlFirstName.getText().toString();
String lastname = sqlLastName.getText().toString();
String emailadd = sqlEmail.getText().toString();
String number = sqlMobileNumber.getText().toString();
String loc = sqlCurrentLocation.getText().toString();
String uname = sqlUsername.getText().toString();
String pwd = sqlPassword.getText().toString();
SoapObject Request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
Request.addProperty("fname", String.valueOf(firstname));
Request.addProperty("lname", String.valueOf(lastname));
Request.addProperty("email", String.valueOf(emailadd));
Request.addProperty("num", String.valueOf(number));
Request.addProperty("loc", String.valueOf(loc));
Request.addProperty("username", String.valueOf(uname));
Request.addProperty("password", String.valueOf(pwd));
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(Request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
Log.d("work","work");
try
{
httpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject)envelope.getResponse();
String result = response.getProperty(0).toString();
Log.d("res",result);
if(result.equals("reg"))
{
Log.d("reg","reg");
return "Registered";
}
else
{
Log.d("no","no");
return "Not Registered";
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.d("tag","onpost");
if(result!=null)
{
if(result.equals("Registered"))
{
Toast.makeText(Registration.this, "You have been registered Successfully", Toast.LENGTH_LONG).show();
}
else if(result.equals("Not Registered"))
{
Toast.makeText(Registration.this, "Try Again", Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(Registration.this, "Somethings wrong", Toast.LENGTH_LONG).show(); ///This is what gets printed on screen
}
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
Your webservice is returning a String.
Try using this to solve your problem
Object result = envelope.getResponse();
when your webservice return values of type byte[] ,you can do this:
SoapObject response=(SoapObject)envelope.bodyIn;
Hope it helps
I am trying to save the username in shared preferences. I used a web service to get the username and password from the database and it works perfectly. The problem is with saving the username in shared preferences. I have given the code below. I have commented the place where the problem arises. I get the following exception:
java.lang.NullPointerException
I cant find whats wrong. please help.
///Login Class////
public class Login extends Activity{
private static final String SOAP_ACTION = "http://tempuri.org/checkLogin";
private static final String OPERATION_NAME = "checkLogin";
private static final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
private static final String SOAP_ADDRESS = "http://10.0.2.2:54714/WebSite1/Service.asmx";
Button sqllogin;
EditText sqlusername, sqlpassword;
TextView tvData1;
CheckBox cb;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sqlusername = (EditText) findViewById(R.id.etuname1);
sqlpassword = (EditText) findViewById(R.id.etpass);
tvData1 = (TextView)findViewById(R.id.textView1);
sqllogin = (Button) findViewById(R.id.bLogin);
sqllogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()){
case R.id.bLogin:
String username = sqlusername.getText().toString();
String password = sqlpassword.getText().toString();
SoapObject Request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
Request.addProperty("uname", String.valueOf(username));
Request.addProperty("pwd", String.valueOf(password));
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(Request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
try {
httpTransport.call(SOAP_ACTION, envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
int response = Integer.parseInt(result.getProperty(0).toString());
if(response == 2)//Response is 2 when username and password valid
{
tvData1.setText("You have logged in successfully");
savePrefs("CHECKBOX",cb.isChecked()); //This line and the following 3 lines is where the problem is.
if (cb.isChecked())
{
savePrefs("NAME",sqlusername.getText().toString());
}
Intent openhomepage = new Intent("com.android.disasterAlertApp.HOME");
startActivity(openhomepage);
}
else
{
tvData1.setText("Invalid Username or password");
}
} catch (Exception exception) {
tvData1.setText(exception.toString());
}
break;
}
}
});
}
private void savePrefs(String key, boolean value){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putBoolean(key, value);
edit.commit();
}
private void savePrefs(String key,String value){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putString(key, value);
edit.commit();
}
}
I dont see where you made cb (the check box ) attached to a view?
You are getting a null pointer because cb is nothing. You haven't found its view yet its just a member and that's it. And since this is also where you are getting your null pointer this is almost certainly what's going wrong.
CheckBox cb is not set! use cb = (CheckBox) findViewById(R.id.somewhat);