I'm a beginner to Mobile Application Development, Currently i've been doing a login (online database) and Register.I wanna pass some argument to the next activity by using putExtra and getStringExtra. Below is my Code for Two Activities:
Login:
public class Login extends AppCompatActivity implements View.OnClickListener {
Button bLogin;
TextView registerLink;
EditText etUsername, etPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
bLogin = (Button) findViewById(R.id.bLogin);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
registerLink = (TextView) findViewById(R.id.tvRegisterLink);
bLogin.setOnClickListener(this);
registerLink.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bLogin:
String Username = etUsername.getText().toString();
String Password = etPassword.getText().toString();
Toast.makeText(this, "Loginin...", Toast.LENGTH_SHORT).show();
new Authenticate(this).execute(Username, Password);
break;
case R.id.tvRegisterLink:
Intent registerIntent = new Intent(Login.this, Register.class);
startActivity(registerIntent);
break;
}
}
public void ParentLogin()
{
String Username = etUsername.getText().toString();
String Password = etPassword.getText().toString();
Intent Main = new Intent(Login.this, MainActivity.class);
Main.putExtra("class","Parent");
Main.putExtra("username",Username);
Main.putExtra("password",Password);
startActivity(Main);
}
public void NannyLogin()
{
String Username = etUsername.getText().toString();
String Password = etPassword.getText().toString();
Intent Main = new Intent(Login.this, MainActivity.class);
Main.putExtra("class", "Nanny");
Main.putExtra("username",Username);
Main.putExtra("password",Password);
startActivity(Main);
}
public class Authenticate extends AsyncTask<String, Void, String> {
private Context context;
public Authenticate(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String Username = arg0[0];
String Password = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?username=" + URLEncoder.encode(Username, "UTF-8");
data += "&password=" + URLEncoder.encode(Password, "UTF-8");
link = "http://juliusgoh.comxa.com/Authenticate.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return ("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
try {
JSONObject jsonObj = new JSONObject(result);
String query_result = jsonObj.getString("query_result");
switch (query_result) {
case "PSUCCESS":
Toast.makeText(context, "Login Successfully....Parent", Toast.LENGTH_SHORT).show();
ParentLogin();
break;
case "NSUCCESS":
Toast.makeText(context, "Login Successfully....Nanny", Toast.LENGTH_SHORT).show();
NannyLogin();
break;
case "FAILURE":
Toast.makeText(context, "Wrong Data. Login failed.", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
break;
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
Second Activity:
public class MainActivity extends AppCompatActivity {
public String job;
public String username;
public String password;
TextView qwe;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
qwe = (TextView)findViewById(R.id.asd);
Intent intent = new Intent();
String strValue = intent.getStringExtra("class");
String strValue1 = intent.getStringExtra("username");
String strValue2 = intent.getStringExtra("password");
qwe.setText(strValue);
}
The code is working fine but in the second activity it shows nothing. im guessing it pass "" null argument.But i have no idea how to solve it.Kindly provide some advise. TQ <3
i've found the solution to my question, my second activity should type Intent intent = getIntent(); instead of Intent intent = new Intent;
Related
I made the login and signup page in android. I want correct data enter in the login form and than its login but when i use incorrect username and password its still login and shows the error like this :- org.json.JSONException: No value for res_response because when i signup the page my data going on the server through url in the format of JSON object.
Registration.java
public class Registration extends Activity {
EditText username, email, password, mobile;
String url = "http://codexpertise.com/codexpertise.com/apitest/signup.php";
Button btnRegister;
ImageButton btnfb;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
username = (EditText) findViewById(R.id.editname);
email = (EditText) findViewById(R.id.editemail);
password = (EditText) findViewById(R.id.editpassword);
mobile = (EditText) findViewById(R.id.editmobile);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnfb = (ImageButton) findViewById(R.id.btnfb);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String name = username.getText().toString().trim();
final String emaill = email.getText().toString().trim();
final String passwordd = password.getText().toString().trim();
final String mobilee = mobile.getText().toString().trim();
compare_version();
Log.e("TAG","Message");
if (TextUtils.isEmpty(name)) {
username.setError("Please enter username");
username.requestFocus();
return;
}
if (TextUtils.isEmpty(emaill)) {
email.setError("Please enter your email");
email.requestFocus();
return;
}
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emaill).matches()) {
email.setError("Enter a valid email");
email.requestFocus();
return;
}
if (TextUtils.isEmpty(passwordd)) {
password.setError("Enter a password");
password.requestFocus();
return;
}
if (TextUtils.isEmpty(mobilee)) {
mobile.setError("Enter a mobile number");
mobile.requestFocus();
return;
}
}
});
btnfb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri uri = Uri.parse("https://www.facebook.com/"); // missing 'http://' will cause crashed
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
private void compare_version() {
JSONObject parameters = new JSONObject();
try {
parameters.put("type", "signup");
parameters.put("username", username.getText().toString());
parameters.put("email", email.getText().toString());
parameters.put("mobileno", mobile.getText().toString());
parameters.put("password", password.getText().toString());
} catch (JSONException e) {
}
JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST, url, parameters,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = response;
String resp_code = jsonObject.getString("resp_code");
String resp_msg = jsonObject.getString("res_response");
System.out.println("response version =====" + response);
resp_code = "200";
if (resp_code.compareTo("200") == 0) {
System.out.println("response msg==" + resp_msg);
Toast.makeText(Registration.this, "response msg==" + resp_msg, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
MyApplication.getInstance().addToRequestQueue(req);
}
}
Mainactivity.java (Its login)
public class MainActivity extends Activity {
public static HashMap<Sound, MediaPlayer> SOUND_MAP=
new HashMap<Sound, MediaPlayer>();
public static int userScore= 0, computerScore=0,
buddyBoxId = 1, computerBoxId = 1;
public static Context CTX;
Button play;
String url = "http://codexpertise.com/codexpertise.com/apitest/login.php";
ProgressDialog progressDialog;
TextView register_caption;
AdView adView = null;
private AdView mAdView;
EditText username, passwordd;
Button btnSignIn, btnRegister;
ImageView fb;
int i=0;
private AdRequest adRequest;
InterstitialAd mInterstitialAd;
static MediaPlayer media;
static Handler mediaHandler;
public static int stat=0, totTurn = 0, maxEnd = 100;
public static SharedPreferences configs;
public static SharedPreferences.Editor configuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.email);
passwordd = (EditText)findViewById(R.id.password);
btnSignIn = (Button) findViewById(R.id.play);
register_caption = (TextView) findViewById(R.id.register_caption);
fb = (ImageButton) findViewById(R.id.btnfb);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String name = username.getText().toString().trim();
final String pass = passwordd.getText().toString().trim();
compare_version();
Log.e("TAG","Message");
if (TextUtils.isEmpty(name)) {
username.setError("Please enter username");
username.requestFocus();
return;
}
if (TextUtils.isEmpty(pass)) {
passwordd.setError("Please enter your Password");
passwordd.requestFocus();
return;
}
else {
Intent i = new Intent(MainActivity.this,Userlist.class);
startActivity(i);
}
}
});
register_caption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(MainActivity.this,Registration.class);
startActivity(in);
}
});
CTX = getApplicationContext();
configs = CTX. getSharedPreferences("snake_n_ladder", 0);
configuration = configs.edit();
loadConfig();
loadMedia();
}
private void compare_version() {
JSONObject parameters = new JSONObject();
try {
parameters.put("type", "userlogin");
parameters.put("username", username.getText().toString());
parameters.put("password", passwordd.getText().toString());
} catch (JSONException e) {
}
JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST, url, parameters,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = response;
String resp_code = jsonObject.getString("resp_code");
String resp_msg = jsonObject.getString("res_response");
System.out.println("response version =====" +response);
resp_code = "200";
if (resp_code.compareTo("200") == 0) {
System.out.println("response msg=="+resp_msg);
Toast.makeText(MainActivity.this, "response msg=="+resp_msg, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
MyApplication.getInstance().addToRequestQueue(req);
}
Change this:
if (resp_code.compareTo("200") == 0) {
System.out.println("response msg==" + resp_msg);
Toast.makeText(Registration.this, "response msg==" + resp_msg, Toast.LENGTH_SHORT).show();
}
To:
if (resp_code.equals("200")) {
System.out.println("response msg==" + resp_msg);
Toast.makeText(Registration.this, "response msg==" + resp_msg, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Registration.this,"Donot Match",Toast.LENGTH_SHORT).show();
}
call compare_version() method in else condition
First you have to understand the different between the login success response and the login failed(on a wrong username password combination) response.
You are reading "res_response" value from your JSON response although it is not in your login failed response.
Also you did a mistake in your code by hard-coding resp_code = "200";
This question already has answers here:
How to use SharedPreferences in Android to store, fetch and edit values [closed]
(30 answers)
Closed 5 years ago.
hey guys so i got a login activity that checks username and password with server to authenticate users. i want to use sharedpermissions to store username and password so that the user wont have log in every time. i also want to create a login button.
i tried to implement it but itjust skips login acitivity and takes me to my second activity. i left some of sharedpermission codes as comments (//)
can anyone show/tell me the best i can do it?
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//String username = "";
//String password = "";
//SharedPreferences pre;
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final TextView tvRegisterLink = (TextView) findViewById(R.id.tvRegisterhere);
final Button bLogin = (Button) findViewById(R.id.bLogin);
if(TextUtils.isEmpty(etUsername.getText().toString())||TextUtils.isEmpty(etPassword.getText().toString())){
Intent intent = new Intent(LoginActivity.this, UserAreaActivity.class);
LoginActivity.this.startActivity(intent);
} else {
Intent registerIntent = new Intent(LoginActivity.this, LoginActivity.class);
LoginActivity.this.startActivity(registerIntent);
}
final String username1 = SharedPreferenceUtils.getUsername(this);
final String password1 = SharedPreferenceUtils.getPassword(this);
// pre = getSharedPreferences("pref",MODE_PRIVATE);
//if(pre.getBoolean("username",true) && pre.getBoolean("password",true)){
tvRegisterLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(registerIntent);
}
});
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String name = jsonResponse.getString("name");
SharedPreferenceUtils.createSP(LoginActivity.this,username1,password1);
Intent intent = new Intent(LoginActivity.this, UserAreaActivity.class);
intent.putExtra("name", name);
intent.putExtra("username", username);
LoginActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(username, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
}
}
public class UserAreaActivity extends AppCompatActivity {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
final TextView etusername = (TextView) findViewById(R.id.textView2);
final TextView etwelcome = (TextView) findViewById(R.id.textView);
final ImageButton red = (ImageButton) findViewById(R.id.imageButton);
final ImageButton messages = (ImageButton) findViewById(R.id.imageButton2);
final ImageButton blue = (ImageButton) findViewById(R.id.imageButton3);
final ImageButton ping = (ImageButton) findViewById(R.id.imageButton4);
final TextView etuname = (TextView) findViewById(R.id.textView3);
final Button Logout = (Button) findViewById(R.id.logout);
//String Name = SharedPreferenceUtils.getName(this);
//etwelcome.setText(Name);
red.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(UserAreaActivity.this, Report.class);
UserAreaActivity.this.startActivity(registerIntent);
}
});
messages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(UserAreaActivity.this, Messages.class);
UserAreaActivity.this.startActivity(registerIntent);
}
});
Logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isClear = SharedPreferenceUtils.clearSP(UserAreaActivity.this);
if(isClear){
Intent registerIntent = new Intent(UserAreaActivity.this, LoginActivity.class);
UserAreaActivity.this.startActivity(registerIntent);
}
}
});
Intent intent = getIntent();
String name = intent.getStringExtra("name");
String username = intent.getStringExtra("username");
String message = "Welcome " + name;
etwelcome.setText(message);
etusername.setText(username);
//Intent in = new Intent(getApplicationContext(), Messages.class);
//in.putExtra("username", username);
//UserAreaActivity.this.startActivity(in);
}
}
You can use SharedPreferences in your code .
Try this .
public class SharedPreferenceUtils {
private static final String SP_NAME = "sp";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
// create
public static boolean createSP(Context context, String username, String password) {
SharedPreferences.Editor editor = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE).edit();
editor.putString(USERNAME, username);
editor.putString(PASSWORD, password);
return editor.commit();
}
// clear
public static boolean clearSP(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
return editor.clear().commit();
}
// get access info
public static String getUsername(Context context) {
SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
return sp.getString(USERNAME, "");
}
// get branch info
public static String getPassword(Context context) {
SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
return sp.getString(PASSWORD, "");
}
}
Use in LoginActivity
SharedPreferenceUtils.createSP(this,username,password);
And use in other Activity
String username = SharedPreferenceUtils.getUsername(this);
String password = SharedPreferenceUtils.getPassword(this);
Edit
if (success) {
String name = jsonResponse.getString("name");
SharedPreferenceUtils.createSP(this, username, password);
}
Edit
private EditText etUsername, etPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
String username = SharedPreferenceUtils.getUsername(this);
String password = SharedPreferenceUtils.getPassword(this);
etUsername.setText(username);
etPassword.setText(password);
}
Edit
if(TextUtils.isEmpty(etUsername.getText().toString())||TextUtils.isEmpty(etPassword.getText().toString())){
Intent intent = new Intent(LoginActivity.this, A.class);
LoginActivity.this.startActivity(intent);
} else {
Intent registerIntent = new Intent(LoginActivity.this, B.class);
LoginActivity.this.startActivity(intent);
}
Edit
boolean isClear = SharedPreferenceUtils.clearSP(UserAreaActivity.this);
if(isClear){
Intent registerIntent = new Intent(UserAreaActivity.this, LoginActivity.class);
UserAreaActivity.this.startActivity(registerIntent);
}
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 7 years ago.
Helo guys,
I'm new at android programming, I'm trying to make login application connect to localhost mysql with android studio based on this web. Here is code:
Mainactivity.java
public class Mainmenu extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainmenu);
Button login=(Button)findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent login=new Intent(v.getContext(),Login.class);
startActivity(login);
}
});
Button register=(Button)findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent regis= new Intent(v.getContext(),Register.class);
startActivity(regis);
}
});
Button exit=(Button)findViewById(R.id.exit);
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
Login.java
public class Login extends ActionBarActivity {
final EditText id=(EditText)findViewById(R.id.handphone);
final EditText pass=(EditText)findViewById(R.id.pass_login);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
TextView login=(TextView)findViewById(R.id.textView);
login.setText("Login to Human Tracker");
Button log=(Button)findViewById(R.id.login);
log.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String password=pass.getText().toString();
String handphone=id.getText().toString();
if (!password.equals("") && !handphone.equals("")) {
Toast.makeText(getApplication(),"Your id or password is wrong",Toast.LENGTH_SHORT).show();
} else {
masuk();
Toast.makeText(getApplication(),"Welcome", Toast.LENGTH_SHORT).show();
Intent user = new Intent(v.getContext(), User.class);
startActivity(user);
}
}
});
}
private void masuk(){
SharedPreferences prefs;
String prefName ="report";
InputStream is=null;
String result=null;
String line=null;
JSONObject jArray= null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("hp",id.getText().toString()));
try {
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://10.0.0.2");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity=response.getEntity();
is=entity.getContent();
} catch (Exception e){
Log.e("Fail 1: Error in HTTP connection",e.toString());
Toast.makeText(getApplicationContext(),"Fail 1: Error in HTTP connection",Toast.LENGTH_SHORT).show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("Fail 2: Error converting result ", e.toString());
}
try
{
JSONObject jobject = new JSONObject(result);
String S_pwd = jobject.getString("pass");
String S_name = jobject.getString("name");
String S_id = jobject.getString("id");
if(S_pwd.equals(pass.getText().toString())) {
Toast.makeText(getBaseContext(), "Login Successfully",
Toast.LENGTH_SHORT).show();
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
//---save the values in the EditText view to preferences---
editor.putString("id", S_id);
editor.putString("name", S_name);
//---saves the values---
editor.commit();
Toast.makeText(getApplicationContext(),"Login success",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getBaseContext(), "Login Failure \n" +
"\n Try Again", Toast.LENGTH_LONG).show();
id.setText("");
pass.setText("");
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
Everything is okay, i can go to User.java before add that private void masuk. Then im debug my application and no error. But why when i press login button on main menu(to go Login.java) it say 'Unfortunately Login has stopped'?
this will not work:
public class Login extends ActionBarActivity {
final EditText id=(EditText)findViewById(R.id.handphone);
final EditText pass=(EditText)findViewById(R.id.pass_login);
first of all call setContentView.
After that assign the Gui elements:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
EditText id=(EditText)findViewById(R.id.handphone);
EditText pass=(EditText)findViewById(R.id.pass_login);
or if you need them as class members:
EditText id;
EditText pass;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
id=(EditText)findViewById(R.id.handphone);
pass=(EditText)findViewById(R.id.pass_login);
I am trying to develop a chat application with a login and registration. The app is working without any errors, when I register it adds the right information in SQLite but when i log in with those details the app says "Logging in" but nothing happens. Does anyone know what is wrong with my code?
LoginActivity.java
public class LoginActivity extends Activity {
// LogCat tag
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Check for empty data in the form
if (email.trim().length() > 0 && password.trim().length() > 0) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
MainActivity.java
public class MainActivity extends Activity
{
private TextView txtName;
private TextView txtEmail;
private Button btnLogout;
private SQLiteHandler db;
private SessionManager session;
public Socket sender;
public BufferedReader br;
public PrintStream bw;
class SocketListener implements Runnable
{
String str;
public void run()
{
try
{
sender = new Socket("127.0.0.1", 1234);
br = new BufferedReader (new InputStreamReader(sender.getInputStream()));
bw = new PrintStream (sender.getOutputStream());
bw.println("Connected");
while (true)
{
final TextView t = (TextView)findViewById(R.id.textView);
String s = br.readLine ();
CharSequence cs = t.getText ();
str = cs + "\r\n" + s;
Log.i("Chat-str:", str);
t.post(new Runnable()
{
public void run()
{
t.setText(str);
}
}
);
}
}
catch (IOException e)
{
Log.e(getClass().getName(), e.getMessage());
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtName = (TextView) findViewById(R.id.name);
txtEmail = (TextView) findViewById(R.id.email);
btnLogout = (Button) findViewById(R.id.btnLogout);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
String email = user.get("email");
// Displaying the user details on the screen
txtName.setText(name);
txtEmail.setText(email);
// Logout button click event
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logoutUser();
}
});
TextView tv = (TextView)findViewById(R.id.textView);
tv.setMovementMethod(new ScrollingMovementMethod());
Button send1 = (Button)findViewById(R.id.button);
send1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
final EditText et = (EditText)findViewById(R.id.editText);
Editable e = et.getText();
final String s = e.toString();
new Thread ()
{
public void run ()
{
bw.println (s);
}
}.start();
}
});
Thread t = new Thread (new SocketListener ());
t.start();
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
* */
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
it doesnt look like you ever log them in. look here
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Check for empty data in the form
if (email.trim().length() > 0 && password.trim().length() > 0) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
what is checkLogin(email, password);
and if it is returning a boolean you should be saying
if(checkLogin){
//log them in
}
can you post the checklogin code?
The reason is that ones i fill in my user name, and password and click login button it is loads again at page requires tu fill user name, and password here is my source code
public class MainActivity extends Activity {
private EditText mTextUserName;
private EditText mTextPassword;
public String user_name;
public String pass_word;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextUserName = (EditText) findViewById(R.id.textUserName);
mTextPassword = (EditText) findViewById(R.id.textPassword);
final Button mButtonLogin = (Button) findViewById(R.id.buttonLogin);
mButtonLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
user_name = mTextUserName.getText().toString();
pass_word = mTextPassword.getText().toString();
// i am passing this intent
Intent goToNextActivity = new Intent(getApplicationContext(), ViewActivity.class);
goToNextActivity.putExtra("username", user_name);
goToNextActivity.putExtra("password", pass_word);
startActivity(goToNextActivity);
}
});
}
and in mine ViewActivity also
public class ViewActivity extends Activity {
private WebView webView;
public String pass_word;
public String user_name;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setDefaultFontSize(20);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
//here i get them
getIntent().getStringExtra("username");
getIntent().getStringExtra("password");
webView.loadUrl("http://intranet.mdis.uz/");
}
but this doest works(( i spended 8 hours on research but nothing helped me
I think this line is wrong:
Intent goToNextActivity = new Intent(getApplicationContext(), ViewActivity.class);
you should not use ApplicationContext when you trying to start new activity. Try this:
Intent goToNextActivity = new Intent(MainActivity.this, ViewActivity.class);
EDIT:
Try this, it should send data via POST:
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setDefaultFontSize(20);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
String username = getIntent().getStringExtra("username");
String password = getIntent().getStringExtra("password");
String data = "username=" + username + "&password=" + password;
webView.postUrl("http://intranet.mdis.uz/", EncodingUtils.getBytes(data, "base64"));
Let me try it.
Do the modification like this once and see plz...
public class MainActivity extends Activity {
private EditText mTextUserName;
private EditText mTextPassword;
public String user_name;
public String pass_word;
ConnectionClass cc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextUserName = (EditText) findViewById(R.id.textUserName);
mTextPassword = (EditText) findViewById(R.id.textPassword);
cc=new ConnectionClass(this);
final Button mButtonLogin = (Button) findViewById(R.id.buttonLogin);
mButtonLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
user_name = mTextUserName.getText().toString();
pass_word = mTextPassword.getText().toString();
user_name=Uri.encode(user_name); // you can encode your parameters so that it does not throw exception for e.g it will replace a space as %20 otherwise if user enters special character error will come.. :)
pass_word=Uri.encode(pass_word); // same as above
String url="http://myserver.com/login.php?username="+user_name"&password="+user_name; // this is your server page url and passing username and password in plain url u can test it in browser to verify its working :)
new AsyncTask<String,Void,String>() // new android versions does not allow network operations on main thread but need to do asynchronously...
{
#Override
protected String doInBackground(String... params) {
return cc.getServerResponse(params[0]);
}
#Override
protected void onPostExecute(String result) { // this method runs on UI thread and is called when background process is done to make it more fancy u can use onPreExecute() to show a loader and dismiss the dialog here :)
super.onPostExecute(result);
if(result!=null)
{
if(result.equals("1") // assuming u r returning "1" if successful.
{
Toast.makeText(context, "Successful", 2000).show();
Intent goToNextActivity = new Intent(MainActivity.this, ViewActivity.class);
goToNextActivity.putExtra("username", user_name);
goToNextActivity.putExtra("password", pass_word);
startActivity(goToNextActivity);
}
}
else
Toast.makeText(context, "Network problem...", 2000).show();
}
}.execute(url);
}
}
});
}
Here is the ConnectionClass
public class ConnectionClass {
Context context;
public ConnectionClass(Context ctx) {
this.context=ctx;
}
public String getServerResponse(String urlLink)
{
try
{
HttpClient client = new DefaultHttpClient();
HttpPost http_get = new HttpPost(url);
HttpResponse responses;
responses = client.execute(http_get);
if (responses != null)
{
InputStream in = responses.getEntity().getContent();
String a = convertStreamToString(in);
// Log.i("RETURN",a+"");
return a;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
}
catch (Exception e)
{
//Toast.makeText(context, e.toString()+" io2", Toast.LENGTH_LONG).show();
}
finally
{
try
{
is.close();
}
catch (Exception e)
{
//Toast.makeText(context, e.toString()+" io3", Toast.LENGTH_LONG).show();
}
}
return sb.toString();
}
}
Hope it helps u :)
Thx