So, here's my project structure. It's just a two tab app.
On the left tab, there's a list of all the available items. On the right tab, there's a list of the user favorite items. In each item there's a button where you click and then that item becomes a favorite. Well, at least that's what I want to achieve. Apparently the items get added to the favorites list, but at the moment the only way to see the new favorites list is closing and reopening the app.
What I need is some way to call the adapter.notifyDataSetChanged() when the item is added as favorite.
Right now, this favorite functionality is done as a method from the Holder I'm using. So, basically the user clicks the fav button on the item, and then the Holder has a clickListener which updates an Array that I store as a JSON in the SharedPreferences, which contains all the favorites items.
Those two tabs are Fragments, and each Fragment has a RecyclerView. They both use the same class:
public class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private PageViewModel pageViewModel;
private int section;
private RecyclerView recyclerView;
private SharedPreferences prefs = null;
public static PlaceholderFragment newInstance(int index) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle bundle = new Bundle();
bundle.putInt(ARG_SECTION_NUMBER, index);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageViewModel = ViewModelProviders.of(this).get(PageViewModel.class);
int index = 1;
if (getArguments() != null) {
index = getArguments().getInt(ARG_SECTION_NUMBER);
}
section = index;
pageViewModel.setIndex(index);
prefs = getContext().getSharedPreferences("app_preferences", MODE_PRIVATE);
}
#Override
public View onCreateView(
#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView = rootView.findViewById(R.id.items_list);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), linearLayoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setLayoutManager(linearLayoutManager);
List<ItemModel> itemList= new ArrayList<>();
// All Items Tab
if (section == 1) {
// Here I get all the Items and set them in the itemList Array
else { // Favorite Items Tab (it retrieves an array of items stored in the SharedPreferences)
Gson gson = new Gson();
String json = prefs.getString("favoriteList", "");
if (json.isEmpty()) {
} else {
Type type = new TypeToken<List<ItemModel>>() {
}.getType();
itemList= gson.fromJson(json, type);
}
}
MyItemAdapter itemAdapter = new MyItemAdapter (getContext(), getActivity(), itemList, section);
recyclerView.setAdapter(itemAdapter);
return rootView;
}
You could use MutableLiveData to observe your list, you can then call adapter.notifyDataSetChanged() inside the observe block.
So, for example,
public class PlaceholderFragment extends Fragment {
private MutableLiveData<List<ItemModel>> mMutableLiveData;
#Override
public View onCreateView(
#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mMutableLiveData = new MutableLiveData<>();
mMutableLiveData.observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
rootView.findViewById(R.id.items_list).getAdapter().notifyDataSetChanged();
}
});
List<ItemModel> itemList= new ArrayList<>();
// All Items Tab
if (section == 1) {
// Here I get all the Items and set them in the itemList Array
else { // Favorite Items Tab (it retrieves an array of items stored in the SharedPreferences)
Gson gson = new Gson();
String json = prefs.getString("favoriteList", "");
if (json.isEmpty()) {
} else {
Type type = new TypeToken<List<ItemModel>>() {
}.getType();
itemList= gson.fromJson(json, type);
mMutableLiveData.setValue(itemList);
}
}
MyItemAdapter itemAdapter = new MyItemAdapter (getContext(), getActivity(), itemList, section);
recyclerView.setAdapter(itemAdapter);
return rootView;
}
}
As you're already using SharedPreferences to save your favorites list, you can register a listener on it to get updates whenever it gets updated and then you can retrieve those changes from SharedPreferences and then update your list.
In your Fragment's onCreateView() method where you check this condition:
// All Items Tab
if (section == 1) {
// Here I get all the Items and set them in the itemList Array
else { // Favorite Items Tab (it retrieves an array of items stored in the SharedPreferences)
pref.unregisterOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener(){
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key){
// here you can retrieve updated data from SharedPreferences and update your list
}
});
Gson gson = new Gson();
String json = prefs.getString("favoriteList", "");
if (json.isEmpty()) {
} else {
Type type = new TypeToken<List<ItemModel>>() {
}.getType();
itemList= gson.fromJson(json, type);
}
}
Related
I made adapter for ListView. If I fill the elements array before creating the adapter and linking it to the listView, the elements are displayed.
But if I use the updateItems () method to add items when the button is clicked, nothing happens.
Code of adapter:
public class ListAdapter extends ArrayAdapter<Lf> {
private LayoutInflater inflater;
private int layout;
private List<Lf> lfs;
public ListAdapter(Context context, int resource, List<Lf> lfs) {
super(context, resource, lfs);
this.lfs = lfs;
this.layout = resource;
this.inflater = LayoutInflater.from(context);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView==null){
convertView = inflater.inflate(this.layout, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder) convertView.getTag();
}
Lf lf = lfs.get(position);
viewHolder.name.setText(lf.getLf());
viewHolder.freq.setText((int)lf.getFreq() + "");
return convertView;
}
public void updateItems(List<Lf> lfs) {
this.lfs.clear();
this.lfs.addAll(lfs);
this.notifyDataSetChanged();
}
private class ViewHolder {
final TextView name, freq;
ViewHolder(View view){
name = (TextView) view.findViewById(R.id.text_item_1);
freq = (TextView) view.findViewById(R.id.text_item_2);
}
}
}
Code of MainActivity:
public class MainActivity extends AppCompatActivity {
EditText editText1;
ListView listView;
ListAdapter adapter;
List<Lf> elements = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = (EditText) findViewById(R.id.edit_text);
listView = (ListView) findViewById(R.id.fragment_list);
// Working... Elements print on screen
for(int i = 0; i < 10; i++) {
Lf temp = new Lf();
temp.setLf("mean");
temp.setFreq(100);
elements.add(temp);
}
adapter = new ListAdapter(this, R.layout.list_item, elements);
listView.setAdapter(adapter);
}
public void activity_button(View view) {
adapter.updateItems(elements);
}
}
If I click on the button, the existing items on the screen are cleared instead of a new one added. But in debug I see that elements normally passed to ListAdapter.
The problem is that your adapter's lfs's field and your activity's elements field both refer to the same List instance. This happens because you pass elements to the ListAdapter constructor, and then simply assign this.lfs = lfs.
So let's look at what happens when you pass elements to updateItems()...
public void updateItems(List<Lf> lfs) {
this.lfs.clear(); // this.lfs and the input lfs are the same list, so this clears both
this.lfs.addAll(lfs); // input lfs is now empty, so addAll() does nothing
this.notifyDataSetChanged();
}
Probably the best thing to do is to create a copy of the list in your adapter's constructor.
this.lfs = new ArrayList<>(lfs);
Now your adapter and activity will reference different lists, so this.lfs.clear() won't accidentally clear out the very list you're passing to it.
I'm having this issue with my android custom listview such that everytime i exit the activity (i.e. click the "back" button on emulator), then return back to the same activity that contains this custom listview, the listview adds an additional row to itself.
For example, originally it is:
item a
When I leave that activity and come back to it, the row doubles:
item a
item a
However, when i restart the emulator again, the custom listview goes back to the original number of data retrieved from sqlite.
How do I stop the rows from doubling themselves?
Here are my codes.
list.java:
//DATABASE
MyItems mi;
//For Items display - ArrayList
private ArrayList<SalesItemInformationLV> displayiteminfo;
/* new ArrayList<SalesItemInformationLV>(); */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_sale_item);
final float sellingpvalue = 13.5f;
final float costpvalue = 19.0f;
final String datesoldvalue = "9/9/1995";
final String staffdiscountvalue = "true";
mi = MyItems.getInstance();
displayiteminfo = mi.retrieveAllForlist(getApplicationContext());
//New array adapter for customised ArrayAdapter
final ArrayAdapter<SalesItemInformationLV> adapter = new itemArrayAdapter(this, 0, displayiteminfo);
//displayiteminfo - the ArrayList of item objects to display.
//Find the list view, bind it with custom adapter
final ListView listView = (ListView)findViewById(R.id.customListview);
listView.setAdapter(adapter);
// listView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 9));
//LONG PRESS CONTEXT MENU
registerForContextMenu(listView);
//Selecting the listview item!
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SalesItemInformationLV saleitem = displayiteminfo.get(position);
String namevalue = saleitem.getItemname();
int qtyvalue = saleitem.getItemquantity();
Intent myintent = new Intent(ListSaleItemActivity.this, ViewSaleDetails.class);
myintent.putExtra("itemname", namevalue);
myintent.putExtra("itemqty", qtyvalue);
myintent.putExtra("itemcp", costpvalue);
myintent.putExtra("itemsp", sellingpvalue);
myintent.putExtra("itemds", datesoldvalue);
myintent.putExtra("itemsstaffdis", staffdiscountvalue);
startActivity(myintent);
}
});
}
//custom Arrayadapter
class itemArrayAdapter extends ArrayAdapter<SalesItemInformationLV>
{
private Context context;
private List<SalesItemInformationLV> item;
//constructor, call on creation
public itemArrayAdapter(Context context, int resource, ArrayList<SalesItemInformationLV> objects) {
//chaining to "default constructor" of ArrayAdapter manually
super(context, resource, objects);
this.context = context;
this.item = objects;
}
//called to render the list
public View getView(int position, View convertView, ViewGroup parent)
{
//get the item we are displaying
SalesItemInformationLV iteminfo = item.get(position);
//get the inflater and inflate the xml layout for each item
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.item_layout, null);
//Each component of the custom item_layout
TextView name = (TextView) view.findViewById(R.id.ItemNameSales);
TextView qty = (TextView)view.findViewById(R.id.ItemNameQty);
//set the name of item - access using an object!
name.setText(String.valueOf(iteminfo.getItemname()));
//set the quantity of item - access using an object!
qty.setText(String.valueOf(iteminfo.getItemquantity()));
return view;
//Now return to onCreate to use this cuztomized ArrayAdapter
}
}
Myitems.java:
public class MyItems extends Application {
//ID and contact information
private List<String> contactList;
private List<Integer> contactIdList;
private static MyItems ourInstance = new MyItems();
//Populate SaleItemInformationLV
private ArrayList<SalesItemInformationLV> displayiteminfo2 =
new ArrayList<SalesItemInformationLV>();
public MyItems()
{
contactList = new ArrayList<String>();
contactIdList = new ArrayList<Integer>();
}
public static MyItems getInstance(){
return ourInstance;
}
//RETRIEVE ALL ENTRIES
//LISTVIEW
public ArrayList<SalesItemInformationLV> retrieveAllForlist(Context c)
{
Cursor myCursor;
String mystring = "";
MyDbAdapter db = new MyDbAdapter(c);
db.open();
//contactIdList.clear();
//contactList.clear();
myCursor = db.retrieveAllEntriesCursor();
if (myCursor !=null && myCursor.getCount()>0)
{
myCursor.moveToFirst();
do {
displayiteminfo2.add(new SalesItemInformationLV(myCursor.getString(db.COLUMN_NAME_ID), db.COLUMN_QTYSOLD_ID));
} while (myCursor.moveToNext());
}
db.close();
return displayiteminfo2;
}
MyItems is a (java-)singleton. Each times that you call public ArrayList<SalesItemInformationLV> retrieveAllForlist(Context), you add objects in displayiteminfo2 et return this list.
If you call a second times retrieveAllForlist, you keep the same list with objects already in it and add more to it.
It's a bad pattern to return a private instance object in a function. Anything outside of your class can modify the list. Just create one for returning it.
public ArrayList<SalesItemInformationLV> retrieveAllForlist(Context c)
{
ArrayList<SalesItemInformationLV> items = new ArrayList<SalesItemInformationLV>();
Cursor myCursor;
String mystring = "";
MyDbAdapter db = new MyDbAdapter(c);
db.open();
//contactIdList.clear();
//contactList.clear();
myCursor = db.retrieveAllEntriesCursor();
if (myCursor != null && myCursor.getCount() > 0)
{
myCursor.moveToFirst();
do {
items.add(new SalesItemInformationLV(myCursor.getString(db.COLUMN_NAME_ID), db.COLUMN_QTYSOLD_ID));
} while (myCursor.moveToNext());
}
db.close();
return items;
}
It looks like MyItems is a singleton. Are you clearing the values before calling
mi.retrieveAllForlist(getApplicationContext())? If not, you may be doubling up the values when onCreate() is called after returning to the activity.
I want a user to input data through an editable text and I want to receive that data through a custom made listview, for that I am trying to use a custom adapter to add a textfield into my listview, through the tostring() method I have converted the data from the editable textview to a string and I am adding that string within my custom adapter to an Arraylist variable values and I’m trying to display that data through get(0) but either the Arraylist is not populating correctly or the data is not displaying properly because whenever I type something within my editable text and press the add button nothing happens, before this I added the string to an Array Adapter and the listview was populating normally, what am I doing wrong?
public class todoFragment extends ListFragment {
private EditText mToDoField;
private Button mAdd;
UsersAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setTitle(R.string.todo_title);
}
public class UsersAdapter extends ArrayAdapter<String> {
public Context context;
public ArrayList<String> values;
public UsersAdapter(Context context, ArrayList<String> values) {
super(context, 0, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = LayoutInflater.from(getContext()).inflate(R.layout.todo_list, parent, false);
TextView todoTextView = (TextView) convertView.findViewById(R.id.todo_TextView);
todoTextView.setText(values.get(0));
return convertView;
}
}
#TargetApi(9) // remember this for isEmpty()
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_todo, container, false);
ArrayList<String> todoList = new ArrayList<String>();
mAdapter = new UsersAdapter(getActivity(), todoList);
ListView listViewToDo = (ListView) v.findViewById (android.R.id.list);
listViewToDo.setAdapter(mAdapter);
mToDoField = (EditText) v.findViewById(R.id.todo_editText);
mAdd = (Button)v.findViewById(R.id.add_button);
mAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String toDo = mToDoField.getText().toString().trim();
if (toDo.isEmpty()){
return;
}
mAdapter.values.add(toDo);
mToDoField.setText("");
}
});
return v;
}
}
Firstly, you should not be doing
todoTextView.setText(values.get(0));
Because this will always return the first element of the values list. You should do
todoTextView.setText(values.get(position));
Secondly,
mAdapter.values.add(toDo);
is not really right. It will work, but its not the best practise. Try using something like
mAdapter.add(toDo);
or
values.add(toDo);
Now once you've added the data to the list, you need to notify the adapter that the data set has been changed. This is done by
mAdapter.notifyDataSetChanged();
When you manually update the data don't forget to call:
mAdapter.notifyDataSetChanged();
Instead of mAdapter.values.add(toDo); UsemAdapter.add(toDo);
Look at the Add Method Of ArrayAdpter Class, it Itself use notifyDataSetChanged() so need to write any extra line of code:
public void add(T object) {
synchronized (mLock) {
if (mOriginalValues != null) {
mOriginalValues.add(object);
} else {
mObjects.add(object);
}
}
if (mNotifyOnChange) notifyDataSetChanged();
}
I apologize if this is similar to other threads, but I have yet to find a good solution on how to update the ListView in my custom ArrayAdapter.
I'm extending FragmentActivity in order to create a custom Dialog popup for adding / updating new List entries (which works fine), but I can't seem to get the ListView in ServerActivityArrayAdapter to update after a change is made.
Obviously, adapter.notifyDataSetChanged(); in the ServersActivity class isn't enough, but I'm stumped as to how to get my ListView to update after the Save button is clicked in the ServerDialog popup. Any help would be greatly appreciated!
public class ServersActivity extends FragmentActivity {
private List<Server> server;
private ListView lv;
private ServerActivityArrayAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.server_list);
server = getServers();
lv = (ListView) findViewById(android.R.id.list);
adapter = new ServerActivityArrayAdapter(this, R.layout.server_list_item, server);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
showServerDialog(position);
}
});
}
...
private void showServerDialog(int position) {
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
ServerDialog serverDialog = new ServerDialog(position);
ServerDialog.newInstance();
serverDialog.show(fragmentManager, "server_dialog");
}
ServerDialog class for adding new List entries
public class ServerDialog extends DialogFragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.settings_fragment, container);
context = getActivity().getApplicationContext();
dbh = new DbHandler(context);
etName = (EditText) view.findViewById(R.id.etName);
etAddress = (EditText) view.findViewById(R.id.etAddress);
etPort = (EditText) view.findViewById(R.id.etPort);
swtchNumDoors = (Switch) view.findViewById(R.id.swtchNumDoors);
Button btnSave = (Button) view.findViewById(R.id.btnSave);
loadData();
String title = (!newServer) ? "Edit Server" : "Add A New Server " + ID;
getDialog().setTitle(title);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
server[ID] = String.valueOf(ID);
server[SERVER_NAME] = etName.getText().toString();
server[ADDRESS] = etAddress.getText().toString();
server[PORT] = etPort.getText().toString();
if (server[ADDRESS].isEmpty() || server[PORT].isEmpty()) {
Toast.makeText(context, "Invalid Entry", Toast.LENGTH_LONG).show();
} else {
saveData();
// TODO - notify ServersActivity of change
}
}
});
return view;
}
public class ServerActivityArrayAdapter extends ArrayAdapter<Server> {
private int layout;
private String[][] values;
private int defServer;
private static LayoutInflater inflater;
ServerActivityArrayAdapter class for displaying ListView
public ServerActivityArrayAdapter(Context context, int layout, List<Server> servers) {
super(context, layout, servers);
this.layout = layout;
int i = 0;
values = new String[servers.size()][5];
for (Server server : servers) {
values[i][0] = Integer.toString(server.id);
values[i][1] = server.name;
values[i][2] = server.address;
values[i][3] = Integer.toString(server.port);
values[i][4] = Integer.toString(server.num_doors);
defServer = (server.default_server) ? i : 0;
i++;
}
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private static class ViewHolder {
private TextView tvServerName;
private CheckBox cbDefault;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View v = convertView;
try {
if(v == null) {
v = inflater.inflate(layout, parent, false);
holder = new ViewHolder();
holder.tvServerName = (TextView) v.findViewById(R.id.tvServerName);
holder.cbDefault = (CheckBox) v.findViewById(R.id.cbDefault);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.tvServerName.setText(values[position][1]);
holder.cbDefault.setChecked(defServer==position);
} catch (Exception e){
System.out.println(e);
}
return v;
}
You could use an interface and have a method in it maybe named updateListView().
Implement this interface in your FragmentActivity. In the implemented method, add code to update the listView.
And in the button code of your dialog, call ((Interfacename) getActivity).updateListView()
Your problem is in the implementation of the adapter. You are instantiating the ArrayAdapter with a List<Server> object (The super call) but then creating your own two dimensional array values to contain the data. You use the values array for the getView() method yet make no mention or show through code how you actually modify that data to update the adapter.
You should be calling back into the adapter to update it. EG, calling add(), remove(), etc. You only mention updating the DB which has nothing to do with updating your adapter. It's not linked in anyway to the DB. Even if you were to call into the previously mentioned mutate methods on the adapter, they wouldn't work unless you specifically override them. The default ArrayAdapter implementation will modify the List<Server> data and not the values two-dim array you created.
But if you find yourself override those mutate methods to support your values two-dim array...there's no point in subclassing the ArrayAdapter. Part of the point of the ArrayAdapter is handling all the data management for you. In such a situation you should be instead subclassing BaseAdapter.
In one of my project I am using 2 fragments.One fragment is displaying a list of items.So I want when the topic will be selected in first fragment the details should be changed in another fragment.Data I am able to pass from one fragment to other but the view is not changing.In which method I should implement the view of second fragment so that it can change accordingly.
Please give me good tutorial or example for these.
Here I have to develop one android example, I have to run the app means displayed category name well on horizontal listview of my first fragment.I have to click any category means how can I pass the category name on 2nd fragment.Please give me solution for this problem.
I have used below code:
public class Home extends FragmentActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
1st fragment code:
public class MainActivity extends Fragment {
static final String URL = "http://dev2.mercuryminds.com/webservices/new_feed_articls.xml";
static String KEY_CATEGORY = "Categories";
static final String KEY_TITLE = "Category";
LazyAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main,
container, false);
final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_TITLE);
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String> ();
Element e = (Element) nl.item(i);
map.put( KEY_TITLE,((Element)nl.item(i)).getAttribute("name"));
// map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
songsList.add(map);
}
HorizontalListView list = (HorizontalListView) view.findViewById(R.id.listView1);
adapter = new LazyAdapter(getActivity(), songsList);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = songsList.get(position);
Intent in = new Intent();
in.setClass(getActivity(), SubCate.class);
// in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
startActivity(in);
}
});
return view;
}}
How can i display category name on 2nd Activity...pls give me code for these...
EDIT:
Hi i have changed code like on my first activity:
HashMap<String, String> map = songsList.get(position);
SubCate frag = (SubCate) getFragmentManager().findFragmentById(R.id.frag_2);
if (frag != null && frag.isInLayout()) {
frag.setText(getCapt(map));
}
}
private String getCapt(HashMap<String, String> map) {
if (map.containsValue("notchbolly")) {
return "dadad";
}
return "veeman";
on next activity:
public void setText(String item) {
TextView view = (TextView) getView().findViewById(R.id.cate);
view.setText(item);
}
its woked well while directly mention the name on if (map.containsValue("notchbolly")).but i have to display the name without mention name directly.if i have to click any category means that category name is displayed on next fragment.how can i do ?????
Using interface method we can transfer data between fragment to fragment
In fragmentA create interface and sent data to this interface and implement this interface method in fragmentB and get required data
the following code is useful for u
Code in FragmentA:
public class FragmentA extends Fragment {
// interface method
public InterfaceDataCommunicatorBetweenfragmentAToFragmentB iInterfaceDataCommunicatorBetweenfragmentAToFragmentB;
// Data to send
String mDataString;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// use this line where u send data
iInterfaceDataCommunicatorBetweenfragmentAToFragmentB.upDatedData(mDataString);
View view = inflater.inflate(R.layout.sent_box, container, false);
return view ;
}
/**
* Interface method to send data to fragmentB
*
*/
public interface InterfaceDataCommunicatorBetweenfragmentAToFragmentB {
public void upDatedData(String data);
}
}
Code in FragmentB:
class FragmentB extends Fragment implements InterfaceDataCommunicatorBetweenfragmentAToFragmentB {
// interface method
public InterfaceDataCommunicatorBetweenfragmentAToFragmentB iInterfaceDataCommunicatorBetweenfragmentAToFragmentB;
// fragmentA data
String mgetUpdatedData
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.get_box, container, false);
return view ;
}
/**
* Interface method coming from fragment a to fragmentB after implement interface in fragmentB
*/
public void upDatedData(String data) {
this.mgetUpdatedData = data;
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
try {
iInterfaceDataCommunicatorBetweenfragmentAToFragmentB = (InterfaceDataCommunicatorBetweenfragmentAToFragmentB ) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement interface");
}
}
You need to implement interface mechanism.
Refer following links for further details.
http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
http://developer.android.com/training/basics/fragments/communicating.html