Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Hi this following code working properly, now i want know how can i add email validation when user register, and where to add those codes, if anyone knows please integrate with my codes (show me where to add those validation code)
package com.prinsapps.whatson;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.prinsapps.library.DatabaseHandler;
import com.prinsapps.library.UserFunctions;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Register extends Activity {
/**
* JSON Response node names.
**/
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_USERNAME = "uname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private static String KEY_ERROR = "error";
/**
* Defining layout items.
**/
EditText inputFirstName;
EditText inputLastName;
EditText inputUsername;
EditText inputEmail;
EditText inputPassword;
Button btnRegister;
TextView registerErrorMsg;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
/**
* Defining all layout items
**/
inputFirstName = (EditText) findViewById(R.id.fname);
inputLastName = (EditText) findViewById(R.id.lname);
inputUsername = (EditText) findViewById(R.id.uname);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.pword);
btnRegister = (Button) findViewById(R.id.register);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
/**
* Button which Switches back to the login screen on clicked
**/
Button login = (Button) findViewById(R.id.bktologin);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Login.class);
startActivityForResult(myIntent, 0);
finish();
}
});
/**
* Register Button click event.
* A Toast is set to alert when the fields are empty.
* Another toast is set to alert Username must be 5 characters.
**/
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ( ( !inputUsername.getText().toString().equals("")) &&
( !inputPassword.getText().toString().equals("")) &&
( !inputFirstName.getText().toString().equals("")) &&
( !inputLastName.getText().toString().equals("")) &&
( !inputEmail.getText().toString().equals("")) )
{
if ( inputUsername.getText().toString().length() > 4 ){
NetAsync(view);
}
else
{
Toast.makeText(getApplicationContext(),
"Username should be minimum 5 characters", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(),
"One or more fields are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Async Task to check whether internet connection is working
**/
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(Register.this);
nDialog.setMessage("Loading..");
nDialog.setTitle("Checking Network");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected Boolean doInBackground(String... args){
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessRegister().execute();
}
else{
nDialog.dismiss();
registerErrorMsg.setText("Error in Network Connection");
}
}
}
private class ProcessRegister extends AsyncTask<String, String, JSONObject> {
/**
* Defining Process dialog
**/
private ProgressDialog pDialog;
String email,password,fname,lname,uname;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputUsername = (EditText) findViewById(R.id.uname);
inputPassword = (EditText) findViewById(R.id.pword);
fname = inputFirstName.getText().toString();
lname = inputLastName.getText().toString();
email = inputEmail.getText().toString();
uname= inputUsername.getText().toString();
password = inputPassword.getText().toString();
pDialog = new ProgressDialog(Register.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Registering ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(fname, lname, email, uname, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
/**
* Checks for success message.
**/
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
String red = json.getString(KEY_ERROR);
if(Integer.parseInt(res) == 1){
pDialog.setTitle("Getting Data");
pDialog.setMessage("Loading Info");
registerErrorMsg.setText("Successfully Registered");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/**
* Removes all the previous data in the SQlite database
**/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/**
* Stores registered data in SQlite Database
* Launch Registered screen
**/
Intent registered = new Intent(getApplicationContext(), Registered.class);
/**
* Close all views before launching Registered screen
**/
registered.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(registered);
finish();
}
else if (Integer.parseInt(red) ==2){
pDialog.dismiss();
registerErrorMsg.setText("User already exists");
}
else if (Integer.parseInt(red) ==3){
pDialog.dismiss();
registerErrorMsg.setText("Invalid Email id");
}
}
else{
pDialog.dismiss();
registerErrorMsg.setText("Error occured in registration");
}
} catch (JSONException e) {
e.printStackTrace();
}
}}
public void NetAsync(View view){
new NetCheck().execute();
}}
Email address can be validated b using the regular expressions.
String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
For example :
public boolean isValidEmail(String email){
String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
return email.matches(EMAIL_PATTERN);
}
Add this method to your activity:
public final static boolean isValidEmail(String email) {
if (TextUtils.isEmpty(email)) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
}
And use it in your
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {...}});
method like this:
if(isValidEmail(inputEmail.getText().toString()){
//go ahead
} else {
//make toast for example
}
You can use below code which can be helpful for you:-
if(android.util.Patterns.EMAIL_ADDRESS.matcher(EMAIL).matches())
{
// Perform action which you want after vaild email id
}
else
{
Toast.makeText(CONTEXT, "Please enter vaild email id", Toast.LENGTH_LONG).show();
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
While creating the android app in user profile when user click on password edit text the pop should be displayed I have implemented it but when i click on edit text It is giving me the below error. I have googled it but not found any useful solution. Please can you tell I am attaching the code :
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:222)
at android.app.AlertDialog$Builder.(AlertDialog.java:452)
at com.example.admin.avisar.UserProfile$2.onClick(UserProfile.java:71)
at android.view.View.performClick(View.java:5612)
at android.view.View$PerformClick.run(View.java:22285)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
06-01 12:35:00.558 1563-5452/? E/ActivityManager: Sending non-protected broadcast com.motorola.motocare.INTENT_TRIGGER from system 4237:com.motorola.process.system/1000 pkg com.motorola.motgeofencesvc
java.lang.Throwable
at com.android.server.am.ActivityManagerService.broadcastIntentLocked(ActivityManagerService.java:18226)
at com.android.server.am.ActivityManagerService.broadcastIntent(ActivityManagerService.java:18826)
at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:512)
at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:2906)
at android.os.Binder.execTransact(Binder.java:565)
code here
package com.example.admin.avisar;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.admin.avisar.network.CompletionListener;
import com.example.admin.avisar.network.NetworkTask;
import com.example.admin.avisar.network.Post_URL;
import com.example.admin.avisar.network.Responce;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class UserProfile extends AppCompatActivity implements CompletionListener{
EditText name,mobno,email,add,accid,pass,yeared;
Button svebtn;
ProgressDialog progressDialog;
private NetworkTask networkTask;
Context context;
String uid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("My Profile");
actionBar.setDisplayHomeAsUpEnabled(true);
name = (EditText)findViewById(R.id.name);
mobno = (EditText)findViewById(R.id.mobno);
email = (EditText)findViewById(R.id.email);
add = (EditText)findViewById(R.id.add);
accid = (EditText)findViewById(R.id.id);
pass = (EditText)findViewById(R.id.pass);
yeared = (EditText)findViewById(R.id.year);
svebtn = (Button)findViewById(R.id.svebtn);
userProfileWebService();
svebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
userProfileUpdate();
}
});
pass.setOnClickListener(new View.OnClickListener() {
String newpass="";
String confirmpass="";
#Override
public void onClick(View view) {
AlertDialog.Builder alert = new AlertDialog.Builder(UserProfile.this);
alert.setTitle("change password"); //Set Alert dialog title here
final EditText newpassed = new EditText(context);
newpassed.setHint("New password");
alert.setView(newpassed);
final EditText confirmpassed = new EditText(context);
confirmpassed.setHint("Confirm password");
alert.setView(confirmpassed);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if(newpassed.length()==0){
newpassed.requestFocus();
newpassed.setError("FIELD CANNOT BE EMPTY");
newpass = confirmpassed.getEditableText().toString();
}else if (confirmpassed.length()==0) {
confirmpassed.requestFocus();
confirmpassed.setError("FIELD CANNOT BE EMPTY");
confirmpass = confirmpassed.getEditableText().toString();
}else if(confirmpass==newpass){
passwordwebservice(newpassed);
}else{
confirmpassed.setError("confirm password doesnot match");
}
// Toast.makeText(context, srt, Toast.LENGTH_LONG).show();
} // End of onClick(DialogInterface dialog, int whichButton)
}); //End of alert.setPositiveButton
alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
dialog.cancel();
}
}); //End of alert.setNegativeButton
AlertDialog alertDialog = alert.create();
alertDialog.show();
}
});
}
private void passwordwebservice(EditText newpassed){
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setProgress(0);
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
networkTask = new NetworkTask(this,this,false);
String newpass = newpassed.getEditableText().toString();
List<NameValuePair> params =new ArrayList<>();
params.add(new BasicNameValuePair("userid",uid));
params.add(new BasicNameValuePair("password",newpass));
params.add(new BasicNameValuePair("userid",uid));
networkTask.execute(params, Post_URL.URL_update_password, 3);
}
//userprofile view webservice
private void userProfileWebService(){
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setProgress(0);
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
networkTask = new NetworkTask(this,this,false);
List<NameValuePair> params =getRequestParams();
networkTask.execute(params, Post_URL.URL_Profile, 1);
}
//parameter passing for userprofile webservice
private List<NameValuePair> getRequestParams() {
SharedPreferences sharedPreferences = getSharedPreferences("A", Context.MODE_PRIVATE);
uid = sharedPreferences.getString("user_id","abc");
Log.e("TAG",uid);
List<NameValuePair> param1 = new ArrayList<NameValuePair>();
param1.add(new BasicNameValuePair("userid", uid));
return param1;
}
private void userProfileUpdate(){
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setProgress(0);
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
networkTask = new NetworkTask(this,this,false);
List<NameValuePair> params =getRequestParamsupdate();
networkTask.execute(params, Post_URL.URL_update_profile, 2);
}
private List<NameValuePair> getRequestParamsupdate(){
String username = name.getText().toString();
String mno = mobno.getText().toString();
String mail = email.getText().toString();
String address = add.getText().toString();
String accout_id = accid.getText().toString();
// String password= pass.getText().toString();
String yearString = yeared.getText().toString();
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("username",username));
pairs.add(new BasicNameValuePair("mobno",mno));
pairs.add(new BasicNameValuePair("email",mail));
pairs.add(new BasicNameValuePair("add",address));
pairs.add(new BasicNameValuePair("userid",accout_id));
// pairs.add(new BasicNameValuePair("password",password));
pairs.add(new BasicNameValuePair("year",yearString));
return pairs;
}
//user profile response handle
private void handleUserProfileResponse(JSONObject serverResponse){
int success=0;
try{
success = serverResponse.getInt(Responce.TAG_SUCCESS);
if(success==1){
progressDialog.dismiss();
//parsing the data
JSONArray user_profile = serverResponse.getJSONArray("user_details");
for(int i =0 ;i<user_profile.length();i++){
String name1 = user_profile.getJSONObject(i).getString("username");
String mno = user_profile.getJSONObject(i).getString("mobno");
//Log.e("TAG",name1);
String mail = user_profile.getJSONObject(i).getString("email");
String address = user_profile.getJSONObject(i).getString("add");
String accountid = user_profile.getJSONObject(i).getString("userid");
String password = user_profile.getJSONObject(i).getString("password");
String year = user_profile.getJSONObject(i).getString("year");
//set data to textview
name.setText(name1);
mobno.setText(mno);
email.setText(mail);
add.setText(address);
accid.setText(accountid);
pass.setText(password);
yeared.setText(year);
}
}
else{
progressDialog.dismiss();
Toast.makeText(UserProfile.this, serverResponse.getString(Responce.TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
}catch (JSONException e){
}
}
private void handleUserProfileUpdateResponse(JSONObject serverResponse){
int success =0;
try{
success = serverResponse.getInt(Responce.TAG_SUCCESS);
if (success ==1){
progressDialog.dismiss();
Toast.makeText(UserProfile.this, serverResponse.getString(Responce.TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
else{
progressDialog.dismiss();
Toast.makeText(UserProfile.this, serverResponse.getString(Responce.TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
}catch(JSONException e)
{
}
}
private void handleUpdatePassResponse(JSONObject serverResponse){
int success =0;
try{
success = serverResponse.getInt(Responce.TAG_SUCCESS);
if (success ==1){
progressDialog.dismiss();
Toast.makeText(UserProfile.this, serverResponse.getString(Responce.TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
else{
progressDialog.dismiss();
Toast.makeText(UserProfile.this, serverResponse.getString(Responce.TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
}catch(JSONException e)
{
}
}
#Override
public void onComplete(JSONObject serverResponse, int RESPONSE_IDENTIFIER_FLAG) throws JSONException {
switch (RESPONSE_IDENTIFIER_FLAG){
case 1:handleUserProfileResponse(serverResponse);
break;
case 2: handleUserProfileUpdateResponse(serverResponse);
break;
case 3:handleUpdatePassResponse(serverResponse);
default:
break;
}
}
}
Pass activity instead of context in following line :
AlertDialog.Builder alert = new AlertDialog.Builder(context);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have a Null Pointer Exception android at line
** if (json.getString(KEY_SUCCESS) != null) {
public class Register extends Activity {
/**
* JSON Response node names.
**/
#Override
public void onBackPressed() {
Intent bkr = new Intent(this,Login.class);
startActivity(bkr);
this.finish();
}
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_USERNAME = "uname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private static String KEY_ERROR = "error";
/**
* Defining layout items.
**/
EditText inputFirstName;
EditText inputLastName;
EditText inputUsername;
EditText inputEmail;
EditText inputPassword;
EditText reinputPassword;
Button btnRegister;
TextView registerErrorMsg;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
/**
* Defining all layout items
**/
inputFirstName = (EditText) findViewById(R.id.fname);
inputLastName = (EditText) findViewById(R.id.lname);
inputUsername = (EditText) findViewById(R.id.uname);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.pword);
reinputPassword = (EditText) findViewById(R.id.rpword);
btnRegister = (Button) findViewById(R.id.register);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
/**
* Button which Switches back to the login screen on clicked
**/
Button login = (Button) findViewById(R.id.bktologin);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Login.class);
startActivityForResult(myIntent, 0);
finish();
}
});
/**
* Register Button click event.
* A Toast is set to alert when the fields are empty.
* Another toast is set to alert Username must be 5 characters.
**/
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ( ( !inputUsername.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) && ( !inputFirstName.getText().toString().equals("")) && ( !inputLastName.getText().toString().equals("")) && ( !inputEmail.getText().toString().equals("")) )
{
if ( inputUsername.getText().toString().length() > 4 )
{
if(inputPassword.getText().toString().equals(reinputPassword.getText().toString()))
NetAsync(view);
else
{
Toast.makeText(getApplicationContext(),
"Passwords Don't Match, Re-Enter Passwords Carefully", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(),
"Username should be minimum 5 characters", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(),
"One or more fields are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Async Task to check whether internet connection is working
**/
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(Register.this);
nDialog.setMessage("Loading..");
nDialog.setTitle("Checking Network");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected Boolean doInBackground(String... args){
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessRegister().execute();
}
else{
nDialog.dismiss();
registerErrorMsg.setText("Error in Network Connection");
}
}
}
private class ProcessRegister extends AsyncTask<String,String,JSONObject> {
/**
* Defining Process dialog
**/
private ProgressDialog pDialog;
String email,password,fname,lname,uname;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputUsername = (EditText) findViewById(R.id.uname);
inputPassword = (EditText) findViewById(R.id.pword);
fname = inputFirstName.getText().toString();
lname = inputLastName.getText().toString();
email = inputEmail.getText().toString();
uname= inputUsername.getText().toString();
password = inputPassword.getText().toString();
pDialog = new ProgressDialog(Register.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Registering ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(fname, lname, email, uname, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
/**
* Checks for success message.
**/
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
String red = json.getString(KEY_ERROR);
if(Integer.parseInt(res) == 1){
pDialog.setTitle("Getting Data");
pDialog.setMessage("Loading Info");
registerErrorMsg.setText("Successfully Registered");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/**
* Removes all the previous data in the SQlite database
**/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/**
* Stores registered data in SQlite Database
* Launch Registered screen
**/
Intent registered = new Intent(getApplicationContext(), Registered.class);
/**
* Close all views before launching Registered screen
**/
registered.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(registered);
finish();
}
else if (Integer.parseInt(red) ==2){
pDialog.dismiss();
registerErrorMsg.setText("User already exists");
}
else if (Integer.parseInt(red) ==3){
pDialog.dismiss();
registerErrorMsg.setText("Invalid Email id");
}
}
else{
pDialog.dismiss();
registerErrorMsg.setText("Error occured in registration");
}
} catch (JSONException e) {
e.printStackTrace();
}
}}
public void NetAsync(View view){
new NetCheck().execute();
}}
NullPointerException on this line means that your json object is equal to null.
So u need to check if this doesn't equal to null before trying to get some value from it.
Whenever I try to login, register, change password or reset password the app just says "Error In Network Connection".
I am using strong internet connection, could you please advise as I have tried to on WI-FI and 4G, however it still says the same error. I am using WAMP server to connect to phpMyAdmin database. Please could you help and advise.
Login. Java File
public class Login extends Activity {
Button BtnLogin;
Button Btnregister;
Button passreset;
EditText inputEmail;
EditText inputPassword;
private TextView loginErrorMsg;
/**
* Called when the activity is first created.
*/
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_USERNAME = "uname";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
#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.pword);
Btnregister = (Button) findViewById(R.id.registerbtn);
BtnLogin = (Button) findViewById(R.id.loginbtn);
passreset = (Button) findViewById(R.id.passres);
loginErrorMsg = (TextView) findViewById(R.id.loginErrorMsg);
passreset.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), PasswordReset.class);
startActivityForResult(myIntent, 0);
finish();
}});
Btnregister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Register.class);
startActivityForResult(myIntent, 0);
finish();
}});
/**
* Login button click event
* A Toast is set to alert when the Email and Password field is empty
**/
BtnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if ((!inputEmail.getText().toString().equals("")) && (!inputPassword.getText().toString().equals(""))) {
NetAsync(view);
} else if ((!inputEmail.getText().toString().equals(""))) {
Toast.makeText(getApplicationContext(),
"Password field empty", Toast.LENGTH_SHORT).show();
} else if ((!inputPassword.getText().toString().equals(""))) {
Toast.makeText(getApplicationContext(),
"Email field empty", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Email and Password field are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Async Task to check whether internet connection is working.
**/
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(Login.this);
nDialog.setTitle("Checking Network");
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
#Override
protected Boolean doInBackground(String... args){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessLogin().execute();
}
else{
nDialog.dismiss();
loginErrorMsg.setText("Error in Network Connection");
}
}
}
/**
* Async Task to get and send data to My Sql database through JSON respone.
**/
private class ProcessLogin extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String email,password;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.pword);
email = inputEmail.getText().toString();
password = inputPassword.getText().toString();
pDialog = new ProgressDialog(Login.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Logging in ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
pDialog.setMessage("Loading User Space");
pDialog.setTitle("Getting Data");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/**
* Clear all previous data in SQlite database.
**/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/**
*If JSON array details are stored in SQlite it launches the User Panel.
**/
Intent upanel = new Intent(getApplicationContext(), Main.class);
upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(upanel);
/**
* Close Login Screen
**/
finish();
}else{
pDialog.dismiss();
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public void NetAsync(View view){
new NetCheck().execute();
}
}
Register.java File
public class Register extends Activity {
/**
* JSON Response node names.
**/
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_USERNAME = "uname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private static String KEY_ERROR = "error";
/**
* Defining layout items.
**/
EditText inputFirstName;
EditText inputLastName;
EditText inputUsername;
EditText inputEmail;
EditText inputPassword;
Button btnRegister;
TextView registerErrorMsg;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
/**
* Defining all layout items
**/
inputFirstName = (EditText) findViewById(R.id.fname);
inputLastName = (EditText) findViewById(R.id.lname);
inputUsername = (EditText) findViewById(R.id.uname);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.pword);
btnRegister = (Button) findViewById(R.id.register);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
/**
* Button which Switches back to the login screen on clicked
**/
Button login = (Button) findViewById(R.id.bktologin);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Login.class);
startActivityForResult(myIntent, 0);
finish();
}
});
/**
* Register Button click event.
* A Toast is set to alert when the fields are empty.
* Another toast is set to alert Username must be 5 characters.
**/
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ( ( !inputUsername.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) && ( !inputFirstName.getText().toString().equals("")) && ( !inputLastName.getText().toString().equals("")) && ( !inputEmail.getText().toString().equals("")) )
{
if ( inputUsername.getText().toString().length() > 4 ){
NetAsync(view);
}
else
{
Toast.makeText(getApplicationContext(),
"Username should be minimum 5 characters", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(),
"One or more fields are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Async Task to check whether internet connection is working
**/
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(Register.this);
nDialog.setMessage("Loading..");
nDialog.setTitle("Checking Network");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected Boolean doInBackground(String... args){
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessRegister().execute();
}
else{
nDialog.dismiss();
registerErrorMsg.setText("Error in Network Connection");
}
}
}
private class ProcessRegister extends AsyncTask<String, String, JSONObject> {
/**
* Defining Process dialog
**/
private ProgressDialog pDialog;
String email,password,fname,lname,uname;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputUsername = (EditText) findViewById(R.id.uname);
inputPassword = (EditText) findViewById(R.id.pword);
fname = inputFirstName.getText().toString();
lname = inputLastName.getText().toString();
email = inputEmail.getText().toString();
uname= inputUsername.getText().toString();
password = inputPassword.getText().toString();
pDialog = new ProgressDialog(Register.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Registering ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(fname, lname, email, uname, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
/**
* Checks for success message.
**/
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
String red = json.getString(KEY_ERROR);
if(Integer.parseInt(res) == 1){
pDialog.setTitle("Getting Data");
pDialog.setMessage("Loading Info");
registerErrorMsg.setText("Successfully Registered");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/**
* Removes all the previous data in the SQlite database
**/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/**
* Stores registered data in SQlite Database
* Launch Registered screen
**/
Intent registered = new Intent(getApplicationContext(), Registered.class);
/**
* Close all views before launching Registered screen
**/
registered.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(registered);
finish();
}
else if (Integer.parseInt(red) ==2){
pDialog.dismiss();
registerErrorMsg.setText("User already exists");
}
else if (Integer.parseInt(red) ==3){
pDialog.dismiss();
registerErrorMsg.setText("Invalid Email id");
}
}
else{
pDialog.dismiss();
registerErrorMsg.setText("Error occured in registration");
}
} catch (JSONException e) {
e.printStackTrace();
}
}}
public void NetAsync(View view){
new NetCheck().execute();
}}
Manifest.java File
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.brad.visor" >
<application
android:icon="#mipmap/logo"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Login">
</activity>
<activity
android:name=".Register">
</activity>
<activity
android:name=".Registered">
</activity>
<activity
android:name=".Main">
</activity>
<activity
android:name=".PasswordReset">
</activity>
<activity
android:name=".ChangePassword">
</activity>
</application>
<!-- Allow to connect with internet and to know the current network state-->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
I think the problem is somewhere in the doInBackground method.
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
Log.i("code",urlc.getResponseCode() );
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I'm trying to do a log in an app that connects with phpmyadmin. When I start the app I get an exception.
This is my code:
public class MainActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText fname;
EditText lname;
EditText username;
EditText password;
EditText location;
EditText contact;
Button btnreg;
Button btncancel;
// url to create new product
private static String url_new_user = "http://192.168.0.1XX/android_test/newUser.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Edit Text
fname = (EditText) findViewById(R.id.fname);
lname = (EditText) findViewById(R.id.lname);
username = (EditText) findViewById(R.id.uname);
password = (EditText) findViewById(R.id.pass);
location = (EditText) findViewById(R.id.addr);
contact = (EditText) findViewById(R.id.contact);
// Create button
btnreg = (Button) findViewById(R.id.btnreg);
btncancel = (Button) findViewById(R.id.btncancel);
// button click event
btnreg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
btncancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Registering New User..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String Firstname = fname.getText().toString();
String Lastname = lname.getText().toString();
String Username = username.getText().toString();
String Password = password.getText().toString();
String Address = location.getText().toString();
String Contact = contact.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("fname", Firstname));
params.add(new BasicNameValuePair("lname", Lastname));
params.add(new BasicNameValuePair("username", Username));
params.add(new BasicNameValuePair("password", Password));
params.add(new BasicNameValuePair("location", Address));
params.add(new BasicNameValuePair("contact", Contact));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_new_user,
"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created a user
Intent i = new Intent(getApplicationContext(), RegActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create user
Log.d("failed to create user", json.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
and this is the logcat:
08-25 16:48:30.499: E/JSON Parser(1410): Error parsing data org.json.JSONException: Value
Change to:
protected String doInBackground(String... args) {
...
if (success == 1) {
return "hooray";
}
...
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
if (file_url != null) {
// successfully created a user
Intent i = new Intent(getApplicationContext(), RegActivity.class);
startActivity(i);
// closing this screen
finish();
}
}
I'm trying to develop my first app, but i need help with something.
So, to access into my app, you have to Log-in writing your own username and password.
My app has a sliding menu on the left, i use the jfeinstein10 library.
Now, i want that in the first row of this menu was dysplayed the username of the user, so you understand that this is a dynamic string.
This is the .xml code of my row:
<item name="list_item_municipio_id" type="slidingmenu" />
<item name="list_item_municipio_label" type="slidingmenu">"Municipio"</item>
<item name="list_item_municipio_icon " type="slidingmenu">"#drawable/iconamunicipio"</item>
Now it is displayed "municipio" with <item name="list_item_municipio_label".
I read that strings are static, and that a possible solution is using SharedPreferences.
Can you give me an example? Because i don't understand how to store the username to a SharedPreferences.
This is the code of the login.java:
package com.baruckis.SlidingMenuImplementation;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends Activity implements OnClickListener{
public static final String PREFS_NAME = "LoginPrefs";
private EditText user, pass;
private Button mSubmit, mRegister;
private ProgressDialog pDialog;
// Attivo una connessione JSON
JSONParser jsonParser = new JSONParser();
//Collego un file php sul mio server
private static final String LOGIN_URL = "http://provasitosaronno.dnshosting.it/php/login.php";
//JSON gestisce le risposte fornite dallo script php
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getString("logged", "").toString().equals("logged")) {
Intent i = new Intent(Login.this, SlidingMenuFromClassActivity.class);
finish();
startActivity(i);
}
//Imposto le due variabili user e pass
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
//Collego i due pulsanti del login e del register
mSubmit = (Button)findViewById(R.id.login);
mRegister = (Button)findViewById(R.id.register);
//Aggiungo la funzione del clicklistener
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
case R.id.register:
Intent i = new Intent(this, Register.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Accesso in corso...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
//Aggiungo i parametri generati dalle variabili
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// Ottengo i risultati dalla connessione http
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
//Aspetto una risposta da JSON
Log.d("Login attempt", json.toString());
//Se il tutto avviene...
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("logged", "logged");
editor.commit();
Log.d("Login Successful!", json.toString());
Intent i = new Intent(Login.this, SlidingMenuFromClassActivity.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
//funzione dismiss
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
Below is a code how you can save information to SharedPreference.
SharedPreferences settings = this.getActivity().getSharedPreferences("MyApp", 0);
SharedPreferences.Editor editor = settings.edit();
String user = "foobar";
editor.putString("user", user);
editor.commit();