EditText to phone memory? - android

I have found a very good solution to my problem on another post (Save entered text in editText via button)
however when I implement this code, my application crashes. Any advice would be appreciated, the error I receive is that the "String or" in the method makeTag() is not used. Please have a look
private Button savenotebutton1;
private SharedPreferences savednotes;
private EditText editText1;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.x1);
savenotebutton1 = (Button) findViewById(R.id.savenotebutton1);
editText1 = (EditText) findViewById(R.id.noteEditText1);
savednotes = getSharedPreferences("notes",MODE_PRIVATE);
editText1.setText(savednotes.getString("tag", "Default Value")); //add this line
savenotebutton1.setOnClickListener(saveButtonListener);
}
private void makeTag(String tag){
String or = savednotes.getString(tag, null);
SharedPreferences.Editor preferencesEditor = savednotes.edit();
preferencesEditor.putString("tag",tag); //change this line to this
preferencesEditor.commit();
}
public OnClickListener saveButtonListener = new OnClickListener(){
#Override
public void onClick(View v) {
if(editText1.getText().length()>0){
makeTag(editText1.getText().toString());
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(editText1.getWindowToken(),0);
}
}
};
}

You should replace this
String or = savednotes.getString(tag, null);
With
String or = savednotes.getString("tag", "Default Value")
Under your makeTag() function
Update: Error is about you are not register your activity into manifest.xml file.

Related

Keeping strings in a login dialog window when orientation change. Android

I'm trying to keep what users typed in my login dialog window when orientation changing, but i always receive this error message:
Attempt to invoke virtual method 'android.view.View
android.widget.RelativeLayout.findViewById(int)' on a null object
reference.
There's the code:
public class ReservationActivity extends AppCompatActivity {
ImageView uDeM_Logo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reservation);
uDeM_Logo = (ImageView)findViewById(R.id.UdeM_Logo);
dimensions();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
RelativeLayout login = (RelativeLayout)findViewById(R.id.loginLayout);
EditText userField = (EditText) login.findViewById(R.id.userEditText);
EditText passField = (EditText) login.findViewById(R.id.passEditText);
String user = userField.getText().toString();
String pass = passField.getText().toString();
outState.putString("User", user);
outState.putString("Pass", pass);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
RelativeLayout login = (RelativeLayout) findViewById(R.id.loginLayout);
EditText userField = (EditText) login.findViewById(R.id.userEditText);
EditText passField = (EditText) login.findViewById(R.id.passEditText);
String user = savedInstanceState.getString("User");
String pass = savedInstanceState.getString("Pass");
userField.setText(user);
passField.setText(pass);
}
public void onConfigurationChanged(Configuration nouvOrient) {
if(nouvOrient.orientation == Configuration.ORIENTATION_LANDSCAPE ||
nouvOrient.orientation == Configuration.ORIENTATION_PORTRAIT)
dimensions();
}
public void dimensions() {
Display display = getWindowManager().getDefaultDisplay();
Point grandeur = new Point();
display.getSize(grandeur);
double hauteur = grandeur.y, dim = hauteur * 0.2492;
int dimsInt = (int) dim;
ViewGroup.LayoutParams parametres = uDeM_Logo.getLayoutParams();
parametres.width = dimsInt;
parametres.height = dimsInt;
uDeM_Logo.setLayoutParams(parametres);
}
public void loginDialog(View log){
final Dialog login = new Dialog(this);
login.setContentView(R.layout.login_dialog);
Button btnLogin = (Button)login.findViewById(R.id.dialogLoginBtn);
Button btnCancel = (Button)login.findViewById(R.id.dialogCancelBtn);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ReservationActivity.this,
"Login Sucessfull", Toast.LENGTH_SHORT).show();
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login.dismiss();
}
});
login.show();
}
}
It seems that you do not need to recreate the activity on orientation change. You can just set this configuration for your activity in your manifest.
android:configChanges="keyboardHidden|orientation
don't do that in onRestoreInstanceState()
RelativeLayout login = (RelativeLayout) findViewById(R.id.loginLayout);
EditText userField = (EditText) login.findViewById(R.id.userEditText);
EditText passField = (EditText) login.findViewById(R.id.passEditText);
But instead make these login, userField, passField a field variables in your Activity class as follows:
private RelativeLayout login;
private EditText userField, passField;
Also move the above 3 code lines from onSaveInstanceState() to onCreate() but modify them to work with your field variables as follows:
login = (RelativeLayout) findViewById(R.id.loginLayout);
userField = (EditText) login.findViewById(R.id.userEditText);
passField = (EditText) login.findViewById(R.id.passEditText);
And I recommend you to restore state at onCreate() instead of onRestoreInstanceState() as follows:
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
String user = savedInstanceState.getString("User");
String pass = savedInstanceState.getString("Pass");
userField.setText(user);
passField.setText(pass);
} else {
// Probably initialize members with default values for a new instance
}
The reason is because onRestoreInstanceState() is called after onStart(), whereas onCreate() is called before onStart()

My app crashes when I touch save button (in Eclipse)

I'm trying to do a Contact Manager but I have one problem: My app crashes when I touch save button for saving my new contact, and I don't know why because Eclipse don't says anything is wrong in my code. I touch the button and the app crashes, but it creates a new database.
public class Insertarcontactes extends Activity {
private TextView mTextView;
private EditText mNom;
private EditText mCognoms;
private EditText mAdressa;
private EditText mFixe;
private EditText mMobil;
private EditText mEmail;
private DatabaseManager mDBM;
protected Cursor mCursor;
private SimpleCursorAdapter mAdapter;
private Button mguardar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.insertarcontactes);
mDBM = new DatabaseManager();
mDBM.openDB(this);
mTextView = (TextView) findViewById(R.id.textView1);
mNom = (EditText) findViewById(R.id.nom);
mCognoms = (EditText) findViewById(R.id.cognoms);
mAdressa = (EditText) findViewById(R.id.adressa);
mFixe = (EditText) findViewById(R.id.telefonfix);
mMobil = (EditText) findViewById(R.id.telefonmobil);
mEmail = (EditText) findViewById(R.id.email);
mguardar = (Button)findViewById(R.id.guardar);
}
public void guardalo(View v) {
if(!mNom.getText().toString().equals("")) {
mDBM.insertarContacto(
mNom.getText().toString(),
mCognoms.getText().toString(),
mAdressa.getText().toString(),
mFixe.getText().toString(),
mMobil.getText().toString(),
mEmail.getText().toString()
);
mNom.setText("");
mCognoms.setText("");
mAdressa.setText("");
mFixe.setText("");
mMobil.setText("");
mEmail.setText("");
mCursor.requery();
mAdapter.notifyDataSetChanged();
Intent vesalallista = new Intent(this, Llistacontactes.class);
startActivity(vesalallista);
}
}
public void tornaenrere(View v){
Intent tornaenrere = new Intent(this, Menuprincipal.class);
startActivity(tornaenrere);
}
#Override
protected void onDestroy() {
mDBM.closeDB();
super.onDestroy();
}
Go to your android manifest file and add write contacts permission
Your mCursor is un-initialized, and you are calling its requery() method mCursor.requery(); in guardalo() method. Hence it should be giving you NullPointerException
You need to initialize this mCursor object in onCreate() method.

SharedPreferences on a Button

I am trying to retrieve the editText value and the button color using shared preferences. For the editText, it works very well but the problem is in saving and loading the color of the button. Note that I want to save the current color of the button by onWriteClick method and color the button by its color by onReadClick.
Here what I wrote:
Button btn ;
EditText c;
private static final String KEY = "key";
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
c = (EditText) findViewById(R.id.editText1);
btn = (Button) findViewById(R.id.button);
preferences = getSharedPreferences("preferences", Context.MODE_PRIVATE);
}
//shared preferences
#SuppressLint("NewApi")
public void onWriteClick() {
Editor editor = preferences.edit();
Editor color = preferences.edit();
editor.putString(KEY, c.getText().toString());
//Here is the problem
color.putString(KEY, btn.setBackgroundColor("#FFFFF"));
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
editor.apply();
} else {
// This call is synchronous and should be done in a background
// thread
editor.commit();
}
}
public void onReadClick() {
String text = preferences.getString(KEY, null);
c.setText(text);
}
}
Any Help please
you are saving EditText content and Button color in the same SharedPreference location using KEY. Define two tag: TEXT_KEY, COLOR_KEY and save the text using TEXT_KEY and the color using COLOR_KEY
Button btn ;
EditText c;
private static final String TEXT_KEY = "tkey";
private static final String COLOR_KEY = "ckey";
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
c = (EditText) findViewById(R.id.editText1);
btn = (Button) findViewById(R.id.button);
preferences = getSharedPreferences("preferences",Context.MODE_PRIVATE);
}
#SuppressLint("NewApi")
public void onWriteClick() {
PaintDrawable pd = (PaintDrawable) btn.getBackground();
Editor editor = preferences.edit();
editor.putString(TEXT_KEY, c.getText().toString()).commit();
editor.putInt(COLOR_KEY, pd.getPaint().getColor()).commit();
}
public void onReadClick() {
c.setText(preferences.getString(KEY, ""));
btn.setBackgroundColor(preferences.getInt(COLOR_KEY, 0);
}
}
On line 10 you should use
(Button) findViewById(R.id.button);
instead of
(EditText) findViewById(R.id.button);
The setBackgroundColor()-method expects an integer. http://developer.android.com/reference/android/view/View.html#setBackgroundColor%28int%29
You could use Color.parseColor() method to parse your color string.
http://developer.android.com/reference/android/graphics/Color.html#parseColor%28java.lang.String%29
colorputString(KEY, btn.setBackgroundColor(Color.parseColor("#FFFFF")));
Update:
Why are you trying to use a String to store the color? Simply use integer. And use the appropriate Getter-Method. setBackgroundColor()-method returns void.
color.putInt(KEY, btn.getBackgroundColor());
2nd Update:
There is no getBackgroundColor-method. But this question will help you: Is there such a method call "getBackgroundColor"?

Trouble converting an editable to a string (username/password test)

I'm trying to create a simple username/password login screen. I have the layout done, and right now, I'm trying to set it so when the username (EditText) == "crete", then it should do something. Here is my code...:
public class Login extends Activity {
public static EditText username, password;
public Button loginbutton;
boolean accessgranted;
public String dbu, dbp, user1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
username = (EditText) this.findViewById(R.id.username);
password = (EditText) this.findViewById(R.id.password);
loginbutton = (Button) this.findViewById(R.id.loginbutton);
user1 = "crete";
loginbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
dbu = (username.getText()).toString();
}
finally{
if (dbu == user1){
username.setText("SUCCESS");
}
}
}
});
}
}
this, sadly, doesn't work. It correctly converts it to a string (i think) because when I tested this code out :
loginbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
dbu = (username.getText()).toString();
}
finally{
username.setText("done" + dbu);
}
}
}
});
It correctly enters what you entered into the EditText, plus the word "done".
There seems to be a problem with creating if-then statements??
You test for String equality with the method .equals("String").
With == you are testing if the references to the objects are equal.
Try using equalsIgnoreCase(String) instead of the == comparator.
Like this: dbu.equalsIgnoreCase(user1)
dub and user1 are two separate String objects. You're comparing them like this: dbu == user1. This will always return false. Instead, replace it with dbu.equals(user1).

Authentication Android

I want to create a static test in my authentication but when I click on button "Valider" nothing happen, instead when I remove the "if" condition and I click on "valider" button the next activity start. I think there is a problem when I put a condition for testing but I don't know what's it. Can you help ? thanks
public class TabAdmin extends Activity implements View.OnClickListener{
private EditText username;
private EditText password;
public String user_name;
public String pass_word;
private Button valider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.authen);
username = (EditText) findViewById(R.id.login);
password = (EditText) findViewById(R.id.pwd);
valider = (Button) findViewById(R.id.valider);
valider.setOnClickListener((OnClickListener) this);
}
public void onClick(View v) {
if (v == valider) {
user_name = username.getText().toString();
pass_word = password.getText().toString();
if((user_name=="admin")&&(pass_word=="admin"))
{
Intent goToNextActivity = new Intent(getApplicationContext(), MenuAdmin.class);
startActivity(goToNextActivity);
}
}
}
try using if (v.equals(valider)) instead of if (v == valider)
For one thing the way you're comparing strings isn't right for Java. Try
if ("admin".equals(user_name) && "admin".equals(pass_word)) {
This isn't a great way of doing passwords though as anyone can read the strings out of the APK.
instead of
if((user_name=="admin")&&(pass_word=="admin"))
use
if((user_name.equals("admin"))&&(pass_word.equals("admin")))
I hope it can help u

Categories

Resources