Android convert EditText to String [duplicate] - java

This question already has answers here:
Method getText() must be called from the UI Thread (Android Studio)
(5 answers)
Closed 7 years ago.
I know how to convert the EditText to a string, no clue why it doesn't work.
String username = user.getText().toString();
user = (EditText)findViewById(R.id.username);
I am getting this error: "Method getText must be called from the UI thread, currently inferred thread is worker"
Full code:
public class Login extends Activity implements OnClickListener{
private EditText user;
private Button bLogin;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://testapp.comlu.com/login.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_login);
user = (EditText)findViewById(R.id.username);
String aID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
bLogin = (Button)findViewById(R.id.login);
bLogin.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().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:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting for login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
int success;
String username = user.getText().toString();
String androidID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("androidID", androidID));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// checking log for json response
Log.d("Login attempt", json.toString());
// success tag for json
success = 1;
if (success == 1) {
Log.d("Successfully Login!", json.toString());
Intent ii = new Intent(Login.this,Menu.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(Login.this, message, Toast.LENGTH_LONG).show();
}
}
}
Any ideas?
Thanks,
Yoshi

I am getting this error: "Method getText must be called from the UI
thread, currently inferred thread is worker"
you could move
String username = user.getText().toString();
in your onClick method, and pass the String to the AsyncTask like
new AttemptLogin().execute(username);
When doInBackground is invoked you can access it trough String... args, E.g. args[0]

You cannot manipulate UI elements from background thread. You are trying to access the UI element in the doInBackground method:
String username = user.getText().toString();
Instead of that, you should pass the data to the async task like:
new AttemptLogin().execute(user.getText().toString());
Also you are starting an activity from the doInBackground method. You should move that piece of code to onPostExecute method.

Related

Android when AsyncTask Process if no internet found how to give warning "please connect internet" [duplicate]

This question already has answers here:
How can i check whether an android device is connected to the web?
(4 answers)
Closed 5 years ago.
Android AsyncTask processing and found no internet connection system give warning "user please connect internet". How can I do this in my code?
Another problem is when internet not connected its show loading but I don't go back page. How to solve this problem?
I don't understand how to do this inside this code.
public class data extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://orangehostbd.com/app/bpl2/index.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(data.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
data.this, contactList,
R.layout.list_item, new String[]{"name", "email",
"mobile"}, new int[]{R.id.name,
R.id.email, R.id.mobile});
lv.setAdapter(adapter);
}
}
}
Create a Helper class.
Inside this class, create a method to check internet connection.
public static boolean isNetworkConnected(Context context) {
final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
Inside your activity class, use above isNetworkConnected() method in doInBackground.
if (Helper.isNetworkConnected(this)) {
// do your stuff
} else{
Toast.makeText(YourActivity.this, "Your internet connection is lost.", Toast.LENGTH_SHORT).show();
}
Use this permission in Manifest file.
<uses-permission android:name="android.permission.INTERNET" />
If the question is "how to display warning inside doInBackground" because you are not allowed to access the gui inside doInBackground technically you can use the progress indicator of asynctask to transfer a message to the gui.
However i would recommond a differen aproach: either
check for problems before starting the async task
or let the async task stop and return with an error as described by #Muthukrishnan Rajendran

Display Listview Count in Textview with id/list?

I am loading my data in a listview from my localhost server. I want to display the count in a textview (locationCount). Any ideas?
My listview has id/list which is referenced for an async class that loads the products. Hence I am bit confused if you treat as a normal listview or is it slightly different?
I have 20 entries in my DB that show, so count should be 20, but when I delete an entry the count should be 19, or 21 if I add. Please explain?
Class:
public class ViewAllLocations extends ListActivity {
String id;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> profileList;
// url to get all products list
private static String url_all_profile = "http://MYIP:8888/android_connect/get_all_location.php";
// url to delete product
private static final String url_delete_profile = "http://MYIP:8888/android_connect/delete_location.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_LOCATION = "Location";
private static final String TAG_ID = "id";
private static final String TAG_LATITUDE = "latitude";
private static final String TAG_LONGITUDE = "longitude";
// products JSONArray
JSONArray userprofile = null;
TextView locationCount;
int count = 0;
Button deleteLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_locations);
// Hashmap for ListView
profileList = new ArrayList<HashMap<String, String>>();
deleteLocation = (Button) findViewById(R.id.deleteLocation);
// Loading products in Background Thread
new LoadAllLocation().execute();
deleteLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DeleteLocation().execute();
}
});
// Get listview
ListView lo = getListView();
getListAdapter().getCount();
locationCount.setText(getListAdapter().getCount());
}
/*****************************************************************
* Background Async Task to Delete Product
* */
class DeleteLocation extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewAllLocations.this);
pDialog.setMessage("Deleting Location...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Deleting product
* */
protected String doInBackground(String... args) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", id));
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
url_delete_profile, "POST", params);
// check your log for json response
Log.d("Delete Product", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// product successfully deleted
// notify previous activity by sending code 100
// Intent i = getIntent();
// send result code 100 to notify about product deletion
//setResult(100, i);
Toast.makeText(getApplicationContext(), "Location Deleted",
Toast.LENGTH_SHORT).show();
finish();
}
} 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();
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllLocation extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewAllLocations.this);
pDialog.setMessage("Loading Locations. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(url_all_profile, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Profiles: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
userprofile = json.getJSONArray(TAG_LOCATION);
// looping through All Products
for (int i = 0; i < userprofile.length(); i++) {
JSONObject c = userprofile.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String latitude = c.getString(TAG_LATITUDE);
String longitude = c.getString(TAG_LONGITUDE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_LATITUDE, latitude);
map.put(TAG_LONGITUDE, longitude);
// adding HashList to ArrayList
profileList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
UserLocation.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ViewAllLocations.this, profileList,
R.layout.locationitem, new String[] { TAG_ID,
TAG_LATITUDE, TAG_LONGITUDE},
new int[] { R.id.id, R.id.latitude, R.id.longitude});
// updating listview
setListAdapter(adapter);
}
});
}
}
Log: "It gets the profiles and then when it reaches the final end it crashes"
04-19 19:09:48.665 26876-27452/com.example.ankhit.saveme D/All Profiles:﹕ {"success":1,"Location":[{"id":"26","longitude":"-0.5509257","latitude":"51.4276462"},{"id":"27","longitude":"-0.5509387","latitude":"51.4277023"},{"id":"28","longitude":"-0.5509387","latitude":"51.4277023"},{"id":"29","longitude":"-0.550991","latitude":"51.4275759"}]}
04-19 19:09:48.675 26876-26876/com.example.ankhit.saveme D/AndroidRuntime﹕ Shutting down VM
04-19 19:09:48.675 26876-26876/com.example.ankhit.saveme W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x42008ac8)
04-19 19:09:48.675 26876-26876/com.example.ankhit.saveme E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.ankhit.saveme.ViewAllLocations$LoadAllLocation$1.run(ViewAllLocations.java:260)
at android.app.Activity.runOnUiThread(Activity.java:4843)
at com.example.ankhit.saveme.ViewAllLocations$LoadAllLocation.onPostExecute(ViewAllLocations.java:246)
at com.example.ankhit.saveme.ViewAllLocations$LoadAllLocation.onPostExecute(ViewAllLocations.java:165)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Override the get count() method in your adapter or post it here and I'll give you some code.
Call adapter.get count() whenever you add or remove an item.

AsyncTask not completing as expected [duplicate]

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

Using String doInBackground(String... args)

I am working on saving my data to a MySQL db. I read that you need to use a new thread to open the db. I have seen examples for using AsyncTask. How would I access the doInBackground method. I have tried a variety of different method call and either get an error or the program does not use the AsyncTask. Here is my code. I have tried different version of AddtoSQLDB db = new AddtoSQLDB()
and CreateNewProduct cn = new CreateNewProduct().
public class AddToMySQLDB extends Activity {
JSONParser jsonParser = new JSONParser();
// TODO Auto-generated method stub
// url to create new product
private static String url_create_product = "http://api.androidhive.info/android_connect/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private ProgressDialog pDialog;
static String name = "";
static String company = "";
static String timeIn = "";
static String signature;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
}
public static void setVariable(String sDate, String visitorsName2, String visitorsCompany2, byte[] signature2) {
name = visitorsName2;
company = visitorsCompany2;
timeIn = sDate;
}
class CreateNewProduct extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// getting JSON Object
// Note that create product url accepts POST method
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("timeIn", timeIn));
params.add(new BasicNameValuePair("signature", signature));
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
/* Intent i = new Intent(getApplicationContext(),
AllProductsActivity.class);
startActivity(i);*/
// closing this screen
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
You need to execute your AsyncTask:
CreateNewProduct cn = new CreateNewProduct();
cn.execute(""); //pass the params you want for doInBackground here

how to add current login user to welcome.java

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

Categories