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.
Related
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);
}
}
}
my MainActivity is calling a second activity PopupWindow which contains a listview. when user clicks on listview I need to return that information to first activity (MainActivity). So in MainActivity I have this two methods. the first method calls the second activity the second gets result from second activity
//event listener for authors list menu (popup window)
authorListImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent popupWinIntent = new Intent(getBaseContext(), AuthorsPopup.class);
popupWinIntent.putExtra("allauthors", allAuthors);
startActivity(popupWinIntent);
}
});
//fetching result -- author from AuthorsPopup activity back
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
String author = data.getStringExtra("author");
Log.v("author ", author);
}
}
}
this method is outside the onCreate() method. some tutorials suggest to create the avobe method just like onActivityResul() I'm assuming that case it would be inside the onCreate() method. mine is a method declaration. so obiously not executing. In my second activity. I have this
//event listener for authros listview
authorListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> paren, View view, int position, long id) {
// Log.v("author: ", authorsList[position]);
String author = authorsList[position];
Intent returnResultIntent = new Intent(getBaseContext(), MainActivity.class);
returnResultIntent.putExtra("author", author);
setResult(RESULT_OK, returnResultIntent);
finish();
}
});
what is the proper way to get data back from second activity?
You need to launch the second activity using startActivityForResult(popupWinIntent,1) rather than startActivity(popupWinIntent) and override the onActivityResult method in your first Activity, like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("author");
}
}
}
The first authorListImageView.setOnClickListener code you listed would go in onCreate
1st Activity
How to get value
SharedPreferences sharedPreferences;
sharedPreferences=getSharedPreferences("FileName",0);
sharedPreferences.getString("KEY","DefaultValue");
sharedPreferences.getBoolean("KEY",false);
2nd Activity
How to set or put the value from activity for getting on other activity
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
sharedPreferences=getSharedPreferences("FileName",0);
editor=sharedPreferences.edit();
editor.putString("KEY","Value");
editor.putBoolean("KEY",true);
editor.apply();
Let say I have two Activities, Activity A and Activity B.
Activity A displays a list of images using the Adapter Z.
When user clicks on any image in Activity A, they will be taken to Activity B to show the full image. I'm passing image path and grid position to Activity using Intent.
Now in Activity B, I place a delete button which should delete the imagepath from the gridview adapter.
Problem is:
How can I access the Activity A adapter in activity B to call remove(position) method in my adapter.
So I can call notifyDataSetChanged in onResume of Activity A to update the gridview images.
Activity A
MyGridView = (GridView) findViewById(R.id.gridview);
adapter = new MyAdapter(this);
MyGridView .setAdapter(adapter );
Intent fullImageActivity = new Intent(getApplicationContext(), ActivityB.class);
fullImageActivity.putExtra("position", position);
fullImageActivity.putExtra("path", mediaPath);
startActivity(fullImageActivity);
Activity B
Intent i = getIntent();
// I'm getting position and path from setOnItemClickListener
position = i.getExtras().getInt("position");
path = i.getExtras().getString("path");
// I want to remove path from my adapter after clicking delete button in Activity B
Adapter
public ArrayList<String> images;
public void remove(int position){
images.remove(position);
}
use startActivityForResult.
Intent fullImageActivity = new Intent(getApplicationContext(), ActivityB.class);
fullImageActivity.putExtra("position", position);
fullImageActivity.putExtra("path", mediaPath);
startActivityForResult(fullImageActivity, 2);
check if deleted at particular position in Activity B . here I override onBackPressed() (For Ex.) method
public void onBackPressed(){
super.onBackPressed()
Intent intent=new Intent();
intent.putExtra("isdeleted",true);
intent.putExtra("pos",position);
setResult(2,intent);
finish();
}
Handle it in onActivityResult in Activity A.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
if(data.getBooleanExtra("isdeleted")){
remove from position array and notify dataset change. // pos = data.getIntExtra("pos")
}
}
}
Sorry for TYPO.
The key here is that you need to share the data and not really the adapter.
Using a singleton
You can use a singleton class to hold the image data and then access the same in both the activities. This ensures sync between both activities at all times.
Singleton Class
public class ImageData{
private ArrayList<ImageModel> mDataOfImages;
private ImageData mHelperInstance;
private ImageData(){
//private constructor to ensure singleton
}
public static ImageData getInstance(){
// return an ImageData instance according to your implementation
// of singleton pattern
}
private void setData(ArrayList<ImageModel> newData){
this.mDataOfImages = newData;
}
private void removeImage(int position){
if(this.mDataOfImages !=null && this.mDataOfImages.size() > position){
mDataOfImages.remove(position);
}
}
}
Activity A
private void saveImageData(ArrayList<ImageModel> data){
if(data !=null){
if(mAdapter !=null){
mAdapter.setData(data);
}
}
}
//Call notifydatasetchanged when activity is opened again
#Override
protected void onStart() {
if(mAdapter !=null){
mAdapter.notifyDataSetChanged();
}
}
MyAdapter
public void setData(ArrayList<ImageMode> newData){
if(newData !=null){
ImageDataSingleton.getInstance().setData(newData);
notifyDataSetChanged();
}
}
Activity B
Use the singleton class to display images in Activity B. Because you are using the model array list, you can easily implement right/left swipes and delete multiple images.
//Delete a image
private void deleteImage(){
ImageDataSingleton.getInstance().removeImage(getCurrentPosition());
// Rest of deletion handling like moving to right or left image
}
I think that you should build your remove method in activity A and be sure that it is static:
public static void remove(int position){
images.remove(position);
}
now you can call it from activity B like this:
ActivityA.remove(position);
I think this will work.
I've tried to make it by onResume but it didn't work, also I tried to make it by startActivityForResult and still nothing. I want to make it as simple as it can be. Should I do something else in my OnResume? All answers, suggestions, clues are wellcome. If you don't know how to do it, pop up thread. Thank you for your time.
In my Adapter i've got class:
class ViewHolder {
TextView tvNazwaT;
TextView tvCenaT;
ImageView ivTowar;
CheckBox chb_czy_zamowic;
}
There is my checkbox which I want to change after on button click(click cause returning to main activity where checkbox is just displayed in my gridview).
All logic form Adapter (actually in getView method) for checkbox is here:
view.chb_czy_zamowic
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(
final CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (buttonView.isChecked()) {
display dialog; }
Here is return button from NextActivity:
Intent returnIntent = new Intent();
setResult(RESULT_OK, returnIntent);
finish();
In my MainActivity i've tryied something in onResume method but I cant get acces to it in any known way.
protected void onResume() {
super.onResume();
MainActivity.lista_wybranych_towarow.clear();
if (MainActivity.lista_wybranych_towarow.isEmpty()) {
b_zatwierdz.setVisibility(View.INVISIBLE);
}
So I tried this in my Adapter:
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Intent intent =
new Intent(getContext(), Zatwierdz.class);
context.startActivityForResult(intent,1);
}
});
In my MainActivity:
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data) {
switch (requestCode) {
case 1:
CheckBox cb = (CheckBox) findViewById(R.id.chb_czy_zamowic);
cb.setChecked(false);
break;
}
}
It also didn't work out.
Here is my all code:
**MainActivity:** http://pastebin.com/DUz6GWbw
**Adapter:** http://pastebin.com/jHWqBaf0
**DefaultActivity:** http://pastebin.com/1VgEAZhZ
I am guessing you have some underlaying data under your grid adapter. When you leave activity, remember checked position in some variable in activity scope, or simply mark it as checked in your data structure. When you came back from another activity, undo that change and call notifyDataSetChanged() on your adapter.
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,