Set database object to be deleted in android - android

I've setup a database in android for my app however I'm stuck trying to delete a object within the database.
I'd like the button within BasicButtonsCard to delete the item that has been clicked on.
For example cardX holds data ABCD while cardY hold EFGH and on clicking the delete button on cardX, it deletes the card and its data.
Help is appreciated.
Code for input field:
public class note extends DialogFragment {
EditText memoryText, memoryTitle;
public interface NewPersonDialogListener{
void onFinishAddPersonDialog(String text, String title);
}
public note(){}
public Dialog onCreateDialog(Bundle savedInstanceState){
LayoutInflater i = getActivity().getLayoutInflater();
View rootview = i.inflate(R.layout.activity_note, null);
memoryText = (EditText)rootview.findViewById(R.id.memoryText);
memoryTitle = (EditText)rootview.findViewById(R.id.memoryTitle);
AlertDialog.Builder b = new AlertDialog.Builder(getActivity());
b.setTitle("Add New Memory");
b.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String text = memoryText.getText().toString();
String title = memoryTitle.getText().toString();
NewPersonDialogListener activity = (NewPersonDialogListener)getActivity();
activity.onFinishAddPersonDialog(text, title);
}
});
b.setNegativeButton("Cancel", null);
b.setView(rootview);
return b.create();
}
}
Code that handles MainActivity in the app:
public class MainActivity extends AppCompatActivity implements note.NewPersonDialogListener{
ImageButton runCommand;
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
String[] mDrawerListItems;
MaterialListView mListView;
MemoryDataSource dataSource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
mDrawerList = (ListView)findViewById(android.R.id.list);
dataSource = new MemoryDataSource(this);
mListView = (MaterialListView) findViewById(R.id.material_listview);
generateList();
mListView.addOnItemTouchListener(new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(CardItemView cardItemView, int i) {
}
#Override
public void onItemLongClick(CardItemView cardItemView, int i) {
}
});
mDrawerListItems = getResources().getStringArray(R.array.drawer_list);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mDrawerListItems));
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
break;
case 1:
intent = new Intent(MainActivity.this, bands.class);
startActivity(intent);
break;
case 2:
intent = new Intent(MainActivity.this, memory_vault.class);
startActivity(intent);
break;
}
mDrawerLayout.closeDrawer(mDrawerList);
}
});
runCommand = (ImageButton)findViewById(R.id.runCommand);
runCommand.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
Intent i = new Intent(MainActivity.this, note.class);
startActivity(i);
*/
note noteFragment = new note();
noteFragment.show(getFragmentManager(), "tag");
}
});
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
toolbar,
R.string.drawer_open,
R.string.drawer_close){
public void onDrawerClosed(View v){
super.onDrawerClosed(v);
invalidateOptionsMenu();
syncState();
}
public void onDrawerOpened(View v){
super.onDrawerOpened(v);
invalidateOptionsMenu();
syncState();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle.syncState();
}
public void generateList(){
dataSource.open();
List<memoryModel> list = dataSource.findMemory();
for (memoryModel model : list){
BasicButtonsCard card = new BasicButtonsCard(this);
card.setTitle(model.getmemoryTitle());
card.setDescription(model.getmemoryText());
card.setBackgroundColorRes(R.color.background_material_dark);
card.setDescriptionColorRes(R.color.abc_secondary_text_material_dark);
card.setTitleColorRes(R.color.abc_secondary_text_material_dark);
card.setLeftButtonText("LEFT");
card.setRightButtonText("RIGHT");
card.setDismissible(true);
card.setOnRightButtonPressedListener(new OnButtonPressListener() {
#Override
public void onButtonPressedListener(View view, Card card) {
Intent intent = new Intent(MainActivity.this, bands.class);
startActivity(intent);
}
});
card.setOnLeftButtonPressedListener(new OnButtonPressListener() {
#Override
public void onButtonPressedListener(View view, Card card) {
}
});
mListView.add(card);
}
}
#Override
public void onResume(){
super.onResume();
}
#Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case android.R.id.home: {
if (mDrawerLayout.isDrawerOpen(mDrawerList)){
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
}
default: return super.onOptionsItemSelected(item);
}
}
#Override
public void onFinishAddPersonDialog(String text, String title) {
dataSource.open();
memoryModel model = new memoryModel();
model.setmemoryText(title);
model.setmemoryTitle(text);
dataSource.create(model);
dataSource.close();
generateList();
}
}

I will assume that you already have a RecyclerView with a button on each row since you didn't mention that as a problem. You should have a view holder class, and in the constructor of that class you can set up your listeners.
class Holder extends RecyclerView.ViewHolder{
public Holder(View itemView){
super(itemView);
View button = itemView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int rowNumber = getPosition();
// call delete method here
}
});
}
public void bind(int index){
// ...
}
}

Solved the issue of deleting data from the database. Since it was contained in a cardview layout with a button all I needed to do was add a onclick listener which would do the following
dataSource.deleteMemory(model.getmemoryTitle());
dataSource.deleteMemory(model.getmemoryText());
mListView.remove(card);

Related

Navigation Drawer does not respond on touch

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);
}
}

How to restore fragment states while using bottom navigation view in android?

I am trying to do restoring the fragment view state values(text view,..etc) when back from second fragment in android bottom navigation view.
MyActivity.java
public class LandingPage extends AppCompatActivity implements ProductFragment.AddToCart {
Fragment fragment;
TextView txtCart;
Button btnCart;
ItemData itemData;
ArrayList<ItemData> itemDataList;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
fragment = new ProductFragment();
loadFragment(fragment);
return true;
case R.id.nav_profile:
fragment = new ReportsFragment();
loadFragment(fragment);
return true;
case R.id.nav_logout:
LogOut();
return true;
}
return true;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing_page);
txtCart = findViewById(R.id.txt_cart);
btnCart = findViewById(R.id.btn_cartImg);
itemDataList = new ArrayList<>();
BottomNavigationView bottomNavigationView = findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
loadFragment(new ProductFragment());
}
private void loadFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
}
ProductFragment.java
public class ProductFragment extends Fragment {
private OnFragmentInteractionListener mListener;
Button btnCart1,btnCart2,btnCart3;
AddToCart addToCart;
TextView txtItem1Des,txtItem1Price,txtItem2Des,txtItem2Price,txtItem3Des,txtItem3Price;
Button btnCart1Inc,btnCart1Dec,btnCart2Inc,btnCart2Dec,btnCart3Inc,btnCart3Dec;
TextView cart1txt,cart2txt,cart3txt;
String itemDes,itemPrice,itemImg,itemCount;
int quantity1,quantity2,quantity3;
public ProductFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_product, container, false);
btnCart1 = view.findViewById(R.id.cart1);
txtItem1Des = view.findViewById(R.id.cart1_desc);
txtItem1Price = view.findViewById(R.id.cart1_price);
btnCart1Inc = view.findViewById(R.id.cart1Inc);
btnCart1Dec = view.findViewById(R.id.cart1Dec);
cart1txt = view.findViewById(R.id.cart1txt);
btnCart2 = view.findViewById(R.id.cart2);
txtItem2Des = view.findViewById(R.id.cart2_desc);
txtItem2Price = view.findViewById(R.id.cart2_price);
btnCart2Inc = view.findViewById(R.id.cart2Inc);
btnCart2Dec = view.findViewById(R.id.cart2Dec);
cart2txt = view.findViewById(R.id.cart2txt);
btnCart3 = view.findViewById(R.id.cart3);
txtItem3Des = view.findViewById(R.id.cart3_desc);
txtItem3Price = view.findViewById(R.id.cart3_price);
btnCart3Inc = view.findViewById(R.id.cart3Inc);
btnCart3Dec = view.findViewById(R.id.cart3Dec);
cart3txt = view.findViewById(R.id.cart3txt);
quantity1 = Integer.parseInt(cart1txt.getText().toString());
quantity2 = Integer.parseInt(cart2txt.getText().toString());
quantity3 = Integer.parseInt(cart3txt.getText().toString());
buttonInitialization();
addingToCart();
return view;
}
private void addingToCart() {
btnCart1Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity1 <= 1){
btnCart1.setVisibility(View.VISIBLE);
btnCart1Dec.setVisibility(View.INVISIBLE);
btnCart1Inc.setVisibility(View.INVISIBLE);
cart1txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(1);
}else {
quantity1 = quantity1-1;
cart1txt.setText(String.valueOf(quantity1));
addToCart.itemCount(cart1txt.getText().toString(),"1");
}
}
});
btnCart1Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity1 = quantity1+1;
cart1txt.setText(String.valueOf(quantity1));
addToCart.itemCount(cart1txt.getText().toString(),"1");
}
});
btnCart2Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity2 <= 1){
btnCart2.setVisibility(View.VISIBLE);
btnCart2Dec.setVisibility(View.INVISIBLE);
btnCart2Inc.setVisibility(View.INVISIBLE);
cart2txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(2);
}else {
quantity2 = quantity2-1;
cart2txt.setText(String.valueOf(quantity2));
addToCart.itemCount(cart2txt.getText().toString(),"2");
}
}
});
btnCart2Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity2 = quantity2+1;
cart2txt.setText(String.valueOf(quantity2));
addToCart.itemCount(cart2txt.getText().toString(),"2");
}
});
btnCart3Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity3 <= 1){
btnCart3.setVisibility(View.VISIBLE);
btnCart3Dec.setVisibility(View.INVISIBLE);
btnCart3Inc.setVisibility(View.INVISIBLE);
cart3txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(3);
}else {
quantity3 = quantity3-1;
cart3txt.setText(String.valueOf(quantity3));
addToCart.itemCount(cart3txt.getText().toString(),"3");
}
}
});
btnCart3Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity3 = quantity3+1;
cart3txt.setText(String.valueOf(quantity3));
addToCart.itemCount(cart3txt.getText().toString(),"3");
}
});
}
private void buttonInitialization() {
btnCart1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem1Price.getText().toString().trim();
itemDes = txtItem1Des.getText().toString().trim();
itemCount = cart1txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"1");
btnCart1.setVisibility(View.INVISIBLE);
btnCart1Dec.setVisibility(View.VISIBLE);
btnCart1Inc.setVisibility(View.VISIBLE);
cart1txt.setVisibility(View.VISIBLE);
}
});
btnCart2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem2Price.getText().toString().trim();
itemDes = txtItem2Des.getText().toString().trim();
itemCount = cart2txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"2");
btnCart2.setVisibility(View.INVISIBLE);
btnCart2Dec.setVisibility(View.VISIBLE);
btnCart2Inc.setVisibility(View.VISIBLE);
cart2txt.setVisibility(View.VISIBLE);
}
});
btnCart3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem3Price.getText().toString().trim();
itemDes = txtItem3Des.getText().toString().trim();
itemCount = cart3txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"3");
btnCart3.setVisibility(View.INVISIBLE);
btnCart3Dec.setVisibility(View.VISIBLE);
btnCart3Inc.setVisibility(View.VISIBLE);
cart3txt.setVisibility(View.VISIBLE);
}
});
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
addToCart = (AddToCart) context;
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
public interface AddToCart{
void cartCount(String item_img,String item_price,String item_desc,String item_count,String item_pos);
void removeItemFromCart(int removeItem);
void itemCount(String itemCount,String position);
}
}
Here in ProductFragment iam going to add values to text view. When i was coming from ReportFragment the view values are going to be cleared in ProductFragment.
I would consider doing that in two steps:
save fragment instance instead of re-creating a new one every time
private ProductFragment productFragment;
private ReportsFragment reportsFragment;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
if(productFragment == null)
productFragment = new ProductFragment();
loadFragment(productFragment);
break;
case R.id.nav_profile:
if(reportsFragment == null)
reportsFragment = new ReportsFragment();
loadFragment(reportsFragment);
break;
case R.id.nav_logout:
LogOut();
return true;
}
return true;
}
};
referring to this question/answer, you should implement in your fragment both void onSaveInstanceState(final Bundle outState) and void onActivityCreated(Bundle savedInstanceState)
In that way you will surely keep the instance of your fragment instead of creating a new one every time (new MyFragment() will always re-create it). In addition, saving your views state in onSaveInstanceState and restoring it in your onActivityCreate, will allow you to keep your views/values.
I wrote that by hand without a compiler, so it might not be perfect.
let me know if you need further information.
Good luck
I am using this solution and it works for me.
You should see my detailed answer to a similar question. I hope it will solve your problem.

Unable to attach Activity interface to Fragment. Getting NullPointerException

I'm writing an app for school and everything works fine when I run the app in the emulator.
The problem is when I connect my phone through usb and run the app on the phone.
Whenever I do something which requires the mListener (in any fragment in the whole app), I get a nullpointerexception on my mListener.
I have searched but have not found a solution or similar problem.
I have the problem in all of my fragments, but I will just show 1 fragment here:
Code of a fragment:
public class QuizFragment extends Fragment {
private OnFragmentQuizInteractionListener mListener;
List<Vraag> quesList;
int qid=0;
Vraag currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc;
Button butNext;
TextView txtResult;
Button btnToonAntwoord;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getActivity().setTitle("Quiz");
final View view = inflater.inflate(R.layout.quiz_layout, container, false);
//btnStart = (Button) getActivity().findViewById(R.id.btnStart);
//btnStart.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// mListener.initQuiz();
// }
//});
//reset the score to 0
mListener.resetScore();
qid=0;
QuizDbHelper db=new QuizDbHelper(view.getContext());
quesList=db.getAllQuestions();
currentQ=quesList.get(qid);
txtQuestion=(TextView) view.findViewById(R.id.textView1);
rda=(RadioButton)view.findViewById(R.id.radio0);
rdb=(RadioButton)view.findViewById(R.id.radio1);
rdc=(RadioButton)view.findViewById(R.id.radio2);
//zet de radiobuttons klaar om geklikt te worden.
rda.setEnabled(true);
rdb.setEnabled(true);
rdc.setEnabled(true);
butNext=(Button)view.findViewById(R.id.btnNext);
btnToonAntwoord=(Button)view.findViewById(R.id.btnToonAntwoord);
txtResult = (TextView) view.findViewById(R.id.resultTextview);
setQuestionView(view);
setOnClickListeners(view);
return view;
}
private void setOnClickListeners(View v){
final View thisView = v;
butNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(qid<8){
//zet de radiobuttons klaar om geklikt te worden.
rda.setEnabled(true);
rdb.setEnabled(true);
rdc.setEnabled(true);
//zet het resultaat terug op niets
txtResult.setText("");
//Wanneer het goed is, voeg 1 bij de score bij
RadioGroup grp = (RadioGroup) thisView.findViewById(R.id.radioGroup1);
RadioButton answer = (RadioButton) thisView.findViewById(grp.getCheckedRadioButtonId());
if (currentQ.getANSWER().equals(checkChecked(answer.getId()))) {
mListener.incrementScore();
}
currentQ=quesList.get(qid);
setQuestionView(thisView);
}else{
//ga naar het eindscherm met het resultaat.
mListener.navigeerEindscore();
}
}
});
btnToonAntwoord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp = (RadioGroup) thisView.findViewById(R.id.radioGroup1);
RadioButton answer = (RadioButton) thisView.findViewById(grp.getCheckedRadioButtonId());
//toon de juiste boodschap aan de hand van het antwoord die gegeven is.
if (currentQ.getANSWER().equals(checkChecked(answer.getId()))) {
txtResult.setText(currentQ.getGoedeFeedback());
}else{
txtResult.setText(currentQ.getSlechteFeedback());
}
//zet de radiobuttons klaar om geklikt te worden.
rda.setEnabled(false);
rdb.setEnabled(false);
rdc.setEnabled(false);
}
});
}
private String checkChecked(int id) {
if(id == R.id.radio0){
return "A";
}else if(id == R.id.radio1){
return "B";
}else{
return "C";
}
}
private void setQuestionView(View v)
{
txtQuestion.setText(currentQ.getQUESTION());
rda.setText(currentQ.getOPTA());
rdb.setText(currentQ.getOPTB());
rdc.setText(currentQ.getOPTC());
qid++;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentQuizInteractionListener) {
mListener = (OnFragmentQuizInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnResultFragmentInteractionListener");
}
}
public interface OnFragmentQuizInteractionListener {
void incrementScore();
void resetScore();
void navigeerEindscore();
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
mainActivity:
{
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,DashboardFragment.OnFragmentLoginInteractionListener,LoginFragment.OnFragmentLoginInteractionListener, RegistratieFragment.OnFragmentRegistratieInteractionListener,QuizFragment.OnFragmentQuizInteractionListener, ResultFragment.OnResultFragmentInteractionListener{
private FragmentManager fragmentManager;
public int quizScore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.onActivityCreateSetTheme(this);
setContentView(R.layout.activity_main);
quizScore = 0;
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(this);
String themeName = pref.getString("Theme1", "Blauw");
//toolbar ophalen
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
Log.i("huidige preferences", themeName);
//toolbar instellen
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
/**if (themeName.equals("Blauw")) {
setTheme(R.style.AppTheme_blauw);
Log.i("MyActivity", "in blauw");
} else if (themeName.equals("Groen")) {
this.setTheme(R.style.AppTheme_groen);
Log.i("MyActivity", "in groen");
} else if (themeName.equals("Roze")) {
this.setTheme(R.style.AppTheme_roze);
Log.i("MyActivity", "in roze");
}**/
fragmentManager = getFragmentManager();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
fragmentManager.beginTransaction().replace(R.id.content_frame, new DashboardFragment()).commit();
}
//backknop werkt hoe hij moet werken
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
int count = getFragmentManager().getBackStackEntryCount();
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
if (count == 0) {
super.onBackPressed();
//additional code
} else {
getFragmentManager().popBackStack();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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.
switch (item.getItemId()) {
case R.id.action_settings:
fragmentManager.beginTransaction().replace(R.id.content_frame, new InstellingenFragment()).commit();
return true;
}
return super.onOptionsItemSelected(item);
}
//region dashboard
public void MijnProfielClicked() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new MijnProfielFragment())
.addToBackStack("MijnProfiel")
.commit();
}
public void AlarmClicked() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new PilAlarmFragment())
.addToBackStack("Pilalarm")
.commit();
}
public void KalenderClicked() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new MenstruatieFragment())
.addToBackStack("Kalender")
.commit();
}
//endregion
//Navigatiemethodes LOGIN
public void Login() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new DashboardFragment())
.addToBackStack("Login")
.commit();
}
//Navigatiemethodes REGISTREREN
public void Registreer() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new DashboardFragment())
.addToBackStack("Registreer")
.commit();
}
public void Annuleren() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new LoginFragment())
.addToBackStack("Registreer")
.commit();
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
switch (item.getItemId()) {
case R.id.nav_dashboard_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new DashboardFragment()).addToBackStack("dashboard").commit();
break;
case R.id.nav_mijnprofiel_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new MijnProfielFragment()).addToBackStack("mijnprofiel").commit();
break;
case R.id.nav_categorieen_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new CategorieenFragment()).addToBackStack("categorieen").commit();
break;
case R.id.nav_pilalarm_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new PilAlarmFragment()).addToBackStack("pilalarm").commit();
break;
case R.id.nav_menstruatie_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new MenstruatieFragment()).addToBackStack("menstruatie").commit();
break;
case R.id.nav_quiz_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new QuizFragment()).addToBackStack("quiz").commit();
break;
case R.id.nav_instellingen_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new InstellingenFragment()).addToBackStack("instellingen").commit();
break;
case R.id.nav_partners_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new PartnersFragment()).addToBackStack("partners").commit();
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//region Partner onclick listeners
public void onVivesPartner_clicked(View view) {
// Perform action on click
goToUrl("http://www.vives.be/");
}
public void onSensoaPartner_clicked(View view) {
// Perform action on click
goToUrl("http://www.sensoa.be/");
}
public void onUgentPartner_clicked(View view) {
// Perform action on click
goToUrl("http://www.ugent.be/");
}
public void onUCCVPartner_clicked(View view) {
// Perform action on click
goToUrl("http://www.ucvvgent.be/nl/");
}
public void onOnePartner_clicked(View view) {
// Perform action on click
goToUrl("http://www.one.be//");
}
private void goToUrl(String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
//endregion
//region quizfragment
#Override
public void incrementScore() {
quizScore++;
}
#Override
public void resetScore() {
quizScore = 0;
}
#Override
public void navigeerEindscore() {
fragmentManager.beginTransaction().replace(R.id.content_frame, new ResultFragment()).commit();
}
#Override
public int getScore() {
return quizScore;
}
//endregion
The error I'm getting (doesn't matter what fragment, it's always nullpointerexception on the mlistener)
java.lang.NullPointerException: Attempt to invoke interface method 'void be.vives.pwo_kinderwens.Quiz.QuizFragment$OnFragmentQuizInteractionListener.resetScore()' on a null object reference
at be.vives.pwo_kinderwens.Quiz.QuizFragment.onCreateView(QuizFragment.java:55)
at android.app.Fragment.performCreateView(Fragment.java:2053)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:894)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.app.BackStackRecord.run(BackStackRecord.java:834)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1452)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:447)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
The problem is that your mListener is not implemented.
I would try the following:
I would add a method to QuizFragment like :
public void setFragmentQuizInteractionListener(OnFragmentQuizInteractionListener mListener)
{
this.mListener = mListener;
}
And then
case R.id.nav_quiz_layout:
QuizFragment quizFragment = new QuizFragment();
quizFragment.setFragmentQuizInteractionListener(this);
fragmentManager.beginTransaction().replace(R.id.content_frame, quizFragment ).addToBackStack("quiz").commit();
break;
And drop the onAttach() method.
Probably not the nicest way but worth a try.
You need to override
public void onAttach (Activity activity)
instead of
public void onAttach (Context context)
The latter was included in API level 23, so previous versions of Android will not call it.
See onAttach (Activity activity)
Use onAttach method in Fragment. Check Fragment Lifecycle
Context context;
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context=context;
}

Moving the Drawer Toggle From Left To Right in Action Bar

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) {
}
}
}

Extended navigation drawer can't change activity. What's going on?

I have created a BaseActivity class with navigation drawer and the other class CheckList extends the BaseActivity to have a navigation drawer.
In BaseActivity, I can change the activity to CheckList through navigation drawer.
But in CheckList. Even I can see the drawer, it is not work for changing class.
BaseActivity:
public class BaseActivity extends AppCompatActivity{
protected DrawerLayout drawerLayout;
protected ListView drawerList;
protected ActionBarDrawerToggle drawerToggle;
protected CharSequence mDrawerTitle;
protected CharSequence mTitle;
protected String[] drawer_menu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initActionBar();
initDrawer();
initDrawerList();
}
protected void initActionBar() {
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_drawer);
}
protected void initDrawer() {
setContentView(R.layout.drawer);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
drawerList = (ListView)findViewById(R.id.left_drawer);
mTitle = mDrawerTitle = getTitle();
drawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getSupportActionBar().setTitle(mTitle);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mDrawerTitle);
}
};
drawerToggle.syncState();
drawerLayout.setDrawerListener(drawerToggle);
}
protected void initDrawerList() {
drawer_menu = this.getResources().getStringArray(R.array.drawer_menu);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.drawer_list_item, drawer_menu);
drawerList.setAdapter(adapter);
drawerList.setOnItemClickListener(new DrawerItemClickListener());
}
//respond when click the ic_drawer
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
protected class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
protected void selectItem(int position) {
//Fragment fragment = null;
switch (position) {
case 0:
break;
case 1:
Intent main = new Intent();
main.setClass(getApplicationContext(), MainActivity.class);
startActivity(main);
finish();
break;
case 2:
Intent checklist = new Intent();
checklist.setClass(getApplicationContext(), CheckList.class);
startActivity(checklist);
finish();
break;
default:
break;
}
/*FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();*/
drawerList.setItemChecked(position, true);
setTitle(drawer_menu[position]);
drawerLayout.closeDrawer(drawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}
CheckList:
public class CheckList extends BaseActivity implements OnClickListener {
Button addBtn;
ListView listView;
ArrayList<String> checkListItem;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.checklist, drawerLayout);
addBtn = (Button)findViewById(R.id.addBtn);
listView = (ListView)findViewById(R.id.listItems);
addBtn.setOnClickListener(this);
checkListItem = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, checkListItem);
listView.setAdapter(adapter);
checkListItem.add(getString(R.string.cl_passport));
checkListItem.add(getString(R.string.cl_charger));
checkListItem.add(getString(R.string.cl_camera));
registerForContextMenu(listView);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.checklist_contextmenu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
switch (item.getItemId()) {
case R.id.cl_contextmenu_delete:
checkListItem.remove(info.position);
adapter.notifyDataSetChanged();
return true;
case R.id.cl_contextmenu_edit:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(CheckList.this);
alertDialog.setTitle(getString(R.string.cl_editItem));
final EditText edit = new EditText(this);
edit.setText(checkListItem.get(info.position));
edit.setSelectAllOnFocus(true);
alertDialog.setView(edit);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
checkListItem.set(info.position, edit.getText().toString());
adapter.notifyDataSetChanged();
}
});
alertDialog.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.create();
alertDialog.show();
return true;
default:
return super.onContextItemSelected(item);
}
}
#Override
public void onClick(View v) {
if(v==this.addBtn) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(CheckList.this);
alertDialog.setTitle(getString(R.string.cl_input));
final EditText checkListInput = new EditText(this);
alertDialog.setView(checkListInput);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
checkListItem.add(checkListInput.getText().toString());
}
});
alertDialog.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.create();
alertDialog.show();
}
}
}
I can't simply change the class to MainActivity in CheckList. But in BaseActivity, I can change to both MainActivity and CheckList.
Many thanks !!
Updated
This is my drawer.xml file
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Add content here -->
</FrameLayout>
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:layout_width="260dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#e5e5e5"
android:dividerHeight="1dp"
android:background="#d6d6d6"/>
</android.support.v4.widget.DrawerLayout>
You're unable to click on the drawer's list items because you're inflating the CheckList Activity's layout directly into the DrawerLayout of the BaseActivity. This is causing it to be "on top" of all of the DrawerLayout's child Views, and your clicks won't propagate through to the drawer ListView underneath. Instead, you want to inflate CheckList's layout into the content_frame FrameLayout within the DrawerLayout.
In the BaseActivity class add a protected field for the FrameLayout, and initialize it just like the other Views.
public class BaseActivity extends AppCompatActivity {
protected DrawerLayout drawerLayout;
protected ListView drawerList;
protected FrameLayout contentFrame;
...
protected void initDrawer() {
setContentView(R.layout.drawer);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.left_drawer);
contentFrame = (FrameLayout) findViewById(R.id.content_frame);
...
}
}
Then change the inflate() call in CheckList as follows:
getLayoutInflater().inflate(R.layout.checklist, contentFrame);

Categories

Resources