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);
Related
I've programmed ( actually followed a tutorial ) simple web service in android, using Ksoap libary. But it seems that it doesn't work well. Below is my simple code:
public class MainActivity extends Activity {
TextView tv;
SoapPrimitive response;
final String SOAP_ACTION = "http://tempuri.org/CelsiusToFahrenheit";
final String METHOD_NAME = "CelsiusToFahrenheit";
final String NAMESPACE = "http://www.tempuri.org/";
final String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getValue();
}
});
}
private void getValue() {
SoapObject soapObject = new SoapObject(NAMESPACE, METHOD_NAME);
soapObject.addProperty("Celsius", "33");
SoapSerializationEnvelope serial = new SoapSerializationEnvelope(SoapEnvelope.VER11);
serial.dotNet = true;
serial.setOutputSoapObject(soapObject);
HttpTransportSE transport = new HttpTransportSE(URL);
try {
transport.call(SOAP_ACTION, serial);
response = (SoapPrimitive) serial.getResponse();
tv.setText(response+"");
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
I only get a response "Error" in my text view. Can anyone tell me what is wrong here?
I found what was wrong. I wrote:
final String NAMESPACE = "http://www.tempuri.org/";
instead of
final String NAMESPACE = "http://tempuri.org/";
It's working now.
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 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");
}
});
}
}
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 have one android app with login, logout functions. The login form contains Username and password and the login button. I want to save the username and the password when the user checks the "Remember me" check box.
My project.java file is shown below:
public class project extends Activity {
private static final int IO_BUFFER_SIZE = 4 * 1024;
/** Called when the activity is first created. */
public int user_id,current_user_id;
public String access_token,username,current_username;
public boolean user_logged_in=false;
public ProgressDialog progdialog;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progdialog = new ProgressDialog(this);
progdialog.setMessage("loading...");
initLogin();
}
public void initLogin(){
setContentView(R.layout.login);
Button button = (Button) findViewById(R.id.login_login);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
login();
}
});
}
public void login(){
try{
String login_username=(((EditText) findViewById(R.id.login_username)).getText()).toString();
String login_password=(((EditText) findViewById(R.id.login_password)).getText()).toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username",login_username));
nameValuePairs.add(new BasicNameValuePair("password",login_password));
String content=postUrlContent(api_url+"landing/authenticate",nameValuePairs);
JSONObject jObject = new JSONObject(content);
JSONObject respObject = jObject.getJSONObject("response");
Boolean success=respObject.getBoolean("success");
String message=respObject.getString("message");
Boolean logged_in=respObject.getBoolean("logged_in");
if(logged_in){
user_id=respObject.getInt("user_id");
access_token=respObject.getString("access_token");
username=respObject.getString("username");
current_username=username;
current_user_id=user_id;
user_logged_in=true;
//initFeeds(username);
test(0);
}else{
createDialog("Error",message);
}
}catch(Exception e){
}
}
You can use your apps shared preferences. The prefs can be accessed anytime using the key you set for these prefs
static final String KEY_USERNAME = "username";
static final String KEY_PASSWORD = "password";
if (rememberMe) { //save username and pw to prefs
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor ed = prefs.edit();
ed.putString(KEY_USERNAME, theUsername);
ed.putString(KEY_PASSWORD, thePW);
ed.commit();
}
To access the information, like in your onCreate method:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String username = prefs.getString(KEY_USERNAME, "Default Value if not found");
String password = prefs.getString(KEY_PASSWORD, ""); //return nothing if no pass saved