How do I add data I have keyed in a EditText box into an array to list in another activity? - java

Below are the 3 java classes which I am using for my android application development. I would like to add the student data (name and phone number) from the AddActivity to be stored in MainActivity page after clicking "Add". I have researched on this and tried using an array. But I am quite confused on how the logic must be for the code to send the data keyed in AddActivity into the MainActivity page. Can anyone give me a guidance on how to work this out and would really be grateful if you could show me another way rather the way I am trying. I want the data to be stored in a ListView format in the MainActivity after each "Add" I have clicked in the AddActivity page. I do hope that someone will be able to guide me in doing this. Thank you.
MainActivity.java -
https://jsfiddle.net/eb1fprnn/
public class MainActivity extends AppCompatActivity {
ListView listView;
Button addStudent;
ArrayList<Student> students = new ArrayList<Student>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add();
}
public void add() {
Student student;
addStudent = (Button) findViewById(R.id.add);
addStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
}
}
AddActivity.java -
https://jsfiddle.net/40k5mas2/
public class AddActivity extends AppCompatActivity {
EditText name, phone;
Button add;
int FphoneNumber;
String Fname;
ArrayList<Student> students;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
students = (ArrayList<Student>) getIntent().getSerializableExtra("AddNewStudent");
setContentView(R.layout.activity_add);
edit();
addStudent();
}
public void edit() {
name = (EditText) findViewById(R.id.StudentName);
phone = (EditText) findViewById(R.id.phone);
final Button addStudent = (Button) findViewById(R.id.AddStudent);
name.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
addStudent.setEnabled(!name.getText().toString().trim().isEmpty());
Fname = name.getText().toString();
String phoneNumber = phone.getText().toString();
FphoneNumber = Integer.parseInt(phoneNumber);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void addStudent() {
add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this, MainActivity.class);
intent.putExtra("studentName",name.getText().toString() );
intent.putExtra("phoneNumber",phone.getText().toString());
startActivity(intent);
Student student = new Student(Fname, FphoneNumber);
students.add(student);
}
});
}
public void addStudent(){
add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this,Record.class);
startActivity(intent);
}
});
}
Student.java -
https://jsfiddle.net/gy0g7b0s/
public class Student {
String mName;
int mPhoneNumber;
public Student (String name, int number){
mName = name;
mPhoneNumber = number;
};
public String getmName() {
return mName;
}
public String getmName(String newName) {
return (this.mName = newName);
}
public int getmPhoneNumber() {
return this.mPhoneNumber;
}
public int getmPhoneNumber(int newPhoneNumber) {
return (this.mPhoneNumber = newPhoneNumber);
}
#Override
public String toString() {
return String.format("%s\t%f",this.mName, this.mPhoneNumber);
}
[1] : [Image of Main Activity Page] http://imgur.com/a/pMWt4
[2] : [Image of Add Activity Page] http://imgur.com/a/8YvVc

as mentioned above, the correct way would be to use the startActivityForResult method. Check this.
And how to go about it, Damn easy!
Modifying your code:
public void add() {
Student student;
addStudent = (Button) findViewById(R.id.add);
addStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivityForResult(intent,123);
}
});
}
}
and in the same activity (MainActivity) listen for the result
Also would recommend you to use the parceler.org lib for sending objects
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode== Activity.RESULT_OK && requestCode==123){
// perform your list addition operation here and notify the adapter for change
// the returned data comes in 'data' parameter and would recommend you to use parcels.org lib
// for sending parcelable pojo across activities and fragments.
list.add(Parcels.unwrap(data.getParcelableArrayExtra(YOUR_KEY)));
adapter.notifyDataSetChanged();
}
}
And in your AddActivity, when you add just do this.
public void addStudent() {
// add the 'add' button view to the oncreatemethod
// add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do not restart the activity that opened this activty
// this activity is anyways on top of the MainActivity. Just finish this activty setting the result
// Intent intent = new Intent(AddActivity.this, MainActivity.class);
// intent.putExtra("studentName",name.getText().toString() );
// intent.putExtra("phoneNumber",phone.getText().toString());
// startActivity(intent);
// How to do that?
Student student = new Student(Fname, FphoneNumber);
Intent intent = new Intent();
intent.putExtra(YOUR_KEY, Parcels.wrap(student));
// you can also do it without the parcels lib
// intent.putExtra("studentName",name.getText().toString() );
// intent.putExtra("phoneNumber",phone.getText().toString());
setResult(123,intent); // set the result code. it should be the same one as the one your listening on in MainAcitivty
// then just finish this activity.
finish();
// this calls the onActivtyResultMethod in MainActivity which furtther does the logic
// students.add(student);
}
});
}
That should work! Cheers!

Use StartActivityForResult for AddActivity and return object from here and use in MainActivity. For example see here

Since you store the data in a file, the add activity should just write the data to the file. Then the main activity should always read the file to refresh the list.

I will suggest using a static class if you don't want to use a Database.
Or if you should use a file is just very simple to write into a file when you add and read from it in the next activity.
Just create a Static class like this.
public static class MyStaticClass{
private static ArrayList <Student> mStudents = new ArrayList<Student>()
public static void addStudent(Student theNewStudent){
mSudents.add(theNewStudent);
}
public static List<Student> getStudents(){
return mStudents;
}
}
or with a file:
public static class MyFileClass{
private static String pathFile = "Your path";
public static void addStudent(Student theNewStudent){
File file = new OutputStreamWriter(new FileOutputStream(pathFile,true)); //the true is to append to the file
file.write(/*parse your student as a string*/);
file.close();
}
public static List<Student> getStudents(){
ArrayList<Student> students = new ArrayList<>()
File file = new File(pathFile);
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
//parse your line to a student object
students.add(yourNewStudent);
}
sc.close();
return students;
}
}
Just call the add student and the get students in the proper class as follows.
MyStaticClass.addStudent(student);
or
MyFileClass.addStudent(student);
Hope it helps.
In your onclick listener:
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this, MainActivity.class);
Student student = new Student(Fname, FphoneNumber);
MyStaticClass.addStudent(student); // or the FileClass
startActivity(intent);
}
and i cant see where do you retrieve the list. but just use the getStudents of the class.

Intent yourFirstAct= new Intent(firstAct.this,second.class);
yourFirstAct.putExtra("","");
startActivitForResult(yourFirstAct);
in first Activity,
#Override
public void onAcitivityResult(....){
super();
}
in your second activity when you done,
do your stuff whatever you want in second activity. and pass it to mainActivity
Intent yoursecAct= new Intent();
yourSecAct.putExtra("","");
setResult(yourSecAct);
finish();
IF YOU ARE USING IN FRAGMENT
if you do startActivityResult() in fragment means,
your fragment mainActivity must return super() in
public void onAcitivityResult(...){super()}

After getting the details from the student, put the respective details in a bundle and just use intent to go back to the main activity. Then use bundles to extract the data in the main activity.

You can use startActivityForResult for the same. if you haven't found the answer yet then please let me know. I will provide you the code.
Many above answers already defined this thing in a very good way.

This is about communication between Activities. You can use event bus to realize this.
https://github.com/JackZhangqj/EventBus
Then 1. Add event bus dependency to the App's build.grade
compile "de.greenrobot:eventbus:3.0.0
Register and unregister your subscribe in the MainActivity.java
#Override
protected void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
protected void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
3.Post event in the AddActivity.java
EventBus.getDefault().post(new Student(name.getText().toString(), phone.getText().toString()));
4.Implement event handling method in MainActivity
//The student is the added student in the AddActivity.java
public void onEventMainThread(Student student) {
}

To kind of expand a little bit on MadScientist's answer, ListView's need adapters in order set the data in it's view. You'll need to define an ArrayAdapter for your list view to communicate with. This will need to go in your MainActivity and will be initialized in the onCreate method. Assuming you want to display both types of information, you'll need to construct your adapter with the built in layout for showing two items via android.R.layout.simple_list_item_2. If you would like to create your own layout, however, you can look up how to do that here.
public class MainActivity extends AppCompatActivity {
Button addStudent;
ArrayAdapter<Student> adapter;
ArrayList<Student> students = new ArrayList<Student>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_2, students);
ListView listView = (ListView) findViewById(R.id.listView);
listView.addAdapter(adapter);
add();
}
Call the startActivityForResult(intent, 123) in your Listener to start the new activity. Then, once you have typed in your data, add your items to the intent and call finish() in your AddActivity. Override the onActivityResult in your MainActivity to pull the items off your intent and add them to your list. Finally, notify the adapter of the changes via adapter.notifyDataSetChanged()

Related

Why does transfering data from one Activity to another doesnt work inside a query in firebasefirestore

i am trying to pass values of filtered chips that a user has selected in order to retrieve only the required shops he want in that particular criteria.
now i created everything and the data i am getting after finishing from my FilterActivity is being passed into my HomeActivity. but this data is not being 'read' or 'accepted' inside my query since it doesn't produce the correct output. When i use a static value inside the query it would work. now i need it to be a changing value depending on what the use has selected.
This is inside my HomeActivity that opens the Filter Activity:
filterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(HomeActivity.this,FilterActivity.class);
startActivityForResult(intent,101);
}
});
this is my FilterActivity with a few examples:
private Chip rate2,rate3,rate4;
private ArrayList<String> selectedChipData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filter);
rate2 = findViewById(R.id.chip_Rate_2);
selectedChipData = new ArrayList<>();
CompoundButton.OnCheckedChangeListener checkedChangeListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(isChecked){
selectedChipData.add(compoundButton.getText().toString().trim());
}else{
selectedChipData.remove(compoundButton.getText().toString().trim());
}
}
};
rate2.setOnCheckedChangeListener(checkedChangeListener);
}
and this is the button the user clicks when he wants to apply one of the filter options:
filter_reset = findViewById(R.id.filter_reset);
filter_reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent resultIntent = new Intent();
resultIntent.putExtra("data",selectedChipData.toString().trim());
setResult(101,resultIntent);
finish();
}
});
now in my HomeActivity i created the onActivityResult:
String Data;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==101){
Data = data.getStringExtra("data");
Log.d("TAG", data.getStringExtra("data"));
Query q = firebaseFirestore.collection("Shops").whereEqualTo("location",Data);
}
}
Query q = firebaseFirestore.collection("Shops").whereEqualTo("location",Data);
// this is my query and how i am trying to pass the matched users selected chip to the location of the Shops table.
What am i missing or doing wrong inside my query and how to fix it? can someone advise?
Did by any chance you forget to tell intent to go back to Home Page
filter_reset = findViewById(R.id.filter_reset);
filter_reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent resultIntent = new Intent(FilterActivity.this, MainActivity.class);
// Changed the above Intent Paras
resultIntent.putExtra("data",selectedChipData.toString().trim());
setResult(101,resultIntent);
finish();
}
});
i found the problem, it wasn't matching with my database because the value is an array and has [] in the result. if i put the [] in my database it works fine.

How do I pass the number of clicks and reset the count in another activity?

The codes are messy at this point since I've been going back and forth so much. Every time user clicks the yes/no button I want the results of counts the button has been clicked to display in another activity. I also want to reset the number of clicks from the second activity as well. All that's needed in the first activity is the question and the yes/no button. Is this possible? Thanks in advance.
public class MainActivity extends AppCompatActivity {
private static final String TAG = "SurveyActivity";
private static final String YES_INDEX = "yes votes";
private static final String NO_INDEX = "no votes";
Button mYesButton;
Button mNoButton;
Button mResetButton;
TextView mSurveyQuestion;
private int yesVoteCount = 0;
private int noVoteCount = 0;
private int resetVotes = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Use res ID to retrieve inflated objects and assign to variables
mYesButton = findViewById(R.id.yes_button);
mNoButton = findViewById(R.id.no_button);
mResetButton = findViewById(R.id.reset_button);
mSurveyQuestion = findViewById(R.id.survey_question);
mYesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addVote();
}
});
mNoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addVote();
}
});
// Resetting vote count
mResetButton.setOnClickListener(new View.OnClickListener() {
#Override
***Should this supposed to be in the second activity?
}
});
}
private void addVote() {
if (mYesButton.isPressed()) {
yesVoteCount++;
} else if (mNoButton.isPressed()) {
noVoteCount++;
}
}
In your main activity
btnShowResut.setOnClickListener(new View.OnClickListener() {
#Override
// Create intent for going to another activity
Intent intent = new Intent(this, AnotherActivity.class);
// Put counts datas to intent
intent.putExtra("yesCountKey", yesVoteCount);
intent.putExtra("noCountKey", noVoteCount);
// NEW : Go to another activity by calling it instead
// REQUEST_CODE is an integer variable
startActivityForResult(intent, REQUEST_CODE);
}
});
In Another activity, you can retrieve datas in onCreate method like this and send action to clear counts of your main activity.
...
onCreate(...){
...
// Retrieve datas from intent
int yesCount = getIntent().getIntExtra("yesCountKey", 0);
int noCount = getIntent().getIntExtra("noCountKey", 0);
mResetButton.setOnClickListener(new View.OnClickListener() {
#Override
// Send a boolean to main activity for clearing votes
Intent intent = new Intent();
intent.putExtra("resetVotes", true);
setResult(RESULT_OK, intent);
// Close second activity
finish();
}
});
}
Finally in the main activity override this method and clear votes
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == 2000 && resultCode == RESULT_OK){
boolean reset = data.getBooleanExtra("resetVotes", false);
if(reset){
yesVoteCount = 0;
noVoteCount = 0;
}
}
}
As the mentioned above, you can get the counts by using intent extras.
However if you want to reset the counts in in the second activity you might want to start the Activity B as startActivityForResult() see the Android documentation here.
Then when Activity B end you can reset the counts in the call back method onActivityResult().
If you don't want to do it like this the next best way might be to reset the counts onResume() of Activity A so that when you return to the activity you will start with fresh counts. See life cycle documentation here

How do I call one method of an activity from another class

This is a part of my activity class,
public class StatusActivity extends AppCompatActivity {
private boolean cFlag = false;
public boolean getFlag() { return cFlag; }
public void setFlag(boolean cFlag) {
this.cFlag = cFlag;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
android.R.id.text1, messages);
ListView listView = findViewById(android.R.id.list);
listView.setAdapter(adapter);
adapters.add(adapter);
Button btn = findViewById(R.id.btnCustomerCheckIn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setFlag(true);
cFlag = getFlag();
Intent intent = new Intent(StatusActivity.this, MainActivity.class);
Toast.makeText(StatusActivity.this, "customer checked in",
Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
this is a part of another class named as position
public class Position {
StatusActivity statusactivity = new StatusActivity();
public boolean ccflag = statusactivity.getFlag();
statusactivity.setFlag(false);
}
when i am calling
statusactivity.setFlag(false);
it is showing an error. couldn't recognize that what is the error that i am getting. but
statusactivity.getFlag();
is working properly. any help is appreciated
StatusActivity statusactivity = new StatusActivity();
This is totally wrong because you are trying to create a new Instance of activity.
If you want to use "setFlag" method from other activity then you must create a static method inside StatusActivity so you can access using directly StatusActivity.
And If you want to call from any fragment of this activity then please get an instance of this activity by the cast from "getActivity()" to StatusActivity and use that instance for call "setFlag" or "getFlag" method.
You can implement like below in Activity.
private static boolean cFlag = false;
public static boolean getFlag() {
return cFlag;
}
public static void setFlag(boolean cFlag) {
StatusActivity.cFlag = cFlag;
}
and call from position class like below
public class Position {
public boolean ccflag = StatusActivity.getFlag();
StatusActivity.setFlag(false);
}
you can not instantiate Activity class. if you want to call a method from activity, fist you should check that activity already running and not destroyed then by having the context of your class you just cast it like below then use its method
StatusActivity statusactivity= (StatusActivity )context;
statusactivity.setFlag(false);

Passing data back and forth between activities

I have a MainActivity which has a ListView, when I click the ListView it opens a new activity for that item.
I want to be able to change the information in that item, then when I click back it changes the ListView.
Here's some of the code I have:
MainActivity:
String[] people;
private ListView mListView;
public static ArrayAdapter<String> adapter;
In onCreate(){
people = new String[] {"", "", "", "", "", "", "", ""};
mListView = (ListView) findViewById(R.id.personListView);
adapter = (new ArrayAdapter<String>(this, R.layout.list_item, people);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Current item
String person = ((TextView) view).getText().toString();
// Launch new activity based on item
Intent intent = new Intent(getApplicationContext(), SinglePerson.class);
//
intent.putExtra("person", person);
//intent.putExtra("peopleList", people);
intent.putExtra("position", position);
startActivityForResult(intent, 1);
//
}
});
I have this in the class which I thought would get the information from the other activity back but nothing happens:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == 1) {
// Make sure the request was successful
if(resultCode == RESULT_OK){
int listPos = data.getIntExtra("listPosition", 1);
//edit listview value at position
people[listPos] = data.getStringExtra("edittextvalue");
adapter.notifyDataSetChanged();
}
}
}
In the other activity class:
public class SinglePerson extends Activity{
String[] people;
int position;
Intent intent;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_person_item_view);
EditText txtPerson = (EditText) findViewById(R.id.person_name);
intent = getIntent();
String person = intent.getStringExtra("person");
//people = intent.getStringArrayExtra("peopleList");
position = intent.getIntExtra("position", 0);
txtPerson.setText(person);
}
private TextWatcher peopleNumberListener = new TextWatcher(){
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
//people[position] = s.toString();
//BillSplit.adapter.notifyDataSetChanged();
intent.putExtra("edittextvalue",s.toString());
intent.putExtra("listPosition", position);
setResult(RESULT_OK, intent);
//finish();
}
};
As per my comment above, if you are pressing the back key then you're not properly finishing the Activity. What you want to do is when you're ready to end the Activity, either in a Button or some other action, then do the following (which it looks like you had already mostly figured out)
...
// you can create a new Intent for the result
Intent newIntent = new Intent();
newintent.putExtra("edittextvalue",s.toString());
newintent.putExtra("listPosition", position);
setResult(RESULT_OK, newintent);
finish();
...
EDIT: In response to those who are posting to override onBackPressed(), this will allow you to intercept the back key when you press it within your Activity and decide how you want to handle it. However, please note the implication of doing this: if this is for the general public, most users will expect the back key to take you some form of "back", but this is not the same as completion or progressing through the normal flow of your app (which you are looking to do by making a selection and then continue where you left off). So while this may accomplish the desired behavior, it's debatable whether this is the correct solution for you.
I would use Singleton if you have more than two activities. If its just two then probably using intent.put. Thanks,

Access variables from onclicklistener android

The the problem is how to use variables inside onclick method, example:
String number = "555 12345";
callbutton.setOnClickListener(new onClickListener(){
#Override
public void onClick(View view) {
Intent phoneCallIntent = new Intent(Intent.ACTION_CALL);
phoneCallIntent.setData(Uri.parse(number));
startActivity(phoneCallIntent);
}
});
I tried this solution and failed. Making custom class for onclicklistener.
String number = "555 12345";
bt.setOnClickListener(new CallButtonClickListener(number){});
public class CallButtonClickListener implements OnClickListener
{
String num;
public CallButtonClickListener(String number) {
this.num = number;
}
#Override
public void onClick(View v)
{
Intent phoneCallIntent = new Intent(Intent.ACTION_CALL);
phoneCallIntent.setData(Uri.parse(num));
startActivity(phoneCallIntent);
}
};
}
How can I pass the string to onclick? I can't define the string inside onclick because I have to use it multiple times.
Make it final:
final String number = "555 12345";
Also the second solution seems alright also as you're passing a copy of the reference. What't wrong with it?
Use final variable or declare them outside onCreate() method

Categories

Resources