Bundle.getString() doesn't seem to get the values - java

I want my MainActivity to get extras from two different activties and I figured the only way to differ from the two activties is to check the key of the Bundles but when i try to get the extras that they come from, they are all null.
Main Activity:
public class UserActivity extends AppCompatActivity {
public String token;
public String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
Intent intent = getIntent();
Bundle b = intent.getExtras();
if(b.containsKey("createBundle"))
{
token = b.getString("sessionID");
name = b.getString("nameID");
}
else if(b.containsKey("logInBundle"))
{
token = b.getString("loginToken");
name = b.getString("loginName");
}
TextView welcome = (TextView) findViewById(R.id.welcomeView);
welcome.setText("Hello, " + name);
}
Activity 1:
public class CreateUserActivity extends Activity {
EditText txtName, txtEmail, txtPassword;
AlertDialogManager alert = new AlertDialogManager();
private String token;
private SharedPreferenceManager sharedPreferenceManager;
public void setToken(String token) {
this.token = token;
}
public String getToken() {
return token;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_user_activity);
txtName = (EditText) findViewById(R.id.loginName);
txtEmail = (EditText) findViewById(R.id.loginEmail);
txtPassword = (EditText) findViewById(R.id.loginPassword);
sharedPreferenceManager = new SharedPreferenceManager();
}
public void checkCreateUser(View view) throws JSONException {
String name = txtName.getText().toString();
String email = txtEmail.getText().toString();
String password = txtPassword.getText().toString();
String tokenAgain = "";
CheckBox checkBox = (CheckBox) findViewById(R.id.login_remember_checkbox);
if (name.trim().length() > 0 && password.trim().length() > 0 && email.trim().length() > 0) {
JSONObject userObj = new JSONObject();
userObj.put("name", name);
userObj.put("email", email);
userObj.put("password", password);
String jsonDocument = userObj.toString();
PostUserTask put = new PostUserTask();
put.execute("http://api.evang.dk/v2/users", jsonDocument);
tokenAgain = getToken();
if (checkBox.isChecked()) {
sharedPreferenceManager.saveData(CreateUserActivity.this, "USERNAME", name);
sharedPreferenceManager.saveData(CreateUserActivity.this, "EMAIL", email);
sharedPreferenceManager.saveData(CreateUserActivity.this, "PASSWORD", password);
sharedPreferenceManager.saveData(CreateUserActivity.this, "TOKEN", tokenAgain);
} else {
sharedPreferenceManager.removeData(CreateUserActivity.this, "USERNAME");
sharedPreferenceManager.removeData(CreateUserActivity.this, "EMAIL");
sharedPreferenceManager.removeData(CreateUserActivity.this, "PASSWORD");
sharedPreferenceManager.removeData(CreateUserActivity.this, "TOKEN");
}
}
else
{
alert.showAlertDialog(CreateUserActivity.this, "Login failed!", "Please enter name, username and password", false);
}
Intent i = new Intent(getBaseContext(), UserActivity.class);
Bundle b = new Bundle();
b.putString("sessionID", tokenAgain);
b.putString("nameID", name);
i.putExtra("createBundle", b);
startActivity(i);
}
Activity 2:
public class LoginActivity extends AppCompatActivity {
EditText userNameTxt, passwordTxt, emailTxt;
SharedPreferenceManager sharedPreferenceManager;
String userName;
String token;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Intent intent = getIntent();
userNameTxt = (EditText) findViewById(R.id.userNameLogin);
passwordTxt = (EditText) findViewById(R.id.passwordLogin);
emailTxt = (EditText) findViewById(R.id.emailLogin);
sharedPreferenceManager = new SharedPreferenceManager();
userName = sharedPreferenceManager.getData(this, "USERNAME");
String email = sharedPreferenceManager.getData(this, "EMAIL");
String password = sharedPreferenceManager.getData(this, "PASSWORD");
token = sharedPreferenceManager.getData(this, "TOKEN");
if(userName != null && email != null && password != null && token != null)
{
userNameTxt.setText(userName);
emailTxt.setText(email);
passwordTxt.setText(password);
}
}
public void onClickLog(View view) {
if(token != null)
{
Intent i = new Intent(getBaseContext(), UserActivity.class);
Bundle b = new Bundle();
b.putString("loginToken", token);
b.putString("loginName", userName);
i.putExtra("logInBundle", b);
startActivity(i);
}
}
}

Accordingly to the code you posted, the following
if(b.containsKey("createBundle")) {
token = b.getString("sessionID");
name = b.getString("nameID");
} else if(b.containsKey("logInBundle")) {
token = b.getString("loginToken");
name = b.getString("loginName");
}
is wrong. onClickLog you are adding a new a Bundle with key logInBundle. What you should check with getIntent().hasExtra(String).
E.g.
if(getIntent().hasExtra("createBundle")) {
b = getIntent().getBundleExtra("createBundle");
} else if (getIntent().hasExtra("logInBundle")) {
b = getIntent().getBundleExtra("logInBundle");
}
and then read from b as you are already doing

Related

Edittext & textview value wont change even the value in the database is already change

edit text value wont change even the value in the database is already change, its show the previous content and I need to debug again the application to show the new data. I already use this but the value still not change until I debug it again.
i can insert in database using this code but when i display the value of it the old value is the one showing not the updated one. thats why the i say the edittext and textview value not changing.
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_userdetails);
super.onCreate(savedInstanceState);
//if the user is not logged in
//starting the login activity
if (!SharedPrefManager.getInstance(this).isLoggedIn()) {
finish();
startActivity(new Intent(this, LoginActivity.class));
}
User user = SharedPrefManager.getInstance(this).getUser();
Circleimage = findViewById(R.id.Circleimage);
bt_update = findViewById(R.id.bt_update);
Btn_Editprofile = findViewById(R.id.Btn_Editprofile);
textViewFullname = findViewById(R.id.textViewFullname);
textViewId = findViewById(R.id.textViewId);
textViewLastname = findViewById(R.id.textViewLastname);
textViewFirstname = findViewById(R.id.textViewFirstname);
textViewMiname = findViewById(R.id.textViewMiname);
textViewSuname = findViewById(R.id.textViewSuname);
textViewUsername = findViewById(R.id.textViewUsername);
textViewAddress = findViewById(R.id.textViewAddress);
textViewAddress1 = findViewById(R.id.textViewAddress1);
textViewBirthday = findViewById(R.id.textViewBirthday);
textViewBirthday1 = findViewById(R.id.textViewBirthday1);
textViewEmail = findViewById(R.id.textViewEmail);
textViewGender = findViewById(R.id.textViewGender);
textViewHeight = findViewById(R.id.textViewHeight);
textViewWeight = findViewById(R.id.textViewWeight);
Btn_Editprofilepic= findViewById(R.id.Btn_Editprofilepic);
spinner1 = findViewById(R.id.spinner1);
//getting the current user
//setting the values to the textviews
textViewFullname.setText(user.getFirstname() + " " + user.getLastname());
textViewId.setText(String.valueOf(user.getId()));
textViewLastname.setText(user.getLastname());
textViewFirstname.setText(user.getFirstname());
textViewMiname.setText(user.getMiddlename());
textViewSuname.setText(user.getSuffix());
textViewUsername.setText(user.getUsername());
textViewAddress.setText(user.getAddress());
textViewAddress1.setText(user.getAddress1());
textViewBirthday.setText(user.getBirthday());
textViewBirthday1.setText(user.getBirthday1());
textViewEmail.setText(user.getEmail());
textViewGender.setText(user.getGender());
textViewHeight.setText(user.getHeight());
textViewWeight.setText(user.getWeight());
textViewdatashow = findViewById(R.id.textViewId);
}
public void btn_update(View view) {
final String Clastname = textViewLastname.getText().toString().trim();
final String Cfirstname = textViewFirstname.getText().toString().trim();
final String Cmiddlename = textViewMiname.getText().toString().trim();
//first we will do the validations
if (TextUtils.isEmpty(Clastname)) {
textViewLastname.setError("Please enter Lastname");
textViewLastname.requestFocus();
return;
}
if (TextUtils.isEmpty(Cfirstname)) {
textViewFirstname.setError("Please enter Firstname");
textViewFirstname.requestFocus();
return;
}
if (TextUtils.isEmpty(Cmiddlename)) {
textViewMiname.setError("Please enter Middlename");
textViewMiname.requestFocus();
return;
}
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Updating....");
progressDialog.show();
StringRequest request = new StringRequest(Request.Method.POST, "http://192.168.3.106/loginregister/update.php",
response -> {
Toast.makeText(ProfileActivity.this, response, Toast.LENGTH_SHORT).show();
//startActivity(new Intent(getApplicationContext(),MainActivity.class));
progressDialog.dismiss();
}, error -> {
Toast.makeText(ProfileActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
progressDialog.dismiss();
}) {
final String id = textViewId.getText().toString().trim();
final String lastname = textViewLastname.getText().toString().trim();
final String firstname = textViewFirstname.getText().toString().trim();
final String middlename = textViewMiname.getText().toString().trim();
final String suffix = textViewSuname.getText().toString().trim();
final String username = textViewUsername.getText().toString().trim();
final String address = textViewAddress.getText().toString().trim();
final String address1 = textViewAddress1.getText().toString().trim();
final String birthday = textViewBirthday.getText().toString().trim();
final String birthday1 = textViewBirthday1.getText().toString().trim();
final String email = textViewEmail.getText().toString().trim();
final String password = textViewGender.getText().toString().trim();
final String height = textViewHeight.getText().toString().trim();
final String weight = textViewWeight.getText().toString().trim();
final String vaccine = spinner1.getText().toString().trim();
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("id", id);
params.put("lastname", lastname);
params.put("firstname", firstname);
params.put("middlename", middlename);
params.put("suffix", suffix);
params.put("username", username);
params.put("address", address);
params.put("address1", address1);
params.put("birthday", birthday);
params.put("birthplace", birthday1);
params.put("email", email);
params.put("password", password);
params.put("height", height);
params.put("weight", weight);
params.put("vaccine", vaccine);
return params;
}
};
bt_update.setEnabled(false);
Btn_Editprofile.setEnabled(true);
textViewAddress.setEnabled(false);
textViewAddress1.setEnabled(false);
textViewBirthday.setEnabled(false);
textViewBirthday1.setEnabled(false);
textViewGender.setEnabled(false);
textViewHeight.setEnabled(false);
textViewWeight.setEnabled(false);
spinner1.setEnabled(false);
Circleimage.setEnabled(false);
RequestQueue requestQueue = Volley.newRequestQueue(ProfileActivity.this);
requestQueue.add(request);
}

Android update user after login by using volley

I'm currently having trouble of updating a user profile after they have login. The table i have is different but is linked together, which mean i get the Username from another table and update the profile details on another table. Here is my php and java file. Additionally, i'm not really good at android and php coding, any guidance will be much appreciated!
UpdateProfile.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if( !empty( $_POST ) )
{
$connect = mysqli_connect("localhost", "root", "", "users");
$Username = $_POST['Username'];
$Dri_IC = $_POST["Dri_IC"];
$Dri_Name = $_POST["Dri_Name"];
$Date_of_Birth = $_POST["Date_of_Birth"];
$Carplate = $_POST["Carplate"];
$Dri_Street_Add = $_POST["Dri_Street_Add"];
$Dri_Postal_Code = $_POST["Dri_Postal_Code"];
$Dri_City = $_POST["Dri_City"];
$Dri_State = $_POST["Dri_State"];
$Dri_Country = $_POST["Dri_Country"];
$statement = mysqli_prepare($connect, "UPDATE dri_details SET Dri_IC='$Dri_IC', Dri_Name='$Dri_Name', Date_of_Birth='$Date_of_Birth',
Carplate='$Carplate', Dri_Street_Add='$Dri_Street_Add', Dri_Postal_Code='$Dri_Postal_Code', Dri_City='$Dri_City', Dri_State='$Dri_State', Dri_Country='$Dri_Country'
INNER JOIN account_details ON account_details.Acc_ID = dri_details.Dri_ID WHERE account_details.Username='$Username'");
mysqli_stmt_bind_param($statement, "sissssssss", $Username, $Dri_IC, $Dri_Name, $Date_of_Birth, $Carplate, $Dri_Street_Add, $Dri_Postal_Code, $Dri_City, $Dri_State, $Dri_Country);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
}
?>
ProfileUpdate.java
public class ProfileUpdate extends AppCompatActivity {
private EditText editTextDriIC, editTextDriName;
private Button buttonUpPro;
private TextView tvDisplay;
SessionManager session;
public static String global_Usernames;
public static String global_AccPass;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_profile);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if(getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Session class instance
session = new SessionManager(getApplicationContext());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// get name
String Username = user.get(SessionManager.KEY_USERNAME);
global_Usernames = Username;
// get password
String Acc_Pass = user.get(SessionManager.KEY_PASSWORD);
global_AccPass = Acc_Pass;
final EditText etIdentitycard = (EditText) findViewById(R.id.etIdentitycard);
final EditText etName = (EditText) findViewById(R.id.etName);
final EditText etDOB = (EditText) findViewById(R.id.etDOB);
final EditText etCarplate = (EditText) findViewById(R.id.etCarplate);
final EditText etAddress = (EditText) findViewById(R.id.etAddress);
final EditText etPostal = (EditText) findViewById(R.id.etPostal);
// Get a reference to the AutoCompleteTextView in the layout
final AutoCompleteTextView etCity = (AutoCompleteTextView) findViewById(R.id.etCity);
// Get the string array
String[] cities = getResources().getStringArray(R.array.city_array);
// Create the adapter and set it to the AutoCompleteTextView
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, cities);
etCity.setAdapter(adapter);
// Get a reference to the AutoCompleteTextView in the layout
final AutoCompleteTextView etState = (AutoCompleteTextView) findViewById(R.id.etState);
// Get the string array
String[] states = getResources().getStringArray(R.array.state_array);
// Create the adapter and set it to the AutoCompleteTextView
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, states);
etState.setAdapter(adapter);
// Get a reference to the AutoCompleteTextView in the layout
final AutoCompleteTextView etCountry = (AutoCompleteTextView) findViewById(R.id.etCountry);
// Get the string array
String[] country = getResources().getStringArray(R.array.countries_array);
// Create the adapter and set it to the AutoCompleteTextView
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, country);
etCountry.setAdapter(adapter);
final Button buttonUpPro = (Button) findViewById(R.id.bUpdate);
final Calendar myCalendar = Calendar.getInstance();
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
private void updateLabel() {
//String myFormat = "YYYY/MM/DD"; //In which you need put here
//DateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
String myFormat = "yyyy/MM/dd"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
//DateFormat sdf = DateFormat.getDateInstance(DateFormat.LONG, Locale.UK);
etDOB.setText(sdf.format(myCalendar.getTime()));
}
};
etDOB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(ProfileUpdate.this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
buttonUpPro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String Dri_IC = etIdentitycard.getText().toString().trim();
final String Dri_Name = etName.getText().toString().trim();
final String Date_of_Birth = etDOB.getText().toString();
final String Carplate = etCarplate.getText().toString().trim();
final String Dri_Street_Add = etAddress.getText().toString().trim();
final String Dri_Postal_Code = etPostal.getText().toString().trim();
final String Dri_City = etCity.getText().toString().trim();
final String Dri_State = etState.getText().toString().trim();
final String Dri_Country = etCountry.getText().toString().trim();
if (etIdentitycard.getText().toString().matches("") || etName.getText().toString().matches("") || etDOB.getText().toString().matches("") || etAddress.getText().toString().matches("")
|| etPostal.getText().toString().matches("") || etCity.getText().toString().matches("") || etState.getText().toString().matches("") || etCountry.getText().toString().matches("")) {
if (TextUtils.isEmpty(Dri_IC)) {
etIdentitycard.setError("You are required to enter your Identification Card Number");
}
if (TextUtils.isEmpty(Dri_Name)) {
etName.setError("You are required to enter your Full Name");
}
if (TextUtils.isEmpty(Date_of_Birth)) {
etDOB.setError("You are required to enter your Date of Birth");
}
if (TextUtils.isEmpty(Dri_Street_Add)) {
etAddress.setError("You are required to enter your House Address");
}
if (TextUtils.isEmpty(Dri_Postal_Code)) {
etPostal.setError("You are required to enter your Postal Code");
}
if (TextUtils.isEmpty(Dri_City)) {
etCity.setError("You are required to enter City name");
}
if (TextUtils.isEmpty(Dri_State)) {
etState.setError("You are required to enter State name");
}
if (TextUtils.isEmpty(Dri_Country)) {
etCountry.setError("You are required to enter Country name");
}
} else {
Response.Listener<String> responeListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonRespone = new JSONObject(response);
boolean success = jsonRespone.getBoolean("success");
/*if (success){
Intent intent = new Intent(RegisterActivity2.this, LoginActivity.class);
RegisterActivity2.this.startActivity(intent);
}*/
if (!success){
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileUpdate.this);
builder.setMessage("Retry")
.setNegativeButton("Retry", null)
.create()
.show();
} else {
Toast.makeText(ProfileUpdate.this, getString(R.string.profile_update_success), Toast.LENGTH_LONG).show();
//Intent intent = new Intent(RegisterActivity2.this, LoginActivity.class);
//RegisterActivity2.this.startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
ProfileUpdateRequest profileUpdateRequest = new ProfileUpdateRequest(Dri_IC, Dri_Name, Date_of_Birth, Carplate, Dri_Street_Add, Dri_Postal_Code, Dri_City, Dri_State, Dri_Country, responeListener);
RequestQueue queue = Volley.newRequestQueue(ProfileUpdate.this);
queue.add(profileUpdateRequest);
}
}
});
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
ProfileUpdateRequest.java
public class ProfileUpdateRequest extends StringRequest {
private static final String PROFILEUPDATE_REQUEST = "http://192.168.1.5/UpdateProfile.php";
private Map<String, String> params;
public ProfileUpdateRequest(String Dri_IC, String Dri_Name, String Date_of_Birth, String Carplate, String Dri_Street_Add, String Dri_Postal_Code, String Dri_City, String Dri_State, String Dri_Country, Response.Listener<String> listener){
super (Method.POST, PROFILEUPDATE_REQUEST, listener, null);
Log.i("Getting url info",""+PROFILEUPDATE_REQUEST + " " + Dri_IC + " " + Dri_Name + " " + Date_of_Birth);
params = new HashMap<>();
params.put("Dri_IC", Dri_IC + "");
params.put("Dri_Name", Dri_Name);
params.put("Date_of_Birth", Date_of_Birth);
params.put("Carplate", Carplate);
params.put("Dri_Street_Add", Dri_Street_Add);
params.put("Dri_Postal_Code", Dri_Postal_Code);
params.put("Dri_City", Dri_City);
params.put("Dri_State", Dri_State);
params.put("Dri_Country", Dri_Country);
params.put("Username", MainActivity.global_Username);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
I'm not sure what went wrong, after i click update on my android, it did not show success or error, and the database did not update as well. Any help will be much appreciated!

Java - Checking if int is empty

I'm trying to do field validation for an int in android studio. The code for the field is as follows;
public class Register extends ActionBarActivity implements View.OnClickListener {
EditText etName, etAge, etUsername, etPassword;
Button bRegister;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etName = (EditText) findViewById(R.id.etName);
etAge = (EditText) findViewById(R.id.etAge);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bRegister:
String name = etName.getText().toString();
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
String ageText = etAge.getText().toString();
if(! TextUtils.isEmpty(ageText)) {
int age = Integer.parseInt(ageText);
}
if(name.length()==0)
{
etName.requestFocus();
etName.setError("Please don't leave the name field empty.");
}else if(username.length()==0)
{
etUsername.requestFocus();
etUsername.setError("Please don't leave the username field empty.");
}else if(password.length()==0)
{
etPassword.requestFocus();
etPassword.setError("Please don't leave the password field empty.");
}/*else if(age == null)
{
etAge.requestFocus();
etAge.setError("Please don't leave the age field empty.");
}*/
else if(!name.matches("[a-zA-Z]"))
{
etName.requestFocus();
etName.setError("Please only use alphabetic characters");
}else{
User user = new User(name, age, username, password);
registerUser(user);
}
break;
}
}
private void registerUser(User user) {
ServerRequest serverRequest = new ServerRequest(this);
serverRequest.storeUserDataInBackground(user, new GetUserCallback() {
#Override
public void done(User returnedUser) {
Intent loginIntent = new Intent(Register.this, Login.class);
startActivity(loginIntent);
}
});
}
}
But I can't get the int age validated, it keps giving me this error;
java.lang.NumberFormatException: Invalid int: ""
User class
public class User {
String name, username, password;
int age;
public User(String name, int age, String username, String password) {
this.name = name;
this.age = age;
this.username = username;
this.password = password;
}
Try this:
String ageText = etAge.getText().toString();
int age = 0;
if(! TextUtils.isEmpty(ageText)) // If EditText is not empty
age = Integer.parseInt(ageText); // parse its content to integer
// Continue validation...
instead of
int age = Integer.parseInt(etAge.getText().toString());
I believe you are looking for something like this:
String ageString = "25"; //age will be null if it is empty or not a number
Integer age = null;
try {
age = Integer.parseInt(ageString);
} catch (NumberFormatException e) {}
if (age == null) {
//enter age
}

Retrieving data from wrong database

I have two SQLiteDatabases in my application. One retrieves the user's input from the class DataEntryHome. The other retrieves the user's input from the class GarmentEntry. I also have two activities which display the user's inputs in the form of a ListView. These are shown in the activities RecapPage and RecapOrderDetails.
To make things simpler for myself as a new java programmer, I have used separate dbHelper, DataProvider and ListDataAdapter classes for the separate databases.
My issue is that in the RecapOrderDetails class, the ListView is populated with the contents from DataEntryHome rather than from GarmentEntry. The ListView in RecapPage works as it should.
Here is all of the code that I think is relevant:
DataEntryHome:
public class DataEntryHome extends AppCompatActivity implements TextWatcher{
private static Button DataEntryButtonN, SaveDataButton, PreviewButton;
Context context = this;
UserDbHelper userDbHelper;
SQLiteDatabase sqLiteDatabase;
EditText ContactName,ContactSurname,ContactEmail,ContactPhone,ContactAddInfo;
Button saveDetails;
public static ArrayList<String> CUSTOMERS = new ArrayList<String>();
String customers[];
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
final EditText surnameArray = (EditText) findViewById(R.id.customerSurnameEntry);
saveDetails = (Button) findViewById(R.id.saveDetailsButton);
saveDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String erm=surnameArray.getText().toString().trim();
if(erm.length() != 0){
CUSTOMERS.add(erm);
surnameArray.setText("");
}
Intent arrayItems = new Intent(DataEntryHome.this, RecapPage.class);
Bundle arrayItemsBundle = new Bundle();
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_entry_home);
ContactName = (EditText) findViewById(R.id.customerFirstNameEntry);
ContactName.addTextChangedListener(this);
ContactSurname = (EditText) findViewById(R.id.customerSurnameEntry);
ContactSurname.addTextChangedListener(this);
ContactEmail = (EditText) findViewById(R.id.customerEmail);
ContactEmail.addTextChangedListener(this);
ContactPhone = (EditText) findViewById(R.id.customerNumber);
ContactPhone.addTextChangedListener(this);
ContactAddInfo = (EditText) findViewById(R.id.addInfo1);
setupSaveDataButton();
}
public void addContact(View view) {
String name = ContactName.getText().toString();
String surname = ContactSurname.getText().toString();
String email = ContactEmail.getText().toString();
String phone = ContactPhone.getText().toString();
String add_info = ContactAddInfo.getText().toString();
userDbHelper = new UserDbHelper(context);
sqLiteDatabase = userDbHelper.getWritableDatabase();
userDbHelper.addInformation(name,surname,email,phone,add_info,sqLiteDatabase);
Toast.makeText(getBaseContext(), "Data saved", Toast.LENGTH_SHORT).show();
userDbHelper.close();
}
RecapPage:
public class RecapPage extends AppCompatActivity{
ListView listView;
SQLiteDatabase sqLiteDatabase;
UserDbHelper userDbHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
Button goButtonAction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recap_page);
goButtonAction = (Button) findViewById(R.id.goButton);
listView = (ListView) findViewById(R.id.list_view);
listView.setClickable(true);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(listDataAdapter);
userDbHelper = new UserDbHelper(getApplicationContext());
sqLiteDatabase = userDbHelper.getReadableDatabase();
cursor = userDbHelper.getInformation(sqLiteDatabase);
if(cursor.moveToFirst()) {
do {
String first_name, surname, email, phone, add_info;
first_name = cursor.getString(0);
surname = cursor.getString(1);
email = cursor.getString(2);
phone = cursor.getString(3);
add_info = cursor.getString(4);
DataProvider dataProvider = new DataProvider(first_name,surname,email,phone,add_info);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
Intent arrayItems = getIntent();
Bundle arrayItemsBundle = arrayItems.getExtras();
}
GarmentEntry:
public class GarmentEntry extends AppCompatActivity {
Spinner tcshenspinner, backprintoptionsspinner, tcbackhenspinner, cosspinner, ppspinner;
ArrayAdapter<CharSequence> tcshenspinneradapter, backprintoptionsspinneradapter, tcbackhenspinneradapter,
cosspinneradapter, ppspinneradapter;
Button nextButton1;
public static ImageView imagePreview;
public static final String IMAGE_RES_ID_1 = "image_res_id_1";
Context contextOrder = this;
OrderDbHelper userDbHelperOrder;
SQLiteDatabase sqLiteDatabaseOrder;
EditText OrderNoOfShirts, OrderFrontText,OrderShirt1;
Spinner OrderColourOfShirts, OrderPrintPosition, OrderColourOfText, OrderBackPrint, OrderBackColour;
Button saveOrderDetails;
public static ArrayList<String> ORDERINFO = new ArrayList<>();
String orderinfo[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.garment_entry);
final EditText shirtArray = (EditText)findViewById(R.id.noofshirts);
saveOrderDetails = (Button)findViewById(R.id.saveOrderDetails);
saveOrderDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String erm=shirtArray.getText().toString().trim();
if (erm.length() != 0){
ORDERINFO.add(erm);
shirtArray.setText("");
}
Intent arrayItemsOrder = new Intent(GarmentEntry.this, RecapOrderDetails.class);
Bundle arrayItemsOrderBundle = new Bundle();
}
});
OrderNoOfShirts = (EditText)findViewById(R.id.noofshirts);
OrderColourOfShirts = (Spinner)findViewById(R.id.cosspinner);
OrderFrontText = (EditText)findViewById(R.id.fronttexthint);
OrderPrintPosition = (Spinner)findViewById(R.id.ppspinner);
OrderColourOfText = (Spinner)findViewById(R.id.tcshenspinner);
OrderBackPrint = (Spinner)findViewById(R.id.backprintoptionsspinner);
OrderBackColour = (Spinner)findViewById(R.id.tcbackhenspinner);
OrderShirt1 = (EditText)findViewById(R.id.nnsshirt1);
}
public void addOrder(View view){
String no_of_shirts = OrderNoOfShirts.getText().toString();
String colour_of_shirts = OrderColourOfShirts.getSelectedItem().toString();
String front_text = OrderFrontText.getText().toString();
String print_position = OrderPrintPosition.getSelectedItem().toString();
String colour_of_text = OrderColourOfText.getSelectedItem().toString();
String back_print = OrderBackPrint.getSelectedItem().toString();
String back_colour = OrderBackColour.getSelectedItem().toString();
String shirt_1 = OrderShirt1.getText().toString();
userDbHelperOrder = new OrderDbHelper(contextOrder);
sqLiteDatabaseOrder = userDbHelperOrder.getWritableDatabase();
userDbHelperOrder.addInformationOrder(no_of_shirts,colour_of_shirts,front_text,print_position,colour_of_text,back_print,
back_colour,shirt_1, null,null,null,null,null,null,null,null,null,null,sqLiteDatabaseOrder);
Toast.makeText(getBaseContext(), "Data saved", Toast.LENGTH_SHORT).show();
userDbHelperOrder.close();
}
RecapOrderDetails:
public class RecapOrderDetails extends AppCompatActivity {
ListView listViewOrder;
SQLiteDatabase sqLiteDatabaseOrder;
UserDbHelper userDbHelperOrder;
Cursor cursorOrder;
ListDataAdapterOrder listDataAdapterOrder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recap_order_details);
listViewOrder = (ListView)findViewById(R.id.list_view_order);
listViewOrder.setClickable(true);
listDataAdapterOrder = new ListDataAdapterOrder(getApplicationContext(),R.layout.order_layout);
listViewOrder.setAdapter(listDataAdapterOrder);
userDbHelperOrder = new UserDbHelper(getApplicationContext());
sqLiteDatabaseOrder = userDbHelperOrder.getReadableDatabase();
cursorOrder = userDbHelperOrder.getInformation(sqLiteDatabaseOrder);
if (cursorOrder.moveToFirst()){
do {
String no_of_shirts, colour_of_shirts, front_text, print_position, text_colour, back_print, back_colour, shirt1;
no_of_shirts = cursorOrder.getString(0);
colour_of_shirts = cursorOrder.getString(1);
front_text = cursorOrder.getString(2);
print_position = cursorOrder.getString(3);
text_colour = cursorOrder.getString(4);
/*back_print = cursorOrder.getString(5);
back_colour = cursorOrder.getString(6);
shirt1 = cursorOrder.getString(7);*/
DataProviderOrder dataProviderOrder = new DataProviderOrder(no_of_shirts,colour_of_shirts,front_text,print_position,
text_colour,null,null,null);
listDataAdapterOrder.add(dataProviderOrder);
}while (cursorOrder.moveToNext());
}
Intent arrayItems = getIntent();
Bundle arrayItemsBundle = arrayItems.getExtras();
}
I THINK the reason why the wrong data is being passed into the second database is because of this:
if (cursorOrder.moveToFirst()){
do {
String no_of_shirts, colour_of_shirts, front_text, print_position, text_colour, back_print, back_colour, shirt1;
no_of_shirts = cursorOrder.getString(0);
colour_of_shirts = cursorOrder.getString(1);
front_text = cursorOrder.getString(2);
print_position = cursorOrder.getString(3);
text_colour = cursorOrder.getString(4);
/*back_print = cursorOrder.getString(5);
back_colour = cursorOrder.getString(6);
shirt1 = cursorOrder.getString(7);*/
DataProviderOrder dataProviderOrder = new DataProviderOrder(no_of_shirts,colour_of_shirts,front_text,print_position,
text_colour,null,null,null);
listDataAdapterOrder.add(dataProviderOrder);
Are the values 0-4 reserved for the first database (for DataEntryHome)?
I also think that this:
userDbHelperOrder = new UserDbHelper(getApplicationContext());
sqLiteDatabaseOrder = userDbHelperOrder.getReadableDatabase();
cursorOrder = userDbHelperOrder.getInformation(sqLiteDatabaseOrder);
has something to do with the matter.
I have figured it out.
On activity RecapOrderDetails, This:
userDbHelperOrder = new UserDbHelper(getApplicationContext());
was this issue.
To resolve it, I had to do the following:
OrderDbHelper = orderDbHelperOrder
in the main method.
And then replace
userDbHelperOrder = new UserDbHelper(getApplicationContext());
with
orderDbHelperOrder = new OrderDbHelper(getApplicationContext());

How do I pass a variable from an activity to a fragment?

I have tried using the code below but it does not work. it just returns a null value when retrieved from the fragment.
MainActivity.java
setting the bundle:
public class MainActivity extends Activity {
ConnectionClass connectionClass;
EditText edtuserid,edtpass;
Button btnlogin;
ProgressBar pbbar;
int user_id;
int lala;
int test2;
String userIDD;
String user_fname;
String user_lname;
int dept_id;
String test;
String user_email;
String user_password;
String user_username;
Bundle profileBundle;
String userid;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionClass = new ConnectionClass();
edtuserid = (EditText) findViewById(R.id.edtuserid);
edtpass = (EditText) findViewById(R.id.edtpass);
btnlogin = (Button) findViewById(R.id.btnlogin);
pbbar = (ProgressBar) findViewById(R.id.pbbar);
pbbar.setVisibility(View.GONE);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userid = edtuserid.getText().toString();
password = edtpass.getText().toString();
int lala = Integer.parseInt(userid);
test2 = lala;
DoLogin doLogin = new DoLogin();
doLogin.execute("");
}
});
}
public class DoLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
#Override
protected void onPreExecute() {
pbbar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r) {
pbbar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, r, Toast.LENGTH_SHORT).show();
if(isSuccess) {
//DITO ANG REDIRECTION
Intent base = new Intent(MainActivity.this, OtherActivity.class);
startActivity(base);
finish();
}
}
#Override
public String doInBackground(String... params) {
if(userid.trim().equals("")|| password.trim().equals(""))
z = "Please enter User Id and Password";
else
{
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select user_id, user_fname, user_lname,department_id, user_email, user_password, user_username from users where user_id='" + userid + "' and user_password='" + password + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
userIDD = rs.getString(1);
user_fname = rs.getString(2);
user_lname = rs.getString(3);
dept_id = rs.getInt(4);
user_email = rs.getString(5);
user_password = rs.getString(6);
user_username = rs.getString(7);
profileBundle = new Bundle();
profileBundle.putInt("userID", user_id);
profileBundle.putInt("deptID", dept_id);
profileBundle.putString("fname", user_fname);
profileBundle.putString("lname", user_lname);
profileBundle.putString("email", user_email);
profileBundle.putString("pass", user_password);
Fragment fragobj=new PathfinderAdd();
fragobj.setArguments(profileBundle);
//Fragment fragobj = new PathfinderAdd();
//fragobj.setArguments(profileBundle);
z = "Logged In as: " + user_username;
isSuccess=true;
}
else
{
z = "Invalid Credentials";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
Log.e("MYAPP", "exception", ex);
z = "Error Somewhere";
}
}
return z;
}
}
public int getMyData() {
int wa = lala;
return wa;
}
}
PahtfinderAdd.java
getting the bundle in the fragment
public class PathfinderAdd extends Fragment {
ConnectionClass connectionClass;
EditText edtideaname, edtbenefit,edtobservation,edtquickwin,targetdate;
Button btnadd;
TextView targettv;
Spinner spinner1, spinner2;
ProgressBar pbbar;
String proid;
CalendarView calendar;
String realDate;
String DAY;
Date targ = null;
String finalDate;
SimpleDateFormat timeFormat;
java.sql.Date sql;
Date date2;
Integer userID;
int user;
public PathfinderAdd(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.addpathfinder, container, false);
connectionClass = new ConnectionClass();
edtideaname = (EditText) rootView.findViewById(R.id.edtideaname);
edtbenefit = (EditText) rootView.findViewById(R.id.edtbenefit);
edtobservation = (EditText) rootView.findViewById(R.id.edyobservation);
edtquickwin = (EditText) rootView.findViewById(R.id.edtquickwin);
targetdate = (EditText) rootView.findViewById(R.id.target);
spinner1 = (Spinner) rootView.findViewById(R.id.spinner1);
spinner2 = (Spinner) rootView.findViewById(R.id.spinner2);
btnadd = (Button) rootView.findViewById(R.id.btnadd);
pbbar = (ProgressBar) rootView.findViewById(R.id.pbbar);
targettv = (TextView) rootView.findViewById(R.id.tvtarget);
pbbar.setVisibility(View.GONE);
calendar = (CalendarView) rootView.findViewById(R.id.calendar1);
proid = "";
userID = getArguments().getInt("userID");
Bundle bundle = this.getArguments();
user = bundle.getInt("userID");
//String lol = new getMyData().
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddPro addPro = new AddPro();
addPro.execute("");
}
});
calendar.setOnDateChangeListener(new OnDateChangeListener() {
public void onSelectedDayChange(CalendarView view, int year_date, int month_date,
int dayOfMonth) {
int day = dayOfMonth;
int month = month_date;
int year = year_date;
DAY=String.valueOf(year)+String.valueOf(month)+String.valueOf(day);
}
});
return rootView;
}
public class AddPro extends AsyncTask<String, String, String> {
String z = "";
Boolean isSuccess = false;
String observation = edtobservation.getText().toString();
String quickwin = edtquickwin.getText().toString();
String ideaname = edtideaname.getText().toString();
String benefit = edtbenefit.getText().toString();
String target_date = targetdate.getText().toString();
String process = spinner1.getSelectedItem().toString();
String benefitType = spinner2.getSelectedItem().toString();
String lol = "2015-11-28";
Integer benefit_type = spinner2.getSelectedItemPosition();
Integer idea_type = spinner1.getSelectedItemPosition();
Integer idea_id;
Integer benefit_id;
Integer pathfinder_id = 1;
Integer pathfinder_status = 9;
Integer pathfinder_prog = 0;
#Override
protected void onPreExecute() {
pbbar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r) {
pbbar.setVisibility(View.GONE);
Toast.makeText(PathfinderAdd.this.getActivity(), r, Toast.LENGTH_SHORT).show();
if(isSuccess==true) {
edtideaname.setText(null);
edtbenefit.setText(null);
edtobservation.setText(null);
edtquickwin.setText(null);
targetdate.setText(null);
}
}
#Override
protected String doInBackground(String... params) {
if (ideaname.trim().equals("") || benefit.isEmpty() || observation.trim().equals("") || quickwin.trim().equals(""))
z = "Please fill all the fields";
else {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
//timeFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
//finalDate = timeFormat.format(targ);
//sql = new java.sql.Date(targ.getTime());
int lol=1;
double benefitInt = Double.parseDouble(benefit);
date2 = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH).parse(DAY);
String newDateString = new SimpleDateFormat("yyyy/MM/dd",Locale.ENGLISH).format(date2);
DateFormat format2 = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH);
Date date3 = format2.parse(newDateString);
java.sql.Date finalDt = new java.sql.Date(date3.getTime());
String dates = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH)
.format(Calendar.getInstance().getTime());
//String date = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH)
//.format(calendar.getDate());
switch (idea_type)
{
case 0:
idea_id = 1;
break;
case 1:
idea_id = 2;
break;
case 2:
idea_id = 3;
break;
case 3:
idea_id = 4;
break;
case 4:
idea_id = 5;
break;
default:
idea_id = 1;
break;
}
switch(benefit_type)
{
case 0:
benefit_id = 1;
break;
case 1:
benefit_id = 2;
break;
default:
benefit_id = 1;
break;
}
String query = "insert into pathfinder (pathfinder_id,pathfinder_name,idea_id,benefit_id,pathfinder_potential_eqv,pathfinder_observation,pathfinder_quickwin,pathfinder_target_closure,pathfinder_status,pathfinder_progress,patfinder_actual_closure,pathfinder_date_raised,user_id)" +
"values ('" +pathfinder_id+ "','" +ideaname+ "','" +idea_id+ "','" +benefit_id+ "','" +benefitInt+ "','" +observation+ "','" +quickwin+ "','" +dates+ "','" +pathfinder_status+ "','" +pathfinder_prog+ "','" +dates+ "','" +dates+ "','" + user+"')";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
z = "Added Successfully";
isSuccess = true;
}
} catch (Exception ex) {
isSuccess = false;
z = "Exceptions";
Log.e("MYAPP", "exception", ex);
}
}
return z;
}
}
}
You can add or replace Fragment by calling this in your activity
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
more Fragment information check this http://developer.android.com/guide/components/fragments.html
To get data from you activity you can create a method in your activity
public dataType getData() {
return data;
}
in your fragment, you can get data by calling
((YourActivityClass) getActivity()).getData();
Hope this help!!
You are setting the Bundle to the Fragment, but where are you replacing/adding the Fragment? I can't see any FragmentTransaction.
Here you have some examples: http://developer.android.com/reference/android/app/Fragment.html
"DetailsActivity" is what you need, if I'm not wrong.
Example:
When you want to start your Fragment from the Activity:
Fragment fragobj=new PathfinderAdd();
fragobj.setArguments(profileBundle);
getFragmentManager().beginTransaction().add(android.R.id.content, fragobj).commit();
Where android.R.id.content is the container for your Fragments. When you do this your Fragment will be shown and the Bundle will be received.
In your Fragment "onCreate":
if (getArguments() != null) {
Bundle bundle = this.getArguments();
user = bundle.getInt("userID");
}

Categories