ArrayList only stores one object - java

My Arraylist Only stores one object in it. Every time a new object is entered, it overwrites the current one.
Calling method:
public void saveBookingInfo(View view) {
EditText applicantNameText = (EditText) findViewById(R.id.applicantNameTextField);
EditText itemToBurnText = (EditText) findViewById(R.id.itemToBurnTextField);
String appName = applicantNameText.getText().toString();
String appItemToBurn = itemToBurnText.getText().toString();
if (appItemToBurn.isEmpty() || appName.isEmpty()) {
Toast.makeText(BookingScreen.this, "Please fill in all fields.", Toast.LENGTH_SHORT).show();
}
else {
sendApplication.storeApplication(appName, appItemToBurn);
this.finish();
}
}
ArrayList method:
public void storeApplication(String name, String item){
ArrayList<Application> peopleAttending = new ArrayList<>(10);
peopleAttending.add(new Application(name, item));
}

You're declaring the List<Application> as local parameter to the method. Move it as a field in the class instead.
private List<Application> peopleAttending = new ArrayList<>();
public void storeApplication(String name, String item) {
peopleAttending.add(new Application(name, item));
}

You are creating a new ArrayList every time you call the method. You should create the ArrayList exactly once and pass a reference to the method, or make the reference an instance variable.

you can try changing the constructor of the class for object sendApplication
class SendApplication{
List<Application> peopleAttending = null;
public SendApplication(){
List<Application> peopleAttending = new ArrayList<Application>();
}
public void storeApplication(String name, String item) {
peopleAttending.add(new Application(name, item));
} //...... other methods follow
}

Related

how to check value of variable has changed or not inside while loop without comparing inside java

i am fetching value from data base which is overriding the old value , how could in know when the variable value has changed.
while(result.next())
{
String rteCd = result.getString("Rte_Cd")
}
every time the rteCd will get get overridden with the database value, i want to check at which point it has changed becoz it can be same also, i need to perform some action when it changes
Npte:- i cant change the database and the query can return same value multiple times
Java.util.Observable might be of help.
The java.util.Observable.hasChanged() method returns if this object has changed.
Here's a sample code you can check out
import java.util.Observable;
import java.util.Observer;
class ObservedObject extends Observable {
private String watchedValue;
public ObservedObject(String value) {
watchedValue = value;
}
public void setValue(String value) {
// if value has changed notify observers
if(!watchedValue.equals(value)) {
watchedValue = value;
// mark as value changed
setChanged();
}
}
}
public class ObservableDemo implements Observer {
public String name;
public ObservableDemo(String name) {
this.name = name;
}
public static void main(String[] args) {
// create watched and watcher objects
ObservedObject watched = new ObservedObject("Original Value");
// watcher object listens to object change
ObservableDemo watcher = new ObservableDemo("Watcher");
// add observer to the watched object
watched.addObserver(watcher);
// trigger value change
System.out.println("setValue method called...");
watched.setValue("New Value");
// check if value has changed
if(watched.hasChanged())
System.out.println("Value changed");
else
System.out.println("Value not changed");
}
public void update(Observable obj, Object arg) {
System.out.println("Update called");
}
}
Output
setValue method called...
Value changed
Declare two more variable outside the while loop and then see the old and new value like this
String oldvalue="";
String newvalue="";
while(result.next())
{
oldvalue=rteCd;
String rteCd = result.getString("Rte_Cd")
newvalue=rteCd;
}
//Now Display them
println("old value"+oldvalue);
println("new value"+newvalue);
String prevRteCd = null;
String rteCd = null;
while(result.next())
{
prevRteCd = rteCd;
rteCd = result.getString("Rte_Cd");
if(prevRteCd! =null && !prevRteCd.equals(rteCd))
{
itChanged(prevRteCd, rteCd);
}
}

Singleton class Arraylist is empty

I have created a singleton ArrayList class in android which is following.
public class SingletonArrayList {
private static SingletonArrayList mInstance;
private ArrayList<String> userNameList = null;
public static SingletonArrayList getInstance() {
if(mInstance == null)
mInstance = new SingletonArrayList();
return mInstance;
}
private SingletonArrayList() {
userNameList = new ArrayList<String>();
}
// retrieve array from anywhere
public ArrayList<String> getArray() {
return this.userNameList;
}
//Add element to array
public void addToArray(String value) {
userNameList.add(value);
}
}
I'm calling this singleton ArrayList in my activity2. It's working fine there(it contains data!).
activty2:
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, SingletonArrayList.getInstance().getArray());
But in activtiy1 it's returing an empty list.
activity1:
Log.i("single",SingletonArrayList.getInstance().getArray().toString());
if(SingletonArrayList.getInstance().getArray().contains(username1)) {
Toast.makeText(getApplicationContext(), "Username already Exists. Please select a different username", Toast.LENGTH_LONG).show();
return;
}
Basically, the problem is that ArrayList is coming empty in one activity and contains data in another activity. Any solutions?

Update static variable from another class

I have an activity on my app where a user can update their registered information stored in a remote database. When the update button is pressed the information in the database is being updated but the static variable is not changing. Here is my code thanks in advance for any help!
btUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String first_name = First_name.getText().toString();
final String last_name = Last_name.getText().toString();
final String email = Email.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
LoginActivity.first_name = jsonResponse.getString("first_name");
LoginActivity.last_name = jsonResponse.getString("last_name");
LoginActivity.email_address = jsonResponse.getString("email");
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(UpdateInfoActivity.this);
builder.setMessage("Submission Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
UpdateInfoRequest updateInfoRequest = new UpdateInfoRequest(first_name, last_name, email, userID, responseListener);
RequestQueue queue = Volley.newRequestQueue(UpdateInfoActivity.this);
queue.add(updateInfoRequest);
Intent intent = new Intent(UpdateInfoActivity.this, MainActivity.class);
UpdateInfoActivity.this.startActivity(intent);
}
});
Change your code to this
if (success) {
LoginActivity.first_name = first_name;
LoginActivity.last_name = last_name;
LoginActivity.email_address = email;
}
and I wouldn't be using static variables like that if you want to have a global user profile you could do this
class User {
private static User user = null;
public String firstName = "";
private User() {}
public static synchronized User getInstance() {
if (user == null) user = new User();
return user;
}
}
to retrieve data from anywhere in project call this
String name = User.getInstance().firstName;
And to modify the data do this
User.getInstance().firstName = UserName;
First Understand that static variables are shared by all objects and methods of the class.
So we only have one instance of the static variable.
The ways to Update static variable from other class -
1.Through object.
2.Through Class name.
Enclosing the code sample.
class A{
static int val;
public A(){val=0; }
//....
}
class B{
A obj= new A();
public void updateStatic(){
obj.val=10; // updates values through object to 10
A.val=100; //updates values through class name to 100
}
//..
}
Hope it Helps
Transfer of data between activities using the static variable is not a better way in my opinion. It is bad practice. Transferring data using intents or save data in storage media and accessing from there will be the better solution.
but the static variable is not changing.
Should be... You told the code to do that
if (success) {
LoginActivity.first_name = jsonResponse.getString("first_name");
LoginActivity.last_name = jsonResponse.getString("last_name");
LoginActivity.email_address = jsonResponse.getString("email");
}
Just want to mention...
1) You update a String, not any TextView or EditText in your question, so if you expected to see a "visual change" in your app, then no, nothing will happen unless you call setText.
2) That code is wrapped in a try-catch, and could error, so check the logs for a JSONException. If those keys aren't sent back from the server, then sure, they won't update. For example, the JSON is only {"success": true }
Still, SharedPrefences should largely be preferred over static variables here.

BackupAgentHelper with multiple sets of SharedPreferences

I have trouble unterstanding the keyPrefix of the addHelper() method.
Does it need to be unique for each BackupAgentHelper Class Instance or for each SharedPreferencesBackupHelper ?
I want to backup two or more sets of SharedPreferences:
Example:
public class PrefsBackupAgent extends BackupAgentHelper {
// Allocate a helper and add it to the backup agent
#Override
public void onCreate() {
SharedPreferencesBackupHelper user1 = new SharedPreferencesBackupHelper(this, "user1_preferences");
addHelper('prefs', user1); // <-- keyPrefix same to both addHelper Calls?
SharedPreferencesBackupHelper user2 = new SharedPreferencesBackupHelper(this, "user2_preferences");
addHelper('prefs', user2); // <--
}
}
or does it need to look like that:
public class PrefsBackupAgent extends BackupAgentHelper {
// Allocate a helper and add it to the backup agent
#Override
public void onCreate() {
SharedPreferencesBackupHelper user1 = new SharedPreferencesBackupHelper(this, "user1_preferences");
addHelper('user1', user1); // <-- or do they need to be unique for each SharedPreferencesBackupHelper ?
SharedPreferencesBackupHelper user2 = new SharedPreferencesBackupHelper(this, "user2_preferences");
addHelper('user2', user2); // <--
}
}
Which one is the correct way?
Thank you!
Your first example is correct.
public class MyBackupAgentHelper extends BackupAgentHelper {
static final String DEFAULT_PREFS = "packagename_preferences";
static final String OTHER_PREFS = "packagename_other_preference";
// A key to uniquely identify the set of backup data
static final String PREFS_BACKUP_KEY = "prefs";
#Override
public void onCreate() {
SharedPreferencesBackupHelper helper1 = new SharedPreferencesBackupHelper(this, DEFAULT_PREFS);
SharedPreferencesBackupHelper helper2 = new SharedPreferencesBackupHelper(this, OTHER_PREFS);
addHelper(PREFS_BACKUP_KEY, helper1);
addHelper(PREFS_BACKUP_KEY, helper2);
}
}

Getter and setter for List

class MipRequest{
private List<String> MipIDs=null;
public List<String> getMipIDs() {
return MipIDs;
}
public void setMipIDs(List<String> mipIDs) {
MipIDs = mipIDs;
}
}
How can i call the get function?
You could call it by using object instance like:
MipRequest mipRequest = new MipRequest();
//set list...
List<String> mipIds = mipRequest.getMipIDs();
//further business logic

Categories

Resources