Intent not passes my to my second Activity - java

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

Related

Retrieve data from database to my app (NOT WORKING)

so i am trying to retrieve data stored in my database.
basically the user inputs a car registration number and a rating (between 1-5)and click button. once the button is clicked my code will execute. which gets text from both editext and send to my server. i have php file saved, which will check if the carregistration number matches the value in the databse. if it matches retrieve the current rating stored in the database. the value is then showed on another acitivity. The php file works fine. i tried by inserting value manually. the problem i have is that when the button is clicked nothign happens. i have used this code to retrieve user name and other details on another app.
dataretrieve.java
public class DataRetrieve extends StringRequest {
private static final String REGISTER_REQUEST_URL = "https://dipteran-thin.000webhostapp.com/Login1.php";
private Map<String, String> params;
public DataRetrieve (String carreg, int rating, Response.Listener<String> listener) {
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("carreg", carreg);
params.put("rating", rating + "");
}
#Override
public Map<String, String> getParams() {
return params;
}
}
Profile.java (where the user inputs carreg and rating)
public class Profile extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
final EditText editText = (EditText) findViewById(R.id.carreg);
final EditText editText1 = (EditText) findViewById(R.id.editText3);
Button button = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String carreg = editText.getText().toString();
final int rating = Integer.parseInt(editText1.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) {
int rating = jsonResponse.getInt("rating");
Intent intent = new Intent(Profile.this, UserAreaActivity.class);
intent.putExtra("rating", rating);
Profile.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
DataRetrieve loginRequest = new DataRetrieve(carreg, rating, responseListener);
RequestQueue queue = Volley.newRequestQueue(Profile.this);
queue.add(loginRequest);
}});
}
}
userareaactivity.java (where value is shown when retrieved)
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 TextView etuname = (TextView) findViewById(R.id.textView3);
final Button Logout = (Button) findViewById(R.id.logout);
//String Name = SharedPreferenceUtils.getName(this);
//etwelcome.setText(Name);
Intent intent = getIntent();
username = intent.getIntExtra("rating", -1);
etusername.setText(username + "");
//Intent in = new Intent(getApplicationContext(), Messages.class);
//in.putExtra("username", username);
//UserAreaActivity.this.startActivity(in);
}
#Override
public void onBackPressed(){
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
Intent intent = new Intent(UserAreaActivity.this, Messages.class);
UserAreaActivity.this.startActivity(intent);
}
return true;
}
I'm getting an error from your php page:
<b>Parse error</b>: syntax error, unexpected ']' in <b>/storage/ssd1/526/2972526/public_html/Login1.php</b> on line <b>8</b><br />
You can see the output of your response in the log by using this line above your JSON parsing (before it throws the exception)
Log.d("Response", response.toString());
I copied your success block into the exception block and it works as expected, so that code is valid. I would also put some kind of alert in the catch to let you know the failure happened when you're done testing.
Side note, change your parameter line to this...it's cleaner:
params.put("rating", String.valueOf(rating));

app crashing when trying to connect Internet

I am working with android studio and whenever I try to connect to internet it show Dialog that "Unfortunately 'app name' stopped" and then if crashes.
I have updated the manifest file for permission as well. please provide any assistance, It might helpful.
Here is the code:
public class Login extends Activity {
TextView msg;
String user,pass;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final EditText password;
TextView regLabel;
Button loginbt;
final EditText username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
regLabel = (TextView) findViewById(R.id.register_label);
msg = (TextView) findViewById(R.id.alert);
regLabel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent register_form = new Intent(Login.this,Register.class);
startActivity(register_form);
}
});
loginbt = (Button) findViewById(R.id.login);
loginbt.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
user = username.getText().toString();
pass = password.getText().toString();
if(user.length()>0 && pass.length()>0) {
try {
new LoginProcess().execute("http://url.com");
} catch (Exception le) {
msg.setText("Error:" + le);
}
}else{
msg.setText("Please Enter Username and Password!");
}
}
});
}
public class LoginProcess extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(Login.this);
protected void onPreExecute(){
Dialog.setMessage("Checking Authentication..");
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
if (Error != null) {
msg.setText("Error in Login: " + Error);
} else {
try {
JSONObject jsonObj = new JSONObject(Content);
String orgPass = jsonObj.getString("password");
if (orgPass.equals(pass)) {
Intent rp = new Intent(Login.this, Menu.class);
startActivity(rp);
finish();
} else {
msg.setText("Wrong Password");
}
} catch (Exception je) {
msg.setText("Error:" + je);
}
}
}
}
}

Android Studio:PutExtra & GetStringExtra With Online Database (no value)

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;

Aplication unfortunately close but no code error - Java android [duplicate]

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);

Android login app not logging user in

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?

Categories

Resources