it's weird , I spend last 5 hours on it , nothing worked. the problem is this ,When I go from activity a to activity b , and press back button and come back to activity a, the navigation drawer not open.
this is the code :
public abstract class DrawerActivity extends ActionBarActivity {
static LinearLayout fullLayout;
static FrameLayout actContent;
static DrawerLayout mDrawerLayout;
static ListView mDrawerList;
static ActionBarDrawerToggle mDrawerToggle;
static LinearLayout mDrawer;
List<HashMap<String, String>> mList;
SimpleAdapter mAdapter;
final private String COUNTRY = "country";
final private String FLAG = "flag";
final private String COUNT = "count";
#Override
public void setContentView(final int layoutResID) {
fullLayout= (LinearLayout) getLayoutInflater().inflate(R.layout.act_layout, null); // Your base layout here
actContent= (FrameLayout) fullLayout.findViewById(R.id.act_content);
getLayoutInflater().inflate(layoutResID, actContent, true); // Setting the content of layout your provided to the act_content frame
super.setContentView(fullLayout);
makelist();
}
mTitle = (String) getTitle();
// Getting a reference to the drawer listview
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting a reference to the sidebar drawer ( Title + ListView )
mDrawer = (LinearLayout) findViewById(R.id.drawer);
// Each row in the list stores country name, count and flag
mList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < mCountries.length; i++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put(COUNTRY, mCountries[i]);
hm.put(FLAG, Integer.toString(mFlags[i]));
mList.add(hm);
}
String[] from = { FLAG, COUNTRY };
int[] to = { R.id.flag, R.id.country };
mAdapter = new SimpleAdapter(this, mList, R.layout.drawer_layout, from,to);
// Getting reference to DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_navigation_drawer, R.string.drawer_open,R.string.drawer_close) {
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
highlightSelectedCountry();
supportInvalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
supportInvalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item != null && item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(Gravity.RIGHT)) {
mDrawerLayout.closeDrawer(Gravity.RIGHT);
Log.v("this","close");
} else {
mDrawerLayout.openDrawer(Gravity.RIGHT);
}
}
return false;
}
};
// Setting event listener for the drawer
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerList.setAdapter(mAdapter);
}
public static boolean open() {
if (mDrawerLayout.isDrawerOpen(mDrawer)) {
mDrawerLayout.closeDrawer(Gravity.RIGHT);
return true;
} else {
mDrawerLayout.openDrawer(Gravity.RIGHT);
return true;
}
}
this is MainActivity class:
public class MainActivity extends DrawerActivity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//suppose this is the imageview on the actionbar
ImageView img=(ImageView)dialogg.findViewById(R.id.img);
dateup.img(new OnClickListener() {
#Override
public void onClick(View v) {
DrawerActivity.open();
}
});
}
one thing I want to notice , the mainActivity extends DrawerActivity class.
Could you help me to solve this ?
thanks you
This
trys to use the method open() from the Abstract class and you use "mDrawerLayout" and this must be null at this moment i think
public void onClick(View v) {
DrawerActivity.open();
}
maybe you use
public void onClick(View v) {
this.open();
}
Then you will use the open-Method of your current Activity
And you have to implement the onClickListener in the Activity
An error msg would be nice to get more information about the error
Related
I am writing an app, where I am combining activivties and navigation drawer, which I have never tried before. Here is the problem: when I am trying to access menu elements by clicking from MainActivity, everything works perfect and clicked elements pass on to other activities. But when I am trying to access drawer from EventActivity, which is opened with one of the fields of the drawer, it just does not respond and closes. This happens whatever field I am trying to press on drawer from EventActivity. Here is the code of both
MainActivity:
public class MainActivity extends AppCompatActivity {
public DrawerLayout drawerLayout;
public ActionBarDrawerToggle actionBarDrawerToggle;
MenuItem event,remind,setting;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = findViewById(R.id.my_drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.nav_open, R.string.nav_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
event=findViewById(R.id.nav_events);
remind=findViewById(R.id.nav_reminders);
setting=findViewById(R.id.nav_settings);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if(item.getItemId()==R.id.nav_events){
Intent intentEv=new Intent(MainActivity.this,EventActivity.class);
startActivity(intentEv);
}
else if(item.getItemId()==R.id.nav_reminders){
Intent intentRem=new Intent(MainActivity.this,RemindersActivity.class);
startActivity(intentRem);
}
else if(item.getItemId()==R.id.nav_settings){
Intent intentSet=new Intent(MainActivity.this,SettingsActivity.class);
startActivity(intentSet);
}
return super.onOptionsItemSelected(item);
}
}
EventActivity
public class EventActivity extends AppCompatActivity {
public DrawerLayout drawerLayout;
public ActionBarDrawerToggle actionBarDrawerToggle;
MenuItem event,remind,setting;
FloatingActionButton fab;
FragmentManager fm;
OpenHelper openHelper;
SQLiteDatabase db;
ArrayList<ObjectItem> maps;
ArrayList<String> listItem;
ArrayAdapter adapter;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
event=findViewById(R.id.nav_events);
remind=findViewById(R.id.nav_reminders);
setting=findViewById(R.id.nav_settings);
fab=findViewById(R.id.fab);
list=findViewById(R.id.list);
openHelper=new OpenHelper(getBaseContext());
db=openHelper.getReadableDatabase();
listItem=new ArrayList<>();
viewData();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selected= (String) list.getItemAtPosition(position);
//Убрать элемент
String desc = null,time = null,date=null;
Cursor csr=db.rawQuery("SELECT description FROM event WHERE header =\"" +selected + "\";",null);
if(csr!=null)
if(csr.moveToFirst())
desc=csr.getString(0);
Cursor csr2=db.rawQuery("SELECT time FROM event WHERE header = \"" +selected + "\";",null);
if(csr2!=null)
if(csr2.moveToFirst())
time=csr2.getString(0);
Cursor csr3=db.rawQuery("SELECT date FROM event WHERE header = \"" +selected + "\";",null);
if(csr3!=null)
if(csr3.moveToFirst())
date=csr3.getString(0);
Dialog dialog = new Dialog(EventActivity.this);
dialog.setContentView(R.layout.itemdialog);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
TextView textHeader = dialog.findViewById(R.id.ItemHeader);
textHeader.setText(selected);
TextView textDesc = dialog.findViewById(R.id.ItemDesc);
textDesc.setText(desc);
TextView textTime = dialog.findViewById(R.id.ItemTime);
textTime.setText(time);
TextView textDate = dialog.findViewById(R.id.ItemDate);
textDate.setText(date);
ImageButton imageButton=dialog.findViewById(R.id.imgBut);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openHelper.deleteData(selected);
maps.clear();
viewData();
dialog.dismiss();
}
});
dialog.show();
}
});
drawerLayout = findViewById(R.id.my_drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.nav_open, R.string.nav_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
event=findViewById(R.id.nav_events);
remind=findViewById(R.id.nav_reminders);
setting=findViewById(R.id.nav_settings);
fm=getSupportFragmentManager();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(EventActivity.this,EventBuilderActivity.class);
startActivity(intent);
}
});
}
private void viewData() {
list.setAdapter(null);
Cursor cursor=openHelper.viewData();
maps = new ArrayList<ObjectItem>();
if(cursor.getCount()==0){
Toast.makeText(this,"No info",Toast.LENGTH_SHORT).show();
} else{
while (cursor.moveToNext()){
maps.add(new ObjectItem(cursor.getString(1),
cursor.getString(2),
cursor.getString(3),cursor.getString(4)));
}
adapter=new MeinAdapter(this, maps);
list.setAdapter(adapter);
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if(item.getItemId()==R.id.nav_events){
Intent intentMain=new Intent(EventActivity.this,MainActivity.class);
startActivity(intentMain);
}
else if(item.getItemId()==R.id.nav_reminders){
Intent intentRem=new Intent(EventActivity.this,RemindersActivity.class);
startActivity(intentRem);
}
else if(item.getItemId()==R.id.nav_settings){
Intent intentSet=new Intent(EventActivity.this,SettingsActivity.class);
startActivity(intentSet);
}
return super.onOptionsItemSelected(item);
}
}
In my Activity I have a drawer list that pops from the right but I'm not able to move the drawer toggle from the left to the right side. Please if somebody can help me solve this issue.I just want to move the toggle to the right of the action bar.
package com.parse.starter;
import com.parse.ParseUser;
public class UserDrawer extends AppCompatActivity {
//Declaring Variables
private ListView DrawerList;
private ArrayAdapter<String> Adapter;
private ActionBarDrawerToggle DrawerToggle;
private DrawerLayout DrawerLayout;
private String ActivityTitle;
final ParseUser currentUser = ParseUser.getCurrentUser();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_drawer);
DrawerList = (ListView) findViewById(R.id.navList);
DrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
Button Sample = (Button) findViewById(R.id.button);
}
//Method To Add Items To The List View
private void addDrawerItems() {
String[] DArray = {"Job List", "Notifications", "Messages", "Log Out"};
Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, DArray);
DrawerList.setAdapter(Adapter);
DrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
Intent i0 = new Intent(UserDrawer.this, Set_Info.class);
startActivity(i0);
} else if (position == 1) {
//Intent i1 = new Intent(Drawer1.this, AddPatient.class);
//startActivity(i1);
} else if (position == 2) {
//Intent i2 = new Intent(Drawer1.this, Notifications.class);
//startActivity(i2);
} else if (position == 3) {
//Intent i3 = new Intent(Drawer1.this, Message_Log.class);
//startActivity(i3);
} else if (position == 4) {
Intent i4 = new Intent(UserDrawer.this, MainActivity.class);
startActivity(i4);
Toast.makeText(getApplicationContext(), "You are Logged Out", Toast.LENGTH_LONG).show();
finish();
}
}
});
}
private void setupDrawer() {
DrawerToggle = new ActionBarDrawerToggle(this, DrawerLayout,
R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Menu");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(ActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
DrawerToggle.setDrawerIndicatorEnabled(true);
DrawerLayout.setDrawerListener(DrawerToggle);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item != null && item.getItemId()==android.R.id.home){
if(DrawerLayout.isDrawerOpen(Gravity.RIGHT)){
//Notice the Gravity.Right
DrawerLayout.closeDrawer(Gravity.RIGHT);
}else{
DrawerLayout.openDrawer(Gravity.RIGHT);
}
}
return false;
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
DrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
DrawerToggle.onConfigurationChanged(newConfig);
}
#SuppressWarnings("ResourceType")
public void SampleClick(View view) {
try {
Intent i = new Intent(UserDrawer.this,Set_Info.class);
startActivity(i);
} catch (Exception e) {
}
}
}
I get this error if I do anything with my navigation drawer.
Motion event has invalid pointer count 0; value must be between 1 and 16.
This error doesn't crash my activity. But just floods my log. Below is the activity. The adapter is custom adapter having image and text in a row.
public class FirstActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private ListView navList;
private NavAdapter navAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
drawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
navList = (ListView)findViewById(R.id.navigation_list);
navAdapter = new NavAdapter(this);
navList.setAdapter(navAdapter);
navList.setOnItemClickListener(this);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.opendrawer, R.string.closedrawer);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
navList.setItemChecked(position, true);
String menuItem = (((TextView)view.findViewById(R.id.drawerTV)).getText().toString());
getSupportActionBar().setTitle(menuItem);
}
}
I was following this article. Unfortunatelly, badge isn't drawn. Of course I changed invalidateOptionsMenu method to supportInvalidateOptionsMenu method.
I was checking the log, step by step and found out that draw method in custom Drawable named BadgeDrawable is never called. Why is that?
I'm trying to use it in AppCompatActivity using Support Design Library version 23.0.1
I saw this answer but it seems to be out of date.
Is there anyone who managed to implement badger counter for MenuItem icon inside android.support.v7.widget.Toolbar?
If the way shown in the article is wrong then could you suggest other way to achieve the result as in example below?:
Here is a setup inside my application:
LayerDrawable XML ic_filter_notifications.xml:
<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/ic_filter_notification"
android:drawable="#drawable/ic_filter_grey600_18dp"
android:gravity="center"/>
<!-- set a place holder Drawable so android:drawable isn't null -->
<item android:id="#+id/ic_filter_badge"
android:drawable="#drawable/ic_filter_grey600_18dp">
</item>
</layer-list>
Menu that I use in the Toolbar menu_activity_main.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cobytu="http://schemas.android.com/apk/res-auto" >
<item
android:id="#+id/menu_settings"
android:orderInCategory="100"
android:title="#string/menu_settings"
cobytu:showAsAction="never"/>
<item
android:id="#+id/menu_logout"
android:orderInCategory="1000000"
android:title="#string/menu_logout"
cobytu:showAsAction="never"/>
<item
android:id="#+id/action_filter"
android:title="#string/filters"
android:icon="#drawable/ic_filter_notifications"
cobytu:showAsAction="always"/>
<item
android:id="#+id/action_location"
android:icon="#drawable/ic_map_marker_radius_grey600_18dp"
android:title="#string/location"
cobytu:showAsAction="always"/>
</menu>
This is function sets the count int for new BadgeDrawable inside UsefulFunctions class - UsefulFunctions.java:
public class UsefulFunctions {
private Context ctx;
public UsefulFunctions(Context context){
ctx = context;
}
public static void setBadgeCount(Context context, LayerDrawable icon,
int count) {
BadgeDrawable badge;
// Reuse drawable if possible
Drawable reuse = icon.findDrawableByLayerId(R.id.ic_filter_badge);
if (reuse != null && reuse instanceof BadgeDrawable) {
badge = (BadgeDrawable) reuse;
} else {
Log.d("mTAG", UsefulFunctions.class.getName()
+ " I'm creating new BadgeDrawable!");
badge = new BadgeDrawable(context);
}
badge.setCount(count);
icon.mutate();
Log.d("mTAG",
UsefulFunctions.class.getName() + " badge: " + badge.toString()
+ " count: " + count);
icon.setDrawableByLayerId(R.id.ic_filter_badge, badge);
}
}
This is the important scrap of my MainActivity where I invoke BadgeDrawable creation. I also show what's inside onCreate and in onOptionsItemSelected, may be needed - MainActivity.java:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, DialogFragmentFilters.FiltersRefreshInterface{
public String username;
//CollapsingToolbarLayout
private CollapsingToolbarLayout mCollapsingToolbarLayout;
//Toolbar
private Toolbar mToolbar;
//TabLayout
private TabLayout mTabLayout;
private ViewPager mPager;
private MyPagerAdapter mAdapter;
//NavigationDraver
private static final String SELECTED_ITEM_ID = "selected_item_id";
private static final String FIRST_TIME = "first_time";
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private NavigationView mNavigationView;
private int mSelectedId;
private boolean mUserSawDrawer = false;
private TextView mNavHeaderNameText;
private TextView mNavHeaderEmailText;
private DatabaseHandler db;
private UserFunctions userFunctions;
private AlertDialog.Builder dialogBuilder;
private AlertDialog alertDialog;
private JSONObject jsonLocation = new JSONObject();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userFunctions = new UserFunctions();
db = new DatabaseHandler(getApplicationContext());
username = db.getUserDetails().get(DatabaseHandler.getKEY_USER_LOGIN());
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
setupToolbar();
setupTablayout();
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
mNavigationView.setNavigationItemSelectedListener(this);
View header = LayoutInflater.from(MainActivity.this).inflate(R.layout.nav_header, null);
mNavHeaderNameText = (TextView) header.findViewById(R.id.tv_nav_header_name);
mNavHeaderNameText.setText("Siema "+username+"!");
mNavHeaderEmailText = (TextView) header.findViewById(R.id.tv_nav_header_email);
mNavHeaderEmailText.setText(db.getUserDetails().get(DatabaseHandler.getKEY_USER_EMAIL()));
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,mToolbar, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
if (!didUserSeeDrawer()) {
showDrawer();
markDrawerSeen();
} else {
hideDrawer();
}
mSelectedId = savedInstanceState == null ? R.id.navigation_item_4 : savedInstanceState.getInt(SELECTED_ITEM_ID);
navigate(mSelectedId);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
showActionDialog(id);
//noinspection SimplifiableIfStatement
switch (id) {
case R.id.menu_settings:
return true;
case R.id.menu_logout:
dialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(
MainActivity.this, R.style.Theme_AppCompat_Light_Dialog));
dialogBuilder
.setTitle(getResources().getString(R.string.logoutAlertTitle))
.setIcon(R.drawable.ic_logout).setMessage(getResources().getString(R.string.logoutAlertMessage)).setPositiveButton(getResources().getString(R.string.logoutAlertYesButton),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
((RelativeLayout) findViewById(R.id.fl_mainContent))
.animate()
.alpha(0f)
.setListener(
new AnimatorListenerAdapter() {
public void onAnimationEnd(
Animator animation) {
mDrawerLayout
.setVisibility(View.INVISIBLE);
mDrawerLayout
.setAlpha(1f);
mDrawerLayout
.animate()
.setListener(null);
}
});
userFunctions.logoutUser(getApplicationContext());
Intent i = new Intent(MainActivity.this, LoginActivity.class);
// MainActivity.this.deleteDatabase("cobytu_db");
startActivity(i);
finish();
}
})
.setNegativeButton(getResources().getString(R.string.logoutAlertNoButton),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
alertDialog = dialogBuilder.create();
alertDialog.show();
return true;
}
return false;
}
public int filterCounter = 0;
class FetchCountTask extends AsyncTask<Void, Void, Integer> {
#Override
protected Integer doInBackground(Void... params) {
// example count. This is where you'd
// query your data store for the actual count.
return 5;
}
#Override
public void onPostExecute(Integer count) {
setNotifCount(count);
}
}
private void setNotifCount(int count){
filterCounter = count;
supportInvalidateOptionsMenu();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_activity_main, menu);
MenuItem item = menu.findItem(R.id.action_filter);
LayerDrawable icon = (LayerDrawable) item.getIcon();
// Update LayerDrawable's BadgeDrawable
Log.d("mTag", "onCreateOptionsMenu: this: " + this.toString());
UsefulFunctions.setBadgeCount(this, icon, filterCounter);
return true;
}
#Override
public void onRefreshFilters(int counter) {
setupTablayout();
Toast.makeText(MainActivity.this, "List has been refreshed! " + counter, Toast.LENGTH_SHORT).show();
filterCounter = counter;
new FetchCountTask.execute();
}
}
I have got two activities. In first you can input jobname and job place into inputtext views. First activity contains also navigation-draver menu (appearing from left side of screen). After clicking "Searc" button, results are shown in listview in second activity. You can long-click on any listview item and then it will be added to navigation-drawer in first activity. You can go back to first activity by clicking "back" arrow. The problem is, that when I will go back to first activity, press "Search" button again and then go back to first activity again, the navigation drawer menu is empty again (all items, which were added on first try are deleted). How to fix that?
Here is pic with my activities (sorry for poor quality):
1- first activity; 2- navigation drawer in first activity with added items from second activity' listview; 3- second activity (listview with search results)
EDIT:
My code from two activities (without imports to shorten it a little):
First (main):
public class MainActivity extends ActionBarActivity {
ListviewActivity lv = new ListviewActivity();
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
public ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
ArrayList<String> arrayFav = new ArrayList<String>();
ArrayList<String> arrayLin = new ArrayList<String>();
private ImageView mImageViewLogo;
private Button mButtonSzukaj;
private EditText mEditTextPraca;
private EditText mEditTextMiejsce;
public static String nazwaStanowiska;
public static String nazwaMiejscowosci;
private Settings mSettings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_layout);
mDrawerList = (ListView)findViewById(R.id.navList);mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mImageViewLogo = (ImageView)findViewById(R.id.imageViewLogo);
mButtonSzukaj = (Button) findViewById(R.id.buttonSzukaj);
mEditTextPraca = (EditText)findViewById(R.id.editTextPraca);
mEditTextMiejsce = (EditText)findViewById(R.id.editTextMiejsce);
final String mPrBefore = mEditTextPraca.getText().toString();
final String mPrAfter = mPrBefore.trim();
final String mMiBefore = mEditTextMiejsce.getText().toString();
final String mMiAfter = mMiBefore.trim();
mEditTextPraca.setText(mPrAfter);
mEditTextMiejsce.setText(mMiAfter);
mSettings = new Settings(this);
mAdapter.notifyDataSetChanged();
if(mAdapter.isEmpty()){
arrayFav.add("Brak ofert");
mDrawerList.setOnItemClickListener(null);
mDrawerList.setOnItemLongClickListener(null);
}
mAdapter.notifyDataSetChanged();
mButtonSzukaj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(mEditTextPraca.getText().toString()) && (TextUtils.isEmpty(mEditTextMiejsce.getText().toString()))) {
mEditTextPraca.setError("Pole obowiązkowe!");
mEditTextMiejsce.setError("Pole obowiązkowe!");
return;
} else if (TextUtils.isEmpty(mEditTextPraca.getText().toString())) {
mEditTextPraca.setError("Pole obowiązkowe!");
return;
} else if (TextUtils.isEmpty(mEditTextMiejsce.getText().toString())) {
mEditTextMiejsce.setError("Pole obowiązkowe!");
return;
} else {
nazwaStanowiska = mEditTextPraca.getText().toString();
nazwaMiejscowosci = mEditTextMiejsce.getText().toString();
Intent myIntent = new Intent(MainActivity.this, ListviewActivity.class);
MainActivity.this.startActivityForResult(myIntent, 1);
mSettings.setmText1(mEditTextPraca.getText().toString());
mSettings.setmText2(mEditTextMiejsce.getText().toString());
mSettings.save();
}
}
});
readPreferences();
}
protected void readPreferences(){
mEditTextPraca.setText(mSettings.getmText1());
mEditTextMiejsce.setText(mSettings.getmText2());
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
ArrayList<String> passedText = data.getStringArrayListExtra("text");
ArrayList<String> passedLink = data.getStringArrayListExtra("link");
//arrayFav.clear();
//arrayLin.clear();
arrayFav.addAll(passedText);
arrayLin.addAll(passedLink);
addDrawerItems();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.podziel_sie_opinia) {
Intent mIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:661249888"));
mIntent.putExtra("sms_body", "Uważam, że aplikacja...");
startActivity(mIntent);
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
private void addDrawerItems() {
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayFav);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Tu pojawi się kliknięta oferta", Toast.LENGTH_LONG).show();
/*Intent myBrowserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.onet.pl"));
startActivity(myBrowserIntent);*/
Intent myBrowserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(arrayLin.get(position)));
myBrowserIntent.putExtra("paramPosition", position);
startActivity(myBrowserIntent);
}
});
mDrawerList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Usunięto z ulubionych!", Toast.LENGTH_SHORT).show();
mAdapter.remove(mAdapter.getItem(position));
mAdapter.notifyDataSetChanged();
if(mAdapter.isEmpty()){
arrayFav.add("Brak ofert");
}
mAdapter.notifyDataSetChanged();
return false;
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Twoje oferty");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
protected void onResume() {
super.onResume();
mAdapter.notifyDataSetChanged();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
and the second one (listview with results):
public class ListviewActivity extends ActionBarActivity {
int global_position =0;
boolean longClick = false;
static String wybranaOferta = "";
ArrayList<String> choosedOffer = new ArrayList<String>();
ArrayList<String> choosedLink = new ArrayList<String>();
MainActivity mainActiv;
static List<String> mLista = new ArrayList<>();
static ArrayList<String> positionArr = new ArrayList<String>();
static List<String> mListaTest1 = new ArrayList<>();
static List<String> mListaTest2 = new ArrayList<>();
static List<String> mListaLinki = new ArrayList<>();
static List<String> mListaNazwy = new ArrayList<>();
static List<String> mListaFirmy = new ArrayList<>();
private JobListAdapter mAdapter;
public Elements jobName, jobName2, jobNameComp, jobName2Comp;
private ProgressBar mProgress;
private Context context;
public ArrayList<String> workList = new ArrayList<String>();
public ArrayList<String> companyList = new ArrayList<String>();
public ArrayList<String> jobList = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private JazzyListView mListView;
public String doURLpraca = MainActivity.nazwaStanowiska;
public String doURLmiejsce = MainActivity.nazwaMiejscowosci;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
mListView = (JazzyListView) findViewById(R.id.list);
mListView.setTransitionEffect(new FanEffect());
mListView.setItemsCanFocus(true);
//Progress bar
mListView.setEmptyView(findViewById(R.id.progressBarLoading));
Toast.makeText(getApplicationContext(), "Wyszukiwanie ofert...", Toast.LENGTH_LONG).show();
new NewThread().execute();
mAdapter = new JobListAdapter(this, jobList);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myBrowserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(mListaLinki.get(position)));
myBrowserIntent.putExtra("paramPosition", position);
startActivity(myBrowserIntent);
}
});
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
choosedOffer.add(mListaTest1.get(position).toString());
choosedLink.add(mListaLinki.get(position).toString());
Toast.makeText(getApplicationContext(), "Dodano do ulubionych!", Toast.LENGTH_SHORT).show();
return false;
}
});
}
protected void onPreExecute() {
}
public void onBackPressed() {
Intent intent = new Intent(ListviewActivity.this, MainActivity.class);
intent.putStringArrayListExtra("text", choosedOffer);
intent.putStringArrayListExtra("link", choosedLink);
setResult(RESULT_OK, intent);
finish();
}
public class NewThread extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg) {
String doURLwork = mainActiv.nazwaStanowiska;
String doURLplace = mainActiv.nazwaMiejscowosci;
Document doc, doc2;
Elements classs, lins;
String uerele;
try {
doc = (Document) Jsoup.connect("http://www.infopraca.pl/praca?q=" + doURLwork + "&lc=" + doURLplace)
.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0").get();
doc2 = (Document) Jsoup.connect("http://www.pracuj.pl/praca/" + doURLwork + ";kw/" + doURLplace + ";wp")
.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0").get();
//Oferty
jobName = doc.select("h2.p-job-title a[href]"); //Infopraca
jobName2 = doc2.select("h2.offer__list_item_link a[href]"); //pracuj.pl
//Firmy
jobNameComp = doc.select("h3.p-name.company a[href]"); //Infopraca
jobName2Comp = doc2.select("h3.offer__list_item_link a[href]"); //pracuj.pl
//Oferty pracy
//Infopraca
mListaTest1.clear();
for (Element jobNames : jobName) {
mListaTest1.add(jobNames.text() + "\n");
}
//Pracuj.pl
for (Element jobNames2 : jobName2) {
mListaTest1.add(jobNames2.text() + "\n");
}
if(mListaTest1.size()==0){
Toast.makeText(getApplicationContext(), "Zmień parametry wyszukiwania!", Toast.LENGTH_LONG).show();
}
//--------------------------------------------------
//Firmy
//Infopraca
mListaTest2.clear();
for (Element jobNames : jobNameComp) {
mListaTest2.add(jobNames.text() + "\n");
}
//Pracuj.pl
for (Element jobNames2 : jobName2Comp) {
mListaTest2.add(jobNames2.text() + "\n");
}
//Linki do ofert
//Infopraca
for (Element link : jobName) {
mListaLinki.add(link.attr("abs:href"));
}
//Pracuj.pl
for (Element link : jobName2) {
mListaLinki.add(link.attr("abs:href"));
}
//Łączenie wyników - oferta + nazwa firmy
jobList.clear();
for(int i=0; i<mListaTest1.size(); i++){
jobList.add(mListaTest1.get(i)+"\n"+mListaTest2.get(i));
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPreExecute(String result) {
}
#Override
protected void onPostExecute(String result) {
mAdapter.notifyDataSetChanged();
}
}
}
Generally, the first activity may be destroyed and recreated each time you go back to it. You might have to save list view items in activity's
onSaveInstanceState(Bundle)
method and load them again in onCreate. A simple example can be found in the first answer here
Or, you can just use fragments instead of two activities.
EDIT:
It seems like onSaveInstanceState only works when the activity is being closed by force, and it's philosophy is that onDestroy() method is not a safe place to save your data since it might not get called for various reasons.
The easiest way to do this is to use fragments instead of separate activities. The list adapter should be a member of activity and instead of opening a new activity, a fragment transaction would take place.
Using the back stack of fragment manager, the back button navigation will also be no problem and it would return the app to its initial state. Since the list is a field of the activity it can be easily shared between the fragments and it would not change due to fragment transactions.