Fatal exception AsyncTask connection to phpmyadmin - java

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

Related

How to pass data from android application to server via Web API?

I created application to pass data from android device to web API.
1.As a first step user should login and if he is valid user application save the token value.
2.Then go to add product interface. In that interface user can add new products to the server.
3.To do this task user should pass token value to the header field at the API.
4.Other details into body field at the API.
This is my login activity
public class LoginActivity extends Activity {
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;
private SQLiteHandler db;
#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);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// 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().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty()) {
// 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(),
RegisterInfo.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_LOGIN, 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");
//String token = jObj.getString("token");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
} 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();
// Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
// Launch main activity
String token=e.getMessage();
new Sharedpreference(token);
Intent intent = new Intent(LoginActivity.this,
Product_Dashboard.class);
startActivity(intent);
finish();
}
}
}, 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("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();
}
This is my product activity
public class MainActivity extends Activity {
private EditText productName;
private EditText Category;
private EditText Description;
private EditText UnitPrice;
private EditText from;
private EditText to;
private EditText Quty;
RadioGroup priceoption;
RadioGroup Quantityoption;
Button Addproductbtn;
public static final String PREFS_NAME = "AOP_PREFS";
public final String PREFS_KEY = "AOP_PREFS_String";
private String Aceept = "#'application/vnd.fxhello.v1+json'";
private String token1;
private String Authontication = "Bearer$" +token1;
//--READ data
// String token = preferences.getString("var1", 0);
String price1 = "TRUE";
String qtySelect1 = "TRUE";
private String service1 = "";
private String limitedQty1 = "";
private String lqty1 = "";
public String getValue(Context context) {
SharedPreferences settings;
String text;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); //1
text = settings.getString(PREFS_KEY, null); //2
token1=text;
return text;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
productName = (EditText) findViewById(R.id.productnameeditText);
Category = (EditText) findViewById(R.id.CategoryeditText);
Description = (EditText) findViewById(R.id.DescriptioneditText);
UnitPrice = (EditText) findViewById(R.id.UnitPriceeditText);
from = (EditText) findViewById(R.id.FromeditText);
to = (EditText) findViewById(R.id.ToeditText);
Quty = (EditText) findViewById(R.id.EnterquantityeditText);
priceoption = (RadioGroup) findViewById(R.id.priceoption);
Quantityoption = (RadioGroup) findViewById(R.id.Quantityoption);
Addproductbtn =(Button)findViewById(R.id.AddNewProductbtn);
Addproductbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String price = price1.toString();
String unit_price = UnitPrice.getText().toString();
String up = unit_price.toString();
String price_range_from = from.getText().toString();
String prf = price_range_from.toString();
String price_range_to = to.getText().toString();
String prt = price_range_to.toString();
String product_name = productName.getText().toString();
String pn = product_name.toString();
String category = Category.getText().toString();
String ct = category.toString();
String description = Description.getText().toString();
String des = description.toString();
String qtySelect = qtySelect1.toString();
String qty = Quty.toString();
String service = service1.toString();
String limitedQty = limitedQty1.toString();
String lmtq = limitedQty.toString();
String lqty = lqty1.toString();
insertToDatabase(price, up, prf, prt, pn, ct, des, qty, service, lmtq, lqty);
Toast.makeText(getApplicationContext(), "New Product Added!", Toast.LENGTH_SHORT).show();
finish();
}
});
}
private void insertToDatabase(String price, String up, String prf, String prt, String pn, String ct, String des, String qty, String service, String lmtq, String lqty) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String paraprice = params[0];
String paraunit_price = params[1];
String paraprice_range_from = params[2];
String paraprice_range_to = params[3];
String paraproduct_name = params[4];
String paracategory = params[5];
String paraDescription = params[6];
String paraqtySelect = params[7];
String paraqty = params[8];
String paraservice = params[10];
String paralimitedQty = params[11];
String paralqty = params[12];
String price = price1.toString();
String Up = up.toString();
String Prf = prf.toString();
String Prt = prt.toString();
String Pn = pn.toString();
String Ct = ct.toString();
String Des = des.toString();
String qtySelect = qtySelect1.toString();
String Lmtq = lmtq.toString();
String service = service1.toString();
String limitedQty = limitedQty1.toString();
String lqty = lqty1.toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("price", price));
nameValuePairs.add(new BasicNameValuePair("unit_price", Up));
nameValuePairs.add(new BasicNameValuePair("price_range_from", Prf));
nameValuePairs.add(new BasicNameValuePair("price_range_to", Prt));
nameValuePairs.add(new BasicNameValuePair("product_name", Pn));
nameValuePairs.add(new BasicNameValuePair("category", Ct));
nameValuePairs.add(new BasicNameValuePair("description", Des));
nameValuePairs.add(new BasicNameValuePair("qtySelect", qtySelect));
nameValuePairs.add(new BasicNameValuePair("lmtq", lmtq));
nameValuePairs.add(new BasicNameValuePair("service", service));
nameValuePairs.add(new BasicNameValuePair("limitedQty", limitedQty));
nameValuePairs.add(new BasicNameValuePair("lqty", lqty));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://uat.fxhello.com/api/seller/productCreate");
httpPost.setHeader("Accept", Aceept);
httpPost.setHeader("Authorization",Authontication);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(price, up, prf, prt, pn, ct, des, qty, service, lmtq, lqty);
}
}
I got this error
FATAL EXCEPTION: AsyncTask #3
Process: com.example.official2.xoxo, PID: 2364
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=11; index=11
at com.example.official2.xoxo.MainActivity$1SendPostReqAsyncTask.doInBackground(MainActivity.java:143)
at com.example.official2.xoxo.MainActivity$1SendPostReqAsyncTask.doInBackground(MainActivity.java:131)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 
12-15 10:09:11.859 2364-2379/com.example.official2.xoxo E/EGL_emulation: tid 2379: eglSurfaceAttrib(1165): error 0x3009 (EGL_BAD_MATCH)

null pointer exception android JSONobject [duplicate]

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.

Running android studio app on physical device "ERROR IN NETWORK CONNECTION"

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

AsyncTask not completing as expected [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I have a CreateUser class which creates a user. This worked correctly until I tried to add a new field for a password check.
In the task I'm checking to see if the password fields match and if they dont I cancel the execution and move to a toast.
It correctly checks the passwords and toasts when incorrect but if they match it still cancels execution and never completes creating a new user.
CODE:
public class Register extends Activity implements OnClickListener{
private EditText user, pass, confirmPass;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "https://xxx.xxx.xxx.xxx/xxx.php";
//ids
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.register);
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
confirmPass = (EditText)findViewById(R.id.passwordConfirm);
mRegister = (Button)findViewById(R.id.register);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage("Creating User...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
String passwordCheck = confirmPass.getText().toString();
try {
//-----------------------------------------------------------------------------Password Check
if (password != passwordCheck) {
cancel(true);
}
if (!this.isCancelled()) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
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) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCancelled() {
pDialog.dismiss();
Toast.makeText(Register.this, "Passwords do not match", Toast.LENGTH_SHORT).show();
}
}}
In your doInBackground, you're comparing 2 strings using != this will only compare the memory addresses of the strings and therefore will evaluate to false even if the value of the two strings is the same. Change it to equals()

how to add current login user to welcome.java

i Have this Login Page so i need the cuurent login user to get display in welcome.java
please and i need the curent user to be display in welcome .java file
public class Login extends Activity implements OnClickListener{
private EditText user, pass;
private Button mSubmit, mRegister;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL =webservice/login.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Look up the AdView as a resource and load a request.
AdView ad = (AdView) findViewById(R.id.ad);
ad.loadAd(new AdRequest());
// setup input fields
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
// setup buttons
mSubmit = (Button) findViewById(R.id.login);
mRegister = (Button) findViewById(R.id.register);
// register listeners
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> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
// save user data
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Login.this);
Editor edit = sp.edit();
edit.putString("username", username);
edit.commit();
Intent i = new Intent(Login.this, ReadComments.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;
}
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
Not sure what you exactly mean. Do you want to display the last successful user to the login prompt?
It looks like it is saved in the shared preferences with the key "user". (See code following the "json success tag" comment).
// setup input fields
user = (EditText) findViewById(R.id.username);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sp.getString("user", "");
user.setText(userName);
pass = (EditText) findViewById(R.id.password);

Categories