Android - SharedPreferences not working? - android

Here's the code where I get to have the SharedPreferences:
public class MainActivity2 extends Activity {
Button b;
EditText et;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
String rfid, getPref;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
b = (Button)findViewById(R.id.loginnext);
et = (EditText)findViewById(R.id.rfid);
tv = (TextView)findViewById(R.id.tv);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity2.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
void login(){
try{
SharedPreferences preferences = getSharedPreferences(getPref, Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://usamobileapp.pe.hu/webservice/check.php");
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
if(response.equalsIgnoreCase("User Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity2.this,"Login Success", Toast.LENGTH_SHORT).show();
editor.putString("rfid" ,rfid);
editor.commit();
}
});
startActivity(new Intent(MainActivity2.this, MainActivity3Activity.class));
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
This is where I'd like the get the Registration ID entered by the user and use it in all activities of the app.
Here is the code to check whether I get to have the SharedPreferences correctly. It displays it through I text view. I wonder why it would not show up. Did I do the SharePreferences correctly?
public class ViewGradesActivity extends ActionBarActivity {
TextView viewPref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_grades);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
String get = settings.getString("rfid", "");
viewPref = (TextView) findViewById(R.id.tv);
viewPref.setText(get);
}
}
By the way, the code above is from another class.
Thanks for the help in advance.

You are receiving this error because you are writing to a different SharedPreferences than you are reading from. If you are using default SharedPreferences, make sure you read and write to the default preferences.
// Read the String from SharedPreferences
String awesomeString = PreferenceManager.getDefaultSharedPreferences(context).getString("key", "");
// Write the String to SharedPreferences
PreferenceManager.getDefaultSharedPreferences(context)
.edit().putString("key", awesomeString).commit();

That's because you don't read and write the preferences in the same preference file.
To write you use:
SharedPreferences preferences = getSharedPreferences(getPref, Context.MODE_PRIVATE);
To read you use:
PreferenceManager.getDefaultSharedPreferences(this);
So you write you preferences in a file getPref (which is null according to your code, don't you get any error?) but you read your preferences in the default file provided by the Android API.

Are you sure that you put any value in rfid? Here
public void run() {
Toast.makeText(MainActivity2.this,"Login Success", Toast.LENGTH_SHORT).show();
editor.putString("rfid" ,rfid);
editor.commit();
}
I think rfid is null. I did not find any place where you are initializing it.
Put rfid in toast or log it and you will see.
And as everybody else say you have to use default shared preferences in both classes. Here you can find why Difference between getDefaultSharedPreferences and getSharedPreferences

Related

how to retrive shared preferences from another class without activity ANDROID

package com.example.win7.simpleloginapp;
public class ServerRequest {
ProgressDialog progressDialog;
public static final int CONNECTION_TIMEOUT = 1000 * 15;
public static final String SERVER_ADDRESS = "ekinidris.site40.net";
final static String TAG_USER = "user";
JSONArray user;
JSONParser jsonParser = new JSONParser();
// Create object of SharedPreferences.
SharedPreferences sharedPref1 = PreferenceManager.getDefaultSharedPreferences(this);
public ServerRequest(Context context) {
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("Processing..");
progressDialog.setMessage("Please Wait....");
}
public void storeUserDataInBackground(user user, GetUserCallback userCallback) {
progressDialog.show();
new StoreUserDataAsyncTask(user, userCallback).execute();
}
public void fetchUserDataInBackground(user user, GetUserCallback callBack) {
progressDialog.show();
new fetchUserDataAsyncTask(user, callBack).execute();
}
public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, user> {
user user;
GetUserCallback userCallback;
public fetchUserDataAsyncTask(user user, GetUserCallback userCallback) {
this.user = user;
this.userCallback = userCallback;
}
#Override
protected user doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("username", user.username));
dataToSend.add(new BasicNameValuePair("password", user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost("http://mysyshcms.cloudapp.net:1005/fetchUserData.php");
user returnedUser = null;
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
HttpResponse httpResponse = client.execute(post);
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
JSONObject jObject = new JSONObject(result);
if(jObject.length()==0)
{
returnedUser = null;
}
else
{
String Name1 = jObject.getString("Name");
//now get Editor
SharedPreferences.Editor editor = sharedPref1.edit();
//put your value
editor.putString("username", Name1);
//commits your edits
editor.commit();
returnedUser = new user(user.username, user.password);
}
} catch (Exception e) {
e.printStackTrace();
}
return returnedUser;
}
#Override
protected void onPostExecute(user returnedUser) {
progressDialog.dismiss();
userCallback.done(returnedUser);
super.onPostExecute(returnedUser);
}
}
}
i have ServerRequest class which is not an activity . In public class fetchUserDataAsyncTask i want to make a shared preferences . this is because i want to pass data that i get from database to another activity (MainActivity)
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#689a92")));
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
setContentView(R.layout.activity_main);
SharedPreferences sharedPref1 = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref1.getString("username", "NOT AVAILABLE");
etUsername.setText(userName);
but i keep getting "NOT AVAILABLE" instead of Name1 that i declare in server request . How to solve this ?
If u to implement SharedPreferences into your current class. You must at first pass related activity context.
try this :
public class ServerRequest {
private Context mContext;
public ServerRequest(Context context) {
mContext = context;
}
public SharedPreferences getSharedPref(){
return mContext.getSharedPreferences(mContext.getPackageName(), Context.MODE_PRIVATE);
}
public void storeData(String data) {
getSharedPref().edit().putString("data", data).apply();
}
public String getData(){
return getSharedPref().getString("data", "");
}
}
Now, on your any classes. You can read back the data by calling
ServerRequest serverRequest = new ServerRequest(getActivity());
Log.d("","The value is : " + serverRequest.getData());
PreferenceManager.getDefaultSharedPreferences(this) is used for default SharedPreferences file that is used by the preference framework.
If you want to save SharedPreferences inside your app then you need to use SharedPreferences interface. To use it you'll need the context of the Activity.
The following snippet shows you how to save data to SharedPreferences:
SharedPreferences sharedPreferences = context.getSharedPreferecnes("Shared_PREF_NAME, Contextt.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("key", 100);
editor.commit();
To retrieve use this:
sharedPreferences.getInt("key", 0);
For more info, visit following links:
http://developer.android.com/reference/android/content/SharedPreferences.html
http://developer.android.com/reference/android/content/SharedPreferences.Editor.html
You can directly save data preference in your onPostExecute method of your fetchUserDataAsyncTask class and you can access that,
like below.
SharedPreferences sharedPref1 = PreferenceManager.getDefaultSharedPreferences(this);
sharedPref1.edit().putString("username",""+username).commit();

Android Login with php getting error after successful json parsing

Hi i am getting an error even if login with correct user name and password.but json response is correct but it is showing user not found.where i need to change the code. Thanks in advance.
i am getting success json data if i login with correct user name and password else failure response i am getting but every time it is showing user not found error.
Login extends Activity {
Button b;
EditText et,pass;
TextView tv;
#SuppressWarnings("deprecation")
HttpPost httppost;
StringBuffer buffer;
#SuppressWarnings("deprecation")
HttpResponse response;
#SuppressWarnings("deprecation")
HttpClient httpclient;
#SuppressWarnings("deprecation")
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
b = (Button)findViewById(R.id.Button01);
et = (EditText)findViewById(R.id.username);
pass= (EditText)findViewById(R.id.password);
tv = (TextView)findViewById(R.id.tv);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(Login.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
#SuppressWarnings("deprecation")
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://192.168.137.224/android_connect/get_product_details.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("name",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
// edited by James from coderzheaven.. from here....
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
// tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
if(response.equalsIgnoreCase("yes"))
{
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Login.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent(Login.this, OtherActivty.class));
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert(){
Login.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
Use http://www.java2s.com/Code/JarDownload/java-json/java-json.jar.zip as a library!
First of all, the JSON is not proper!
Proper JSON:
{
"success": "yes",
"message": "Logged In"
}
Second use this to retrieve the contents of the "success" variable:
JSONObject myjson = new JSONObject(response);
System.out.println(myjson.getString("success"));

login page with httpget and asynctask in android

Hi I'm new to android and have task to create a login page that will connect with server and check user exist using http Get and AsyncTask and PHP API for this is ready. i went through few tutorials on AsyncTask and i understood but i m not sure how to work with http Get and AsyncTask. can anyone please help how to link both and create login page.
P.S: i have two EditText to accept username and password and two Buttons one for login and other for register and have corresponding DB as well.
This is sample code-
public class LoginActivity extends Activity
{
Intent i;
Button signin, signup;
String name = "", pass = "";
byte[] data;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream;
SharedPreferences app_preferences, pref;
List<NameValuePair> nameValuePairs;
EditText editTextId, editTextP;
SharedPreferences.Editor editor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
signin = (Button) findViewById(R.id.signin);
signup = (Button) findViewById(R.id.signup);
editTextId = (EditText) findViewById(R.id.editTextId);
editTextP = (EditText) findViewById(R.id.editTextP);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
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);
}
signin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
signin.setEnabled(false);
signup.setEnabled(false);
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(LoginActivity.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
signin.setEnabled(true);
signup.setEnabled(true);
}
else
{
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if(name.matches(emailPattern))
new LoginTask().execute();
signin.setEnabled(false);
signup.setEnabled(false);
}
}
});
signup.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Move_next();
}
});
}
public void Move_to_next()
{
final Handler handle = new Handler();
Runnable delay = new Runnable() {
public void run() {
startActivity(new Intent(LoginActivity.this, SplashActivity.class));
finish();
}
};
handle.postDelayed(delay,2000);
}
public void Move_next()
{
startActivity(new Intent(LoginActivity.this, SignUpActivity.class));
finish();
}
#SuppressLint("NewApi")
private class LoginTask extends AsyncTask <Void, Void, String>
{
#SuppressLint("NewApi")
#Override
protected void onPreExecute()
{
super.onPreExecute();
// Show progress dialog here
}
#Override
protected String doInBackground(Void... arg0) {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://website.com/yourpagename.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 "";
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Hide progress dialog here
if (buffer.charAt(0) == 'Y')
{
Toast.makeText(LoginActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
Move_to_next();
}
else
{
Toast.makeText(LoginActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
signin.setEnabled(true);
signup.setEnabled(true);
}
}
}
}

Log in and Signup page

I am creating sign up page for my app. I have 4 text fields in below code EditEmail, EditPass, EditRepass, EditMobile. I already made login page, now I need to make some changes in my login code to make sign up page work. But I think I made few mistakes. In login I have a check box, but in this code it is not required. I do not know how to tackle with checbox code. I want to send the above 4 fields to my remote server and check if "email id" is not used before then user get registered. How should I make the following code perfect.
public class SignUpActivity extends Activity
{
EditText editEmail, editPass, editRepass, editMobile;
Button submit,exit;
String name = "", pass = "", repass = "", mobile = "";
SharedPreferences app_preferences;
Intent i;
CheckBox check;
byte[] data;
HttpPost httppost;
HttpResponse response;
HttpClient httpclient;
StringBuffer buffer;
InputStream inputStream;
List<NameValuePair> nameValuePairs;
#Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
submit = (Button) findViewById(R.id.submit);
exit = (Button) findViewById(R.id.exit);
editEmail=(EditText)findViewById(R.id.editEmail);
editPass=(EditText)findViewById(R.id.editPass);
editRepass=(EditText)findViewById(R.id.editRepass);
editMobile=(EditText)findViewById(R.id.editMobile);
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_repass = app_preferences.getString("repassword", "0");
String Str_mobile = app_preferences.getString("mobile", "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);
}
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
name = editEmail.getText().toString();
pass = editPass.getText().toString();
repass = editRepass.getText().toString();
mobile = editMobile.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.putString("repassword", repass);
editor.putString("umobile", mobile);
editor.commit();
}
if (name.equals("") || pass.equals("") || repass.equals("") || mobile.equals("") ) {
Toast.makeText(SignUpActivity.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
} else {
}
}
});
exit.setOnClickListener(new View.OnClickListener ()
{
public void onClick(View v)
{
finish();
}
});
}
public void Move_to_next1()
{
startActivity(new Intent(SignUpActivity.this, SplashActivity.class));
finish();
}
#SuppressLint("NewApi")
private class LoginTask extends AsyncTask <Void, Void, String>
{
#SuppressLint("NewApi")
#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/login1.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
nameValuePairs.add(new BasicNameValuePair("RePassword", repass.trim()));
nameValuePairs.add(new BasicNameValuePair("Mobile", mobile.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 "";
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Hide progress dialog here
if (buffer.charAt(0) == 'Y')
{
Toast.makeText(SignUpActivity.this, "Succesfully Registered", Toast.LENGTH_SHORT).show();
Move_to_next1();
}
else
{
Toast.makeText(SignUpActivity.this, " E-Mail Already Registered", Toast.LENGTH_SHORT).show();
}
}
}
}

StartActivity() red highlighted

Basically I want to have a button to start a new activity after login.
I found that I was not able to call the StartActivity() as what I did before in the login page.Please guide
This is the login page where I used StartActivity(this,sth.class)sucessfully
public class Login extends Activity
{
/** Called when the activity is first created. */
Button login;
String name="",pass="";
EditText username,password;
TextView tv;
byte[] data;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream;
SharedPreferences app_preferences ;
List<NameValuePair> nameValuePairs;
CheckBox check;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
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"))
{
username.setText(Str_user);
password.setText(Str_pass);
check.setChecked(true);
}
login.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
name = username.getText().toString();
pass = password.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(Login.this, "Blank Field..Please Enter", Toast.LENGTH_LONG).show();
}
else
{
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://fyptest.comyr.com/main.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(Login.this, "error"+e.toString(), Toast.LENGTH_LONG).show();
}
if(buffer.charAt(0)=='Y')
{
Toast.makeText(Login.this, "login successfull", Toast.LENGTH_LONG).show();
Move_to_next();
}
else
{
Toast.makeText(Login.this, "Invalid Username or password", Toast.LENGTH_LONG).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()
{
//may perform checking based on ID
startActivity(new Intent(this, MainMenu.class));
}
But this, my startActivity is being underlined in red
public class MainMenu extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
Button new_folder = (Button)findViewById(R.id.new_folder);
new_folder.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// show another class
startActivity(new Intent(this,Folder_Details.class));
}
});
}
}
It shows "The constructor Intent(new View.OnClickListener(){}, Class) is undefined" and "Remove arguments to match Intent()" options
I have included the <Activity></Activity> in Manifest. And the code showed above, imports are cut off
Yes this is because, you are trying to use "this" with refernce to your button instead of your activity. You have to replace it like this,
Instead of startActivity(new Intent(this, Folder_Details.class));
do this,
startActivity(new Intent(MainMenu.this, Folder_Details.class));
Modify it as
startActivity(new Intent(MainMenu.this,Folder_Details.class));
You are using a View.OnClickListener instead of a Context instance.
startActivity(new Intent(MainMenu.this,Folder_Details.class));

Categories

Resources