Changing password of user - Update Database Table PHP/JAVA - java

I have been trying to make a 'change password' function by myself. Meaning when a user wants to change his password, a dialog will pop up and it shows three fields: Old Password, New Password and Confirm New Password. The old password is taken care of by using SharedPreferences.
public void invokeChangePass WORKS. So you do not have to look at that.
The problem is in the php file and the private void updateDataBase It will not change the password of the user in the database.
Everything aside from the php file and updateDatabase function works so do not worry about that.
Useful notes:
I know it's vulnerable to mysql injection. Not my priority at the moment.
EmailKey and PassKey are made in SharedPreferences when the user logs in.
It is supposed to find the EmailKey in the database, in order to change the password of that user.
It is as a while ago since I made this so it might have dumb mistakes or things I just forgot to add.
Thank you very much.
JAVA FILE:
public class ChangePassDialog extends Activity {
private EditText setOldPass;
private EditText setNewPass;
private EditText setNewPass2;
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_changepass);
setOldPass = (EditText) findViewById(R.id.setOldPass);
setNewPass = (EditText) findViewById(R.id.setNewPass);
setNewPass2 = (EditText) findViewById(R.id.setNewPass2);
}
public void invokeChangePass(View view) {
String oldpass = setOldPass.getText().toString();
String pass = setNewPass.getText().toString();
String pass2 = setNewPass2.getText().toString();
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String passKey = sharedpreferences.getString("passKey", "DEFAULT");
String name = sharedpreferences.getString("emailKey", "DEFAULT");
// onPreExecute();
if (oldpass.equals(passKey) && pass.length() >= 6 && pass.length() <= 30 && (pass2.length() >= 0 && (pass.equals(pass2)) && (!pass.equals(pass.toLowerCase()) &&
!pass.equals(pass.toUpperCase()) &&
pass.matches(".*\\d+.*")))) {
updateDatabase(pass, name);
setNewPass2.requestFocus();
setNewPass2.setError("TEST WORKING.");
} else {
errorTest(oldpass, pass, pass2);
}
}
private void updateDatabase(String pass, String name) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String name = params[0];
String pass = params[1];
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("pass", pass));
nameValuePairs.add(new BasicNameValuePair("name", name));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://calisapp.esy.es/changepass.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
InputStream entity = response.getEntity().getContent();
InputStreamReader inputStream = new InputStreamReader(entity);
BufferedReader bufferedReader = new BufferedReader(inputStream);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
String s = result.trim();
if(s.equalsIgnoreCase("success")){
Intent intent = new Intent(ChangePassDialog.this, Settings.class);
startActivity(intent);
Toast.makeText(ChangePassDialog.this, "Registered successfully", Toast.LENGTH_LONG).show();
finish();
}
// loadingDialog.dismiss();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name,pass);
}
PHP FILE:
<?php
define('HOST','X');
define('USER','X');
define('PASS','X');
define('DB','X');
$con = mysqli_connect(HOST,USER,PASS,DB);
$name = $_POST['name'];
$pass = $_POST['pass'];
$sql = "UPDATE tbl_user SET password='$pass' WHERE username = '$name'";
if(mysqli_query($con,$sql)){
echo 'success';
}
mysqli_close($con);
?>

First. I don't think it's a good idea to use AsyncTask for that, as it could cause some problems. This is discussed here.
But well, that's not your priority nor your question, so let's get along.
Change this
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
for this
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
And change this
InputStreamReader inputStream = new InputStreamReader(entity);
BufferedReader bufferedReader = new BufferedReader(inputStream);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
To this
HttpResponse response = httpClient.execute(httpPost);
String resp = EntityUtils.toString(response.getEntity(),"UTF-8");
return resp;
And try to change your php file to this
<?php
define('HOST','X');
define('USER','X');
define('PASS','X');
define('DB','X');
$name = $_POST['name'];
$pass = $_POST['pass'];
if (isset($name) && isset($pass)) {
$mysqli = new mysqli(HOST,USER,PASS,DB);
if ($mysqli->connect_error) {
die('Error while connecting to database!');
}
$sql = "UPDATE tbl_user SET password='" .$pass ."' WHERE username ='" . $name . "'";
$res = $mysqli->query($sql);
if ($res) {
echo "success";
}
$mysqli->close();
}
?>

Related

How do I take the string from the login and display it on a profile page?

Below is my working login code. I now want the 'name' the person logged in with to be displayed on a profile page. Searched all over but could not find it.
For example:
Person logged in with name 'example#mail.com' ('username' in code below). I want 'example#mail.com' to be displayed on a TextView on a different page.
Thanks for the help!
private EditText editTextUserName;
private EditText editTextPassword;
public static final String USER_NAME = "USERNAME";
String username;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextUserName = (EditText) findViewById(R.id.editTextUserName);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
}
public void invokeLogin(View view){
username = editTextUserName.getText().toString();
password = editTextPassword.getText().toString();
login(username,password);
}
private void login(final String username, String password) {
class LoginAsync extends AsyncTask<String, Void, String>{
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
String uname = params[0];
String pass = params[1];
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", uname));
nameValuePairs.add(new BasicNameValuePair("password", pass));
String result = null;
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://calisapp.esy.es/login.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result){
String s = result.trim();
loadingDialog.dismiss();
if(s.equalsIgnoreCase("success")){
Intent intent = new Intent(MainActivity.this, UserProfile.class);
intent.putExtra(USER_NAME, username);
finish();
startActivity(intent);
} else {
editTextUserName.requestFocus();
editTextUserName.setError("Wrong E-mail address or password");
}
}
}
LoginAsync la = new LoginAsync();
la.execute(username, password);
}
There are three ways, you can do this
1. Using Shared Preferences
2. Storing the value on Local Database
3. Passing the value via Intent.
If their login is successful, use SharedPreferences to store it. Something like this:
SharedPreferences myPrefs = getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE);
myPrefs.edit().putString(EMAIL_KEY, someEmail#example.com).apply();
myPrefs.edit().putString(PASSWORD_KEY, somePassword).apply();
EDIT: DOES NOT WORK FOR SOME REASON.
Thanks guys. I did not know you could use multiple intents so I did that. If anyone happens to need to know how I did it. Probably better to use shared preferences but I just need it on one more page for now, and I'm not a fan of making things harder than they could be.
I added a second intent to the login class on successfull login, that will carry the username string over to my settings/profile.
Intent intent2 = new Intent (MainActivity.this, Settings.class);
intent2.putExtra(USER_NAME, username);
On the settings page I called it by a intent.getStringExtra. I used a textview to show the string.
Intent intent2 = getIntent();
String username = intent2.getStringExtra(MainActivity.USER_NAME);
TextView showEmail = (TextView) findViewById(R.id.SettingsShowEmail);
showEmail.setText(username);
Intent intent2 = new Intent (MainActivity.this, Settings.class);
intent2.putExtra("username", username);
startActivity(intent2);
on the settings activity
String username = getIntent().getExtras().getString("username");
TextView showEmail = (TextView) findViewById(R.id.SettingsShowEmail);
showEmail.setText(username);

Android registration form using HTTP Post, Java, Json, PHP

I'm trying to register users to my web hosted SQL database. The java application will hopefully POST the values over to the web to be formatted before being put into an SQL statement.
Below is my code to process the POST request on the server.
$password=$_POST["password"];
$username=$_POST["username"];
$first = $_POST["first"];
$second = $_POST["second"];
$password = sha1($password);
$query = "INSERT INTO plateusers (email, password, first, second)
VALUES ('$username','$password', '$first', '$second')";
if ($query_run = mysqli_query($mysqli_conn, $query)) {
$response["success"] = 1;
$response["message"] = "You have been registered";
die(json_encode($response));
}
else
{
$response["success"] = 0;
$response["message"] = "Invalid details";
die(json_encode($response));
}
mysql_close();
Firstly I am aware of my statement being open to injection however security will come after it working.
I then created a form for users to input their details in my RegisterActivity, the code for that is:
public class RegisterActivity extends ActionBarActivity {
Context c;
EditText eTEmail;
EditText eTPassword;
EditText eTFname;
EditText eTSname;
ImageButton iBLogin;
String password;
String email;
String fname;
String sname;
String url = "*******";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
c = this;
setContentView(R.layout.activity_register);
//Casting
eTEmail = (EditText) findViewById(R.id.eTEmail);
eTPassword = (EditText) findViewById(R.id.eTPassword);
eTFname = (EditText) findViewById(R.id.eTFname);
eTSname = (EditText) findViewById(R.id.eTSname);
iBLogin = (ImageButton) findViewById(R.id.iBLogin);
iBLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// _("Login button hit");
email = eTEmail.getText() + "";
fname = eTFname.getText() + "";
sname = eTSname.getText() + "";
password = eTPassword.getText() + "";
if (sname.length() == 0 || fname.length() == 0 || email.length() == 0 || password.length() == 0) {
Toast.makeText(c, "Please fill in all fields", Toast.LENGTH_SHORT).show();
return;
}
if (sname.length() > 0 && fname.length() > 0 && email.length() > 0 && password.length() > 0) {
//Do networking
Networking n = new Networking();
n.execute(url, Networking.NETWORK_STATE_REGISTER);
}
}
});
}
//AsyncTask good for long running tasks
public class Networking extends AsyncTask {
public static final int NETWORK_STATE_REGISTER = 1;
#Override
protected Object doInBackground(Object[] params) {
getJson((String) params[0], (Integer) params[1]);
return null;
}
}
private void getJson(String url, int state) {
//Do a HTTP POST, more secure than GET
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
boolean valid = false;
switch (state) {
case Networking.NETWORK_STATE_REGISTER:
//Building key value pairs to be accessed on web
postParameters.add(new BasicNameValuePair("username", email));
postParameters.add(new BasicNameValuePair("password", password));
postParameters.add(new BasicNameValuePair("first", fname));
postParameters.add(new BasicNameValuePair("second", sname));
valid = true;
break;
default:
// Toast.makeText(c, "Unknown state", Toast.LENGTH_SHORT).show();
}
if (valid == true) {
//Reads everything that comes from server
BufferedReader bufferedReader = null;
StringBuffer stringBuffer = new StringBuffer("");
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters);
request.setEntity(entity);
//Send off to server
HttpResponse response = httpClient.execute(request);
//Reads response and gets content
bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
String LineSeparator = System.getProperty("line.separator");
//Read back server output
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line + LineSeparator);
}
bufferedReader.close();
} catch (Exception e) {
//Toast.makeText(c, "Error during networking", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
decodeResultIntoJson(stringBuffer.toString());
//Toast.makeText(c, "Valid details", Toast.LENGTH_SHORT).show();
} else {
//Toast.makeText(c, "Invalid details", Toast.LENGTH_SHORT).show();
}
}
private void decodeResultIntoJson(String response) {
/* Example from server
{
"success":1,
"message":"You have been successfully registered"
}
*/
if (response.contains("error")) {
try {
JSONObject jo = new JSONObject(response);
String error = jo.getString("error");
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
JSONObject jo = new JSONObject(response);
String success = jo.getString("success");
String message = jo.getString("message");
// Toast.makeText(c, "Register successful", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is my first attempt at developing an Android application, any help will be appreciated thanks.
Url variable has been commented out for obvious reasons, it links to the php script mentioned above.
When run there seems to be no addition to the database, however running the script alone will allow input into the database I think there is a problem POSTing the data
Making sure my application could connect to the internet solved the problem. This was a problem I didn't know I had until I found the appropiate code to fix the problem.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Send data from java android to webserver with post method

I want to send data from Java Android to mysql php server.
This is my code for button click:
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
String result="";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://geospy.zz.mu/default.php");
try {
List <NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserName", username));
nameValuePairs.add(new BasicNameValuePair("PassWord", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
StringBuilder sb = new StringBuilder();
String line;
InputStream instream = entity.getContent();
BufferedReader bf = new BufferedReader(new InputStreamReader(instream));
while ((line = bf.readLine()) != null ) {
sb.append(line).append("\n");
}
result = sb.toString();
Log.i("Read from server", result);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
status.setText(username);
//Intent intent = new Intent(LoginActivity.this, PembukaActivity.class);
//startActivity(intent);
}
This is my code in login.php:
<?php
include("connect.php");
//define $myusername and $mypassword
$myusername = $_POST['UserName'];
$mypassword = $_POST['PassWord'];
//to protect mysql injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$mypassword = $mypassword;
$sql = "SELECT ID_MEMBER FROM MEMBER WHERE USERNAME='".$myusername."' and PASSWORD= '".$mypassword."'";
echo $sql;
$result = mysql_query($sql);
//mysql_num_row is counting table row
$count = mysql_num_rows($result);
echo "<script> alert('".$count."')</script>";
if($count == 1)
{
session_start();
$row = mysql_fetch_array($result);
//$_SESSION['login'] = $myusername;
$_SESSION['id_member'] = $row['id_member'];
header('Location: login.php');
}
else
{
header('Location: default.php');
}
?>
I add this permission in manifest:
<uses-permission android:name="android.permission.INTERNET" />
But the application was stopped after i run it. I don't know where is the error.
Try doing your networking in an ASyncTask so that your networking isnt done on the UIThread, i think thats why your crashing
something like this
class TheTask extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute()
{ super.onPreExecute();
}
protected Void doInBackground(Void ...params)
{
loginPost();//View view); // View view replace
// i think even having view as a parameter will crash
// doinbackground method you have to change it i think
}
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
// Back to UIThread, i think handle status.setText(username);
// from here and take it out of your loginPost() method UI operations will
// crash doInBackground(Void ...params)
}
}
then call it in your code like this
new TheTask().execute();
EDIT: well all of your views and whatnot will crash doinbackground method use on PreExecute and OnpostExecute for begining and ending with UIOperations
You need to use AsyncTask.
public class UserLogin extends AsyncTask<ArrayList<String>, Void, String> {
protected String doInBackground(ArrayList<String>... userdata) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.website.com/script.php");
String result = null;
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", userdata[0].get(0)));
nameValuePairs.add(new BasicNameValuePair("pass", userdata[0].get(1)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
InputStream is = response.getEntity().getContent();
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
while ((line = rd.readLine()) != null) {
total.append(line);
}
result = total.toString();
}
catch(NoHttpResponseException e){
Log.d("resultLoginError", e.getMessage());
}
catch(Exception e){
Log.d("resultLoginOther", e.toString());
}
return result;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected void onPostExecute(String result) {
Log.d("resultOnLogin", "LOGGED?");
}
}
public String Login(String user, String pass) throws InterruptedException, ExecutionException{
ArrayList<String> userdata = new ArrayList<String>();
userdata.add(user);
userdata.add(pass);
return new UserLogin().execute(userdata).get();
}
This is what I personally use for login.
script.php is a PHP file that handles POST values (Username and password) and sends back confirmation to app.

JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

I tried hard to search the solution but I still not manage to solve it. Kindly help. Here my java code : -
public class MainActivity extends Activity {
String project_id;
String id;
InputStream is=null;
String result=null;
String line=null;
int code = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText e_id =(EditText) findViewById(R.id.editText1);
final EditText e_prjId =(EditText) findViewById(R.id.editText2);
Button insert =(Button) findViewById(R.id.button1);
id = e_id.getText().toString();
project_id = e_prjId.getText().toString();
insert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
insert();
}
});
}
public void insert() {
final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",id));
nameValuePairs.add(new BasicNameValuePair("Project_Id",project_id));
new Thread(new Runnable() {
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.111/insert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e){
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e){
Log.e("Fail 2", e.toString());
}
try {
Log.i("tagconvertstr", "["+result+"]");
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(code==1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again",Toast.LENGTH_LONG).show();
}
}
}).start();
}
php:-
<?php
$uname='root';
$pwd='';
$con = new PDO("mysql:host=192.168.0.111;dbname=wktask", $uname, $pwd);
$ID=$_REQUEST['ID'];
$Project_Id=$_REQUEST['Project_Id'];
$flag['code']=0;
if($r= $con->query("insert into task(ID,Project_Id) values('$ID','$Project_Id')"))
{
$flag['code']=1;
}
echo(json_encode($flag));
?>
I really no idea that what is the reason I keep receive error message from JSON exception error. Really appreciate somemore can help me.
Thanks
Be careful, PHP associative array are case sensitive
You are sending id:
nameValuePairs.add(new BasicNameValuePair("id",id));
which is not equal to ID
In addition to that mistake, you dont check the data in your php script, I rewrote it for you:
$data = array();
if(isset($_POST['id'], $_POST['Project_Id']){
$id=$_POST['id'];
$project_id=$_POST['Project_Id'];
$uname='root';
$pwd='';
$con = new PDO("mysql:host=192.168.0.111;dbname=wktask", $uname, $pwd);
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $con->prepare('INSERT INTO task (`ID`, `Project_Id`) values(:id, :project_id)'))
$success = $stmt->execute(array(':id'=>$id, ':project_id'=>$project_id));
if($success){
$data['code'] = 1;
$data['msg'] = 'INSERT successful';
}else{
$data['code'] = 0;
$data['msg'] = 'INSERT Failed';
}
}else{
$data['code'] = 0;
$data['msg'] = 'values are not set';
}
echo(json_encode($data));

Returning a value from another class to Activity in Android

HI i have been trying to pass values from android form to php page through json and get the result through JSON i have got an example and implemented it. In that example i am passing username and password entered in android form to php page through json in the page it is retrieving the role of the details passed form database and passing the result to android class and my function is setting the retrieved value to a text filed and the result is displayed in the particular text field. Now want i want is i want to return the result as a String and retrieve it in MainActivity. I'm pasting the code below. Please help me.
MainActivity.class
public class MainActivity extends ActionBarActivity {
private EditText usernameField,passwordField,role;
private TextView status,method;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);
role = (EditText)findViewById(R.id.editText3);
}
public void login(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
//method.setText("Get Method");
new SigninActivity(this,role,0).execute(username,password);
}
SigninActivity.class
public class SigninActivity extends AsyncTask<String,Void,String>{
private EditText roleField;
private Context context;
private int byGetOrPost = 0;
private static InputStream is;
//JSONObject jsonParser;
public SigninActivity(Context context,EditText roleField,int flag) {
this.context = context;
this.roleField = roleField;
this.is=null;
// this.jsonParser= new JSONObject();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", username));
params.add(new BasicNameValuePair("password", password));
/////////////////////////////////////////////////////////////////////////////
String link = "http://Myapp.com/login.php";
//URL url = new URL(link);
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
link+= "?" + paramString;
HttpGet httpGet = new HttpGet(link);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
StringBuilder sb = new StringBuilder();;
/////////////////////////////////////////////////////////////////////////////
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return sb.toString();
}catch(Exception e){
return new String("Exception:-- " + e.getMessage());
}
}
protected void onPostExecute(String result){
this.roleField.setText(result);
}
}
Here the result is retrieved and set to the text filed in onPostExecute() function in SigninActivity class itself what i want to do is i want the value to be returned in MainActivity as a String to do further manipulations instead of using a textView
Its very simple
Use this for sending in the next activity
resp = new JSONObject(result);
JSONObject Login1Result = resp.getJSONObject("LoginResult");
String strMessage = Login1Result.getString("EmployeeID");
JSONObject status = Login1Result.getJSONObject("status");
if (status.getString("message").equalsIgnoreCase("OK"))
{
Intent i = new Intent(getApplicationContext(), next.class);
i.putExtra("new_variable_name",strMessage);
startActivity(i);
for getting it in next activity
{
Bundle extras = getIntent().getExtras();
String strEmployeeID="";
if (extras != null)
{
String value = extras.getString("new_variable_name");
strEmployeeID = value;
}
Intent i = new Intent(getApplicationContext(), nextTonext.class);
i.putExtra("new_variable_name",strEmployeeID);
startActivity(i);
}
You can try SharedPreferences, it's easy to use and quite powerful You can find it here

Categories