I am trying to update listView from another fragment class after i delete an item from listView from current class. For example, i delete a consumer that has an expense, then the expense of that consumer will also be deleted.
But consumer and expense is different page that using tab control, which is fragment, when i delete consumer, the expense list is not updated, until i go to previous activity, then enter the page again. What can i do to update the expense list when consumer from consumer list is deleted? Thanks.
Here is the code for consumer/participant list :
public class Participant extends ListFragment implements OnClickListener{
Intent intent;
TextView friendId;
Button addparticipant;
String eventId;
ListView lv;
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
ArrayList<HashMap<String, String>> friendList = controller
.getAllFriends(queryValues);
if (friendList.size() != 0) {
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
friendId = (TextView) view.findViewById(R.id.friendId);
String valFriendId = friendId.getText().toString();
Intent objIndent = new Intent(getActivity(),
EventPage.class);
objIndent.putExtra("friendId", valFriendId);
startActivity(objIndent);
}
});
lv.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
friendId = (TextView) arg1.findViewById(R.id.friendId);
registerForContextMenu(getListView());
return false;
}
});
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
friendList, R.layout.view_friend_entry, new String[] {
"friendId", "friendName", "friendSpending" },
new int[] { R.id.friendId, R.id.friendName,
R.id.friendSpending });
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.participant, container, false);
addparticipant = (Button) rootView.findViewById(R.id.addpart);
addparticipant.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent objIntent = new Intent(getActivity(),
AddParticipant.class);
objIntent.putExtra("eventId", eventId);
startActivity(objIntent);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
String[] menuItems = getResources().getStringArray(R.array.menu);
for (int i = 0; i < menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
int menuItemIndex = item.getItemId();
EventController controller = new EventController(getActivity());
switch (menuItemIndex) {
case 0:
String valFriendId = friendId.getText().toString();
Intent objIndent = new Intent(getActivity(),
EditParticipant.class);
objIndent.putExtra("friendId", valFriendId);
startActivity(objIndent);
break;
case 1:
String valFriendId2 = friendId.getText().toString();
controller.deleteFriend(valFriendId2);
onResume();
}
return true;
}
#Override
public void onResume() {
super.onResume();
if (getListView() != null) {
updateData();
}
}
private void updateData() {
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
controller.getAllFriends(queryValues),
R.layout.view_friend_entry, new String[] { "friendId",
"friendName", "friendSpending" }, new int[] {
R.id.friendId, R.id.friendName, R.id.friendSpending });
setListAdapter(adapter);
}
}
Using Broadcasts:
Create this class in your list fragment:
public class UpdateReceiver extends BroadcastReceiver {
public static final String NEW_UPDATE_BROADCAST =
"your.package.NEW_UPDATE_BROADCAST";
#Override
public void onReceive(Context context, Intent intent) {
//Update the list
}
}
Declare this in the fragment:
private UpdateReceiver updateReceiver = null;
Use this to register the receiver (when you create the fragment):
IntentFilter filter = new IntentFilter(UpdateReceiver.NEW_UPDATE_BROADCAST);
filter.addCategory(Intent.CATEGORY_DEFAULT);
updateReceiver = new UpdateReceiver();
registerReceiver(updateReceiver, filter);
Use this to unregister(when you destroy the fragment):
if (updateReceiver != null){
unregisterReceiver(updateReceiver);
updateReceiver = null;
}
Then when you want to request the update you send the broadcast like this:
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(UpdateReceiver.NEW_UPDATE_BROADCAST);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
sendBroadcast(broadcastIntent);
You can even send data in the bradcast intent if you need and receive it in the onReceive method...
Related
I'm doing an app to help me at school. But, I have a problem: when I want the position (int position) of the listView, it ALWAYS returns the first position, even if I select the third position, for example.
public class TestsActivity extends ListActivity implements AdapterView.OnItemClickListener, DialogInterface.OnClickListener {
private List<Map<String, Object>> tests;
private AlertDialog dialogDelete;
private int selectedTest;
private Application dao;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tests_activity);
dao = new Application(this);
android.app.ActionBar actionBar = getActionBar();
actionBar.setTitle("My tests");
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
String[] from = {"subject", "content"};
int[] to = {R.id.subject, R.id.content};
SimpleAdapter adapter = new SimpleAdapter(this, listTests(), R.layout.test_list_activity, from, to);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
registerForContextMenu(getListView());
this.dialogDelete = createDialogDelete();
}
private List<Map<String, Object>> listTests() {
tests = new ArrayList<Map<String, Object>>();
List<Test> TestList = dao.listTests();
for (Test test : TestList) {
Map<String, Object> item = new HashMap<String, Object>();
Long id = test.getId();
String subject = test.getSubject();
item.put("id", test.getId());
item.put("subject", subject);
test.add(item);
}
return tests;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Map<String, Object> map = tests.get(position);
String subject = (String) map.get("subject");
String msg = "Test of" + subject;
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
selectedTest = position;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.tests_context_menu, menu);
}
public boolean onContextItemSelected(MenuItem item) {
Intent intent;
String id = String.valueOf(tests.get(selectedTest).get("id"));
switch (item.getItemId()) {
case R.id.remove:
dialogDelete.show();
break;
case R.id.edit:
intent = new Intent(this, NewTestActivity.class);
intent.putExtra(Constantes.TEST_ID, id);
startActivity(intent);
return true;
}
return super.onContextItemSelected(item);
}
#Override
public void onClick(DialogInterface dialog, int item) {
Intent intent;
String id = String.valueOf(tests.get(selectedTest).get("id"));
switch (item) {
case DialogInterface.BUTTON_POSITIVE:
tests.remove(selectedTest);
dao.removeTest(id);
getListView().invalidateViews();
break;
case DialogInterface.BUTTON_NEGATIVE:
dialogDelete.dismiss();
break;
}
}
private AlertDialog createDialogDelete() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.confirm_delete_test);
builder.setPositiveButton(getString(R.string.yes), (android.content.DialogInterface.OnClickListener) this);
builder.setNegativeButton(getString(R.string.no), (android.content.DialogInterface.OnClickListener) this);
return builder.create();
}
#Override
protected void onDestroy() {
dao.close();
super.onDestroy();
}
}
How can I solve it?
for (Test test : TestList) {
Map<String, Object> item = new HashMap<String, Object>();
Long id = test.getId();
String subject = prova.getSubject();
item.put("id", prova.getId());
item.put("subject", subject);
tests.add(item);
}
Try to change from
test.add(item);
to
tests.add(item);
Have you ever call listTests() in you Activity? What it this private method for?
You should call listTests() somewhere.
maybe u should use an custom BaseAdapter
it's help u clearly to create every ceil of listview
private class Simple extends BaseAdapter {
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup)
{
return view;
}
}
Based on your responses, here are my suggestions.
1) In listTests(), change from:
test.add(item);
TO:
tests.add(item);
The reason is object tests is the ArrayList containing the object test.
2) Since the code depends on the list dao from List<Test> TestList = dao.listTests(); I want to avoid the list items being unexpectedly removed. So
in protected void onDestroy(), remove:
dao.close();
I am trying to update listView from another fragment class after i delete an item from listView from current class. For example, i delete a consumer that has an expense, then the expense of that consumer will also be deleted. But consumer and expense is different page that using tab control, which is fragment, when i delete consumer, the expense list is not updated, until i go to previous page, then enter the page again. What can i do to update the expense list when consumer from consumer list is deleted? i heard of using broadcast receiver is able to do that, but how can i implement it in my code? I am new in android, please guide me.Thanks
Here is the code for consumer/participant list :
public class Participant extends ListFragment implements OnClickListener{
Intent intent;
TextView friendId;
Button addparticipant;
String eventId;
ListView lv;
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
ArrayList<HashMap<String, String>> friendList = controller
.getAllFriends(queryValues);
if (friendList.size() != 0) {
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
friendId = (TextView) view.findViewById(R.id.friendId);
String valFriendId = friendId.getText().toString();
Intent objIndent = new Intent(getActivity(),
EventPage.class);
objIndent.putExtra("friendId", valFriendId);
startActivity(objIndent);
}
});
lv.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
friendId = (TextView) arg1.findViewById(R.id.friendId);
registerForContextMenu(getListView());
return false;
}
});
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
friendList, R.layout.view_friend_entry, new String[] {
"friendId", "friendName", "friendSpending" },
new int[] { R.id.friendId, R.id.friendName,
R.id.friendSpending });
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.participant, container, false);
addparticipant = (Button) rootView.findViewById(R.id.addpart);
addparticipant.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent objIntent = new Intent(getActivity(),
AddParticipant.class);
objIntent.putExtra("eventId", eventId);
startActivity(objIntent);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
String[] menuItems = getResources().getStringArray(R.array.menu);
for (int i = 0; i < menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
int menuItemIndex = item.getItemId();
EventController controller = new EventController(getActivity());
switch (menuItemIndex) {
case 0:
String valFriendId = friendId.getText().toString();
Intent objIndent = new Intent(getActivity(),
EditParticipant.class);
objIndent.putExtra("friendId", valFriendId);
startActivity(objIndent);
break;
case 1:
String valFriendId2 = friendId.getText().toString();
controller.deleteFriend(valFriendId2);
onResume();
}
return true;
}
#Override
public void onResume() {
super.onResume();
if (getListView() != null) {
updateData();
}
}
private void updateData() {
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
controller.getAllFriends(queryValues),
R.layout.view_friend_entry, new String[] { "friendId",
"friendName", "friendSpending" }, new int[] {
R.id.friendId, R.id.friendName, R.id.friendSpending });
setListAdapter(adapter);
}
}
Here is the code for expense list:
public class Expense extends ListFragment implements OnClickListener {
Button addexp;
TextView expenseId;
ListView lv;
String eventId, friendId;
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
ArrayList<HashMap<String, String>> expenseList = controller
.getAllExpenses(queryValues);
if (expenseList.size() != 0) {
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
expenseId = (TextView) view.findViewById(R.id.expenseId);
String valExpenseId = expenseId.getText().toString();
Intent objIndent = new Intent(getActivity(),
EditExpense.class);
objIndent.putExtra("expenseId", valExpenseId);
startActivity(objIndent);
}
});
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
expenseList, R.layout.view_expense_entry, new String[] {
"expenseId", "expenseName","expenseQuantity" }, new int[] {
R.id.expenseId, R.id.expenseName, R.id.expenseQuantity });
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.expense, container, false);
addexp = (Button) rootView.findViewById(R.id.addexp);
addexp.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent objIntent = new Intent(getActivity(), AddExpense.class);
objIntent.putExtra("eventId", eventId);
startActivity(objIntent);
}
#Override
public void onResume() {
super.onResume();
if (getListView() != null) {
updateData();
}
}
private void updateData() {
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
controller.getAllExpenses(queryValues),
R.layout.view_expense_entry, new String[] { "expenseId",
"expenseName", "expenseQuantity" }, new int[] { R.id.expenseId,
R.id.expenseName, R.id.expenseQuantity });
setListAdapter(adapter);
}
}
Same scenario with me, if you used FragmentPagerAdapter, Try like this in FirstFragment
private void updateSecondFragment(){
//Way to get TagName which generated by FragmentPagerAdapter
String tagName = "android:switcher:" + R.id.pager + ":" + 1; // Your pager name & tab no of Second Fragment
//Get SecondFragment object from FirstFragment
SecondFragment f2 = (SecondFragment)getActivity().getSupportFragmentManager().findFragmentByTag(tagName);
//Then call your wish method from SecondFragment to update appropriate list
f2.updateList();
}
I got that idea by reading this. Then edit a little !
One way could be creating the methods in the activity that contains the two fragments, and access to the fragments methods from the activity. You can update the database and reload the list in the same method.
For example, In the activity
public void updateFragment2(){ ... }
In fragment 1 you should call:
((ActivityClass)getActivity()).updateFragment2();
In the section "Communicating with the Activity" you can see the explanation of this example:
http://developer.android.com/guide/components/fragments.html
I have a problem with my listview that when I add a task to my database, I need to update my listview with this new added task....
I'm new to android and Eclipse...
Here is my code for Main (that shows the ListView)
public class Main extends ListActivity {
Button newCat;
TextView todaytaskId;
ResultDatabase controller5 = new ResultDatabase(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
newCat = (Button) findViewById(R.id.bNewCat);
newCat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen = new Intent(getApplicationContext(),
CategoryList.class);
startActivity(nextScreen);
}
});
ArrayList<HashMap<String, String>> todaytaskList = controller5
.getTodayTasks();
if (todaytaskList.size() != 0) {
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
todaytaskId = (TextView) view
.findViewById(R.id.todaytaskId);
String valtaskId = todaytaskId.getText().toString();
Intent objIndent = new Intent(getApplicationContext(),
DelayTask.class);
objIndent.putExtra("todaytaskId", valtaskId);
startActivity(objIndent);
}
});
SimpleAdapter adapter = new SimpleAdapter(Main.this, todaytaskList,
R.layout.view_today_task, new String[] { "taskId",
"taskName", "taskTime" }, new int[] {
R.id.todaytaskId, R.id.todaytasktv,
R.id.todaytasktimetv});
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
Here's my code to select tasks from ResultDatabase class
public ArrayList<HashMap<String, String>> getTodayTasks() {
ArrayList<HashMap<String, String>> wordList;
wordList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM tasks where taskDate = date('now') AND taskDone = 'No'";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("taskId", cursor.getString(0));
map.put("taskName", cursor.getString(1));
map.put("taskTime", cursor.getString(3));
// map.put("taskDate", cursor.getString(4));
wordList.add(map);
} while (cursor.moveToNext());
}
return wordList;
}
After modifying the data set that is connected on the adapter you must call notifyDataSetChanged to notify the adapter to update the views with the new data. You must also call requery on the Cursor to update the cursor with new data. To clarify you should call requery before notifyDataSetChanged.
Check sample code below
public class WeatherAppActivity extends ListActivity {
Button buton;
ItemsAdapter lista;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
List<String> initialList = new ArrayList<String>();
initialList.add("Bucuresti");
initialList.add("Sibiu");
lista=new ItemsAdapter(this, initialList);
buton=(Button)findViewById(R.id.button1);
buton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
lista.add(""+System.currentTimeMillis()); // e chiar getText()
lista.notifyDataSetChanged();
}
});
setListAdapter(lista);
}
class ItemsAdapter extends ArrayAdapter<String> {
public ItemsAdapter(Context context, List<String> list) {
super(context, R.layout.lista, list);
}
#Override
public View getView(final int position, View row, final ViewGroup parent) {
final String item = getItem(position);
ItemWrapper wrapper = null;
if (row == null) {
row = getLayoutInflater().inflate(R.layout.lista, parent, false);
wrapper = new ItemWrapper(row);
row.setTag(wrapper);
} else {
wrapper = (ItemWrapper) row.getTag();
}
wrapper.refreshData(item);
return row;
}
class ItemWrapper {
TextView text;
public ItemWrapper(View row) {
text = (TextView) row.findViewById(R.id.elementLista);
}
public void refreshData(String item) {
text.setText(item);
}
}
}
}
I am using slidemenu example from github and it's showing slide menu only with text and header but I need to add different icon with it. I am trying to use a custom adapter but it's not working...
slidemenu.java:
public class SlideMenu implements SlideMenuAnimationContainer.Listener {
public final static String[] slideMenuOptions = { "Recent Update", "Notification", "Wardrobe" };
public final static String TAG = "SlideMenu";
protected static final String TextView = null;
Intent intent;
private Context context;
private SlideMenuAnimationContainer slideMenuAnimationContainer;
public SlideMenu( Context context, SlideMenuAnimationContainer mainAnimationLayout){
this.context = context;
this.slideMenuAnimationContainer = mainAnimationLayout;
}
public void init(){
final Activity activity = (Activity) context;
//Set Content's show menu button's action
ImageView showMenuButton = (ImageView) activity.findViewById( R.id.content_button);
showMenuButton.setOnClickListener( new OnClickListener(){
#Override
public void onClick( View v){
slideMenuAnimationContainer.toggleSlideMenu();
}
});
//Contruct the SlideMenu items here, you can replace this ArrayAdapter with your customr ArrayAdapter
List<SlideMenuItem> slideMenuList = new ArrayList<SlideMenuItem>();
slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Header, "Updates"));
slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Activity, "Recent Update"));
// slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Header, "Header 2"));
slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Activity, "Notification"));
slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Header, "Category"));
slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Activity, "Wardrobe"));
slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Activity, "Gadgets"));
SlideMenuArrayAdapter slideMenuArrayAdaptar = new SlideMenuArrayAdapter( context, android.R.layout.simple_list_item_1, slideMenuList);
ListView menuListView = (ListView) activity.findViewById( R.id.slideMenuListView);
menuListView.setAdapter( slideMenuArrayAdaptar);
menuListView.setOnItemClickListener( new OnItemClickListener(){
#Override
public void onItemClick( AdapterView<?> parent, View view, int position, long id){
// Close sidebar
slideMenuAnimationContainer.closeSlideMenuAndActOnClick( parent, view, position, id);
}
});
//Implement your logic here within the execute() function when an item is clicked with in the SlideMenu
//Called after the SlideMenu collapses.
slideMenuAnimationContainer.setMenuItemSelectedAction( new MenuItemSelectedAction(){
#Override
public void execute( AdapterView<?> parent, View view, int position, long id){
//Only act when a ListViewItem with type Activity is clicked
TextView textView = (TextView)view.findViewById( R.id.MenuActivityListViewItem_text);
if( textView != null && textView.getId() == R.id.MenuActivityListViewItem_text){
//Start new activity
CharSequence selectedActivityName = textView.getText();
if( selectedActivityName.equals( "Recent Update")) {
intent = new Intent( activity, Activity1.class);
}
else if( selectedActivityName.equals( "Notification")) {
intent = new Intent( activity, Activity2.class);
}
else if( selectedActivityName.equals( "Wardrobe")) {
intent = new Intent( activity, Activity3.class);
}
else if( selectedActivityName.equals( "Gadgets")) {
intent = new Intent( activity, Gadgets_Activity.class);
}
intent =intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
activity.startActivity( intent);
}
}
});
}
//Callback of SlideMenuAnimationContainer.Listener to monitor status of SlideMenu
#Override
public void onSlideMenuOpened(){
Log.d( TAG, "opened");
}
//Callback of SlideMenuAnimationContainer.Listener to monitor status of SlideMenu
#Override
public void onSlideMenuClosed(){
Log.d( TAG, "closed");
}
//Callback of SlideMenuAnimationContainer.Listener to monitor status of SlideMenu
#Override
public boolean onContentTouchedWhenOpening(){
//The content area is touched when sidebar opening, close sidebar
Log.d( TAG, "going to close sidebar");
slideMenuAnimationContainer.closeSlideMenu();
return true;
}
}
and Adapter:
public class SlideMenuArrayAdapter extends ArrayAdapter<SlideMenuItem> {
private List<SlideMenuItem> slideMenuItemList;
public SlideMenuArrayAdapter( Context context, int textViewResourceId, List<SlideMenuItem> slideMenuItemList) {
super( context, textViewResourceId, slideMenuItemList);
this.slideMenuItemList = slideMenuItemList;
}
#Override
public View getView( int position, View view, ViewGroup parent) {
SlideMenuItem slideMenuItem = slideMenuItemList.get( position);
LayoutInflater layoutInflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if( slideMenuItem.getSlideMenuItemType() == SlideMenuItemType.Header){
view = layoutInflater.inflate( R.layout.menu_header_listview_item, null);
TextView textView = (TextView) view.findViewById( R.id.MenuListHeaderListViewItem_text);
textView.setText( slideMenuItem.getText());
}
else if( slideMenuItem.getSlideMenuItemType() == SlideMenuItemType.Activity){
view = layoutInflater.inflate( R.layout.menu_activity_listview_item, null);
TextView textView = (TextView) view.findViewById( R.id.MenuActivityListViewItem_text);
textView.setText( slideMenuItem.getText());
}
else{
view = null; //Left for operation
}
return view;
}
}
Try like this
ListView listView = (ListView) menu.findViewById(R.id.list);
ArrayList<String[]> datavalues=new ArrayList<String[]>();
String[] menuhome=new String[2];
menuhome[0]=""+R.drawable.home_sidebar;
menuhome[1]="Home";
datavalues.add(menuhome);
String[] menuprofile=new String[2];
menuprofile[0]=""+R.drawable.profile_sidebar;
menuprofile[1]="Profile";
datavalues.add(menuprofile);
String[] menusearch=new String[2];
menusearch[0]=""+R.drawable.search_sidebar;
menusearch[1]="Search";
datavalues.add(menusearch);
String[] menugallery=new String[2];
menugallery[0]=""+R.drawable.gallery_sidebar;
menugallery[1]="Gallery";
datavalues.add(menugallery);
String[] menulogout=new String[2];
menulogout[0]=""+R.drawable.logout_sidebar;
menulogout[1]="Logout";
datavalues.add(menulogout);
SlideMenuAdapter menuadapter=new SlideMenuAdapter(datavalues, this);
listView.setAdapter(menuadapter);
private class SlideMenuAdapter extends BaseAdapter{
ArrayList<String[]> data;
ActivityListing context;
public SlideMenuAdapter(ArrayList<String[]> datavalues,
ActivityListing contextobj) {
// TODO Auto-generated constructor stub
data=datavalues;
context=contextobj;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return data.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
final int pos=arg0;
// This a new view we inflate the new layout
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View convertView = inflater.inflate(R.layout.menurow, null, false);
int drawable=Integer.parseInt(data.get(arg0)[0].trim());
Button btnOption=(Button) convertView.findViewById(R.id.btnoption);
btnOption.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(drawable), null, null, null);
btnOption.setText(data.get(arg0)[1].trim());
btnOption.setTextColor(Color.rgb(143, 7, 0));
btnOption.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
callOptions(data.get(pos));
}
});
return convertView;
}
Basically, I'm working on a app which has a tab-activity including 4 tabs and also I'm using the actvityGroup to manage the activities and backKey pressed() method.
When my app first starts it sends a request to server and shows the progress bar (using AsyncTask) as shown in below image.
After this, my complete UI appears as
it loads new actvity on click event of button "GO" (code is given below)
btnGo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent bookSearchResultActivityIntent = new Intent();
bookSearchResultActivityIntent
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
bookSearchResultActivityIntent.setClass(getParent(),
BookSearchResultActivity.class);
bookSearchResultActivityIntent.putExtra("LANG", language);
bookSearchResultActivityIntent.putExtra("SEARCH_KEYWORDS",
edTxt_SearchField.getText().toString());
MyActivityGroup activityStack = (MyActivityGroup) getParent();
activityStack.push("BooksSearchActivity",
bookSearchResultActivityIntent);
also here is my ActivtyGroup.java code
public class MyActivityGroup extends ActivityGroup {
private Stack<String> stack;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (stack == null) {
stack = new Stack<String>();
}
push("1stStackActivity", new Intent(this, Home.class));
}
#Override
public void finishFromChild(Activity child) {
pop();
}
#Override
public void onBackPressed() {
pop();
}
public void push(String id, Intent intent) {
Window window = getLocalActivityManager().startActivity(id,
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
stack.push(id);
setContentView(window.getDecorView());
}
}
public void pop() {
if (stack.size() == 1) {
finish();
}
LocalActivityManager manager = getLocalActivityManager();
manager.destroyActivity(stack.pop(), true);
if (stack.size() > 0) {
Intent lastIntent = manager.getActivity(stack.peek()).getIntent()
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window newWindow = manager.startActivity(stack.peek(), lastIntent);
setContentView(newWindow.getDecorView());
}
}
}
ok now my question is that when i press the backKey(); it should come to the previous actvity.
Yes it comes to the previous activity but it send request to the server again and shows the progress bar again and loads until the server sends response. it wastes my time.
I only want to load the HomeTab just once (when i play the app). not again and again
I am also adding the
setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
while starting the activity
also added following code in menifest.xml file
android:configChanges="keyboard|keyboardHidden|orientation"
but not working yet.
and here is the code of my Home tab(which sends the request to server in onCreate method)
public class Home extends Activity {
/** Called when the activity is first created. */
static final String URL = "http://www.shiaislamiclibrary.com/requesthandler.ashx";
static final String KEY_ITEM = "Book"; // parent node
static final String KEY_BOOKAUTHOR = "BookAuthor";
static final String KEY_BOOKDATEPUBLISHED = "DatePublished";
static final String KEY_BOOKTITLE = "BookTitle";
static final String KEY_BOOKCODE = "BookCode";
static final String KEY_BOOKIMAGE = "BookImage";
String searchLang;
String searchKeywords;
LayoutInflater inflater = null;
ArrayList<String> BookTitle = new ArrayList<String>();
ArrayList<String> BookCoverPhotos = new ArrayList<String>();
ArrayList<String> BookAuther = new ArrayList<String>();
ArrayList<String> BookPublishDate = new ArrayList<String>();
ArrayList<String> ImageByte = new ArrayList<String>();
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
Context ctx = this;
Activity act = this;
Context context = Home.this;
URL bookImageURL = null;
Bitmap bitMapImage = null;
Button btnGo;
Spinner spnrLanguage;
Spinner spnrBrowseBy;
String language;
EditText edTxt_SearchField;
GridView gridView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.home_activity);
View viewToLoad = LayoutInflater.from(this.getParent()).inflate(
R.layout.home_activity, null);
this.setContentView(viewToLoad);
gridView = (GridView) findViewById(R.id.gridview);
spnrLanguage = (Spinner) findViewById(R.id.spnrLanguage);
spnrBrowseBy = (Spinner) findViewById(R.id.spnrBrowseBy);
edTxt_SearchField = (EditText) findViewById(R.id.EditTxt_Search);
btnGo = (Button) findViewById(R.id.btn_GO);
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// checking for availbe internet Connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
new UIThread().execute(URL, "Imam Ali");
}
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
Toast.makeText(context, BookTitle.get(pos), Toast.LENGTH_SHORT)
.show();
Intent bookSearchResultActivityIntent = new Intent();
bookSearchResultActivityIntent.setClass(getParent(),
BookOverView.class);
bookSearchResultActivityIntent.putExtra("BITMAP",
bitmapArray.get(pos));
bookSearchResultActivityIntent.putExtra("BOOK_TITLE",
BookTitle.get(pos));
bookSearchResultActivityIntent.putExtra("BOOK_AUTHOR",
BookAuther.get(pos));
bookSearchResultActivityIntent.putExtra("BOOK_PUBLISH_DATE",
BookPublishDate.get(pos));
MyActivityGroup activityStack = (MyActivityGroup) getParent();
activityStack.push("BookOverViewActivity",
bookSearchResultActivityIntent);
}
});
// //////////////////// Spinners handler/////////////////////////
ArrayAdapter<String> adapterLanguage = new ArrayAdapter<String>(
context, android.R.layout.simple_spinner_item, getResources()
.getStringArray(R.array.spnr_language_array));
ArrayAdapter<String> adapterBrowseBy = new ArrayAdapter<String>(
context, android.R.layout.simple_spinner_item, getResources()
.getStringArray(R.array.spnr_browse_array));
spnrLanguage.setAdapter(adapterLanguage);
spnrBrowseBy.setAdapter(adapterBrowseBy);
spnrLanguage.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
Toast.makeText(getParent(),
spnrLanguage.getItemAtPosition(pos) + "",
Toast.LENGTH_SHORT).show();
language = spnrLanguage.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spnrBrowseBy.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
Toast.makeText(context,
spnrBrowseBy.getItemAtPosition(pos) + "",
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
// ////////////////////Search Button Handler/////////////////
btnGo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!edTxt_SearchField.getText().toString().equals("")) {
Intent bookSearchResultActivityIntent = new Intent();
bookSearchResultActivityIntent
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
bookSearchResultActivityIntent.setClass(getParent(),
BookSearchResultActivity.class);
bookSearchResultActivityIntent.putExtra("LANG", language);
bookSearchResultActivityIntent.putExtra("SEARCH_KEYWORDS",
edTxt_SearchField.getText().toString());
MyActivityGroup activityStack = (MyActivityGroup) getParent();
activityStack.push("BooksSearchActivity",
bookSearchResultActivityIntent);
} else {
Toast.makeText(context, "Search Field Empty",
Toast.LENGTH_SHORT).show();
}
}
});
}
private class UIThread extends AsyncTask<String, Integer, String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(getParent(),
"Acumlating Books from server...",
"This may Take a few seconds.\nPlease Wait...");
}
#Override
protected String doInBackground(String... params) {
String URL = params[0];
String searchKeywords = params[1];
XMLParser parser = new XMLParser();
String XMLString = parser.getXmlFromUrl(URL, searchKeywords,
searchLang);
// Log.i("XML Response", XMLString);
Document doc = parser.getDomElement(XMLString);
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
BookTitle.add(parser.getValue(e, KEY_BOOKTITLE));
BookCoverPhotos.add("http://shiaislamicbooks.com/books_Snaps/"
+ parser.getValue(e, KEY_BOOKCODE) + "/1_thumb.jpg");
BookAuther.add(parser.getValue(e, KEY_BOOKAUTHOR));
BookPublishDate.add(parser.getValue(e, KEY_BOOKDATEPUBLISHED));
Log.i("URLs", BookCoverPhotos.toString());
}
for (int i = 0; i < BookAuther.size(); i++) {
try {
bookImageURL = new URL(BookCoverPhotos.get(i));
} catch (MalformedURLException e) {
e.printStackTrace();
Log.i("URL", "ERROR at image position" + i + "");
}
try {
bitMapImage = BitmapFactory.decodeStream(bookImageURL
.openConnection().getInputStream());
bitmapArray.add(bitMapImage);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("BITMAP", "ERROR" + i);
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
ImageAdapter adapter = new ImageAdapter(getBaseContext(), act);
gridView.setAdapter(adapter);
}
}
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
context = c;
}
// ---returns the number of images---
public int getCount() {
// return imageIDs.length;
return bitmapArray.size();
// return 6;
}
public ImageAdapter(Context ctx, Activity act) {
inflater = (LayoutInflater) act
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// ---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// ---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent) {
// ImageView bmImage;
final ViewHolder holder;
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.grid_style, parent, false);
holder = new ViewHolder();
holder.txt_BooksTitle = (TextView) vi
.findViewById(R.id.txt_BookTitle);
holder.img_BookCoverPhoto = (ImageView) vi
.findViewById(R.id.imgBookCover);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
holder.txt_BooksTitle.setText(BookTitle.get(position) + "");
holder.img_BookCoverPhoto.setImageBitmap(bitmapArray.get(position));
return vi;
}
}
class ViewHolder {
TextView txt_BooksTitle;
ImageView img_BookCoverPhoto;
}
}
please have a look on my activity group class and tell what should i do.
thanks in advance
When loading your data in the Home Tab activity, put it inside some static arrays.
ArrayList<String> BookTitle = new ArrayList<String>();
ArrayList<String> BookCoverPhotos = new ArrayList<String>();
ArrayList<String> BookAuther = new ArrayList<String>();
ArrayList<String> BookPublishDate = new ArrayList<String>();
ArrayList<String> ImageByte = new ArrayList<String>();
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
From a quick glimpse on the code, make them static ArrayList<...> ... = null; and check inside the onCreate() method:
if(BookTitle == null)
{
//needs init
BookTitle = new ArrayList<String>();
//perform connect to server and parse response.
}
When the application activity home tab is stopped then restarted, the data will be in memory already and it will skip the if clause keeping the old data for re-use.
Make sure you will clear the static variables when you really want to kill the app - on a quit button click, call a static method to init them to null again, or if you want them to be valid for let's say 12 hours, memorize the timestamp in a static variable and each time you kill/pause the main activity perform a check on it (wheather is null or has a date, if it has a date, check if 12 hours have passed, if yes, clear the static variable contents)
This is the quick and easy way. Another way is to store them in the application database if you don't want to deal with static variables.
There are a lot of options, the point is you kinda have to mark them as "global persistent" data with static, or store them in a databse / file etc.