How to add client side validation before execute asynctask? - android

Hello I am new to android,in my app I have Login page and it works fine with my response but I want to add something like this,if my user name and password edittext is blank and user click on login button it should show message instead of start async task.
public class LoginPage extends Activity implements OnClickListener{
private Button btn;
private EditText user;
private EditText pass;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
// Session Manager Class
SessionManager session;
// Progress Dialog
private ProgressDialog pDialog;
//JSON parser class
JSONParser jsonParser = new JSONParser();
private Button btn1;
private String userid;
private static final String LOGIN_URL = "xxxxx";
private static final String TAG_SUCCESS = "status";
private static final String TAG_LOGIN = "login";
private static String TAG_USERID="user_login_id";
private static final String TAG_SESSION="session";
String session_id="";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_page);
// Session Manager
session = new SessionManager(getApplicationContext());
user=(EditText)findViewById(R.id.loginmailid);
pass=(EditText)findViewById(R.id.loginpwd);
Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show();
btn=(Button)findViewById(R.id.login);
btn1=(Button)findViewById(R.id.btnreg);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login:
if(user.equals(null) || pass.equals(null))
{
Toast.makeText(getApplicationContext(), "Enter Email and Password", Toast.LENGTH_SHORT).show();
}
else
{
new AttemptLogin().execute();
System.out.println("<<<<<<<<<<<<<<<<<<<<< Session ID : " + session_id);
session.createLoginSession(session_id);
System.out.println(session);
break;
}
case R.id.btnreg:
Intent i = new Intent(this, RegistrationForm.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask {
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginPage.this);
pDialog.setMessage("Login..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("unused")
#Override
protected String doInBackground(String...args) {
//Check for success tag
//int success;
Looper.prepare();
String username = user.getText().toString();
String password = pass.getText().toString();
try {
//Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("version", "apps"));
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());
JSONObject jobj = new JSONObject(json.toString());
final String msg = jobj.getString("msg");
session_id = jobj.getString("user_login_id");
System.out.println("Session ID : " + session_id);
System.out.println("MSG : " + msg);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
return json.getString(TAG_SUCCESS);
//JSONArray arr = json.getJSONArray("login");
//System.out.println(arr.toString());
//JSONObject arr1 = new JSONObject(json);
//String ss=arr1.getString("status");
//System.out.println(ss);
//System.out.println(arr1.getString("status"));
//String date = jObj.getString("status");
}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.equals("success")) {
session.createLoginSession(session_id);
// Log.d("Login Successful!", json.toString());
Intent i = new Intent(LoginPage.this, MainActivity.class);
i.putExtra("id", session_id);
System.out.println("Session Id : >>>>>>>>>>>>>>>>" + session_id);
startActivity(i);
}else{
//Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
}
}}
}

try like this,
if(user.getText().toString().trim().length() > 0 && pass.getText().toString().trim().length() > 0)
{
new AttemptLogin().execute();
System.out.println("<<<<<<<<<<<<<<<<<<<<< Session ID : " + session_id);
session.createLoginSession(session_id);
System.out.println(session);
break;
}
else
{
Toast.makeText(getApplicationContext(), "Enter Email and Password", Toast.LENGTH_SHORT).show();
}

try it this way...
case R.id.login:
if(user.getText().toString().trim().length()==0 || pass.getText().toString().trim().length()==0)
{
Toast.makeText(getApplicationContext(), "Enter Email and Password", Toast.LENGTH_SHORT).show();
}
else
{
new AttemptLogin().execute();
System.out.println("<<<<<<<<<<<<<<<<<<<<< Session ID : " + session_id);
session.createLoginSession(session_id);
System.out.println(session);
break;
}

Related

How to Insert data in a remote mysql database using in android which has a Spinner control

Please am having a "failed to insert" error sending data from my android app to a remote mysql database. It has a Spinner control. I'm calling an api on the remote server to to the insert, but it fails to insert.
Below is My Main Activity code
public class RCrimeActivity extends AppCompatActivity implements View.OnClickListener{
private EditText nop, wh;
private Button bReport;
private Spinner ct;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://www.nigeriacrimewatch.com/ncwrcapi.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rcrime);
nop = (EditText) findViewById(R.id.nop);
wh = (EditText) findViewById(R.id.wh);
ct = (Spinner) findViewById(R.id.ct);
bReport = (Button) findViewById(R.id.btnReport);
bReport.setOnClickListener(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent homescr = new Intent(RCrimeActivity.this, MainActivity.class);
startActivity(homescr);
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnReport:
new AttemptReport().execute();
// here we have used, switch case, because on login activity you may //also want to show registration button, so if the user is new ! we can go the //registration activity , other than this we could also do this without switch //case. default:
default:
break;
}
}
class AttemptReport extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog *
*/
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RCrimeActivity.this);
pDialog.setMessage("Reporting crime...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// here check for success tag
int success;
String name = nop.getText().toString();
String address = wh.getText().toString();
String type = ct.getSelectedItem().toString();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("nop", name));
params.add(new BasicNameValuePair("wh", address));
params.add(new BasicNameValuePair("ct", type));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// checking log for json response
Log.d("Report attempt", json.toString());
// success tag for json
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Crime Reported!", json.toString());
Intent ii = new Intent(RCrimeActivity.this, MapActivity.class);
finish();
// this finish() method is used to tell android os that we are done with current //activity now! Moving to other activity
startActivity(ii);
return json.getString(TAG_MESSAGE);
} else {
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* Once the background process is done we need to Dismiss the progress dialog asap *
**/
protected void onPostExecute(String message) {
pDialog.dismiss();
if (message != null) {
Toast.makeText(RCrimeActivity.this, message, Toast.LENGTH_LONG).show();
}
}
}
API Code
<?php
error_reporting(E_ALL);
ini_set('display_errors',TRUE);
include_once "conn/nconn.php";
$username=$_POST["username"]; $email=$_POST["email"];
$password=$_POST["password"];
if (!empty($_POST)) {
if (empty($_POST['username']) || empty($_POST['email']) || empty($_POST['password'])) {
// Create some data that will be the JSON response
$response["success"] = 0; $response["message"] = "One or both of the fields are empty .";
//die is used to kill the page, will not let the code below to be executed. It will also //display the parameter, that is the json data which our android application will parse to be //shown to the users
die(json_encode($response));
}
$query = " INSERT INTO gmusers (username, email, password, created) values ('$username','$email','$password', now())";
$sql1=mysql_query($query); if (!empty($sql1)) { $response["success"] = 1;
$response["message"] = "Registered sucessfully"; die(json_encode($response));
} else{
$response["success"] = 0; $response["message"] = "Failed to register";
die(json_encode($response));
}
} else{
$response["success"] = 0; $response["message"] = " One or both of the fields are empty ";
die(json_encode($response));
}
?>

How to send id with json request?

I have two things in my project first is login page which extended with Activity and to check username and password I am using following json {"status":"success","msg":"Your are now Login Successfully","user_login_id":2650}.
Now second thing is I am using navigation drawer which is extended with Activity and it uses different Fragment file,now after user log in successfully first fragment will display in which I want to parse some data in List view and for that I am using following json {"matching":[{"name":"Dynamic Street","profile_id":"","image":"path"}]}.So the problem is I need to use user login id 2650 to parse data in List view and want to send it with request in my http URL.
public class LoginPage extends Activity implements OnClickListener{
private Button btn;
private EditText user;
private EditText pass;
// Progress Dialog
private ProgressDialog pDialog;
//JSON parser class
JSONParser jsonParser = new JSONParser();
private Button btn1;
private static final String LOGIN_URL = "http://XXXXX/login";
private static final String TAG_SUCCESS = "status";
private static final String TAG_LOGIN = "login";
private static final String TAG_USERID="user_login_id";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_page);
user=(EditText)findViewById(R.id.loginmailid);
pass=(EditText)findViewById(R.id.loginpwd);
btn=(Button)findViewById(R.id.login);
btn1=(Button)findViewById(R.id.btnreg);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
case R.id.btnreg:
Intent i = new Intent(this, RegistrationForm.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginPage.this);
pDialog.setMessage("Login..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("unused")
#Override
protected String doInBackground(String...args) {
//Check for success tag
//int success;
Looper.prepare();
String username = user.getText().toString();
String password = pass.getText().toString();
try {
//Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("version", "apps"));
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());
JSONObject jobj = new JSONObject(json.toString());
final String msg = jobj.getString("msg");
System.out.println("MSG : " + msg);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
return json.getString(TAG_SUCCESS);
//System.out.println(arr.toString());
//JSONObject arr1 = new JSONObject(json);
//String ss=arr1.getString("status");
//System.out.println(ss);
//System.out.println(arr1.getString("status"));
//String date = jObj.getString("status");
// json success tag
// success = json.getInt(TAG_SUCCESS);
}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.equals("success")) {
// Log.d("Login Successful!", json.toString());
Intent i = new Intent(LoginPage.this, MainActivity.class);
i.putExtra("user_login_id", TAG_USERID);
startActivity(i);
}else{
//Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
}
}}
}
for fragment class check this https://stackoverflow.com/questions/26816016/how-to-parse-json-data-from-server-using-fragment
You can send the LOGIN_ID value from Activity as:
Bundle bundle = new Bundle();
bundle.putString("LOGIN_ID", value);
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment get value in onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("LOGIN_ID");
return inflater.inflate(R.layout.fragment, container, false);
}
Edit :
Remove return line, check this code :
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String strtext = getArguments().getString("LOGIN_ID");
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
aList = new ArrayList<HashMap<String,String>>();
new LoadAlbums().execute();
return rootView;
}
You dont need NameValuePairs. remove below lines.
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("version", "apps"));
create another object.
JsonObject request = new JsonObject();
request.put("email", username));
request.put("password", password));
request.put("version", "apps"));
You can also add ID in it request.put("ID", ID_VALUE));
ask server developer format of request he will let you know exact format he is parsing on server.
change the code,
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginPage.this);
pDialog.setMessage("Login..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("unused")
#Override
protected JsonObject doInBackground(String...args) {
//Check for success tag
//int success;
Looper.prepare();
String username = user.getText().toString();
String password = pass.getText().toString();
try {
//Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("version", "apps"));
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());
JSONObject jobj = new JSONObject(json.toString());
final String msg = jobj.getString("msg");
System.out.println("MSG : " + msg);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
return jobj;
//System.out.println(arr.toString());
//JSONObject arr1 = new JSONObject(json);
//String ss=arr1.getString("status");
//System.out.println(ss);
//System.out.println(arr1.getString("status"));
//String date = jObj.getString("status");
// json success tag
// success = json.getInt(TAG_SUCCESS);
}catch (JSONException e) {
e.printStackTrace();
}
return null;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(JsonObject file_url) {
//dismiss the dialog once product deleted
pDialog.dismiss();
if(jobj.getString("status").equals("success")) {
// Log.d("Login Successful!", json.toString());
Intent i = new Intent(LoginPage.this, MainActivity.class);
i.putExtra("user_login_id", jobj.getString("user_login_id"));
startActivity(i);
}else{
//Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
}
}}
class AttemptLogin extends AsyncTask<String, String, String> {
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginPage.this);
pDialog.setMessage("Login..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("unused")
#Override
protected String doInBackground(String...args) {
//Check for success tag
//int success;
Looper.prepare();
String username = user.getText().toString();
String password = pass.getText().toString();
try {
//Building Parameters
JSONObject object = new JSONObject();
object.put("email", username);
object.put("password", password);
object.put("version", "apps");
String dat = object.toString();
JSONObject object1 = new JSONObject();
object1.put("userAuthentication", object);
String dat1 = object1.toString();
httppost.setEntity(new StringEntity(dat1, HTTP.US_ASCII));
httppost.setHeader("Content-type", "application/json;" + HTTP.UTF_8);
HttpResponse response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
content));
String line;
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
result = builder.toString();
}catch (JSONException e) {
e.printStackTrace();
}
return result;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(String file_url) {
//dismiss the dialog once product deleted
pDialog.dismiss();
if(result!=null) {
// Log.d("Login Successful!", json.toString());
Intent i = new Intent(LoginPage.this, MainActivity.class);
i.putExtra("user_login_id", TAG_USERID);
startActivity(i);
}else{
//Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
}
}}
}

retrieve data using json in android

I need to display the result in android text view that I obtained by json result. I only get the success message when I run the app. I want to get the textview displayed.
Java Code:
JSONObject hay;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "////////////////////// "; // change to the webhost
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
//JSON element ids from repsonse of php script:
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.activity_main);
//setup input fields
user = (EditText) findViewById(R.id.user);
txtFname = (TextView) findViewById(R.id.fname);
txtMname = (TextView) findViewById(R.id.lname);
txtLname = (TextView) findViewById(R.id.mname);
//setup buttons
get = (Button) findViewById(R.id.get);
//register listeners
get.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AttemptLogin().execute();
}
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(MainActivity.this);
pDialog.setMessage("Attempt 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();
try {
// Building Parameters
List < NameValuePair > params = new ArrayList < NameValuePair > ();
params.add(new BasicNameValuePair("username", username));
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());
//
//Intent i = new Intent(Login.this, MainActivity.class);
//finish();
//startActivity(i);
//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();
try {
JSONObject json = null;
JSONObject hay = new JSONObject((Map) json);
JSONArray user = hay.getJSONArray("user");
JSONObject jb = user.getJSONObject(0);
String firstname = jb.getString("firstname");
String middlename = jb.getString("middlename");
String lastname = jb.getString("lastname");
// displaying all data in textview
txtFname.setText("Firstname: " + firstname);
txtMname.setText("Middle Name: " + middlename);
txtLname.setText("Last Name " + lastname);
} catch (Exception e) {
e.printStackTrace();
}
if (file_url != null) {
Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
PHP Code:
<?php
require('config.inc.php');
if (!empty($_POST)) {
//initial query
$query = "Select last_name, first_name, middle_initial FROM admin where username = :user";
$query_params = array(':user' => $_POST['username']);
//execute query
try {
$stmt = $db -> prepare($query);
$result = $stmt -> execute($query_params);
} catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt -> fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["user"] = array();
foreach($rows as $row) {
$user = array();
// $user["designation"] = $row["designation"];
$user["middlename"] = $row["middle_initial"];
$user["firstname"] = $row["first_name"];
$user["lastname"] = $row["last_name"];
//update our repsonse JSON data
array_push($response["user"], $user);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No user available!";
die(json_encode($response));
}
} else {}
?>
<form action="test.php" method="POST">
Username: <input type="text" name="username">
<input type="submit" value="Submit">
</form>
sorry can't comment but what you getting at post execute from background task is file_url as string which is your param at on post execute......i think if you are getting result all params like first name ,lastName etc then you needed to pass jsonObject at onpost Execute
so you can parse at onPostExecute...your jsonResult and display it in textbox
Problem is in you current code is
txtFname.setText("Firstname: " + firstname);
in which firstName is from
String firstname = jb.getString("firstname");
JSONObject jb= user.getJSONObject(0);
JSONArray user = hay.getJSONArray("user");
JSONObject hay = new JSONObject ((Map) json);
JSONObject json = null;
i have reversed it so you can find problem here json is null so here is problem and pls try logging at each point and let we know so we and you can have exact idea....or give us json format...
the problem is with your this code segment:
JSONObject json = null;
JSONObject hay = new JSONObject((Map) json);
JSONArray user = hay.getJSONArray("user");
JSONObject jb = user.getJSONObject(0);
String firstname = jb.getString("firstname");
String middlename = jb.getString("middlename");
String lastname = jb.getString("lastname");
here what you are doing is: making another JSONObject as
JSONObject json = null;
that is creating a variable with local scope, the local variable will have more priority than global, that you understood. actually you need the json which is created from doInBackgrounnd(). so pass the json from doInBackground to onPostExecute: it is simple,
change the statements:
return json.getString(TAG_MESSAGE); => return json;
return json.getString(TAG_MESSAGE); => return json;
also change the type of doInBackground to JSONObject and avoid making a new local JSONObject and trying to get datafrom that (bcz it is null you initialized with).
JSONObject json = null; //remove this
JSONObject hay = new JSONObject((Map) json); //remove this
JSONArray user = hay.getJSONArray("user"); // change hay to json
also change the
protected void onPostExecute(String file_url)// to protected void onPostExecute(JSONObject json)
EDIT 2
here is your changed code, let me know what you are getting if some errors.
//edited1
public static JSONObject json = null;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "////////////////////// "; // change to the webhost
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_USER = "user";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setup input fields
user = (EditText) findViewById(R.id.user);
txtFname = (TextView) findViewById(R.id.fname);
txtMname = (TextView) findViewById(R.id.lname);
txtLname = (TextView) findViewById(R.id.mname);
//setup buttons
get = (Button) findViewById(R.id.get);
//register listeners
get.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AttemptLogin().execute();
}
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(MainActivity.this);
pDialog.setMessage("Attempt 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();
try {
// Building Parameters
List < NameValuePair > params = new ArrayList < NameValuePair > ();
params.add(new BasicNameValuePair("username", username));
Log.d("request!", "starting");
// getting product details by making HTTP request
// edited2
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());
//
//Intent i = new Intent(Login.this, MainActivity.class);
//finish();
//startActivity(i);
//finish();
//edited3
return json.getString(TAG_MESSAGE);
//return json;
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
//edited4
return json.getString(TAG_MESSAGE);
//return json;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String message) {
// dismiss the dialog once product deleted
pDialog.dismiss();
try {
//JSONObject json = null;
//JSONObject hay = new JSONObject((Map) json);
JSONArray user = json.getJSONArray("user");
JSONObject jb = user.getJSONObject(0);
String firstname = jb.getString("firstname");
String middlename = jb.getString("middlename");
String lastname = jb.getString("lastname");
// displaying all data in textview
txtFname.setText("Firstname: " + firstname);
txtMname.setText("Middle Name: " + middlename);
txtLname.setText("Last Name " + lastname);
} catch (Exception e) {
e.printStackTrace();
}
if (file_url != null) {
Toast.makeText(MainActivity.this, json.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
}
}
did four changes in total: mentioned as edited# wherever I did. please fins them and make it in your file,

Android json get sharedpreferences

i am trying to make get a json value to display on another class but it is returning a null value and i am trying to save it using sharedpreferences and it is not working . i want to get editor.putString("username", username); display the username on the next class which is menu . and it is displaying anon
public class MainActivity extends Activity {
Button login,signin,reg,forr;
private EditText user,pass;
private ProgressDialog pDialog;
int flag=0;
JSONParser jsonParser = new JSONParser();
private static String LOGIN_URL = "http://10.0.2.2/wordtinss/login.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String DAIRY = "dairy";
public static final String PREFS_NAME = "LoginPrefs";
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login=(Button)findViewById(R.id.login);
user=(EditText)findViewById(R.id.username);
pass=(EditText)findViewById(R.id.password);
reg=(Button) findViewById(R.id.reg);
forr=(Button) findViewById(R.id.forg);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getString("logged", "").toString().equals("logged")) {
Intent intent = new Intent(MainActivity.this, Menu.class);
startActivity(intent);
}
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, Register.class);
finish();
startActivity(i);
}
//Close code that check online details
});
//Close log in
forr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, Forget.class);
finish();
startActivity(i);
}
//Close code that check online details
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Check all fields
if(user.length()<1 || pass.length()<1)
{
Toast.makeText(MainActivity.this,"Please Enter both username and password", Toast.LENGTH_LONG).show();
return;
}
//check connectivity
if(!isOnline(MainActivity.this))
{
Toast.makeText(MainActivity.this,"No network connection", Toast.LENGTH_LONG).show();
return;
}
//from login.java
new loginAccess().execute();
}
//code to check online details
private boolean isOnline(Context mContext) {
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
{
return true;
}
return false;
}
//Close code that check online details
});
//Close log in
}
class loginAccess extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// 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());
// Clear all previous data in database
String dar=json.getString(DAIRY);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("logged", "logged");
editor.putString("username", username);
editor.putString("dairy", dar);
editor.commit();
Intent i = new Intent(getApplicationContext(),Menu.class);
finish();
startActivity(i);
// Close all views before launching Dashboard
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
if(flag==1)
Toast.makeText(MainActivity.this,"Please Enter Correct informations", Toast.LENGTH_LONG).show();
}
}
}
public class Menu extends Activity {
private List<list> myCars = new ArrayList<list>();
int flag=0;
String namee ,dar;
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
private static String LOGIN_URL = "http://10.0.2.2/wordtinss/login.php";
private static final String dairy= "dairy";
private static final String TAG_MESSAGE = "message";
public static final String PREFS_NAME = "LoginPrefs";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
populateCarlist();
populateListView();
registerclick();
SharedPreferences un = PreferenceManager.getDefaultSharedPreferences(Menu.this);
namee = un.getString("username", "anon");
TextView usern= (TextView) findViewById(R.id.usern);
usern.setText(namee);
}
}
Use:
namee = getSharedPreferences(PREFS_NAME , Context.MODE_PRIVATE).getString("username", "anon");
instead. Because I think you're using different preference files.

Activity has leaked window.com.android.internal.policy.impl.PhoneWindow$DecorView

public class Login extends Activity implements OnClickListener {
private EditText user, pass;
private Button mSubmit, mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://192.168.2.4/mybringbacktutorial/login.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);
// 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();
}
}
}
}
Guys how to create user session here in this code? i want ReadComments.class to have a logout button and when user press the back button the session of the log in user will not be destroy, also when application is close, if the app. is open again the user has the his log in still there.
In your doInBackground of AttemptLogin class try to add pDialog.dismiss(); before you call finish() when if (success == 1)
in your onDestory() check whether the dialog is showing or not if showing dismiss it like this..
#Override
protected void onDestroy() {
if (pDialog != null) {
if (pDialog.isShowing()) {
pDialog.dismiss();
pDialog = null;
}
}
super.onDestroy();
}

Categories

Resources