TextView is null after setContentView - java

I've looked at several similar questions on here, but none of them have explained my problem. I am simply trying to reference a TextView by it's id, but I keep getting Null Pointer Exceptions whenever I try to do anything with it. I made sure to put my assignment after both setContentView() is called and the fragment is inflated. To make sure there wasn't anything else causing problem I removed the other portions of my code and tested for null immediately after assignment. Regardless of this, it's still showing as null.
Here's my code:
public class MainActivity extends Activity
{
//MEMBER VARIABLES
TextView mQuestionText;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null)
{
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
mQuestionText = (TextView) findViewById(R.id.questionTextView);
if (mQuestionText == null)
System.out.println("debug:: " + "null");
}
#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();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment
{
public PlaceholderFragment()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
And here's the fragment_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="edu.wichita.eecs.cs697ac.w387u669.assignment3.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/questionTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="41dp"
android:text="Question"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button1"
android:layout_toRightOf="#+id/questionTextView"
android:text="False" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/questionTextView"
android:layout_marginTop="35dp"
android:layout_toLeftOf="#+id/questionTextView"
android:text="True" />
</RelativeLayout>
Thanks for your help!
EDIT: After doing some other research, I learned that I could override the onStart() method and move my code there as I would have access to the views (even those from the fragment). However this is just a bypass that doesn't really use fragments as they are meant to be used.
protected void onStart()
{
super.onStart();
TextView test = (TextView) findViewById(R.id.questionTextView);
test.setText("hello");
}
Hope that helps someone

questionTextView TextView is in fragment_main.xml layout of PlaceholderFragment, so use onCreateView of Fragment to initialize TextView as:
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
TextView mQuestionText = (TextView)rootView.findViewById(R.id.questionTextView);

if your using Fragment you shoud reference it from the fragment OnCreateView method
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null)
{
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#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();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment
{
public PlaceholderFragment()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
TextView QuestionText = (TextView) rootView.findViewById(R.id.questionTextView);
if (mQuestionText == null)
System.out.println("debug:: " + "null");
return rootView;
}
} }

You have set setContentView(R.layout.activity_main) but your xml name is fragment_main.xml
Use this XML in setContentView i.e. setContentView(R.layout.fragment_main)

Related

Android - Swipe refresh on active fragment

I have a fragment inside the MainActivity
on the menu, there is a refresh button and swipe refresh option which calls myUpdateOperation() method
This fragment may be different according to user's selection.
How can I make sure the right fragment currently active gets refreshed when the refresh action is invoked?
content_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.app.MainActivity"
tools:showIn="#layout/app_bar_main">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/main_fragment"
android:name="com.example.app.main_fragment.MainFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="7"
tools:layout="#layout/fragment_main" />
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
mSwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.i(TAG, "onRefresh called from SwipeRefreshLayout");
// This method performs the actual data-refresh operation.
// The method calls setRefreshing(false) when it's finished.
myUpdateOperation();
mSwipeRefreshLayout.setRefreshing(false);
}
}
);
}
void myUpdateOperation(){
// TODO: 20-Mar-17
Toast.makeText(this, "Refresh", Toast.LENGTH_SHORT).show();
}
Fragment1.java
public class Fragment1 extends Fragment {
public Fragment1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_1, container, false);
}
public void fragment1refresh(){
// TODO: this to be call when refresh on MainActivity and also fragment_1 is visible
}
}
Fragment2.java
public class Fragment2 extends Fragment {
public Fragment2() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_2, container, false);
}
public void fragment2refresh(){
// TODO: this to be call when refresh on MainActivity and also fragment_2 is visible
}
}
For this make your Fragment1 and Fragment2 class extends CustomFragment
The code for CustomFragment can be something like this
public abstarct class CustomFragment extends Fragment {
public CustomFragment() {
// Required empty public constructor
}
public abstract void refresh();
}
Change Fragment1 implementation to:
public class Fragment1 extends CustomFragment {
public Fragment1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_1, container, false);
}
#Override
public void refresh(){
// TODO: this to be call when refresh on MainActivity and also fragment_1 is visible
}
}
Similarly change the implementation of Fragment2 class.
Now in your MainActivity class get a reference to current visible fragment. This can be done as:
CustomFragment currentFragment = (CustomFragment)mFragmentManager.findFragmentById(R.id.main_fragment);
Now inside change myUpdateOperation() implementation to :
private void myUpdateOperation(){
// TODO: 20-Mar-17
currentFragment.refresh();
}
Get the current fragment from the fragment manager, then check which fragment type matches with it:
Fragment currentFragment = mFragmentManager.findFragmentById(R.id.main_fragment);
if (currentFragment instanceof Fragment1) {
((Fragemnt1) currentFragment).fragment1refresh()
} if (currentFragment instanceof Fragment2) {
((Fragemnt2) currentFragment).fragment2refresh()
}

Button in ListView not clickable

I want to click on a button inside an item of a ListView and it should have the same effect from clicking the whole item. But when I click button nothing happens, when I click image its all Okey. How to fix it?
I tried setting on the button:
android:focusable="true"
android:clickable="true"
I also experimented with android:descendantFocusability.
None of my tries made the buttons clickable.
my_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:descendantFocusability="blocksDescendants"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_toLeftOf="#+id/imageArrow"
android:layout_toStartOf="#+id/imageArrow"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageArrow"
android:layout_alignTop="#+id/button"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="#drawable/r_arr" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
ListView listView = (ListView)findViewById(R.id.listView);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
MyCustomAdapter adapter = new MyCustomAdapter(this, values);
setListAdapter(adapter);
}
#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;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String item = (String) getListAdapter().getItem(position);
Toast.makeText(this, item + " selected", Toast.LENGTH_SHORT).show();
}
}
MyCustomAdapter.java
public class MyCustomAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] names;
static class ViewHolder {
public TextView myButton;
public ImageView image;
}
public MyCustomAdapter(Activity context, String[] names) {
super(context, R.layout.my_item, names);
this.context = context;
this.names = names;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
// reuse views
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.my_item, null);
// configure view holder
ViewHolder viewHolder = new ViewHolder();
viewHolder.myButton = (Button)rowView.findViewById(R.id.button);
viewHolder.image = (ImageView) rowView.findViewById(R.id.imageArrow);
viewHolder.myButton.setFocusable(false);
rowView.setTag(viewHolder);
}
// fill data
ViewHolder holder = (ViewHolder) rowView.getTag();
String s = names[position];
String abs=Integer.toString(position + 1);
holder.myButton.setText(s+ " number " + abs);
holder.image.setImageResource(R.drawable.r_arr);
return rowView;
}
}
Please write onclicklistener on your button.
You just have to configure onClick method something like this:
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//your code goes here
}
});
Put button click listener in your getView
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
// reuse views
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.my_item, null);
// configure view holder
ViewHolder viewHolder = new ViewHolder();
viewHolder.myButton = (Button) rowView.findViewById(R.id.button);
viewHolder.image = (ImageView) rowView.findViewById(R.id.imageArrow);
viewHolder.myButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Button click functionalty here
});
rowView.setTag(viewHolder);
}
// fill data
ViewHolder holder = (ViewHolder) rowView.getTag();
String s = names[position];
String abs=Integer.toString(position + 1);
holder.myButton.setText(s+ " number " + abs);
holder.image.setImageResource(R.drawable.r_arr);
return rowView;
}
}
To make your both listview item and button clickable, do this.
make ListView focusable android:focusable="true"
Button not focusable in your custom listview item android:focusable="false"
Method 1:
First replace button code in xml as below
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:focusable="false"
android:onClick="onClick"
android:focusableInTouchMode="false"
android:layout_toLeftOf="#+id/imageArrow"
android:layout_toStartOf="#+id/imageArrow"
/>
Then go to your activity and write code as below
public void onClick(View v)
{
super.onClick(v);
if (v.getId() == R.id.button)
{
//your code goes here
}
}
or You can add below peace of code in you oncreate
Method 2 :
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
It is not recommended to have two click listeners for a same row item in listview.
You can have in a Listview Custom Adapter. You can customize this according to your requirement.
or
You can have in your Activity / Fragment listview onclicklistener. This cannot be customized and when you click the whole row is selected.

Multiple Tabs with Different Fragments

I am pretty new to Android. I am making a new App which makes use of Tabs.
Now, I want to display different fragments in the tabs.
Please note that my MinSDK is Android KitKat 4.4 so I wont be using deprecated methods
My Code is:
MainActivity.java
public class MainActivity extends ActionBarActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#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.search)
{
Toast.makeText(getApplicationContext(),"You tapped on SEARCH !", Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_1, container, false);
Button b1 = (Button) rootView.findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Done", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
}
Fragment_Main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment">
<EditText
android:id="#+id/et1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter your Name (Fragment Main"/>
<EditText
android:id="#+id/et2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/et1"
android:hint="Enter your ID (Fragment Main)"/>
<Button
android:id="#+id/b1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_below="#+id/et2"/>
</RelativeLayout>
Fragment_1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity$FragmentOne">
<Button
android:id="#+id/b1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_below="#+id/et2"/>
</RelativeLayout>
I have changed the tools:context in fragment_1.xml for my tests. I don't know what it does
Now, when the user opens the App, he should see the Fragment_Main fragment. When he swipes for the next tab, he should see fragment_1.
Please help in detail as i am very new.
So what exactly doesn't work?
I can only guess, but you don't use Fragment_Main.xml anywhere.
You are already passing position of view pager to your fragment, you should retrieve it and inflate layout based on it. Something like this inside your fragment:
private int mFragmentIndex = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mFragmentIndex = getArguments().getInt(ARG_SECTION_NUMBER);
}
}
and in onCreateView you should inflate different layout based on fragment index:
View rootView;
if (mFragmentIndex == 1) {
rootView = inflater.inflate(R.layout.Fragment_Main, container, false);
} else {
rootView = inflater.inflate(R.layout.fragment_1, container, false);
}
Anyway, I would suggest using different fragments, instead of inflating different layouts. Something like this:
#Override
public Fragment getItem(int position) {
if (position == 0) {
return MainFragment.newInstance();
} else {
return SomeOtherFragment.newInstance();
}
}

Android app crashing on startup [duplicate]

This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I have just started android app development..and while opening the following app it says "Unfortunately your app has crashed". Can anyone point out the error in this code.
fragmentmain.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffbb"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="85dp"
android:text="Info of Departments and Student Bodies"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="190dp" >
</ListView>
</LinearLayout>
MainActivity.java
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//adding items to list view
final ListView listview = (ListView) findViewById(R.id.listView);
String values[] = new String[]{"Departments" , "Student_bodies"};
final ArrayList<String> list = new ArrayList<String>();
for (int i=0 ; i < values.length; ++i){
list.add(values[i]);
}
ArrayAdapter<String> ap = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1,values);
listview.setAdapter(ap);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if (((TextView)arg1).getText().toString() == "Departments"){
startActivity(new Intent(MainActivity.this,Departments.class));
}
if (((TextView)arg1).getText().toString() == "Student_bodies"){
startActivity(new Intent(MainActivity.this,Student_bodies.class));
}
}
});
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
it is just simple implementation of list view and implementing onClick() on its elements to go to different Activity.thankful if anyone points out mistakes.
Your layout file named FragmentMain but You using activity_main as parameter of setContentView() method. Try to change to setContentView(R.layout.FragmentMain);
Please remove code from onCreate() and added in onCreateView(), as you are using fragment.
And your listview is also define in fragment_main.xml ,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
final ListView listview = (ListView) rootView.findViewById(R.id.listView);
String values[] = new String[]{"Departments" , "Student_bodies"};
final ArrayList<String> list = new ArrayList<String>();
for (int i=0 ; i < values.length; ++i){
list.add(values[i]);
}
ArrayAdapter<String> ap = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1,values);
listview.setAdapter(ap);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if (((TextView)arg1).getText().toString() == "Departments"){
startActivity(new Intent(MainActivity.this,Departments.class));
}
if (((TextView)arg1).getText().toString() == "Student_bodies"){
startActivity(new Intent(MainActivity.this,Student_bodies.class));
}
}
});
return rootView;
}

Call NavigationDrawer in ALL Activitys

I have a NavigationDrawer and I would call it more Activity without having to copy and paste the same code in different classes. Thus, all the code that I would have to paste in the various classes, I put it in a class of its own, called NavDrawer. Here is the code.
NavDrawer
public class NavDrawer extends Activity{
ListView mDrawerList;
DrawerLayout mDrawer;
CustomActionBarDrawerToggle mDrawerToggle;
String[] menuItems;
Intent intent, intent2, intent3, intent4, intent5, intent6;
public void _initMenu() {
NsMenuAdapter mAdapter = new NsMenuAdapter(this);
// Add Header
mAdapter.addHeader(R.string.ns_menu_main_header);
// Add first block
menuItems = getResources().getStringArray(
R.array.ns_menu_items);
String[] menuItemsIcon = getResources().getStringArray(
R.array.ns_menu_items_icon);
int res = 0;
for (String item : menuItems) {
int id_title = getResources().getIdentifier(item, "string",
this.getPackageName());
int id_icon = getResources().getIdentifier(menuItemsIcon[res],
"drawable", this.getPackageName());
NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
mAdapter.addItem(mItem);
res++;
}
mDrawerList = (ListView) findViewById(R.id.drawer);
if (mDrawerList != null)
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
#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) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.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 = mDrawer.isDrawerOpen(mDrawerList);
//menu.findItem(R.id.item1).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
/*
* The action bar home/up should open or close the drawer.
* ActionBarDrawerToggle will take care of this.
*/
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle {
public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout mDrawerLayout){
super(
mActivity,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.ns_menu_open,
R.string.ns_menu_close);
}
#Override
public void onDrawerClosed(View view) {
getActionBar().setTitle(getString(R.string.ns_menu_close));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(getString(R.string.ns_menu_open));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// Highlight the selected item, update the title, and close the drawer
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
if(position==0) {
//Open an Activity
}
if(position==1) {
//Open an Activity
}
if(position==2) {
//Open an Activity
}
//You should reset item counter
mDrawer.closeDrawer(mDrawerList);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.examplelayout);
getActionBar().setDisplayHomeAsUpEnabled(true);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
_initMenu();
mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer);
mDrawer.setDrawerListener(mDrawerToggle);
_initMenu();
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
}
}
NsMenuAdapter
public class NsMenuAdapter extends ArrayAdapter<NsMenuItemModel> {
public NsMenuAdapter(Context context) {
super(context, 0);
}
public void addHeader(int title) {
add(new NsMenuItemModel(title, -1, true));
}
public void addItem(int title, int icon) {
add(new NsMenuItemModel(title, icon, false));
}
public void addItem(NsMenuItemModel itemModel) {
add(itemModel);
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return getItem(position).isHeader ? 0 : 1;
}
#Override
public boolean isEnabled(int position) {
return !getItem(position).isHeader;
}
public static class ViewHolder {
public final TextView textHolder;
public final ImageView imageHolder;
public final TextView textCounterHolder;
public ViewHolder(TextView text1, ImageView image1,TextView textcounter1) {
this.textHolder = text1;
this.imageHolder = image1;
this.textCounterHolder=textcounter1;
}
}
public View getView(int position, View convertView, ViewGroup parent) {
NsMenuItemModel item = getItem(position);
ViewHolder holder = null;
View view = convertView;
if (view == null) {
int layout = R.layout.ns_menu_row_counter;
if (item.isHeader)
layout = R.layout.ns_menu_row_header;
view = LayoutInflater.from(getContext()).inflate(layout, null);
TextView text1 = (TextView) view.findViewById(R.id.menurow_title);
ImageView image1 = (ImageView) view.findViewById(R.id.menurow_icon);
TextView textcounter1 = (TextView) view.findViewById(R.id.menurow_counter);
view.setTag(new ViewHolder(text1, image1,textcounter1));
}
Object tag = view.getTag();
if (tag instanceof ViewHolder) {
holder = (ViewHolder) tag;
}
if(item != null && holder != null)
{
if (holder.textHolder != null)
holder.textHolder.setText(item.title);
if (holder.textCounterHolder != null){
if (item.counter > 0){
holder.textCounterHolder.setVisibility(View.VISIBLE);
}else{
holder.textCounterHolder.setVisibility(View.GONE);
}
}
if (holder.imageHolder != null) {
if (item.iconRes > 0) {
holder.imageHolder.setVisibility(View.VISIBLE);
holder.imageHolder.setImageResource(item.iconRes);
} else {
holder.imageHolder.setVisibility(View.GONE);
}
}
}
return view;
}
}
NsMenuItemModel
public class NsMenuItemModel {
public int title;
public int iconRes;
public int counter;
public boolean isHeader;
public NsMenuItemModel(int title, int iconRes,boolean header,int counter) {
this.title = title;
this.iconRes = iconRes;
this.isHeader=header;
this.counter=counter;
}
public NsMenuItemModel(int title, int iconRes,boolean header){
this(title,iconRes,header,0);
}
public NsMenuItemModel(int title, int iconRes) {
this(title,iconRes,false);
}
}
In classes where I want to have the NavigationDrawer I do nothing but extend the class NavigationDrawer, so I have a code like this
public class ExampleClass extends NavDrawer
And when I run the application in the ActionBar visualize the image and NavigationDrawer displayed but is EMPTY. Why?
In addition, in the onCreate of the class NavDrawer I set layout as the layout of an Activity, but if I have to see it in ALL Activity, can not be linked to ONE that A specific layout specific Activity. So I thought I'd create one specifically for the NavigationDrawer, containing one and only its structure. code:
<?xml version="1.0" encoding="utf-8"?>
<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 navigation drawer -->
<ListView
android:id="#+id/drawer"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#F3F3F4"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" >
</ListView>
</android.support.v4.widget.DrawerLayout>
It can work or not?
The layout of the example has a structure similar to this
<?xml version="1.0" encoding="utf-8"?>
<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" >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/drawer"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#F3F3F4"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" >
</ListView>
</android.support.v4.widget.DrawerLayout>
I hope to have answers to all these and I apologize if my questions may seem trivial but are days that I am looking desperately for a solution, but I just can not. I hope to get answers and help. Thanks in advance.

Categories

Resources