I am using Tab Layout. I am showing data in ListView inside ListFragment. Data is showing in ListView but problem is when we press tabb again, same data will add in Listview. So every time continue same data add in listView.
Code here-
public class HomeFragments extends ListFragment {
int[] ust_icon = {R.drawable.title,R.drawable.t2,R.drawable.t2};
String[] live_on = {"NA","NA","NA"};
String[] total_subtopics = {"3","3","3"};
String[] title = {"semiconductor devices ##","Equations of state ##","pn junction ##"};
String[] pos = {"1","5","6"};
String[] completed_subtopics = {"3","3","3"};
String[] live = {"false","false","false"};
String[] id = {"13","14","15"};
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
SimpleAdapter adapter;
public HomeFragments() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home_fragments, container, false);
HashMap<String, String> map = new HashMap<String, String>();
for (int i=0;i<3;i++)
{
map = new HashMap<String, String>();
map.put("ust_icon", Integer.toString(ust_icon[i]));
map.put("live_on",live_on[i]);
map.put("total_subtopics",total_subtopics[i]);
map.put("title",title[i]);
map.put("pos",pos[i]);
map.put("completed_subtopics",completed_subtopics[i]);
map.put("live",live[i]);
map.put("id",id[i]);
data.add(map);
}
String[] from = {"ust_icon","live_on","total_subtopics","title","pos","completed_subtopics","live","id"};
int[] to = {R.id.img1,R.id.txt1,R.id.txt2,R.id.txt3,R.id.txt4,R.id.txt5,R.id.txt6,R.id.txt7};
adapter = new SimpleAdapter(getActivity(),data, R.layout.list1, from, to);
setListAdapter(adapter);
return view;
}
#Override
public void onStart() {
super.onStart();
}
}
how to resolve this issue Please help....
I think I have your answer. Just wait for me a couple minute when I got home and then I’ll answer you ok?
Edit:
Try to construct your data and set your adapter in onActivityCreated()
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home_fragments, container, false);
return view;
}
and
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
HashMap<String, String> map = new HashMap<String, String>();
for (int i=0;i<3;i++)
{
map = new HashMap<String, String>();
map.put("ust_icon", Integer.toString(ust_icon[i]));
map.put("live_on",live_on[i]);
map.put("total_subtopics",total_subtopics[i]);
map.put("title",title[i]);
map.put("pos",pos[i]);
map.put("completed_subtopics",completed_subtopics[i]);
map.put("live",live[i]);
map.put("id",id[i]);
data.add(map);
}
String[] from = {"ust_icon","live_on","total_subtopics","title","pos","completed_subtopics","live","id"};
int[] to = {R.id.img1,R.id.txt1,R.id.txt2,R.id.txt3,R.id.txt4,R.id.txt5,R.id.txt6,R.id.txt7};
adapter = new SimpleAdapter(getActivity(),data, R.layout.list1, from, to);
setListAdapter(adapter);
}
if the code above not working, try to replace this:
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
by this: ArrayList<HashMap<String,String>> data;
and then in your onCreateView : data = new ArrayList<HashMap<String, String>>();
Try adding condition to your code like i did below.i just created boolean variable called check.if tab opens first time it will set listview as well as set it's value to true.now condition wont run and you will not get listview element add again and again
public class HomeFragments extends ListFragment {
int[] ust_icon = {R.drawable.title,R.drawable.t2,R.drawable.t2};
String[] live_on = {"NA","NA","NA"};
String[] total_subtopics = {"3","3","3"};
String[] title = {"semiconductor devices ##","Equations of state ##","pnjunction ##"};
String[] pos = {"1","5","6"};
String[] completed_subtopics = {"3","3","3"};
String[] live = {"false","false","false"};
String[] id = {"13","14","15"};
public static final boolean check = false;
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
SimpleAdapter adapter;
public HomeFragments() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home_fragments, container, false);
HashMap<String, String> map = new HashMap<String, String>();
for (int i=0;i<3;i++)
{
map = new HashMap<String, String>();
map.put("ust_icon", Integer.toString(ust_icon[i]));
map.put("live_on",live_on[i]);
map.put("total_subtopics",total_subtopics[i]);
map.put("title",title[i]);
map.put("pos",pos[i]);
map.put("completed_subtopics",completed_subtopics[i]);
map.put("live",live[i]);
map.put("id",id[i]);
data.add(map);
}
if(check == false)
{
String[] from = {"ust_icon","live_on","total_subtopics","title","pos","completed_subtopics","live","id"};
int[] to = {R.id.img1,R.id.txt1,R.id.txt2,R.id.txt3,R.id.txt4,R.id.txt5,R.id.txt6,R.id.txt7};
adapter = new SimpleAdapter(getActivity(),data, R.layout.list1, from, to);
setListAdapter(adapter);
check = true;
}
return view;
}
#Override
public void onStart() {
super.onStart();
}
Related
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);
}
}
I have an ArrayList of my custom model class which I am instantiating by URL of images taken from Internet in my Home_Fragment using an AsyncTask
The first time the List is created it has 12 items/URL's from the website.
Now, I am passing these on a FullscreenView Activity that is linked to my ViewPager Adapter
-> I have set an onLoadMoreListener in my Home_Fragment that adds more items to the ArrayList, now I want to add those to my ViewPager Adapter dynamically,
How can I accomplish this?
Home_Fragment
class ReadHTML extends AsyncTask<String, Integer, String> {
List list;
#Override
protected String doInBackground(String... params) {
try {
Document document = Jsoup.connect(params[0]).get();
Element wall = document.select("ul.postul").first();
//Log.i("LIST ", wall.toString());
Elements url = wall.getElementsByAttribute("src");
list = url.eachAttr("src");
for (int i = 0; i < list.size(); i++) {
wallpaperNumber++;
String string = //Dummy
String septemp[] = //Dummy2
sep[1] = "http://" + string
wallpapersModelArrayList.add(new WallpapersModel(
string,///
sep[1],
"jpg",
wallpaperNumber
));
}
}catch (Exception e){}
return null;
}
Fullscreen Activity
setContentView(R.layout.fullscreen_activity_view);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = findViewById(R.id.view_pager);
arrayList = getIntent().getParcelableArrayListExtra("array");
final int pos = getIntent().getIntExtra("position", 0);
fullScreenSwipeAdapter = new
FullScreenSwipeAdapter(FullWallpaperViewActivity.this, arrayList);
viewPager.setAdapter(fullScreenSwipeAdapter);
viewPager.setCurrentItem(pos);
viewPager.setOnTouchListener(new View.OnTouchListener(){}
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {}
ViewPager Adapter
public FullScreenSwipeAdapter(Activity activity, ArrayList<WallpapersModel> arrayList) {
this.activity = activity;
this.arrayList = arrayList;
Fresco.initialize(activity);
}
#Override
public int getCount() {
return this.arrayList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == (object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(R.layout.fullwallpaper_view_layout, container, false);
draweeView = v.findViewById(R.id.full_image_view);
draweeView.setImageURI(arrayList.get(position).getWallpaperFullURL());
container.addView(v);
return v;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((CoordinatorLayout)object);
}
First make a new instance of your ArrayAdapter and set all the new items like this:
public class Activity() extends AppCompatActivity {
CustomArrayAdapter mArrayAdapter;
ViewPager mViewPager;
public void updateViewpager(){
mArrayAdapter = new ArrayAdapter(context, itemList); // old items with new items
mViewPager.setAdapter(mArrayAdapter);
mArrayAdapter.notifyDataSetChanged();
}
...
Hope it helps,
After adding new items to ArrayList, just notify your adapter of the changes using -
arrayAdapter.notifyDataSetChanged();
This is my adapter class:
public class MyAdapter extends ArrayAdapter {
private Context context;
private LayoutInflater inflater;
private List<HashMap<String, String>> aList=new ArrayList<HashMap<String,String>>();
int[] to;
public MyAdapter(Context context, List<HashMap<String, String>> aList) {
super(context, R.layout.layoutarray, aList);
this.context = context;
this.aList = aList;
inflater = LayoutInflater.from(context);
}
HashMap<String, String> m;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (null == convertView) {
convertView = inflater.inflate(R.layout.layoutarray, parent, false);
}
TextView title1=(TextView)convertView.findViewById(R.id.posttitle);
TextView description1=(TextView)convertView.findViewById(R.id.postdesc);
//TextView image1=(ImageView)rootView.findViewById(R.id.postimage);
TextView date=(TextView)convertView.findViewById(R.id.postdate);
ImageView image1=(ImageView)convertView.findViewById(R.id.postimage);
title1.setText(aList.get(aList.get(0).get("Title")));
// Picasso.with(context).load(m.get("Image")).into(image1);
return convertView;
}
}
This is my Activity:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
TextView textView = new TextView(getActivity());
final View rootView = inflater.inflate(R.layout.aa, container, false);
Firebase.setAndroidContext(getActivity());
Firebase ref = new Firebase(FIREBASE_URL);
final List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
final ListView listView = (ListView) rootView.findViewById(R.id.listView);
final MyAdapter adapter = new MyAdapter(getActivity(),aList);
listView.setAdapter(adapter);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
for (DataSnapshot single : child.getChildren()) {
Map<String, Object> map = (Map<String, Object>) single.getValue();
namerc = (String) map.get("Namerc");
image = (String) map.get("Imagerc");
description = (String) map.get("Description");
title=(String) map.get("Title");
if (namerc!=null && description!=null && title!=null) {
String[] title1={title};
String[] desc1={description};
String[] name1={namerc};
String[] image1={image};
Toast.makeText(getActivity(), description, Toast.LENGTH_SHORT).show();
HashMap<String,String>data=new HashMap<String, String>();
for (int i=0; i<title1.length;i++) {
data.put("Title", title1[i]);
data.put("Desc",desc1[i]);
data.put("Name",name1[i]);
data.put("Image",image1[i]);
}
aList.add(0,data);
adapter.notifyDataSetChanged();
}
}
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
return rootView;
}
}
I want to set the values from my List to text view (which is a listiview).
but when i set it it is showing only first data in the listview. i am not understanding what is going wrong ,how to fetch all the data from List and set it to listview.
please help me to solve this..
I guess you are getting the same value each time. Get value for the right position in your adapter. Something like this:
title1.setText(aList.get(position).get("Title"));
I recently started working on an Android project and given my lack of understanding of UI programming, I find myself in a fix, when I try to dynamically add a entry to the UI.
I am working on a chat-application in which when a new message is received, it should be added at the bottom. For that I need to notify that the data-set has changed. When I was directly calling data-set has changed, I was getting an error. So I used a local broadcast reciever on the adapter.
Unfortunately, I don't know how to pass the ArrayList which contains a HashMap. I will post the code of the adapter and where I am trying to notify where data has changed. I hope someone can help me out. THanks a lot.. :-)
Code :
public static void recieveUpdatedMessage(String channelName, Map<String, Object> input){
//The input here contains message from our PUSH system
Intent intent = new Intent();
HashMap<String, String> insertMap = new HashMap<>();
insertMap.put(chatText, String.valueOf(input.get("text")));
insertMap.put(firstName,String.valueOf("firstname"));
insertMap.put(groupChannel, "/service/chat" + String.valueOf(groupAccountId));
ArrayList<HashMap<String, String>> chatMessagesHashMapList = new ArrayList<HashMap<String, String>>();
chatMessagesHashMapList.add(insertMap);
// Below is where I am trying to send data.
// intent.putExtra(chatMessagesHashMapList);//send any data to your adapter
intent.setAction("myaction");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
The adapter code, it's in same java file :
public class ChatMessagesAdapter extends BaseAdapter {
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent)
{
if(intent.getAction().equals("MYREFRESH"))
{
notifyDataSetChanged();
}
}
};
private Activity activity = null;
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater = null;
public ChatMessagesAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("MYREFRESH");
LocalBroadcastManager.getInstance(context).registerReceiver(broadcastReceiver, intentFilter);
activity = a;
data = d;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.chat_messages_row, parent, false);
TextView chatText = (TextView) vi.findViewById(R.id.chatText);
ImageView userImage = (ImageView) vi.findViewById(R.id.chatImage);
TextView firstName = (TextView) vi.findViewById(R.id.personName);
HashMap<String, String> chatList = new HashMap<>();
chatList = data.get(position);
chatText.setText(chatList.get(ChatMessagesActivity.chatText));
userImage.setImageBitmap(convertByteArrayToBitmap(chatList.get(ChatMessagesActivity.chatImage)));
firstName.setText(chatList.get(ChatMessagesActivity.firstName));
return vi;
}
}
I hope I was clear. If there is anything missing, kindly let me know. How can I tell the activity that there is a new message and put it at the bottom.
You really should not use a BroadcastReceiver that way. Try adding an add method to the Adapter to make it easier to add an item and automatically notify a change.
public void add(HashMap<String, String> item) {
data.add(item);
notifyDataSetChanged();
}
Then in the recieveUpdatedMessage method you can do something similar to the following.
public void recieveUpdatedMessage(String channelName, Map<String, Object> input) {
HashMap<String, String> insertMap = new HashMap<>();
insertMap.put(chatText, input.get("text").toString());
insertMap.put(firstName, input.get("firstname").toString());
insertMap.put(groupChannel, "/service/chat" + input.get("groupaccountid").toString());
myAdapter.add(insertMap);
}
A few notes for improvement
Instead of using a HashMap it would be better to create a class to hold the data for you.
Since your BaseAdapter is already using a List you could extend an ArrayAdapter instead since that already has an add method that also calls notifyDataSetChanged() by default.
You can pass latest data in your case you are creating data with HashMap directly into intent using bundle. & retrive it from the onReceive method of BroadCastReceiver
How to Pass data check your updated method recieveUpdatedMessage below
recieveUpdatedMessage
public static void recieveUpdatedMessage(String channelName, Map<String, Object> input) {
//The input here contains message from our PUSH system
Intent intent = new Intent();
HashMap<String, String> insertMap = new HashMap<>();
insertMap.put(chatText, String.valueOf(input.get("text")));
insertMap.put(firstName, String.valueOf("firstname"));
insertMap.put(groupChannel, "/service/chat" + String.valueOf(groupAccountId));
ArrayList<HashMap<String, String>> chatMessagesHashMapList = new ArrayList<HashMap<String, String>>();
// Added your map into Bundler as a Serializable
Bundle bundle = new Bundle();
bundle.putSerializable("chatMapKey", insertMap);
// after adding map into bundle . bundle is added into Intent
intent.putExtras(bundle);
// Below is where I am trying to send data.
// intent.putExtra(chatMessagesHashMapList);//send any data to your adapter
intent.setAction("MYREFRESH");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
How to retrive data from bundle & update it in listview check your ChatMessagesAdapter updated code.
ChatMessagesAdapter
public class ChatMessagesAdapter extends BaseAdapter {
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("MYREFRESH")) {
Bundle bundle = intent.getExtras();
// Get the bundle from intent
if (bundle!=null && bundle.containsKey("chatMapKey")) {
// get the Serializable object which is pass as a broadcast from the Bundle
refreshChat((HashMap<String, String>) bundle.getSerializable("chatMapKey"));
}
}
}
};
private Activity activity = null;
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater = null;
private int size = 0;
public ChatMessagesAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("MYREFRESH");
LocalBroadcastManager.getInstance(context).registerReceiver(broadcastReceiver, intentFilter);
activity = a;
data = d;
if (data != null)
size = data.size();
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void refreshChat(HashMap<String, String> newChatMap) {
if (data == null) {// Added Condition for safe side you can remove it
data = new ArrayList<HashMap<String, String>>();
}
data.add(newChatMap);
size = data.size();
notifyDataSetChanged();
}
#Override
public int getCount() {
return size;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.chat_messages_row, parent, false);
TextView chatText = (TextView) vi.findViewById(R.id.chatText);
ImageView userImage = (ImageView) vi.findViewById(R.id.chatImage);
TextView firstName = (TextView) vi.findViewById(R.id.personName);
HashMap<String, String> chatList = new HashMap<>();
chatList = data.get(position);
chatText.setText(chatList.get(ChatMessagesActivity.chatText));
userImage.setImageBitmap(convertByteArrayToBitmap(chatList.get(ChatMessagesActivity.chatImage)));
firstName.setText(chatList.get(ChatMessagesActivity.firstName));
return vi;
}
}
Suggestions
Avoid using Broadcast reciver like you have used. Register it in
Activity onReusme/onStart & Unregister it in its onPause/onStop
method check this The visible lifetime
Try to maintain data with database like at the time of message
receive insert it in database & at the time of refreshing data get
the data from database
I am messing around creating a "slide in"(facebook style) menu for Android, this menu will be rendered as a clickable ListView using onItemClickListener. However, when i use a custom adapter for the listview it shows nothing.
The activity which runs it is my "Root activity" which means all other activities extends it. If i place the same code in another activity it can render the listview using this adapter just fine. Also, .setOnItemClickListener seems to do nothing in the root activity. Something does not get setup like it should when this view is created, any ideas? This is the code:
public class RootActivity extends Activity {
public static final String KEY_TITLE = "title";
public static final String KEY_ID = "id";
ActionBar actionBar;
ListView slideMenu;
ListMenuAdapter adapter;
ArrayList<HashMap<String, String>> menuOptions;
private String[] menuItems={"Budget","Charts","By category"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rootview);
menuOptions = new ArrayList<HashMap<String, String>>();
slideMenu = (ListView) findViewById(R.id.slideMenuList);
slideMenu.setSaveEnabled(false);
HashMap<String, String> map;
for(int i = 0 ; i<menuItems.length ; i++ ) {
map = new HashMap<String, String>();
map.put(KEY_TITLE, menuItems[i]);
map.put(KEY_ID, ""+i);
menuOptions.add(map);
}
adapter = new ListMenuAdapter(this, menuOptions);
slideMenu.setAdapter(adapter);
Log.println(9, "slidemendeb2", ""+slideMenu.getAdapter().getCount());
slideMenu.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Log.println(9, "Testitemclick", ""+arg0);
}
});
}}
A sample of another activity which exends RootActivity:
public class SpentMain extends RootActivity {
public static final String KEY_TITLE = "title";
public static final String KEY_ID = "id";
ArrayList<Tag> tags;
ArrayList<Integer> tagInts = new ArrayList<Integer>();
TagDataSource tagDataSource;
Button costButton;
EditText sum;
Boolean removed = false;
ActionBar actionBar;
CheckBox checkBox;
ListView list;
ListCheckboxAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rootview);
costButton = (Button) findViewById(R.id.costadd);
sum = (EditText) findViewById(R.id.editText1);
ArrayList<HashMap<String, String>> tagsList = new ArrayList<HashMap<String, String>>();
tagDataSource = new TagDataSource(this);
tagDataSource.open();
tags = tagDataSource.getAllTags();
tagDataSource.close();
HashMap<String, String> map;
for(int i = 0 ; tags.size()>i ; i++ ) {
map = new HashMap<String, String>();
map.put(KEY_TITLE, tags.get(i).getTitle().toString());
map.put(KEY_ID, tags.get(i).getId().toString());
tagsList.add(map);
}
list=(ListView)findViewById(R.id.list);
adapter = new ListCheckboxAdapter(this, tagsList);
list.setAdapter(adapter);
// Row click event
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
for(int i = 0; tagInts.size()>i; i++) {
if(tagInts.get(i)==position) {
tagInts.remove(i);
removed = true;
}
}
if(removed==false) {
tagInts.add(position+1);
}
removed = false;
for(int i=0; i<((ViewGroup)view).getChildCount(); ++i) {
View nextChild = ((ViewGroup)view).getChildAt(i);
if(nextChild.getClass()==android.widget.CheckBox.class) {
checkBox = (CheckBox) nextChild;
if(checkBox.isChecked()==true) {
checkBox.setChecked(false);
} else {
checkBox.setChecked(true);
}
}
}
}
});}
As i said, if i use this adapter to render it within SpentMain it works fine but not within RootActivity. Any help is greatly appreciated.
Ok so i managed to fix the problem, what i did was to move the code out of onCreate in RootActivity and into its on method "buildSideMenu()". I then call that method in my SpentMain.class onCreate method like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rootview);
super.buildSideMenu();
}
I noticed that if i call super.buildSideMenu() before setContentView(R.layout.rootview) it will not work. So the problem was that since super.onCreate was being run before setContentView some things had probably not been set up properly at the time my menu was being built. Hope this can help someone else!