Android - Navigation Drawer to implement activity changing - java

I've been reading a lot of questions and tutorials in regards to implementing a Navigation Drawer to change between Fragments. For this question, these implementations are not wanted as I wish to change from one activity, to the next.
I've implemented a custom Sidebar Adaptor with extends ArrayAdapter<String>. This allows to to implement my own styling to my navigation drawer. See the first code snippet below.
public class SidebarAdaptor extends ArrayAdapter<String> {
Context context;
int layoutResourceId;
String data[] = null;
public SidebarAdaptor(Context context, int layoutResourceId, String[] data)
{
// Initiate the ArrayAdapter
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ControlHolder holder;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ControlHolder();
TextView control = (TextView)row.findViewById(R.id.textItem);
holder.control = control;
row.setTag(holder);
}
else
{
holder = (ControlHolder)row.getTag();
}
String text = data[position];
holder.control.setText(text);
return row;
}
static class ControlHolder
{
TextView control;
}
}
This adapter is then set in the onCreate function in my MainActivity class. See below.
private void customiseSidebar() {
SidebarAdaptor sidebarAdaptor = new SidebarAdaptor(
this,
R.layout.side_bar_custom_row,
new String[]{"Login", "Offline Access", "Register", "Forgotten Password"}
);
ListView listView1 = (ListView) findViewById(R.id.navList);
listView1.setAdapter(sidebarAdaptor);
listView1.setOnItemClickListener(new DrawerItemClickListener());
}
The DrawerItemClickListener class then holds what activity to switch to once the user pressed any of the options in the Navigation Drawer. See the final code snippet below.
package ap.classes;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import ap.ForgottenPassword;
import apMainActivity;
import ap.OfflineAccess;
import ap.RegisterAccount;
public class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
/** Swaps fragments in the main content view */
private void selectItem(int position) {
switch(position)
{
case 0:
Intent intent = new Intent(MainActivity.this, OfflineAccess.class);
startActivity(intent);
break;
case 1:
Intent intent = new Intent(MainActivity.this, RegisterAccount.class);
startActivity(intent);
break;
case 2:
Intent intent = new Intent(MainActivity.this, ForgottenPassword.class);
startActivity(intent);
break;
}
}
Now I seem to be having three quite substantial issues:
The first being the following error message: MainActivity is not an enclossing class
The second states that it; Cannont resolve method startActivity in android.content.Intent
The final issue is, as soon as I click anything in the NavigationDrawer, the drawer then closes without any keypresses being registered.
Thank you Stackoverflow.

First fix first two issues:
The first being the following error message: MainActivity is not an enclossing class
The second states that it; Cannont resolve method startActivity in android.content.Intent
According to code you provided you are not in the scope of the Activity class when making call
Intent intent = new Intent(MainActivity.this, OfflineAccess.class);
startActivity(intent);
above tells compiler to call method DrawerItemClickListener.startActivity(Intent intent), and there is no such method. Instead you should pass instance of an activity and call its startActivty method.
Second one MainActivity is not an enclossing class error is thrown because of usage MainActivity.this instead of passing instance of context.
To sum up you could do:
public class DrawerItemClickListener implements ListView.OnItemClickListener {
private Activity mActivity;
public DrawerItemClickListener(Activity activity){
mActivity = activity;
}
/** Swaps fragments in the main content view */
private void selectItem(int position) {
switch(position)
{
case 0:
Intent intent = new Intent(mActivity, OfflineAccess.class);
mActivity.startActivity(intent);
break;
/.../
}
}

Yes i had faced similar problem.While Fragments with navigation drawer it will be easy but using Activity. You must create a Custom Navigation Drawer. I give my idea.enter code here
public class DrawerItemClickListener extends AppCompatActivity{
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
private List<DrawerList> drawerListList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentView());
drawerListList = new ArrayList<>();
mDrawerList = (ListView) findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
}
#Override
protected void onPostResume() {
super.onPostResume();
}
protected abstract int getContentView();
private void addDrawerItems() {
drawerListList.add(new DrawerList("1", R.drawable.1));
drawerListList.add(new DrawerList("2", R.drawable.2));
drawerListList.add(new DrawerList("3", R.drawable.3));
drawerListList.add(new DrawerList("4", R.drawable.4));
drawerListList.add(new DrawerList("5", R.drawable.5));
CustomDrawerAdapter adapter = new CustomDrawerAdapter(this, R.layout.list_view_menu, drawerListList);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (id == 0) {
intent = new Intent(DrawerItemClickListener .this, FirstActivity.class);
startActivity(intent);
onDrawerClose();
} else if (id == 1) {
intent = new Intent(DrawerItemClickListener .this, SecondActivity.class);
startActivity(intent);
onDrawerClose();
} else if (id == 2) {
intent = new Intent(DrawerItemClickListener .this, ThirdActivity.class);
startActivity(intent);
onDrawerClose();
} else if (id == 3) {
intent = new Intent(DrawerItemClickListener .this, FouthActivity.class);
startActivity(intent);
onDrawerClose();
}
}
}
});
}
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("Navigation!");
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);
}
public void onDrawerClose() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
onBackPressed();
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#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();
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And Custom Adapter is below
public class CustomDrawerAdapter extends ArrayAdapter<DrawerList> {
private Context context;
private List<DrawerList> drawerItemList;
private int layoutResID;
public CustomDrawerAdapter(Context context, int layoutResourceID, List<DrawerList> listItems) {
super(context, layoutResourceID, listItems);
this.context = context;
this.drawerItemList = listItems;
this.layoutResID = layoutResourceID;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
DrawerItemHolder drawerHolder;
View view = convertView;
if (view == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
drawerHolder = new DrawerItemHolder();
view = inflater.inflate(layoutResID, parent, false);
drawerHolder.ItemName = (TextView) view.findViewById(R.id.drawer_itemName);
drawerHolder.icon = (ImageView) view.findViewById(R.id.drawer_icon);
view.setTag(drawerHolder);
} else {
drawerHolder = (DrawerItemHolder) view.getTag();
}
DrawerList dItem = this.drawerItemList.get(position);
drawerHolder.icon.setImageDrawable(view.getResources().getDrawable(dItem.getMenuImage()));
drawerHolder.ItemName.setText(dItem.getMenuName());
return view;
}
private static class DrawerItemHolder {
TextView ItemName;
ImageView icon;
}
}
And you extend it from each activity like
public class FirstActivity extends DrawerItemClickListener {
..
}
And also Listview Added in each xml layout.
Hope It will be helpful.

Related

Try to pass variable information from a listview to a new activity

I am new to Android application programming and I have been struggling for several days now to pass information from an item in a listview on a click. I am posting what I have done to this point here.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private LeagueAdapter mLeagueAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLeagueAdapter = new LeagueAdapter();
final ListView listLeague = (ListView) findViewById(R.id.listView);
listLeague.setAdapter(mLeagueAdapter);
// Handle clicks on the ListView
listLeague.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int whichItem, long id) {
/*
Create a temporary League
Which is a reference to the League
that has just been clicked
*/
// Create a new dialog window
//DialogShowLeague dialog = new DialogShowLeague();
// Send in a reference to the League to be shown
//dialog.sendLeagueSelected(tempLeague);
// Show the dialog window with the League in it
//dialog.show(getFragmentManager(), "");
String selected = ListView[whichItem];
Intent i = new Intent(getApplicationContext(), BowlersActivity.class);
i.putExtra("name", selected);
startActivity(i);
}
});
}
public void createNewLeague(League n){
mLeagueAdapter.addLeague(n);
}
#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.action_addLeague) {
DialogNewLeague dialog = new DialogNewLeague();
dialog.show(getFragmentManager(), "");
return true;
}
return super.onOptionsItemSelected(item);
}
public class LeagueAdapter extends BaseAdapter {
List<League> leagueList = new ArrayList<League>();
#Override
public int getCount() {
return leagueList.size();
}
#Override
public League getItem(int whichItem) {
// Returns the requested league
return leagueList.get(whichItem);
}
#Override
public long getItemId(int whichItem) {
// Method used internally
return whichItem;
}
#Override
public View getView(
int whichItem, View view, ViewGroup viewGroup) {
/*
Prepare a list item to show our data
The list item is contained in the view parameter
The position of the data in our ArrayList is contained
in whichItem parameter
*/
// Has view been inflated already
if(view == null){
// No. So do so here
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.single_league_list_item, viewGroup,false);
}// End if
// Grab a reference to all our TextView and ImageView widgets
TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
// Hide any ImageView widgets that are not relevant
League tempLeague = leagueList.get(whichItem);
// Add the text to the heading and description
txtTitle.setText(tempLeague.getTitle());
return view;
}
public void addLeague(League n){
leagueList.add(n);
notifyDataSetChanged();
}
}
}
DialogNewLeague.java
public class DialogNewLeague extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_new_league, null);
final EditText editTitle = (EditText) dialogView.findViewById(R.id.editTitle);
Button btnCancel = (Button) dialogView.findViewById(R.id.btnCancelLeague);
Button btnOK = (Button) dialogView.findViewById(R.id.btnAddLeague);
builder.setView(dialogView).setMessage("Add New mLeague");
btnCancel.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
// Handle the OK button
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create a new note
League newLeague = new League();
// Set its variables to match the users entries on the form
newLeague.setTitle(editTitle.getText().toString());
// Get a reference to MainActivity
MainActivity callingActivity = (MainActivity) getActivity();
// Pass newNote back to MainActivity
callingActivity.createNewLeague(newLeague);
// Quit the dialog
dismiss();
}
});
return builder.create();
}
}
League.java
package rvogl.ca.mydialog;
public class League {
private String mLeague;
public String getTitle() {
return mLeague;
}
public void setTitle(String mLeague) {
this.mLeague = mLeague;
}
}
BowlersActivty.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class BowlersActivity extends AppCompatActivity {
League mLeague;
String title;
String editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bowlers);
Bundle extras = getIntent().getExtras();
String name = extras.getString("name");
editText.setText(name);
}
}
I have been through almost all the posts on this site that I can find and I have tried several of them without any success.
At this point now the app just crashes when I click on an item in the league listview.
Any suggests and advice on how to accomplish this would be appreciated.
I am able to get the information to an Alert Dialog using the following:
DialogShowLeague
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class DialogShowLeague extends DialogFragment {
League mLeague;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_show_league, null);
TextView txtTitle = (TextView) dialogView.findViewById(R.id.txtTitle);
txtTitle.setText(mLeague.getTitle());
Button btnOK = (Button) dialogView.findViewById(R.id.btnOK);
builder.setView(dialogView).setMessage("Your mLeague");
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
return builder.create();
}
public void sendLeagueSelected(League leagueSelected) {
mLeague = leagueSelected;
}
}
Is it not possible to accomplish this using something similar. I just don't know what to replace dialogView with.
You can pass value on listview click like the code below. Implement Serializable interface in your model class i.e League
listLeague.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override public void onItemClick(AdapterView<?> adapter, View view, int pos, long id) {
League selected = (League)adaper.getItemAtPosition(pos);
Intent i = new Intent(getApplicationContext(), BowlersActivity.class);
i.putExtra("name", (Serializable)selected);
startActivity(i);
}
});
Edit
Replace your model class with this
public class League implement Serializable {
private String mLeague;
public String getTitle() {
return mLeague;
}
public void setTitle(String mLeague) {
this.mLeague = mLeague;
}
}
Get data on second activity like this
String name = extras.getSerializableExtra("name").getTitle();
I have managed to figure this out using the following code:
MainActivity
mLeagueAdapter = new LeagueAdapter();
final ListView listLeague = (ListView) findViewById(R.id.listView);
listLeague.setAdapter(mLeagueAdapter);
listLeague.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int pos, long id) {
String leagueName = mLeagueAdapter.getItem(pos).getTitle();
Intent myIntent = new Intent(getBaseContext(), BowlersActivity.class);
myIntent.putExtra("value1", leagueName);
startActivity(myIntent);
}
});
In my second Activity BowlersActivity.java
String savedExtra = getIntent().getStringExtra("value1");
TextView myText = (TextView) findViewById(R.id.tvLeagueName);
myText.setText(savedExtra);
My problem was that I was attempting to get the league name from an empty variable "selected" Once I got the position of the League that I was clicking on in the list view by using the my mLeagueAdapter, passing it on by .putExtra was no longer an issue.
#Fazal Hussain thank-you so much for all your patience and assistance it was greatly appreciated.

Fragment "disappears" after opening new fragment and then coming back

This is kind of hard to explain so I took screenshots of my problem.
So this is my MainActivity.java
I open the navigation drawer and click on Milestones which will bring me to Milestones.java
Here I am at Milestones.java fragment...
working fine for now...
Just how I want it to look.
But when we leave Milestones and go anywhere else and come back it will be messed up. So I will go to Kick Counter.
Here I am in my KickCounter.java fragment
Open navigation drawer and going back to Milestones...
So right now I have fragment Months0Through6 open with Milestones fragment. Some times Months0Through6 and Month12Plus fragments does not show up right away after coming back some times it does. What is always messed up at this point is the Months6Through12 fragment will never display again unless you restart the app. Also swapping between the three fragments is laggy after coming back but never on first view.
Here it is. Where did it go?
youtube video: https://www.youtube.com/watch?v=6yMYcluvqbs
Get Source Here: https://github.com/delaroy/RecyclerViewFragment
I got my code from this youtube video which is almost exactly identical but his MainActivity (which I made into my Milestones fragment) is an activity whereas I used a fragment so I was thinking that might have something to do with my problem.
Milestones.java
public class Milestones extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public Milestones() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Milestones.
*/
// TODO: Rename and change types and number of parameters
public static Milestones newInstance(String param1, String param2) {
Milestones fragment = new Milestones();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_milestones, container, false);
Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
ViewPager viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
//dont know if this will work
PagerAdapter pagerAdapter = new PagerAdapter(getFragmentManager(), getContext());
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = (TabLayout) rootView.findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
for(int i = 0; i < tabLayout.getTabCount(); i++){
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
// Inflate the layout for this fragment
return rootView;
}
// not boiler plate
#Override
public void onResume() {
super.onResume();
}
// probably just adding extra menu dont need it
/*#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
*/
//not boilerplate
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id == R.id.action_settings){
return true;
}
return super.onOptionsItemSelected(item);
}
//not boilerplate
class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[]{"0-6 Months", "6-12 Months", "12+ Months"};
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Months0Through6();
case 1:
return new Months6Through12();
case 2:
return new Months12Plus();
}
return null;
}
#Override
public CharSequence getPageTitle(int position){
return tabTitles[position];
}
public View getTabView(int position){
View tab = LayoutInflater.from(getContext()).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
MilestonesAdapter.java
public class MilestonesAdapter extends RecyclerView.Adapter<MilestonesAdapter.MyViewHolder> {
private String[] mDataset;
public static class MyViewHolder extends RecyclerView.ViewHolder{
public CardView mCardView;
public TextView mTextView;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_text);
}
}
public MilestonesAdapter(String[] myDataset){
mDataset = myDataset;
}
#Override
public MilestonesAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position){
holder.mTextView.setText(mDataset[position]);
}
#Override
public int getItemCount() { return mDataset.length; }
Just posting Months0Through6.java because the other two are exactly the same just different strings.
public class Months0Through6 extends android.support.v4.app.Fragment {
public Months0Through6() {
// Required empty public constructor
}
#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 rootView = inflater.inflate(R.layout.fragment_blank, container, false);
RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
rv.setHasFixedSize(true);
MilestonesAdapter adapter = new MilestonesAdapter(new String[]{"Month 0 stuff", "Example Two", "Example Three", "Example Four", "Example Five" , "Example Six" , "Example Seven"});
rv.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
return rootView;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity
implements KickCounter.OnFragmentInteractionListener, MommyMetrics.OnFragmentInteractionListener, Milestones.OnFragmentInteractionListener, NavigationView.OnNavigationItemSelectedListener {
Intent shareIntent;
String sharetext = "Hey check out mommy-info here at http://www.mommy-info.com";
private WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Connects to www.mommy-info.com
myWebView = (WebView)findViewById(R.id.webView_ID);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.mommy-info.com");
myWebView.setWebViewClient(new WebViewClient());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
//back button in navigation drawer logic
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
//back button in webView logic
else if(myWebView.canGoBack()){
myWebView.goBack();
}
else if(getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
}
else{
super.onBackPressed();
}
}
#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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.kick_counter_ID) {
KickCounter kickCounter = new KickCounter();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.full_screen_ID, kickCounter).addToBackStack(null).commit();
} else if (id == R.id.nav_mommy_metrics) {
MommyMetrics mommyMetrics = new MommyMetrics();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.full_screen_ID, mommyMetrics).addToBackStack(null).commit();
} else if (id == R.id.nav_milestones) {
Milestones milestones = new Milestones();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.full_screen_ID, milestones).addToBackStack(null).commit();
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "my app");
shareIntent.putExtra(Intent.EXTRA_TEXT, sharetext);
startActivity(Intent.createChooser(shareIntent, "share via"));
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
In Fragments you need to use getChildFragmentManager(), You are using same Fragment manager in the fragments as in Activity. Hope this will help

RecycleView on Fragment using Custom Adapter with Retrofit

public class AgentAdapter extends RecyclerView.Adapter<AgentAdapter.CustomViewHolder> {
private List<Agent> agentList;
private Context mContext;
public AgentAdapter(Context context, List<Agent> agentList) {
this.agentList= agentList;
this.mContext = context;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.agent_row, null);
CustomViewHolder viewHolder = new CustomViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
final Agent agent = agentList.get(i);
//Setting text view title
customViewHolder.textViewAgentName.setText(agent.getAgentName());
customViewHolder.textViewAgentPhone.setText(agent.getAgentPhone());
customViewHolder.textViewAgentRegion.setText(agent.getRegion());
customViewHolder.textViewAgentStatus.setText(agent.getAgentStatus());
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemClickListener.onItemClick(agent);
}
};
customViewHolder.textViewAgentName.setOnClickListener(listener);
}
#Override
public int getItemCount() {
return (null != agentList ? agentList.size() : 0);
}
public void updateAnswers(List<Agent>agent ) {
agentList = agent;
notifyDataSetChanged();
}
class CustomViewHolder extends RecyclerView.ViewHolder {
protected TextView textViewAgentName;
protected TextView textViewAgentPhone;
protected TextView textViewAgentRegion;
protected TextView textViewAgentStatus;
public CustomViewHolder(View view) {
super(view);
this.textViewAgentName = (TextView) view.findViewById(R.id.textAgentName);
this.textViewAgentPhone= (TextView) view.findViewById(R.id.textAgentPhone);
this.textViewAgentRegion = (TextView) view.findViewById(R.id.textAgentRegion);
this.textViewAgentStatus = (TextView) view.findViewById(R.id.textAgentStatus);
}
}
private OnItemClickListener onItemClickListener;
public OnItemClickListener getOnItemClickListener() {
return onItemClickListener;
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
That's my fragment and this is my Adapter
public class AgentAdapter extends RecyclerView.Adapter<AgentAdapter.CustomViewHolder> {
private List<Agent> agentList;
private Context mContext;
public AgentAdapter(Context context, List<Agent> agentList) {
this.agentList= agentList;
this.mContext = context;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.agent_row, null);
CustomViewHolder viewHolder = new CustomViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
final Agent agent = agentList.get(i);
//Setting text view title
customViewHolder.textViewAgentName.setText(agent.getAgentName());
customViewHolder.textViewAgentPhone.setText(agent.getAgentPhone());
customViewHolder.textViewAgentRegion.setText(agent.getRegion());
customViewHolder.textViewAgentStatus.setText(agent.getAgentStatus());
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemClickListener.onItemClick(agent);
}
};
customViewHolder.textViewAgentName.setOnClickListener(listener);
}
#Override
public int getItemCount() {
return (null != agentList ? agentList.size() : 0);
}
public void updateAnswers(List<Agent>agent ) {
agentList = agent;
notifyDataSetChanged();
}
class CustomViewHolder extends RecyclerView.ViewHolder {
protected TextView textViewAgentName;
protected TextView textViewAgentPhone;
protected TextView textViewAgentRegion;
protected TextView textViewAgentStatus;
public CustomViewHolder(View view) {
super(view);
this.textViewAgentName = (TextView) view.findViewById(R.id.textAgentName);
this.textViewAgentPhone= (TextView) view.findViewById(R.id.textAgentPhone);
this.textViewAgentRegion = (TextView) view.findViewById(R.id.textAgentRegion);
this.textViewAgentStatus = (TextView) view.findViewById(R.id.textAgentStatus);
}
}
private OnItemClickListener onItemClickListener;
public OnItemClickListener getOnItemClickListener() {
return onItemClickListener;
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
and this is my MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
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();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//add this line to display menu1 when the activity is loaded
displaySelectedScreen(R.id.nav_menu2);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
//initializing the fragment object which is selected
switch (itemId) {
case R.id.nav_menu1:
fragment = new caseFragment();
break;
case R.id.nav_menu2:
fragment = new testFragment();
break;
}
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
when i tried to open my fragment, the app crashed and the logcat is blank.
previously i could show my json data from activity but now when i tried to use fragment instead, it crashed.
Im using java and android studio.
Anyone know why? Thx in advance.

NoClassDefFoundError error in Android Slider

I am creating an app with a slider and it was working fine and then I added another view and implemented an OnClickListener() for the newly added Views after that I am getting the following error when I open my app
Process: com.spintum.preexam, PID: 31905
java.lang.NoClassDefFoundError: com.spintum.preexam.CustomList$DrawerItemHolder
at com.spintum.preexam.CustomList.getView(CustomList.java:38)
at android.widget.AbsListView.obtainView(AbsListView.java:2338)
at android.widget.ListView.makeAndAddView(ListView.java:1812)
at android.widget.ListView.fillDown(ListView.java:698)
at android.widget.ListView.fillFromTop(ListView.java:759)
at android.widget.ListView.layoutChildren(ListView.java:1645)
at android.widget.AbsListView.onLayout(AbsListView.java:2149)
at android.view.View.layout(View.java:15125)
at android.view.ViewGroup.layout(ViewGroup.java:4862)
at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:931)
at android.view.View.layout(View.java:15125)
at android.view.ViewGroup.layout(ViewGroup.java:4862)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
at android.view.View.layout(View.java:15125)
at android.view.ViewGroup.layout(ViewGroup.java:4862)
at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:374)
at android.view.View.layout(View.java:15125)
at android.view.ViewGroup.layout(ViewGroup.java:4862)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
at android.view.View.layout(View.java:15125)
at android.view.ViewGroup.layout(ViewGroup.java:4862)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2317)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2023)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1189)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6223)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
at android.view.Choreographer.doCallbacks(Choreographer.java:591)
at android.view.Choreographer.doFrame(Choreographer.java:560)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
The class in which the logcat shows the NoClassDefFound error is as follows
public class CustomList extends ArrayAdapter<DrawerItem> {
Context context;
List<DrawerItem> drawerItemList;
int layoutResID;
public CustomList(Context context, int layoutResourceID,
List<DrawerItem> listItems) {
super(context, layoutResourceID, listItems);
this.context = context;
this.drawerItemList = listItems;
this.layoutResID = layoutResourceID;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
DrawerItemHolder drawerHolder;
View view = convertView;
if (view == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
drawerHolder = new DrawerItemHolder();
view = inflater.inflate(layoutResID, parent, false);
drawerHolder.ItemName = (TextView) view.findViewById(R.id.drawer_item_text);
drawerHolder.icon = (ImageView) view.findViewById(R.id.drawer_item_icon);
view.setTag(drawerHolder);
} else {
drawerHolder = (DrawerItemHolder) view.getTag();
}
DrawerItem dItem = (DrawerItem) this.drawerItemList.get(position);
drawerHolder.icon.setImageDrawable(view.getResources().getDrawable(
dItem.getImgResID()));
drawerHolder.ItemName.setText(dItem.getItemName());
return view;
}
private static class DrawerItemHolder {
TextView ItemName;
ImageView icon;
}
}
The error is shown in drawerHolder = new DrawerItemHolder(); line.
I have not made any changes to this class so I am thinking the problem might be caused by the extra views that I added in my original activity that acts as a fragment container. The activity's code is as follows
public class Home extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
private static int pos;
List<DrawerItem> dataList = new ArrayList<DrawerItem>();
View statistics,test,syllabus,share;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
this.getActionBar().setBackgroundDrawable(
getResources().getDrawable(R.color.background));
this.overridePendingTransition(R.layout.fade_in, R.layout.fade_out);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
statistics=findViewById(R.id.statistics_container);
test=findViewById(R.id.test_container);
syllabus=findViewById(R.id.syllabus_container);
share=findViewById(R.id.share_container);
statistics.setOnClickListener(mBottomDrawerListener);
syllabus.setOnClickListener(mBottomDrawerListener);
test.setOnClickListener(mBottomDrawerListener);
share.setOnClickListener(mBottomDrawerListener);
TextView image=(TextView)findViewById(R.id.statistics_image);
TextView text=(TextView)findViewById(R.id.statistics);
image.setTextColor(Color.parseColor("#03a9f4"));
text.setTextColor(Color.parseColor("#03a9f4"));
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,GravityCompat.START);
int width = getResources().getDisplayMetrics().widthPixels;
DrawerLayout.LayoutParams params = (android.support.v4.widget.DrawerLayout.LayoutParams) mDrawerList.getLayoutParams();
//params.width = (width * 75) / 100;
mDrawerList.setLayoutParams(params);
// set up the drawer's list view with items and click listener
/*
* mDrawerList.setAdapter(new ArrayAdapter<String>(this,
* R.layout.list_item, mPlanetTitles));
*/
dataList.add(new DrawerItem("Home", R.drawable.home));
dataList.add(new DrawerItem("Intelligence Questionnaire",
R.drawable.bulb));
dataList.add(new DrawerItem("Change Country", R.drawable.location));
dataList.add(new DrawerItem("LeaderBoard", R.drawable.cup));
dataList.add(new DrawerItem("How to play", R.drawable.help));
dataList.add(new DrawerItem("Exam Tips", R.drawable.tip));
mDrawerList.setAdapter(new CustomList(Home.this, R.layout.list_item,dataList));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
Typeface iconfont=FontManager.getTypeface(getApplicationContext(),FontManager.FONTAWESOME);
FontManager.markAsIconContainer(findViewById(R.id.btm_nav_bar),iconfont);
}
public View.OnClickListener mBottomDrawerListener=new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager=getFragmentManager();
setBlackText(v);
TextView image,text;
switch (v.getId()){
case R.id.statistics_container:
fragmentManager.beginTransaction().replace(R.id.content_frame,new HomePage()).commit();
image=(TextView)v.findViewById(R.id.statistics_image);
text=(TextView)v.findViewById(R.id.statistics);
image.setTextColor(Color.parseColor("#03a9f4"));
text.setTextColor(Color.parseColor("#03a9f4"));
break;
case R.id.syllabus_container:
image=(TextView)v.findViewById(R.id.syllabus_image);
text=(TextView)v.findViewById(R.id.syllabus_btm);
image.setTextColor(Color.parseColor("#03a9f4"));
text.setTextColor(Color.parseColor("#03a9f4"));
break;
case R.id.test_container:
image=(TextView)v.findViewById(R.id.test_image);
text=(TextView)v.findViewById(R.id.Tests);
image.setTextColor(Color.parseColor("#03a9f4"));
text.setTextColor(Color.parseColor("#03a9f4"));
break;
case R.id.share_container:
image=(TextView)v.findViewById(R.id.share_image);
text=(TextView)v.findViewById(R.id.share_btm);
image.setTextColor(Color.parseColor("#03a9f4"));
text.setTextColor(Color.parseColor("#03a9f4"));
break;
}
}
};
public void setBlackText(View v){
TextView img[]=new TextView[4];
TextView t1,t2,t3,t4;
img[0]=(TextView)findViewById(R.id.statistics_image);
t4=(TextView)findViewById(R.id.statistics);
img[1]=(TextView)findViewById(R.id.test_image);
t1=(TextView)findViewById(R.id.Tests);
img[2]=(TextView)findViewById(R.id.syllabus_image);
t2=(TextView)findViewById(R.id.syllabus_btm);
img[3]=(TextView)findViewById(R.id.share_image);
t3=(TextView)findViewById(R.id.share_btm);
for(TextView singleTextView:img){
singleTextView.setTextColor(Color.parseColor("#000000"));
}
t1.setTextColor(Color.parseColor("#000000"));
t2.setTextColor(Color.parseColor("#000000"));
t3.setTextColor(Color.parseColor("#000000"));
t4.setTextColor(Color.parseColor("#000000"));
}
/*
* #Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater
* inflater = getMenuInflater(); inflater.inflate(R.menu.activity_main,
* menu); return super.onCreateOptionsMenu(menu); }
*
* Called whenever we call invalidateOptionsMenu()
*
* #Override public boolean onPrepareOptionsMenu(Menu menu) { // If the nav
* drawer is open, hide action items related to the content view boolean
* drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
* //menu.findItem(R.id.action_websearch).setVisible(!drawerOpen); return
* super.onPrepareOptionsMenu(menu); }
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch (item.getItemId()) {
case 1:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available,
Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
/*
* Fragment fragment = new HomePage(); Bundle args = new Bundle();
* args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
* fragment.setArguments(args);
*/
pos = position;
FragmentManager fragmentManager = getFragmentManager();
switch (pos) {
case 0:
fragmentManager.beginTransaction().replace(R.id.content_frame, new Fragment_Statistics()).commit();
break;
case 1:
break;
case 2:
fragmentManager.beginTransaction().replace(R.id.content_frame, new Country()).commit();
case 3:break;
case 4:break;
case 5:break;
}
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
The DrawerItem class used in the Home activity is given below
public class DrawerItem {
String ItemName;
int imgResID;
public DrawerItem(String itemName, int imgResID) {
super();
ItemName = itemName;
this.imgResID = imgResID;
}
public String getItemName() {
return ItemName;
}
public void setItemName(String itemName) {
ItemName = itemName;
}
public int getImgResID() {
return imgResID;
}
public void setImgResID(int imgResID) {
this.imgResID = imgResID;
}}
Can someone see where I am going wrong? Thanks in advance..
DrawerItemHolder class should be public, or at least it should not be private.

Icon to Navigation Drawer

I am trying to add icons to my Navigation Drawer in Android. I have the following code in my main
public class MainActivity extends ActionBarActivity {
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
private myAdapter MyAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerList = (ListView)findViewById(R.id.navList);mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void addDrawerItems() {
String[] osArray = {"Math", "Physics", "Chemistry"};
MyAdapter = new myAdapter(this);
mDrawerList.setAdapter(MyAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(position) {
case 0:
Intent a = new Intent(MainActivity.this, MathActivity.class);
startActivity(a);
break;
case 1:
Intent b = new Intent(MainActivity.this, PhysicsActivity.class);
startActivity(b);
break;
case 2:
Intent c = new Intent(MainActivity.this, ChemistryActivity.class);
startActivity(c);
break;
default:
}
}
});
}
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("Navigation!");
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
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#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;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
class myAdapter extends BaseAdapter {
private Context context;
String SchoolCategories[];
int[] images = {R.drawable.math_icon,R.drawable.physics_icon,R.drawable.chemistry_icon};
public myAdapter(Context context){
this.context = context;
SchoolCategories = context.getResources().getStringArray(R.array.school);
}
#Override
public int getCount() {
return SchoolCategories.length;
}
#Override
public Object getItem(int position) {
return SchoolCategories[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = null;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.custom_row, parent, false);
}
else{
row =convertView;
}
TextView titleTextView =(TextView) row.findViewById(R.id.textViewRow1);
ImageView titleImageView = (ImageView) row.findViewById(R.id.imageViewRow1);
titleTextView.setText(SchoolCategories[position]);
titleImageView.setImageResource(images[position]);
return row;
}
}
}
And the following XML Layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/math_icon"
android:id="#+id/imageViewRow1"
/>
<TextView
android:layout_margin="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textViewRow1"
/>
</LinearLayout>
I am simple just trying to add icons to the navigation drawer, but this does not work and I am not sure what goes wrong. The application just shuts down. All help is really appreciated!
Here is my log-cat:
05-25 12:27:33.053 3909-3909/oscarorellana.nowwetryitmyway.physicsproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: oscarorellana.nowwetryitmyway.physicsproject, PID: 3909
android.content.ActivityNotFoundException: Unable to find explicit activity class {oscarorellana.nowwetryitmyway.physicsproject/oscarorellana.nowwetryitmyway.physicsproject.MathActivity}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1761)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1485)
at android.app.Activity.startActivityForResult(Activity.java:3736)
at android.app.Activity.startActivityForResult(Activity.java:3697)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:820)
at android.app.Activity.startActivity(Activity.java:4007)
at android.app.Activity.startActivity(Activity.java:3975)
at oscarorellana.nowwetryitmyway.physicsproject.MainActivity$1.onItemClick(MainActivity.java:57)
This was solved with changing this line:
inflater.inflate(R.layout.custom_row, parent, false);
To this line:
row = inflater.inflate(R.layout.custom_row, parent, false);

Categories

Resources