Passing data back and forth between activities - java

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,

Related

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

Activity to Fragment sending data and access arraylist in Fragment

I have a fragment which is present in Bottom Navigation Activity. The Fragments contain the custom recyclerview. There is a comment button when i press it opens another activity for comments. Below is in the RecyclerView adapter.
viewholder.commentlay.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//commenttofragment.clear();
Intent comment = new Intent(fp, com.fooddoof.fuddict.comment.class);
int id = dusers.get(position).getId();
int comcount = dusers.get(viewholder.getAdapterPosition()).getCommentcount();
comment.putExtra("id",id);
comment.putExtra("ownerid",userid);
comment.putExtra("maincommentposition",position);
comment.putExtra("commentcountonposition", comcount);
fp.startActivityForResult(comment,1);
}
});
In Comment activity after doing some tasks I need to send some values to this fragment. So I Override the OnBackPressed method. I have created a method in Fragment to receive it.
#Override
public void onBackPressed()
{
Bundle args = new Bundle();
args.putInt("maincommentcount",maincommentcount);
args.putInt("maincommentposition", maincommentposition);
FolowersPost f = new FolowersPost();
f.getdatafromcomment(args);
finish();
}
I receive it like below in Fragment.
public void getdatafromcomment(Bundle args)
{
int count = args.getInt("maincommentcount");
int p=args.getInt("maincommentposition",999999999);
Log.e("Shiva","count--->"+count+"p--->"+p);
}
The Values are received but I need to access the arraylist in Fragement which is passed in Adapter for displaying the recyclerView. But I am not able to access it while I am coming back to fragment which is present in the method under OnCreateView. I tried with OnResume to access it but works for some time only. I have declared the Arraylist as global variable also.
You are already using startActivityForResult. now you just need to use onActivityResult.
But you just need to start activity from fragment instead of from adapter.
onClick from fragment:
Intent comment = new Intent(getActivity(), com.fooddoof.fuddict.comment.class);
startActivityForResult(comment, 1);
onBackPressed in your comment activity:
#Override
public void onBackPressed() {
Intent returnIntent = new Intent();
returnIntent.putExtra("maincommentcount",10);
returnIntent.putExtra("maincommentposition",20);
setResult(Activity.RESULT_OK,returnIntent);
finish();
// super.onBackPressed();
}
onActivityResult in fragment:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
int mMaincommentcount = data.getIntExtra("maincommentcount", 0);
int mMaincommentposition = data.getIntExtra("maincommentposition", 0);
System.out.println("mMaincommentcount = " + mMaincommentcount + ", mMaincommentposition = " + mMaincommentposition);
}
}
}

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

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()

having issues with starting an activity using Intent

I'm frustrated as to how I can get the function to work properly.
I've been researching and looking around about Intents.
At first I thought I got it right but I was wrong, some overview on what I mean.
I have made an app with 6 buttons, all of which that open different applications.
Clock, 2. Calendar, 3. Browser, 4. Messaging, 5. Phone, and 6. Contacts.
This is my onClick method for launching the contacts application.
// Contacts Launch
Button contacts_launch = (Button) findViewById(R.id.contacts_launch);
contacts_launch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent_contacts = new Intent(Intent.ACTION_MAIN);
intent_contacts.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(intent_contacts);
}
});
The onClick Intent method is the same for all my buttons, just the intent name has been changed according to the applications name, like messaging is intent_message.
When launching the application, and when I tapped the button. It prompted me with a window where I could select the application. And it ran the app every time I selected the button.
But when I select another application, it launches the contacts app? And doesn't let me choose it like before. How can I fix this? I'm pretty sure I'm using the intent function wrong.
Thanks for your time.
Please check code again, that was my modified one that didn't work which was the one with only one intent method. I added the code that I used at first where it let me choose. That's the one with the intent and category. (The one you can see now)
if you dont want to select the Activity over and over again (like when using createChooser) try this:
public class Chooser extends Activity implements OnClickListener {
private static final int NUM = 6;
private static final CharSequence DEFAULT = "click for select the app, long click to clear it";
private Intent[] mIntents = new Intent[NUM];
private LinearLayout mLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLayout = new LinearLayout(this);
mLayout.setOrientation(LinearLayout.VERTICAL);
for (int i = 0; i < NUM; i++) {
Button b = new Button(this);
b.setTag(i);
b.setText(DEFAULT);
b.setOnClickListener(this);
registerForContextMenu(b);
mLayout.addView(b);
}
setContentView(mLayout);
}
private CharSequence getName(Intent intent) {
PackageManager mgr = getPackageManager();
ResolveInfo info = mgr.resolveActivity(intent, 0);
if (info != null) {
return info.loadLabel(mgr);
}
return intent.getComponent().getShortClassName();
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
int itemId = (Integer) v.getTag();
if (mIntents[itemId] != null) {
menu.add(Menu.NONE, itemId, Menu.NONE, "Clear");
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
int i = item.getItemId();
Button b = (Button) mLayout.getChildAt(i);
b.setText(DEFAULT);
mIntents[i] = null;
return super.onContextItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Button b = (Button) mLayout.getChildAt(requestCode);
b.setText(getName(data));
mIntents[requestCode] = data;
startActivity(data);
}
}
#Override
public void onClick(View v) {
int i = (Integer) v.getTag();
if (mIntents[i] == null) {
Intent intent = new Intent(Intent.ACTION_PICK_ACTIVITY);
Intent filter = new Intent(Intent.ACTION_MAIN);
filter.addCategory(Intent.CATEGORY_LAUNCHER);
intent.putExtra(Intent.EXTRA_INTENT, filter);
startActivityForResult(intent, i);
} else {
startActivity(mIntents[i]);
}
}
}
Hi Use the below Code to open contacts:
#SuppressWarnings("deprecation")
Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
startActivity(intent);
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("sms:"));
sendIntent.putExtra("sms_body", urlToShare);
startActivity(sendIntent);
This is a sample code to open message application or hangout. You can do like this for others also.

How to update adapter in onCreate in antoher class?

So i have an DataAdapter in onCreate method and i want to update it from another class.
main_spinList = (Spinner) findViewById(R.id.main_spinList);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
main_spinList.setAdapter(dataAdapter);
//=========================================Spinner==================
main_spinList.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
filepath = String.valueOf(main_spinList.getSelectedItem());
}
public void onNothingSelected(AdapterView<?> arg0) {
Log.e("klkl", "klkl");
}
});
I can update like this from AsyncTask but how can i update the adapter from another class with dataAdapter.notifyDataSetChanged(); ?
new FtpGet(){
public void onPostExecute(ArrayList<String> result) {
list.clear();
list.addAll(result);
dataAdapter.notifyDataSetChanged();
}
}.execute();
Another problem is that API 9 devices cant perform AsyncTask like from above in setOnSelectedItem method, it doesnt update the spinner.
I think you better look at "Getting a Result from an Activity" and "Retrieving result data from a sub-activity", because you don't need to refresh the adapter until you go back to it's activity.
onActivityResult() will allow you to get the status from the sub activity and you can refresh the adapter from the same activity when you are back to it.
In your adapter activity put this code where you start the other activity:
Intent i = new Intent(this, ActivityTwo.class);
startActivityForResult(i, REQUEST_CODE);
and add this method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
if (data.hasExtra("result")) {
ArrayList<String> result = data.getExtras().getSerializableExtra("result");
list.addAll(result);
dataAdapter.notifyDataSetChanged();
}
}
}
And when closing the sub activity and you want to refresh the adapter use this:
Intent data = new Intent();
data.putExtra("result", result);
setResult(RESULT_OK, data);
finish();
use interface in the activity you implement the interface and in the other class you just trigger it. and it it's method you use notify for the adapter.

Categories

Resources