I'm using shared preference to store user data, and in my start screen, I want to check whether username has already logged in or not, when user is still not logged out yet it will redirect to UserView.java when the application starts, otherwise it will go to LoginActivity.java
I've used these tutorial as my references :
Android Hive Tutorial Shared Pref, and
Android example tutorial Shared Pref..
but when I exit my activity without logging out, next time I open my application it's status is logged out (its like the session has ended although I have not logged out yet from my application),,
What should I do to fix this thing, so whenever I exit my application (without logging out) my data is still there in shared pref and will be redirected to UserView.java, Am i making any mistakes with my codes?
These are my code:
userSessionManager.java
package com.thesis.teamizer;
import java.util.HashMap;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class userSessionManager {
// Shared Preferences Reference
SharedPreferences CurrentSession;
// Editor Reference for Editing Shared Preferences
Editor editor;
// Context Reference
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharef Preferences Name
public static String PrefName = "MyUsername";
// All Shared Preferences Keys
private static final String IS_USER_LOGIN = "IsUserLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_USERNAME = "username";
// Constructor
public userSessionManager(Context context) {
this._context = context;
CurrentSession = _context.getSharedPreferences(PrefName, PRIVATE_MODE);
editor = CurrentSession.edit();
}
public void createUserLogin(String username) {
// User has already login
editor.putBoolean(IS_USER_LOGIN, true);
// Storing username in pref
editor.putString(KEY_USERNAME, username);
// Editor ready to execute the previous codes
editor.commit();
}
public boolean checkLogin() {
// Check login status. If the user is not logged in
if (!this.isUserLoggedIn()) {
return true;
}
return false;
}
// Read session using hashmap
public HashMap<String, String> getUserDetails() {
// Use hashmap to store user credentials
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_USERNAME, CurrentSession.getString(KEY_USERNAME, null));
// return user
return user;
}
public void logOut() {
// clearing all data from Shared pref
editor.remove(KEY_USERNAME);
editor.clear();
editor.commit();
}
// Will check if the user is Login or not by getting the boolean of
// IS_USER_LOGIN from CurrentSession(pref)
private boolean isUserLoggedIn() {
// TODO Auto-generated method stub
return CurrentSession.getBoolean(IS_USER_LOGIN, false);
}
}
LoginActivity.java
package com.thesis.teamizer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity implements View.OnClickListener {
private EditText etUsername;
private EditText etPassword;
private Button bLogin, bRegis, bAdmin;
userSessionManager session;
String loginUrl;
JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private ProgressDialog pDialog;
String Username;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
Declaration();
bLogin.setOnClickListener(this);
bRegis.setOnClickListener(this);
bAdmin.setOnClickListener(this);
if (session.checkLogin()) {
Intent intent = new Intent("com.thesis.teamizer.USERVIEW");
finish();
startActivity(intent);
}
}
private void Declaration() {
// TODO Auto-generated method stub
etUsername = (EditText) findViewById(R.id.etLoginUsername);
etPassword = (EditText) findViewById(R.id.etLoginPassword);
bLogin = (Button) findViewById(R.id.bLogin);
bRegis = (Button) findViewById(R.id.bRegister);
bAdmin = (Button) findViewById(R.id.bAdminadmin);
session = new userSessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
Username = user.get(userSessionManager.KEY_USERNAME);
myIP ip = new myIP();
String myIp = ip.getIp();
String thisPhp = "doLogin.php";
loginUrl = myIp + thisPhp;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLogin:
new AttemptLogin().execute();
break;
case R.id.bRegister:
Intent i = new Intent("com.thesis.teamizer.REGISTRATIONACTIVITY");
startActivity(i);
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(LoginActivity.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 = etUsername.getText().toString();
String password = etPassword.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(loginUrl, "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());
String currentLoginUsername = username;
session.createUserLogin(currentLoginUsername);
Intent intent = new Intent("com.thesis.teamizer.USERVIEW");
finish();
startActivity(intent);
String sukses = "Sukses login";
return sukses;
} else if (success == 0) {
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();
Toast.makeText(getApplicationContext(), file_url,
Toast.LENGTH_SHORT).show();
}
}
}
UserView.java
package com.thesis.teamizer;
import java.util.HashMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class UserView extends Activity implements View.OnClickListener {
public Button createGr, viewGr, createAn, viewAn, notification, logout,
calendar, createEvent, myEvent, createTask, myTask;
public String Username;
userSessionManager session;
Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.user_view);
sessionAndDeclaration();
createGr.setOnClickListener(this);
viewGr.setOnClickListener(this);
createAn.setOnClickListener(this);
viewAn.setOnClickListener(this);
notification.setOnClickListener(this);
logout.setOnClickListener(this);
createEvent.setOnClickListener(this);
calendar.setOnClickListener(this);
myEvent.setOnClickListener(this);
createTask.setOnClickListener(this);
myTask.setOnClickListener(this);
}
private void sessionAndDeclaration() {
// TODO Auto-generated method stub
session = new userSessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
// get name
Username = user.get(userSessionManager.KEY_USERNAME);
TextView a = (TextView) findViewById(R.id.tvUserVUsername);
a.setText(Username);
createGr = (Button) findViewById(R.id.bCreateGroup);
viewGr = (Button) findViewById(R.id.bViewMyGroup);
createAn = (Button) findViewById(R.id.bCreateAnnouncement);
viewAn = (Button) findViewById(R.id.bViewMyAnnouncement);
notification = (Button) findViewById(R.id.bNotification);
logout = (Button) findViewById(R.id.bDoLogout);
calendar = (Button) findViewById(R.id.bGoToMyCalendar);
createEvent = (Button) findViewById(R.id.bCreateEvent);
myEvent = (Button) findViewById(R.id.bGoToMyEvent);
createTask = (Button) findViewById(R.id.bGoToCreateTask);
myTask = (Button) findViewById(R.id.bGoToMyTask);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bCreateGroup:
i = new Intent("com.thesis.teamizer.CREATEGROUPACTIVITY");
startActivity(i);
break;
case R.id.bViewMyGroup:
i = new Intent("com.thesis.teamizer.MYGROUPACTIVITY");
startActivity(i);
break;
case R.id.bCreateAnnouncement:
i = new Intent("com.thesis.teamizer.CREATEANNOUNCEMENTACTIVITY");
startActivity(i);
break;
case R.id.bViewMyAnnouncement:
i = new Intent("com.thesis.teamizer.VIEWALLANNOUNCEMENT");
startActivity(i);
break;
case R.id.bNotification:
i = new Intent("com.thesis.teamizer.NOTIFICATION");
startActivity(i);
break;
case R.id.bDoLogout:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to Logout?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
finish();
session.logOut();
Intent i = new Intent(
"com.thesis.teamizer.LOGINACTIVITY");
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
startActivity(i);
finish();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
break;
case R.id.bGoToMyCalendar:
i = new Intent("com.thesis.teamizer.VIEWCALENDAR");
startActivity(i);
break;
case R.id.bCreateEvent:
i = new Intent("com.thesis.teamizer.CREATEEVENT");
startActivity(i);
break;
case R.id.bGoToMyEvent:
i = new Intent("com.thesis.teamizer.MYEVENT");
startActivity(i);
break;
case R.id.bGoToCreateTask:
i= new Intent("com.thesis.teamizer.CREATETASK");
startActivity(i);
break;
case R.id.bGoToMyTask:
i = new Intent("com.thesis.teamizer.MYTASK");
startActivity(i);
break;
}
}
}
Related
I have a login screen that take the username and password from user and validate it in the backend. Code i have written so far is below
package com.example.opinion;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.POST;
public class Login extends Activity {
private Button login;
private Button reg;
private EditText uname;
private EditText pword;
public static final String BASE_URL = "http://192.168.0.105/";
public interface LoginApi{
#POST("login")
Call<HttpBinResponse> userLogin(#Body LoginData data);
}
static class HttpBinResponse {
String result;
}
public class LoginData {
String username;
String password;
public LoginData(String uname, String pword) {
this.username = uname;
this.password = pword;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login =(Button) findViewById(R.id.btnlogin);
reg =(Button) findViewById(R.id.btnregister);
uname = (EditText)findViewById(R.id.uname);
pword = (EditText)findViewById(R.id.pass);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name = uname.getText().toString();
String pass = pword.getText().toString();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
LoginData user = new LoginData(name, pass);
System.out.println(user.username+user.password);
LoginApi apiService = retrofit.create(LoginApi.class);
Call<HttpBinResponse> call = apiService.userLogin(user);
call.enqueue(new Callback<HttpBinResponse>() {
#Override
public void onResponse(Call<HttpBinResponse> call, Response<HttpBinResponse> response) {
int statusCode = response.code();
HttpBinResponse decodedResponse = response.body();
if (decodedResponse == null)
return;
// at this point the JSON body has been successfully parsed
System.out.println(decodedResponse.result);
}
#Override
public void onFailure(Call<HttpBinResponse> call, Throwable t) {
}
});
Intent it= new Intent(Login.this, Home.class);
startActivity(it);
}
});
reg.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent it = new Intent(Login.this, Registration.class);
startActivity(it);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
}
In the above code LoginData class is used to attach the body for my post request.
HttpBinResponse class is for getting the response and store it in the result attribute. But i checked that my code is not returning any thing as the decodedResponse.result is null.
see this:
05-30 11:35:59.186 31176-31194/? I/OpenGLRenderer﹕ Initialized EGL,
version 1.4 05-30 11:36:08.783 31176-31176/com.example.opinion
I/System.out﹕ hkbffghjk 05-30 11:36:08.877
31176-31176/com.example.opinion I/System.out﹕ null
instead of null it should be a json object with key as result and its value.
Can anyone tell me how to get the proper response.
it seems like the url i'm creating is not created properly, either the body of the post request is not getting attached or some other problem.
i checked my sever logs and found that the request is reaching the server but nothing happens after that.
Okay So this is an activity class where I am trying to export my sharedPreferences that are saved to a CSV file. This does not work. What am I doing wrong? How do I correctly write the sharedPreferences items to a CSV file?
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Admin extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
Button btViewContacts = (Button)findViewById(R.id.btnViewContacts);
Button btDeleteContacts = (Button)findViewById(R.id.btnDeleteContacts);
Button btExportCSV = (Button)findViewById(R.id.btnExportCSV);
final Context context = this;
final SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(this);
btViewContacts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Admin.this, Contacts.class));
}
});
btDeleteContacts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//DISPLAY ALERT DIALOG
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); //show an alertDialog when user selects delete radio button and clicks process, prompt to confirm
//set title
alertDialogBuilder.setTitle("DELETE ALL CONTACTS?");
//set dialog message
alertDialogBuilder
.setMessage("Are you sure you want to delete ALL acquired contact info?")
.setCancelable(true)
//no button
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) { //if user selects no, close dialog
// TODO Auto-generated method stub
//if clicked this will close the dialog and do nothing.
dialog.cancel();
}
})
//yes button
.setPositiveButton("Yes", new DialogInterface.OnClickListener() { //if user selects yes, clear the shared preferences and display confirmation message when deleted.
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//if this button is clicked it will erase the values in memory
SharedPreferences.Editor editor = sharedPref.edit();
editor.clear();
editor.commit();
//displays toast message confirming deletion of race info
Toast.makeText(Admin.this, "Contact Info Deleted.", Toast.LENGTH_SHORT).show();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
Map<String, ?> allEntries = sharedPref.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Log.d("TAG", entry.getKey() + ": " + entry.getValue().toString());
}
btExportCSV.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
generateCsvFile(Environment.getExternalStorageDirectory().getPath());
}
});
}
private void generateCsvFile(String sFileName)
{
final SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(this);
String delimiter = ",";
try
{
FileWriter writer = new FileWriter(sFileName);
writer.append("First Name");
writer.append(',');
writer.append("Last Name");
writer.append(',');
writer.append("Email");
writer.append(',');
writer.append("Phone");
writer.append(',');
writer.append("Address");
writer.append(',');
writer.append("City");
writer.append(',');
writer.append("State");
writer.append(',');
writer.append("Zip");
writer.append('\n');
Map<String, ?> allEntries = sharedPref.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Map<String,?> all = sharedPref.getAll();
Iterator it = all.entrySet().iterator();
Map.Entry pairs = (Map.Entry)it.next();
if (pairs.getKey().toString().startsWith("contactid_")) {
String strContact = sharedPref.getString((String)pairs.getKey(), "");
String[] data = TextUtils.split(strContact, delimiter);
writer.write(strContact);
writer.append('\n');
}
Toast.makeText(Admin.this, "ContAcq's Exported to .CSV.", Toast.LENGTH_SHORT).show();
//generate whatever data you want
writer.flush();
writer.close();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Ok,
I'm doing this for 4 straight hours. And the facebook Login still doesn't work. The session state is always OPENING. ALWAYS. onActivityResult NEVER gets called. The key in the developer console is correct, the starting class is correct, and this is my code
package XXXXX
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import ua.org.zasadnyy.zvalidations.Field;
import ua.org.zasadnyy.zvalidations.Form;
import ua.org.zasadnyy.zvalidations.validations.HasMinimumLength;
import ua.org.zasadnyy.zvalidations.validations.IsEmail;
import ua.org.zasadnyy.zvalidations.validations.NotEmpty;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Base64;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
public class SplashScreen extends FragmentActivity {
public static String TAG = "SplashScreen";
/**
* LoginActivity
*/
private static final int LOGIN = 0;
private static final int SIGNUP = 1;
private static final int SELECTUSERNAME = 2;
private static final int FRAGMENT_COUNT = SELECTUSERNAME +1;
private boolean isResumed = false;
private Fragment[] fragments = new Fragment[FRAGMENT_COUNT];
private MenuItem settings;
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback =
new Session.StatusCallback() {
#Override
public void call(Session session,
SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
/**
* UI Elements
*/
Button btn_signUp;
Button btn_signUpSubmit;
LoginButton btn_facebookAuth;
//Edit Text
EditText edittextEmail;
EditText edittextPassword;
//Form
Form signUpForm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
setContentView(R.layout.splash);
FragmentManager fm = getSupportFragmentManager();
fragments[LOGIN] = fm.findFragmentById(R.id.loginFragment);
fragments[SIGNUP] = fm.findFragmentById(R.id.signUpFragment);
fragments[SELECTUSERNAME] = fm.findFragmentById(R.id.selectUserNameFragment);
FragmentTransaction transaction = fm.beginTransaction();
for(int i = 0; i < fragments.length; i++) {
transaction.hide(fragments[i]);
}
transaction.commit();
btn_signUp = ( Button ) findViewById(R.id.btn_signUpMail);
btn_signUp.setOnClickListener( listener_btn_signUp );
btn_signUpSubmit = (Button) findViewById(R.id.btn_signUpSubmit);
btn_signUpSubmit.setOnClickListener(listener_btn_signUpSubmit);
edittextEmail = (EditText)findViewById(R.id.et_signUpMail);
edittextPassword = (EditText)findViewById(R.id.et_signUpPw);
signUpForm = new Form ( this );
signUpForm.addField(Field.using(edittextEmail).validate(NotEmpty.build(this.getApplicationContext())).validate(IsEmail.build(this.getApplicationContext())));
signUpForm.addField(Field.using(edittextPassword).validate(NotEmpty.build(this.getApplicationContext())).validate(HasMinimumLength.build(this.getApplicationContext(), 8)));
btn_facebookAuth = (LoginButton)findViewById(R.id.login_button);
btn_facebookAuth.setReadPermissions(Arrays.asList("email"));
}
private OnClickListener listener_btn_signUp = new OnClickListener() {
#Override
public void onClick(View v) {
showFragment(SIGNUP, true);
}
};
private OnClickListener listener_btn_signUpSubmit = new OnClickListener() {
#Override
public void onClick(View v) {
if (signUpForm.isValid()) {
Log.i("SignupFragment", "Form is valid");
// User userModel = new User();
// userModel.isFacebookConnected = "0";
// userModel.userEmail = edittextEmail.getText().toString();
// userModel.userPassword = edittextPassword.getText().toString();
// SelectUserNameFragment selectUserNameFragment = new SelectUserNameFragment();
// SelectUserNameFragment.user = userModel;
// getFragmentManager()
// .beginTransaction()
// .replace(android.R.id.content, selectUserNameFragment)
// .addToBackStack("")
// .commit();
} else {
Log.i("SignupFragment", "Form not valid");
}
}
};
private void showFragment(int fragmentIndex, boolean addToBackStack) {
Log.i(TAG, "showFragment");
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
for (int i = 0; i < fragments.length; i++) {
if (i == fragmentIndex) {
transaction.show(fragments[i]);
} else {
transaction.hide(fragments[i]);
}
}
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.commit();
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
Log.i(TAG, "onSessionStateChange");
FragmentManager manager = getSupportFragmentManager();
int backStackSize = manager.getBackStackEntryCount();
for (int i = 0; i < backStackSize; i++) {
manager.popBackStack();
}
System.out.println ( state.name() );
if (state.isOpened()) {
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
try {
User userModel = new User();
userModel.facebookId = user.getId();
Map<String, String> where = new HashMap<String, String>();
where.put("where", "WHERE facebookId='" + user.getId() + "'" );
userModel.loadModelFrom(where);
if ( userModel.userData.isEmpty() ) {
userModel.isFacebookConnected = "1";
userModel.userEmail = user.asMap().get("email").toString();
SelectUserNameFragment.user = userModel;
showFragment(SELECTUSERNAME, true);
} else {
Intent intent = new Intent ( getApplicationContext(), DashboardActivity.class );
intent.putExtra("User", userModel);
startActivity(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).executeAsync();
// showFragment(DASHBOARD, false);
} else if (state.isClosed()) {
showFragment(LOGIN, false);
}
}
#Override
protected void onResumeFragments() {
super.onResumeFragments();
Log.i(TAG, "onResumeFragments");
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
Intent intent = new Intent ( this, DashboardActivity.class );
intent.putExtra("Session", session);
startActivity(intent);
} else {
showFragment(LOGIN, false);
}
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "onResume");
uiHelper.onResume();
isResumed = true;
}
#Override
public void onPause() {
super.onPause();
Log.i(TAG, "onPause");
uiHelper.onPause();
isResumed = false;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
uiHelper.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.i(TAG, "onSaveInstanceState");
uiHelper.onSaveInstanceState(outState);
}
}
What did I forget?
Apparently it is not allowed to have
android:noHistory="true" in your manifest. I removed it and now it works.
I'm trying to create an if statement, for example if the user doesn't type anything into the the two edit text's, then it displays a toast and resets everything. But for some reason, my code completely ignores this and just goes to the else statement instead.
Can anyone help?
My Code:
package com.gta5news.bananaphone;
import java.io.File;
import android.R.string;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LogIn extends Activity implements OnClickListener {
Button send;
EditText user;
EditText pass;
CheckBox staySignedIn;
SharedPreferences shareduser;
SharedPreferences sharedpass;
public static String settings = "MySharerdUser";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
send = (Button) findViewById(R.id.bLogIn);
user = (EditText) findViewById(R.id.eTuser);
pass = (EditText) findViewById(R.id.eTpassword);
staySignedIn = (CheckBox) findViewById(R.id.Cbstay);
send.setOnClickListener(this);
SharedPreferences settings = getPreferences(MODE_PRIVATE);
String name = settings.getString("name", "");
String password = settings.getString("pwd", "");
user.setText(name);
pass.setText(password);
if (staySignedIn.isChecked()) {
SharedPreferences MySharedUser = getPreferences(MODE_PRIVATE);
settings.edit().putString("name", user.getText().toString())
.putString("pwd", pass.getText().toString()).commit();
}
if (user.length() > 0)
;
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLogIn:
if (user.length() < 0)
Toast.makeText(this,
"Try to type in your username and password again!",
Toast.LENGTH_LONG).show();
else {
String u = user.getText().toString();
String p = pass.getText().toString();
Bundle send = new Bundle();
send.putString("key", u);
send.putString("key", p);
Intent a = new Intent(LogIn.this, FTPClient.class);
startActivity(a);
Toast.makeText(this, "Yay, you signed in!", Toast.LENGTH_LONG)
.show();
break;
}
}
}
}
if (user.length() == 0)
try it because user.length() is never come in Less Than Zero
You have to use
user.getText().toString().length()
Do you need an onClickListener for you checkbox???
checkbox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks, depending on whether it's now checked
if (((CheckBox) v).isChecked()) {
Toast.makeText(HelloFormStuff.this, "Selected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(HelloFormStuff.this, "Not selected", Toast.LENGTH_SHORT).show();
}
}
});
ProgressDialog quits updating when orientation of screen changes. I have put into place a fix that salvages the asynctask and sets the activity of the asynctask to the new activity after it is destroyed and rebuilt. The percentage complete on the progressdialog stays at the percentage it was at before the orientation change.
What am I missing?
package net.daleroy.fungifieldguide.activities;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Toast;
import net.daleroy.fungifieldguide.R;
import net.daleroy.fungifieldguide.fungifieldguideapplication;
public class FungiFieldGuide extends Activity {
//static final int PROGRESS_DIALOG = 0;
//ProgressThread progressThread;
private final static String LOG_TAG = FungiFieldGuide.class.getSimpleName();
fungifieldguideapplication appState;
private DownloadFile mTask;
public boolean mShownDialog;
ProgressDialog progressDialog;
private final static int DIALOG_ID = 1;
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
if ( id == DIALOG_ID ) {
mShownDialog = true;
}
}
private void onTaskCompleted() {
Log.i(LOG_TAG, "Activity " + this + " has been notified the task is complete.");
//Check added because dismissDialog throws an exception if the current
//activity hasn't shown it. This Happens if task finishes early enough
//before an orientation change that the dialog is already gone when
//the previous activity bundles up the dialogs to reshow.
if ( mShownDialog ) {
dismissDialog(DIALOG_ID);
Toast.makeText(this, "Finished..", Toast.LENGTH_LONG).show();
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch(id) {
case DIALOG_ID:
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading Database (only first run)...");
return progressDialog;
default:
return super.onCreateDialog(id);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
appState = ((fungifieldguideapplication)this.getApplication());
Object retained = getLastNonConfigurationInstance();
if ( retained instanceof DownloadFile ) {
Log.i(LOG_TAG, "Reclaiming previous background task.");
mTask = (DownloadFile) retained;
mTask.setActivity(this);
//showDialog(DIALOG_ID);
}
else {
if(!appState.service.createDataBase())
{
Log.i(LOG_TAG, "Creating new background task.");
//showDialog(DIALOG_ID);
mTask = new DownloadFile(this);
mTask.execute("http://www.codemarshall.com/Home/Download");
}
}
//showDialog(PROGRESS_DIALOG);
View btn_Catalog = findViewById(R.id.btn_Catalog);
btn_Catalog.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(getBaseContext(), Cat_Genus.class);//new Intent(this, Total.class);
startActivity(i);
}
});
View btn_Search = findViewById(R.id.btn_Search);
btn_Search.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(getBaseContext(), Search.class);//new Intent(this, Total.class);
startActivity(i);
}
});
}
#Override
public Object onRetainNonConfigurationInstance() {
mTask.setActivity(null);
return mTask;
}
#Override
public void onDestroy()
{
super.onDestroy();
//progressDialog.dismiss();
//progressDialog = null;
appState.service.ClearSearchParameters();
}
private class DownloadFile extends AsyncTask<String, Integer, Boolean>{
private FungiFieldGuide activity;
private boolean completed;
private String Error = null;
private String Content;
private DownloadFile(FungiFieldGuide activity) {
this.activity = activity;
}
#Override
protected void onPreExecute()
{
showDialog(DIALOG_ID);
}
#Override
protected Boolean doInBackground(String... urlarg) {
int count;
try {
URL url = new URL(urlarg[0]);
URLConnection conexion = url.openConnection();
conexion.setDoInput(true);
conexion.setUseCaches(false);
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(conexion.getInputStream());
OutputStream output = new FileOutputStream("/data/data/net.daleroy.fungifieldguide/databases/Mushrooms.db");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)total*100/lenghtOfFile);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.i(LOG_TAG, e.getMessage());
}
return null;
}
#Override
public void onProgressUpdate(Integer... args){
progressDialog.setProgress(args[0]);
}
#Override
protected void onPostExecute(Boolean result)
{
completed = true;
notifyActivityTaskCompleted();
}
private void notifyActivityTaskCompleted() {
if ( null != activity ) {
activity.onTaskCompleted();
}
}
private void setActivity(FungiFieldGuide activity) {
this.activity = activity;
if ( completed ) {
notifyActivityTaskCompleted();
}
}
}
}
This is not a real solution but to prevent this I just disabled orientation changes during the life of the AsyncTask with adding first:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
and when the job is done:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
Hope this helps.