How to merge following code with Async Task. I see lots of tutorials and make changes in code but unable to do completly. This code is completely fine and working proper but some one advise me to make it Async Task so that when login successful message disappear Move_to_next method is called to start new activity. so please someone add async task code in it so that its work proper.
Code-
public class LoActivity extends Activity {
Intent i;
Button signin;
TextView error;
CheckBox check;
String name="",pass="";
byte[] data;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream;
SharedPreferences app_preferences ;
List<NameValuePair> nameValuePairs;
EditText editTextId, editTextP;
#Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
signin = (Button) findViewById (R.id.signin);
editTextId = (EditText) findViewById (R.id.editTextId);
editTextP = (EditText) findViewById (R.id.editTextP);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
check = (CheckBox) findViewById(R.id.check);
String Str_user = app_preferences.getString("username","0" );
String Str_pass = app_preferences.getString("password", "0");
String Str_check = app_preferences.getString("checked", "no");
if(Str_check.equals("yes"))
{
editTextId.setText(Str_user);
editTextP.setText(Str_pass);
check.setChecked(true);
}
signin.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
name = editTextId.getText().toString();
pass = editTextP.getText().toString();
String Str_check2 = app_preferences.getString("checked", "no");
if(Str_check2.equals("yes"))
{
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("username", name);
editor.putString("password", pass);
editor.commit();
}
if(name.equals("") || pass.equals(""))
{
Toast.makeText(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
}
else
{
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://abc.com/register.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len));
}
inputStream.close();
}
catch (Exception e)
{
Toast.makeText(LoActivity.this, "error"+e.toString(), Toast.LENGTH_SHORT).show();
}
if(buffer.charAt(0)=='Y')
{
Toast.makeText(LoActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(LoActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
}
}
}
});
check.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// Perform action on clicks, depending on whether it's now checked
SharedPreferences.Editor editor = app_preferences.edit();
if (((CheckBox) v).isChecked())
{
editor.putString("checked", "yes");
editor.commit();
}
else
{
editor.putString("checked", "no");
editor.commit();
}
}
});
}
public void Move_to_next()
{
startActivity(new Intent(LoActivity.this, QnActivity.class));
}
}
All you need to add asyctask call in your signin button click the code is following
Context mContext=this;
String[] result = new String[2];
signin.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
AsyncGetAccessToken aSyncGetToken=new AsyncGetAccessToken();
aSyncGetToken.execute()}});
Make a private class AsyncTask:
private class AsyncGetAccessToken extends AsyncTask<Void, Void, String>
{
#Override
protected String doInBackground(Void... Data) {
name = editTextId.getText().toString();
pass = editTextP.getText().toString();
String Str_check2 = app_preferences.getString("checked", "no");
if(Str_check2.equals("yes"))
{
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("username", name);
editor.putString("password", pass);
editor.commit();
}
if(name.equals("") || pass.equals(""))
{
Toast.makeText(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
}
else
{
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://abc.com/register.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len));
}
result[0] = response.getStatusLine().getStatusCode()+"";
result[1] = buffer .toString();
inputStream.close();
}
catch (Exception e)
{
Toast.makeText(LoActivity.this, "error"+e.toString(), Toast.LENGTH_SHORT).show();
}
if(buffer.charAt(0)=='Y')
{
Toast.makeText(LoActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(LoActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
}
}
return result;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showLoading();
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
hideLoading();
}
}
for stop loading:
private void hideLoading()
{
if (pDialogTh.isShowing()) {
pDialogTh.cancel();
}
}
for start loading :
private ProgressDialog pDialogTh = null;
private void showLoading()
{
// if(pDialog==null)
pDialogTh = ProgressDialog.show(mContext, "", "Loading...",
true, true);
pDialogTh.setCancelable(false);
if (!pDialogTh.isShowing()) {
pDialogTh.show();
}
}
Try this way
I have edit in your code just copy paste and try
public class LoActivity extends Activity {
Intent i;
Button signin;
TextView error;
CheckBox check;
String name = "", pass = "";
byte[] data;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream;
SharedPreferences app_preferences;
List<NameValuePair> nameValuePairs;
EditText editTextId, editTextP;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
signin = (Button) findViewById(R.id.signin);
editTextId = (EditText) findViewById(R.id.editTextId);
editTextP = (EditText) findViewById(R.id.editTextP);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
check = (CheckBox) findViewById(R.id.check);
String Str_user = app_preferences.getString("username", "0");
String Str_pass = app_preferences.getString("password", "0");
String Str_check = app_preferences.getString("checked", "no");
if (Str_check.equals("yes")) {
editTextId.setText(Str_user);
editTextP.setText(Str_pass);
check.setChecked(true);
}
signin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
name = editTextId.getText().toString();
pass = editTextP.getText().toString();
String Str_check2 = app_preferences.getString("checked", "no");
if (Str_check2.equals("yes")) {
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("username", name);
editor.putString("password", pass);
editor.commit();
}
if (name.equals("") || pass.equals("")) {
Toast.makeText(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
} else {
new LoginTask().execute();
}
}
});
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on clicks, depending on whether it's now
// checked
SharedPreferences.Editor editor = app_preferences.edit();
if (((CheckBox) v).isChecked()) {
editor.putString("checked", "yes");
editor.commit();
} else {
editor.putString("checked", "no");
editor.commit();
}
}
});
}
public void Move_to_next() {
startActivity(new Intent(LoActivity.this, QnActivity.class));
}
private class LoginTask extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Show progress dialog here
}
#Override
protected String doInBackground(Void... arg0) {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://abc.com/register.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data))) {
buffer.append(new String(data, 0, len));
}
inputStream.close();
return buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Hide progress dialog here
if (buffer.charAt(0) == 'Y') {
Toast.makeText(LoActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
Move_to_next();
} else {
Toast.makeText(LoActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
}
}
}
}
Try this:
if(name.equals("") || pass.equals(""))
{
Toast.makeText(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
}else{
RequestClient reqClient = new RequestClient(ClassName.this);
String AppResponse = null;
AppResponse = reqClient.execute().get()
}
In App response you will get your response change the data type of it as per your requirement.
Create a class RequestClient.java
public class RequestClient extends AsyncTask<String, Void, String>{
Context context;
public RequestClient(Context c) {
context = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl){
String responseString="";
HttpClient client = null;
try {
client = new DefaultHttpClient();
HttpGet get = new HttpGet(aurl[0]);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
responseString = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", responseString);
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
}
Log.d("ANDRO_ASYNC_RESPONSE", responseString);
client.getConnectionManager().shutdown();
return responseString;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
}
}
Im new on android, so in my (little reserchs) ive learn that, if we want make some task that includs network access, or other heavy operation, we need do this on some async task. So in my opinion u can do something like this:
signin.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
...
if(name.equals("") || pass.equals(""))
{
Toast.makeText(Lo.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
}
else
{
...
YourAsyncClass test = new YourAsyncClass(this);
//you can give various string parameters, in this case, u can send the url, make it an constant
test.execute(YOUR_URL_LIKE_CONSTANT);
}
if(buffer.charAt(0)=='Y')
{
Toast.makeText(LoActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
}
...
And your YourAsynClass may be like this:
public class YourAsynClass extends AsyncTask<String, Void, String> {
...
public YourAsynClass () {
...
}
//this method is executed before the real task
#Override
protected void onPreExecute() {
super.onPreExecute();
...
//here you can call some load dialog box
}
#Override
protected String doInBackground(String... params){
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://abc.com/register.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len));
}
inputStream.close();
}
catch (Exception e)
{
Toast.makeText(LoActivity.this, "error"+e.toString(), Toast.LENGTH_SHORT).show();
}
return buffer.toString();
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
//u can hide the load dialog here
}
Related
hey friends i am developing android login registration system using php and mysql on localhost.. i done coding part but my code content some run-time error when i run my app then it at register screen shows "Invalid username or password or email" that means i am getting jsonresult 0 from php means my data like(name,email,pass) is not passing to php....below is my code
for Register.java
public class Register extends Activity {
TextView tvlogin;
EditText etuname,etemail,etpass,etmobno;
Button userreg;
String name,email,pass;
// private ProgressDialog pDialog;
int flag=0;
private static String url = "http://10.0.2.2/examtime/register.php";
// private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
//StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
//.detectDiskReads().detectDiskWrites().detectNetwork()
//.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
etuname=(EditText)findViewById(R.id.et_name);
etemail=(EditText)findViewById(R.id.et_email);
etpass=(EditText)findViewById(R.id.et_password);
userreg=(Button)findViewById(R.id.button1);
// etmobno=(EditText)findViewById(R.id.editText1);
tvlogin=(TextView)findViewById(R.id.tv_login);
userreg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
userReg(v);
}
});
}
public void userReg(View v)
{
name=etuname.getText().toString();
email=etemail.getText().toString();
// mobno=etmobno.getText().toString();
pass=etpass.getText().toString();
if(name.equals("") || pass.equals("") || email.equals("")){
Toast.makeText(Register.this, "Username or password or email must be filled", Toast.LENGTH_LONG).show();
return;
}
if(name.length() <= 1 || pass.length() <= 1){
Toast.makeText(Register.this, "Username or password length must be greater than one", Toast.LENGTH_LONG).show();
return;
}
// request authentication with remote server4
AsyncDataClass asyncRequestObject = new AsyncDataClass();
asyncRequestObject.execute(url, name, pass, email);
}
private class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResult = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name", params[1]));
nameValuePairs.add(new BasicNameValuePair("pass", params[2]));
nameValuePairs.add(new BasicNameValuePair("email", params[3]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
System.out.println("Returned Json object " + jsonResult.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Resulted Value: " + result);
if(result.equals("") || result == null){
Toast.makeText(Register.this, "Server connection failed", Toast.LENGTH_LONG).show();
return;
}
int jsonResult = returnParsedJsonObject(result);
if(jsonResult == 0){
Toast.makeText(Register.this, "Invalid username or password or email", Toast.LENGTH_LONG).show();
return;
}
if(jsonResult == 1){
Intent intent = new Intent(Register.this, Profile.class);
intent.putExtra("USERNAME", name);
intent.putExtra("MESSAGE", "You have been successfully Registered");
startActivity(intent);
}
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
private int returnParsedJsonObject(String result){
JSONObject resultObject = null;
int returnedResult = 0;
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
//-------
}
and for login.java my mainactivity.java
public class MainActivity extends Activity {
TextView userReg;
Button userLogin;
EditText et_email,et_pass;
String login_email,login_pass;
String Logurl = "http://10.0.2.2/examtime/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userReg=(TextView)findViewById(R.id.Register);
userLogin=(Button)findViewById(R.id.Login);
et_email=(EditText)findViewById(R.id.email);
et_pass=(EditText)findViewById(R.id.pword);
userReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
userReg(v);
}
});
}
public void userReg(View v)
{
startActivity(new Intent(this,Register.class));
}
public void userLogin(View v)
{
login_email=et_email.getText().toString();
login_pass=et_pass.getText().toString();
if(login_email.equals("") || login_pass.equals("")){
Toast.makeText(MainActivity.this, "Username or password must be filled", Toast.LENGTH_LONG).show();
return;
}
if(login_email.length() <= 1 || login_pass.length() <= 1){
Toast.makeText(MainActivity.this, "Username or password length must be greater than one", Toast.LENGTH_LONG).show();
return;
}
// request authentication with remote server4
AsyncDataClass asyncRequestObject = new AsyncDataClass();
asyncRequestObject.execute(Logurl, login_email, login_pass);
startActivity(new Intent(this,Home.class));
}
private class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResult = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name", params[1]));
nameValuePairs.add(new BasicNameValuePair("pass", params[2]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Resulted Value: " + result);
if(result.equals("") || result == null){
Toast.makeText(MainActivity.this, "Server connection failed", Toast.LENGTH_LONG).show();
return;
}
int jsonResult = returnParsedJsonObject(result);
if(jsonResult == 0){
Toast.makeText(MainActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
return;
}
if(jsonResult == 1){
Intent intent = new Intent(MainActivity.this, Profile.class);
intent.putExtra("USERNAME",login_email);
intent.putExtra("MESSAGE", "You have been successfully login");
startActivity(intent);
}
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
private int returnParsedJsonObject(String result){
JSONObject resultObject = null;
int returnedResult = 0;
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
}
and my php code is
index.php
<?php
require_once 'include/user.php';
$username = "";
$password = "";
$email = "";
if(isset($_POST['name'])){
$username = $_POST['name'];
}
if(isset($_POST['pass'])){
$password = $_POST['pass'];
}
if(isset($_POST['email'])){
$email = $_POST['email'];
}
// Instance of a User class
$userObject = new User();
// Registration of new user
if(!empty($username) && !empty($password) && !empty($email)){
$hashed_password = md5($password);
$json_registration = $userObject->createNewRegisterUser($username, $hashed_password, $email);
echo json_encode($json_registration);
}
// User Login
if(!empty($username) && !empty($password) && empty($email)){
$hashed_password = md5($password);
$json_array = $userObject->loginUsers($username, $hashed_password);
echo json_encode($json_array);
}
?>
and my User.php
<?php
include_once 'db.php';
class User{
private $db;
private $db_table = "stud";
public function __construct(){
$this->db = new DbConnect();
}
public function isLoginExist($username, $password){
$query = "select * from " . $this->db_table . " where name = '$username' AND pass = '$password' Limit 1";
$result = mysqli_query($this->db->getDb(), $query);
if(mysqli_num_rows($result) > 0){
mysqli_close($this->db->getDb());
return true;
}
mysqli_close($this->db->getDb());
return false;
}
public function createNewRegisterUser($username, $password, $email){
$query = "insert into stud (name, pass, email) values ('$username', '$password', '$email')";
$inserted = mysqli_query($this->db->getDb(), $query);
if($inserted == 1){
$json['success'] = 1;
}else{
$json['success'] = 0;
}
mysqli_close($this->db->getDb());
return $json;
}
public function loginUsers($username, $password){
$json = array();
$canUserLogin = $this->isLoginExist($username, $password);
if($canUserLogin){
$json['success'] = 1;
}else{
$json['success'] = 0;
}
return $json;
}
}
?>
i know i am missing something i try to explain it sorry for bad English and i am also new to android and also new in stack overflow
tbh it was too much code for me to read through all of this, but I think I know what you want.
first check if Name already exists:
<?php>
$text = $_POST["text1"];
$db = #new mysqli("mysql.hostinger.de", "...", "...", "...");
if($db->connect_error){
die("<pre>".$db->connect_error."</pre>");
}
$num = $sql->num_rows;
$sql = $db->query("SELECT name FROM Rangliste");
$num = $sql->num_rows;
if($num > 0){
while($row = $sql->fetch_object()){
if($row->name == $text){
echo("Name already exists!");
}else{
echo("Name accepted!");
}
}
}
and so on... connect it with your java
when I sent post login data use login button like this :
loginbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String user = email.getText().toString().trim();
final String pwd = password.getText().toString().trim();
if (email.getText().toString().equals("")) {
Utils.toast(context, "Username empty...");
} else if (password.getText().toString().equals("")) {
Utils.toast(context, "Password empty...");
} else if (!isValidEmail(user)) {
email.setError("Invalid Email");
} else if (user.length() < 2) {
Utils.toast(context, "Username to short...");
} else if (pwd.length() < 2) {
Utils.toast(context, "Password to short...");
} else if (!isValidPassword(pwd)) {
password.setError("Invalid Password");
} else {
progress.setVisibility(View.VISIBLE);
SendfeedbackJob job = new SendfeedbackJob();
job.execute(user, pwd);
}
}
});
private class SendfeedbackJob extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "UserLoginTask";
#Override
protected String doInBackground(String... params) {
String user = params[0];
String pwd = params[1];
// do above Server call here
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("email", user ));
postParameters.add(new BasicNameValuePair("password", pwd ));
String responseString = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.219:90/auth/login");
// no idea what this does :)
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// This is the line that send the request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String responseAsText = EntityUtils.toString(response.getEntity());
Utils.log("daftar isi: " + responseAsText);
JSONObject loginjson = new JSONObject(responseAsText);
Utils.log("json object: " + loginjson);
String roleString = loginjson.getString("role");
Utils.log("role: " + roleString);
if(roleString.equals("member")){
Intent intent = new Intent(context, home.class);
startActivity(intent);
}else if(roleString.equals("studio")){
Intent intent = new Intent(context, VendorDashboard.class);
startActivity(intent);
}
}
catch (Exception e)
{
Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
}
return "processing";
}
#Override
protected void onPostExecute(String message) {
//process message
}
}
actually it will get feedback JSON response like this :
{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxNCIsImlzcyI6Imh0dHA6XC9cLzE5Mi4xNjguMC4yMTk6OTBcL2F1dGhcL2xvZ2luIiwiaWF0IjoiMTQ0NTI0NzIyMSIsImV4cCI6IjE0NDY0NTY4MjEiLCJuYmYiOiIxNDQ1MjQ3MjIxIiwianRpIjoiNTY4MDEyZDUwNTg1NDFjM2UzNGVjMGViYzMzZDkzMGQifQ.zw5c5kLIlvPYIMhEzEnF_fCOu77XTq2prcDtSHJY7bk","role":"studio"}
How to get role (JSON response feedback) so I can use if and else if statement after execute HTTP Post Request (after Utils.toast(context, responseAsText);)?
Update after I used asynctask, it did not produce error onclick.
Update it is done. Thanks mr.shreyash.
Question closed.
I have this code working with me, I am confused with the control flow.
How is the interface used here as a Response Listener? How is the overridden method responseObject(JSONObject resp, String type) in LoginActivity class triggering?
And after calling AsyncTask where the control goes?
public class LoginActivity extends Activity implements ResponseListener{
login = (Button) findViewById(R.id.btnLogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String username = mUsernameField.getText().toString();
String password = mPasswordField.getText().toString();
String[] param = {username, password};
new ServerRequests.LoginUserAsyncTask(LoginActivity.this,this).execute(param);
}
#Override
public void responseObject(JSONObject resp, String type) {
try{
if (resp.has("api_key")) {
String api_key = resp.getString("api_key");
String user_id = resp.getString("user");
Log.i("api_key", api_key);
SharedPreferences settings = LoginActivity.this.getSharedPreferences(Constants.NADA_SP_KEY, 0);
final SharedPreferences.Editor editor = settings.edit();
editor.putString(Constants.NADA_API_KEY, api_key);
editor.putString(Constants.NADA_USER_ID, user_id);
editor.putBoolean(Constants.NADA_IS_LOGGED_IN, true);
editor.commit();
Log.i("first Visit", "False");
String should_show_questions_screen = resp.getString("should_set_basic_questions");
if (should_show_questions_screen.compareToIgnoreCase("true")==0){
Intent intent=new Intent(LoginActivity.this,RegistrationSuccessfulScreen.class);
startActivity(intent);
finish();
}else {
Intent intent = new Intent(LoginActivity.this, UserNavigationActivity.class);
startActivity(intent);
finish();
}
}
}catch (JSONException e){
e.printStackTrace();
}
}
//Heres my ServerRequest Class which uses AsyncTask
public class ServerRequests {
public static class LoginUserAsyncTask extends AsyncTask<String, Void, String> {
static JSONObject udetails;
Context mContext;
ResponseListener mResponseListener;
SweetAlertDialog progressDialog;
public LoginUserAsyncTask(Context mContext,ResponseListener listener) {
this.mContext = mContext;
this.mResponseListener = listener;
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog =new SweetAlertDialog(mContext, SweetAlertDialog.PROGRESS_TYPE);
progressDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
progressDialog.setTitleText("please wait connecting..");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpPost post = null;
udetails = new JSONObject();
String response_data = "";
if (params.length == 2) {
try {
post = new HttpPost(Config.SERVER_BASE_URL + "/login");
udetails.put("username", params[0]);
udetails.put("password", params[1]);
SharedPreferences settings = mContext.getSharedPreferences(Constants.NADA_SP_KEY, 0);
final SharedPreferences.Editor editor = settings.edit();
editor.putString(Config.USER_NAME, params[0]).commit();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
try {
post = new HttpPost(Config.SERVER_BASE_URL + "/login_with_fb");
udetails.put("fb_id", params[0]);
udetails.put("fb_auth_token", params[1]);
SharedPreferences settings = mContext.getSharedPreferences(Constants.NADA_SP_KEY, 0);
final SharedPreferences.Editor editor = settings.edit();
editor.putString(Config.USER_NAME, params[0]).commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
StringEntity se = new StringEntity(udetails.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse response = client.execute(post);
int response_code = response.getStatusLine().getStatusCode();
response_data = EntityUtils.toString(response.getEntity());
Log.i("api_token", response_data);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response_data;
}
#Override
protected void onPostExecute(String response) {
progressDialog.dismiss();
JSONObject resp = new JSONObject();
try {
resp = new JSONObject(response);
if (resp.has("status")) {
if (resp.getString("status").compareToIgnoreCase("unauthorised")==0){
AppMsg appMsg = AppMsg.makeText((Activity)mContext, resp.getString("message"), style);
appMsg.show();
}
}
mResponseListener.responseObject(resp,"LOGIN");
} catch (JSONException e) {
AppMsg appMsg = AppMsg.makeText((Activity)mContext, "Something went wrong", style);
appMsg.show();
e.printStackTrace();
}
}
}
//Here's Interface Which has this method
public interface ResponseListener {
public void responseObject(JSONObject data,String type);
}
Your LoginActivity implements ResponseListener. In this line: new ServerRequests.LoginUserAsyncTask(LoginActivity.this,this).execute(param);, you pass your activity twice into the LoginUserAsyncTask constructor. Notice that the constructor takes in a Context and a ResponseListener. You can do this because your activity implements ResponseListener.
Now LoginUserAsyncTask can call the responseObject method on your activty because it has a refrence to it as a ResponseListener. It does that in the onPostExecute method of the AsyncTask. The activity is kind of listning to when the task is done, then it's responseObject method is called.
Becaus the work of the AsyncTask is done asynchronously it returns "straight away" and the next statement is executed.
I also think your missing part of the first method.
First code:
`db_img = Jasonobject.getString("image");
imagelink.setText(db_img);`
The code above is grab the data from mysql database.
"imagelink" is textview.
The code will display the data into textview
"image"from mysql is string because is url link.
Second code:
new DownloadImageTask((ImageView) findViewById(R.id.qrimg)).
execute("http://localhost/project/image/pic1.jpg");
The second code is load the image base on the URL
My problem is how to pass the value from first code into .execute("HERE")
Code:
`
EditText etacode;
EditText txtName;
Button btnscanitem;
//testing
TextView imagelink;
//hidden textview
TextView texttime;
TextView textunit;
TextView textrm;
TextView textexp;
Button btnconfrim;
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acode);
btnscanitem = (Button) findViewById(R.id.btnscanitem);
etacode = (EditText) findViewById(R.id.etacode);
etacode.setVisibility(View.GONE);
//testing
imagelink = (TextView) findViewById(R.id.imagelink);
btnconfrim = (Button) findViewById(R.id.btnconfrim);
btnconfrim.setVisibility(View.GONE);
img = (ImageView) findViewById(R.id.img);
img.setVisibility(View.GONE);
img.setImageResource(0);
}
class task extends AsyncTask<String, String, Void>
{
private ProgressDialog progressDialog = new ProgressDialog(AcodeActivity.this);
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Fetching data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
task.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select = "http://Localhost/getproduct.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
// Fetch data from Json database
try {
JSONArray Jarray = new JSONArray(result);
for(int i=0;i<Jarray.length();i++)
{
JSONObject Jasonobject = null;
Jasonobject = Jarray.getJSONObject(i);
String apromoid = Jasonobject.getString("aid");
String db_img="";
if(etcode.getText().toString().equalsIgnoreCase(apromoid)) {
db_img = Jasonobject.getString("image");
imagelink.setText(db_img);
String temp;
temp = db_img;
//String imagelink = temp;
//(db_img);
break;
}
}
this.progressDialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.acodescanner, menu);
return true;
}
public void onClick (View view){
if(view.getId() == R.id.btnscanitem){
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.initiateScan();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
// handle scan result
String acode;
acode = scanResult.getContents();
EditText etacode = (EditText) findViewById(R.id.etacode);
etacode.setText(acode);
new task().execute();
//String textlink = getimagelink;
new DownloadImageTask((ImageView) findViewById(R.id.qrimg))
.execute(db_img);
}
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
`
Please have read so many on this,(it says i should not put the dialog in the doInbackground) But have been trying to get this done for a while,Its actually my first android app(with java). Please how do i show the loading bar,disable button (till there's response) and redirect to another activity on success.
public class Index extends Activity implements OnClickListener {
EditText username, password;
Button login;
String uname,pass;
TextView login_err;
HttpClient httpclient;
HttpPost htpost;
ArrayList <NameValuePair> namearray;
HttpResponse response;
HttpEntity entity;
int Server_response;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_index);
login_err= (TextView) findViewById(R.id.login_err);
initialise();
}
private void initialise() {
username = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
login= (Button) findViewById(R.id.login_btn);
login.setOnClickListener(this);;
}
public void onClick(View v) {
String umail=username.getText().toString();
String pass= password.getText().toString();
if(umail.length()!=0 && pass.length()!=0){
new MyAsyncTask().execute();
}else{
Toast.makeText(getBaseContext(), "Please provide username and password",Toast.LENGTH_SHORT).show();
}
}//END onClick()
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}//END convertStreamToString()
private class MyAsyncTask extends AsyncTask <Void, Void, Void> {
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Void result) {
if(Server_response==1){
mProgressDialog.dismiss();
}
}
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(Index.this, "Loading...", "Logging In...");
}
protected Void doInBackground(Void... params) {
//Create new default HTTPClient
httpclient = new DefaultHttpClient();
//Create new HTTP POST with URL to php file as parameter
htpost = new HttpPost("http://10.0.2.2/fanaticmobile/log_in.php");
//Assign input text to strings
uname= username.getText().toString();
pass= password.getText().toString();
//Next block of code needs to be surrounded by try/catch block for it to work
try {
//Create new Array List
namearray = new ArrayList<NameValuePair>();
//place them in an array list
namearray.add(new BasicNameValuePair("username", uname));
namearray.add(new BasicNameValuePair("password", pass));
//Add array list to http post
htpost.setEntity(new UrlEncodedFormEntity(namearray));
//assign executed form container to response
response= httpclient.execute(htpost); //response from the PHP file
//check status code, need to check status code 200
if(response.getStatusLine().getStatusCode()==200){
//assign response entity to http entity
entity= response.getEntity();
//check if entity is not null
if(entity != null){
//Create new input stream with received data assigned
InputStream instream = entity.getContent();
//Create new JSON Object. assign converted data as parameter.
JSONObject jresponse = new JSONObject(convertStreamToString(instream));
//assign json responses to local strings
String logged= jresponse.getString("logged");
if(logged.equals("true")){
Server_response=1;
//Please i want to redirect to a new activity here
}else{
Log.d("Error Invalid credentials",logged);
Server_response=0;
}
}
}
} catch(Exception e){
Toast.makeText(getBaseContext(), "Connection Error", Toast.LENGTH_SHORT).show();
return null;
}
return null;
}
}
}
You should take a look at the loginActivity class from the android sdk there's a template that do what you want.
They have a method that shows an animation while the asynctask is running, you just have to call it before executing your asynctask like that
showProgress(true);
mAuthTask = new UserLoginTask();
mAuthTask.execute();
here's the method:
private void showProgress(final boolean show) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
mLoginStatusView.setVisibility(View.VISIBLE);
mLoginStatusView.animate().setDuration(shortAnimTime)
.alpha(show ? 1 : 0)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginStatusView.setVisibility(show ? View.VISIBLE
: View.GONE);
}
});
mLoginFormView.setVisibility(View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime)
.alpha(show ? 0 : 1)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE
: View.VISIBLE);
}
});
} else {
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
and then in your asynctask you use onPostExecute which will be called after the asynctask is completed and you can stop the login animation and launch a new activity from there
protected void onPostExecute(String[] userDetails) {
showProgress(false);
}