Disclaimer: I am a newbie to Android development :)
How can I pass the string values collected from this first class to the class below? I attempted this but only got null values.
Here's my main activity.
public class Register extends AppCompatActivity {
protected SnapToSellDataSource mDataSource;
public String sFullname;
public String sEmail;
public String sMobileNumber;
public String sPassword;
EditText full_name, email, mobile_number, pwd, copwd;
Button registerButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mDataSource = new SnapToSellDataSource(Register.this);
full_name = (EditText) findViewById(R.id.editText);
email = (EditText) findViewById(R.id.editText2);
mobile_number = (EditText) findViewById(R.id.editText3);
pwd = (EditText) findViewById(R.id.editText4);
copwd = (EditText) findViewById(R.id.editText5);
registerButton = (Button) findViewById(R.id.button);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Register register = new Register();
String editPassword = pwd.getText().toString();
String editConfirmPassword = copwd.getText().toString();
if(editPassword.equals(editConfirmPassword)) {
//This isn't overwriting the null class variables I
//instantiated so that I can pass them to the class below
sFullname = full_name.getText().toString();
sEmail = email.getText().toString();
sMobileNumber = mobile_number.getText().toString();
sPassword = pwd.getText().toString();
mDataSource.insertUser(register);
}
}
});
}
}
Here's the class that should receive the string values:
public class SnapToSellDataSource {
private SQLiteDatabase mDatabase;
private SnapToSellHelper mHelper;
private Context mContext;
public SnapToSellDataSource(Context context){
mContext = context;
mHelper = new SnapToSellHelper(mContext);
}
public void insertUser(Register register){
ContentValues values = new ContentValues();
values.put(SnapToSellHelper.COL_NAME, register.sFullname);
values.put(SnapToSellHelper.COL_EMAIL, register.sEmail);
values.put(SnapToSellHelper.COL_NUMBER, register.sMobileNumber);
values.put(SnapToSellHelper.COL_PASSWORD, register.sPassword);
mDatabase.insert(SnapToSellHelper.TBL_USERS, null, values);
}
}
I attempted to getText, getString from the second class but my app crashed maybe since the widgets were not yet assigned ids at the class level. Passing actual string values encased in quoation marks ("") works so it means the DatabaseHelper is properly set up.
I also tried declaring class variables and assigning the widget values to them but kept getting the "Cannot resolve symbol" error.
How you get a read from the local variables and pass them to the class variables that can then be set as public and read by another class; in this case, the second class?
You can not simply create instances of an activity in Android. Activities are not classes that you just do a “new” on and call their constructor. An instance of an Activity is created when the app starts or when an Intent starts an activity.
So doing this: Register register = new Register(); is not good! You can find good arguments here
Instead you can pass those values as parameters to the insertUser(params...) method or create a new User class and instantiate it with those string values and pass it to insertUser(user) method.
Method call:
mDataSource.insertUser(sFullname, sEmail, sMobileNumber, sPassword);
Method definition:
public void insertUser(String sFullname, String sEmail, String sMobileNumber, String sPassword) {
ContentValues values = new ContentValues();
values.put(SnapToSellHelper.COL_NAME, sFullname);
values.put(SnapToSellHelper.COL_EMAIL, sEmail);
values.put(SnapToSellHelper.COL_NUMBER, sMobileNumber);
values.put(SnapToSellHelper.COL_PASSWORD, sPassword);
mDatabase.insert(SnapToSellHelper.TBL_USERS, null, values);
}
Related
I'm trying to create an app for my own use, and I'm trying to save 3 editText boxes to Sharedpref so I can use those values to calculate things later in the app.
Here's the code:
SharedPreferences mSharedPreferences;
private EditText mEditTextBench;
private EditText mEditTextSquat;
private EditText mEditTextDead;
private Button mButton;
public String maxDead = mSharedPreferences.getString("maxDead", "DEFAULT");
Then in the oncreate method I have:
mSharedPreferences= PreferenceManager.getDefaultSharedPreferences(this.getBaseContext());
mButton = (Button) findViewById(R.id.button);
mEditTextBench = (EditText) findViewById(R.id.editTextBench);
mEditTextSquat = (EditText) findViewById(R.id.editTextSquat);
mEditTextDead = (EditText) findViewById(R.id.editTextDead);
and my button onclicklistener:
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString("maxDead", mEditTextDead.getText().toString());
editor.commit();
If I put the public String maxDead as a final string in the onCreate method, it works, but I want to be able to change the string in the future, using the editText. I don't think I can put it as a final.
The way the code is now, I get this error:
Attempt to invoke interface method 'java.lang.String android.content.SharedPreferences.getString(java.lang.String, java.lang.String)' on a null object reference
your code should be like this.
SharedPreferences mSharedPreferences;
private EditText mEditTextBench;
private EditText mEditTextSquat;
private EditText mEditTextDead;
private Button mButton;
public String maxDead;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
mSharedPreferences= PreferenceManager.getDefaultSharedPreferences(this.getBaseContext());
maxDead = mSharedPreferences.getString("maxDead", "DEFAULT");
mButton = (Button) findViewById(R.id.button);
mEditTextBench = (EditText) findViewById(R.id.editTextBench);
mEditTextSquat = (EditText) findViewById(R.id.editTextSquat);
mEditTextDead = (EditText) findViewById(R.id.editTextDead);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString("maxDead", mEditTextDead.getText().toString());
editor.commit();
}
});
}
EDIT : here I am showing my way of using SharedPreference
SharedPreferences myPreference;
String MY_PREFERENCE = "my_preference";
inside onCreate initialise SharedPreference:
myPreference = getSharedPreferences(MY_PREFERENCE, Context.MODE_PRIVATE);
for getting value
String data = myPreference.getString("maxDead", "")
for editing SharedPreference :
SharedPreferences.Editor editor = myPreference.edit();
editor.putString("maxDead", mEditTextDead.getText().toString());
editor.commit();
I hope this will help.
I am also very new to Android but I'll try to answer. The reason why you are getting the exception is because when the Activity is created there is nothing in the String maxDead, given it is assigned on the top as private String maxDead. You only assign a value to it when you click your button. Where do you want to use this value? I can't comment yet, that's why I am writing this in an answer. :(
This is an example of how I use SharedPreferences:
SharedPreferences spref = getSharedPreferences("MY_PREFS", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = spref.edit();
editor.putString("maxDead", mEditTextDead.getText().toString());
editor.apply;
And then somewhere (another activity/fragment) where you need the value:
String maxDead = spref.getString("maxDead", "");
You're getting the error because of this :
public String maxDead = mSharedPreferences.getString("maxDead", "DEFAULT");
as you've not initialized mSharedPreferences so, its throwing NullPointerException.
change this to :
public String maxDead;
and then initialize maxDead in your onCreate method after you initialize mSharedPreferences :
maxDead = mSharedPreferences.getString("maxDead", "DEFAULT");
UPDATE
You're not getting the updated value of the maxDead inside the onClickListener as the value of the variable maxData is set only once in the onCreate. So the variable is not updated when the value of maxData is updated in the SharedPreferences. So, instead of keeping a variable you should use a method like this to get the latest value from the SharedPreference :
private String getMaxDead(){
if(mSharedPreferences == null)
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.getBaseContext());
return mSharedPreferences.getString("maxDead", "DEFAULT");
}
So use : getMaxDead() in your toast and it will work.
I am adding multiple Edittext at the click of button. I am also getting the value of these Edittext, but I am unable to store data in array.
EditText textIn;
Button buttonAdd, buttonShow;
LinearLayout container;
List<EditText> allEds = new ArrayList<EditText>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonAdd = (Button)findViewById(R.id.add);
buttonShow = (Button) findViewById(R.id.show);
container = (LinearLayout)findViewById(R.id.container);
buttonAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater =
(LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.row, null);
EditText editText1 = (EditText) addView.findViewById(R.id.editText1);
EditText editText2 = (EditText) addView.findViewById(R.id.editText2);
allEds.add(editText1);
allEds.add(editText2);
Button buttonRemove = (Button) addView.findViewById(R.id.remove);
buttonRemove.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((LinearLayout) addView.getParent()).removeView(addView);
}
});
container.addView(addView);
}
});
buttonShow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String[] strings = new String[allEds.size()];
for(int i=0; i < allEds.size(); i++){
strings[i] = allEds.get(i).getText().toString();
Log.e("My data", strings[i]);
}
}
});
Here I am getting all value using strings[i], but I want to store value in array like this. [{"Name": "Smith","Age", "26"},{"Name": "Jhon","Age", "30"}]. Here I will get Smith,26 and Jhon, 30 from multiple generated Edittext. Array will be extended after generating more dynamic fields.
Please help me.
You say you have to get it as an array. As I see it, you're already getting it as a String array. What else do you want? The way you're describing the expected result looks like a half-baked json output. Perhaps you can create a class that represents the Person whose info you want and then create an ArrayList of the Person type. Also to make things easier to stuff in the Person object you can declare a constructor that takes name and age as parameter. In your loop you can create a Person object using that constructor and then add that object to the ArrayList.
This would help :
class Person{
String name;
int age;
Person(String name, int age){
this.name=name;
this.age=age;
}
}
Then before going into your loop, declare an ArrayList of type Person
ArrayList<Person>persons=new ArrayList<Person>();
And finally in your loop :
Person temp = new Person(*get the name, get the age*);
persons.add(temp);
And voila!, you have your person ArrayList ready.
I am spinning my wheels trying to create and Save a Customer Object to SQLite in Android,
Here is my Customer Class
public class Customer {
private int id;
private String Name;
private String EmailAddress;
private String Phone;
private Double InitialValue;
private Double BalanceOnCard = 0.00;
private String CardUID;
private Date EnrollmentDate = new Date();
private Date LastTransactionDate = new Date();
public Customer(){}
In my Activity I create private variables like so
public class EnrollmentActivity extends MenuOnlyActivity {
private CustomerSQLiteHelper db;
private final String TAG = "Customer_Add";
Button submitButton;
Button cancelButton;
private EditText customerNameEditText;
private EditText customerEmailEditText;
private EditText customerPhoneEditText;
private EditText valueToAddEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_enrollment);
submitButton = (Button) findViewById(R.id.buttonEnrollment);
cancelButton = (Button) findViewById(R.id.CancelEnrollment);
customerNameEditText = (EditText) findViewById(R.id.editTextCustomerName);
customerEmailEditText = (EditText) findViewById(R.id.editTextCustomerEmailAddress);
customerPhoneEditText = (EditText) findViewById(R.id.editTextBusinessPhoneNumber);
valueToAddEditText = (EditText) findViewById(R.id.editTextValueToAdd);
And here is the SubmitButton listener and it is within this code block that it fails, Its not getting to the point of calling the DatabaseHelper to save the Customer object, it fails somewhere right after creating a blank Customer object and starting to set the instance variables.
Log.i(TAG, "Entering Submit Button event");
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (customerNameEditText.getText().length() == 0) {
Toast.makeText(EnrollmentActivity.this, "Enter Customer's name", Toast.LENGTH_SHORT).show();
customerNameEditText.requestFocus();
return;
}
Log.i(TAG, "Create new customer");
//Create new customer object
Customer enteredCustomer = new Customer();
Log.i(TAG, "Created blank customer object");
Log.i(TAG, "populate the new customer object");
//Populate the values of the new object with the values entered in the screen
enteredCustomer.setId(1);
enteredCustomer.setName(customerNameEditText.getText().toString());
enteredCustomer.setEmailAddress(customerEmailEditText.getText().toString());
enteredCustomer.setPhone(customerPhoneEditText.getText().toString());
String enteredValueSting = valueToAddEditText.getText().toString();
double storedValue = Double.parseDouble(enteredValueSting); //convert String to Double
enteredCustomer.setInitialValue(storedValue);
enteredCustomer.setCardUID("ABC123");
Log.i(TAG, "Creating DB Instance");
db = new CustomerSQLiteHelper(EnrollmentActivity.this);
Log.i(TAG, "Created Database instance");
if (db.create(enteredCustomer) != -1) {
Toast.makeText(EnrollmentActivity.this,"Add Customer Successful",Toast.LENGTH_SHORT).show();
customerNameEditText.getText().clear();
customerEmailEditText.getText().clear();
customerPhoneEditText.getText().clear();
valueToAddEditText.getText().clear();
} else {
Toast.makeText(EnrollmentActivity.this, "Add Customer failed", Toast.LENGTH_SHORT).show();
}
}
});
The error message is all over the place, It consistently gives a toast "Unfortunately PROJECT_NAME has stopped" The current console error is "n established connection was aborted by the software in your host machine
java.io.IOException: An established connection was aborted by the software in your host machine" I have restarted Eclipse and Emulator a couple of times. Any help/suggestion will be greatly appreciated.
After more hair pulling I did two things to isolate and resolve the issue, first I created a a default constructor and initialized the parameters to sensible defaults, null for strings and 0 for Ints, then I renamed all my XML IDs to match the Java variables I created in the Activity. Now I am able to create instance of my Customer objects and persist to database.
i want to pass tow values from activity to AsyncTask class and send them from Background process to SOAP web service , but it return my null or wrong , i'm sure there is something wrnog in passing value from LoginActivity to AsyncTask .
here is my LoginActivity code :
final EditText LoginId = (EditText) findViewById(R.id.IDLogin);
final EditText LoginPass = (EditText) findViewById(R.id.LoginPass);
contextOfApplication = getApplicationContext();
mPrefs = getSharedPreferences(PREFS, 0);
boolean rememberMe = mPrefs.getBoolean("rememberMe", false);
final String login1 = LoginId.getText().toString();
final String pass1 = LoginPass.getText().toString();
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(LoginActivity.this);
prefs.edit().putString("login1", login1).commit();
prefs.edit().putString("password1", pass1).commit();
here is calling and passing activity context to AsyncTask Constractor :
loginBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ProgressDialog progressDialog = new ProgressDialog(
LoginActivity.this);
progressDialog.setMessage("جاري تسجيل الدخول الرجاء الانتظار");
progressDialog.show();
AsyncTaskWebServiceCaller MyTask = new AsyncTaskWebServiceCaller(
LoginActivity.this, progressDialog,
getApplicationContext());
MyTask.execute();
}
});
my FULL AsyncTask code :
public class AsyncTaskWebServiceCaller extends AsyncTask<Void, Void, String> {
Activity mActivity;
Context context;
LoginActivity MyClass = new LoginActivity();
public static Context contextOfApplication;
ProgressDialog progressDialog;
Context applicationContext = LoginActivity.getContextOfApplication();
// Constractor
public AsyncTaskWebServiceCaller(Activity activity,
ProgressDialog progressDialog, Context context) {
super();
this.progressDialog = progressDialog;
this.mActivity = activity;
this.context = context;
}
// BackGround Process
#Override
protected String doInBackground(Void... voids) {
// this is executed in a background thread.
// the result is returned to the UI thread via onPostExecute
try {
final String NAMESPACE = "http://ws.sams.com";
final String URL = "http://88.198.82.92:8080/sams1/services/LoginActvityWs?WSDL"; // usint
// //
// localhost
final String METHOD_NAME = "login";
final String SOAP_ACTION = "http://ws.sams.com/login";
final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
final HttpTransportSE androidHttpTransport = new HttpTransportSE(
URL);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext);
String user = prefs.getString("login1", null);
String pass = prefs.getString("password2", null);
to pass values to AsyncTask subclass you either :
1- pass them throw a constructor :
class MyTask extends AsyncTask<Void,Void,Void>{
MyObject myObject = null;
public MyTask(MyObject myObject){
this.myObject = myObject;
}
//....
2- pass it in the execute() method parameters :
// your code on the Main thread which will call the execute() method
// ....
new MyTask().execute(myObject); // i dont remember the exact name of this method, any way
and snippets from your AsyncTask subClass will be
class MyTask extends AsyncTask<Void,MyObject,Void>{
#Override
public void doInBackGround(MyObject...params){
MyObject myObject = params[0];
// the rest of your code
}
just put in mind that if you want to do or edit any thing that is running on the UI thread, you
cant do it in the "doInBackground()" method, either on the preExecute() or the postExecute(), or
run it in a Runnable object (inside the doInBackground() method) but by calling runOnUI(myRunnable);
hope this helps, and just i cant remember the methods name for now, just CTRL + SPACE will help on your IDE :D
you are already doing it in your constructor
AsyncTaskWebServiceCaller MyTask = new AsyncTaskWebServiceCaller(
LoginActivity.this, progressDialog,
getApplicationContext());
thats passing values there
also you are passing the context twice LoginActivity.this gives you context and activity so you do not need to use getApplicationContext(). Its recommended that you never use getApplicationContext() really
Edit:
if you want context all you have to do is
public AsyncTaskWebServiceCaller(Context context,ProgressDialog progressDialog) {
super();
this.progressDialog = progressDialog;
this.context = context;
}
you do not need the activity
to use shared preferences all you need to do is
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
I'm working my way through "Sam's Tech Yourself Android Application Development in 24 Hours" and at some point my Nickname and Email settings stopped saving correctly. It now doesn't save the Nickname at all and saves the Email to both. What have I done to cause this, and how can I fix it?
I think that these are the relevant areas of the code, but if you need more please ask.
As far as I can tell, this is still code from the book, and it used to work. Maybe a typo somewhere?
public class QuizActivity extends Activity {
public static final String GAME_PREFERENCES = "GamePrefs";
public static final String GAME_PREFERENCES_NICKNAME = null; //String
public static final String GAME_PREFERENCES_EMAIL = null; //String
#Override
protected void onPause() {
super.onPause();
EditText nicknameText = (EditText) findViewById(R.id.EditText_Nickname);
EditText emailText = (EditText) findViewById(R.id.EditText_Email);
String strNickname = nicknameText.getText().toString();
String strEmail = emailText.getText().toString();
// TODO: fix password and email saving and displaying improperly
Editor editor = mGameSettings.edit();
editor.putString(GAME_PREFERENCES_NICKNAME, strNickname);
editor.putString(GAME_PREFERENCES_EMAIL, strEmail);
editor.commit();
Toast.makeText(QuizSettingsActivity.this, R.string.settings_saved,
Toast.LENGTH_SHORT).show();
}
public void initNicknameEntry() {
EditText nicknameText = (EditText) findViewById(R.id.EditText_Nickname);
if (mGameSettings.contains(GAME_PREFERENCES_NICKNAME)) {
nicknameText.setText(mGameSettings.getString(
GAME_PREFERENCES_NICKNAME, ""));
}
}
public void initEmailEntry() {
EditText emailText = (EditText) findViewById(R.id.EditText_Email);
if (mGameSettings.contains(GAME_PREFERENCES_EMAIL)) {
emailText.setText(mGameSettings.getString(GAME_PREFERENCES_EMAIL,
""));
}
}
You must initialize these to distinct values:
public static final String GAME_PREFERENCES_NICKNAME = "Nickname"; //String
public static final String GAME_PREFERENCES_EMAIL = "Email"; //String
Otherwise SharedPreferences cannot distinguish between the two keys and will always return the first key found.