Fragment Tabs Strange Crashes - java

Does anyone know what to do with this Fragment Tabs Problem?
I am a very novice programmer with not much experience, especially in the world of Android application developing. I recently started a project with fragment tabs and I find that when I try to access a object (for lack of a better word, but I mean like a TextView, Spinner, EditText, etc.) by something like
TextView textBox = (TextView) getView().findViewById(R.id.scouter_name_box);
the compiler finds no errors, but the app crashes. I have tried putting this line of code in a function, in the body of the fragment by itself (after onCreate()), and at the end of onCreate(). This doesn't help. The Error Log also doesn't say anything.
Furthermore, when I comment out this line, the rest of the app runs seamlessly. The app doesn't have any other activities except MainActivity and the three tab Fragments.
WHAT CAN I DO TO ACCESS THE TEXTVIEWS, SPINNERS, ETC?
also, as I mentioned I am very new. If you need a better explanation please ask, and sorry if I don't understand what you are saying at first.
We all have to start somewhere
Please help,
and Thank you in Advance
Tab XML File:
<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" >
<TextView android:id="#+id/input_scouter_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:text="Scouter Name:"
android:textSize="25sp"
android:textStyle="bold" />
<Spinner android:id="#+id/choose_scouter_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/input_scouter_name"
android:entries="#array/scouter_name_list" />
</RelativeLayout>
MainActivity Java File:
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
// Declare Tab Variable
Tab tab;
ScoutingData ScoutData;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the actionbar
ActionBar actionBar = getActionBar();
// Hide Actionbar Icon
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.drawable.red_and_blue_frisbees);
// Hide Actionbar Title
actionBar.setDisplayShowTitleEnabled(true);
// Create Actionbar Tabs
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create Home Tab
tab = actionBar.newTab().setTabListener(new FragmentsTab0());
// Set Tab Title
tab.setText("General");
actionBar.addTab(tab);
// Create first Tab
tab = actionBar.newTab().setTabListener(new FragmentsTab1());
// Set Tab Title
tab.setText("Autonomous");
actionBar.addTab(tab);
// Create Second Tab
tab = actionBar.newTab().setTabListener(new FragmentsTab2());
// Set Tab Title
tab.setText("Teleop");
actionBar.addTab(tab);
// Create Third Tab
tab = actionBar.newTab().setTabListener(new FragmentsTab3());
// Set Tab Title
tab.setText("Endgame");
actionBar.addTab(tab);
}
}
Tab Java File:
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.widget.Spinner;
public class FragmentsTab0 extends Fragment implements ActionBar.TabListener {
private Fragment mFragment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from tab0fragment.xml
getActivity().setContentView(R.layout.tab0fragment);
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
mFragment = new FragmentsTab0();
// Attach tab0fragment.xml layout
ft.add(android.R.id.content, mFragment);
ft.attach(mFragment);
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
// Remove tab0fragment.xml layout
ft.remove(mFragment);
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
//Heeere's the Problem
Spinner scouterName = (Spinner) getView().findViewById(R.id.choose_scouter_name);
}

First off, remove Spinner scoutername = (Spinner) getView().findViewById(R.id.choose_scouter_name). Secondly, remove getActivity().setContentView(R.layout.tab0fragment); from your onCreate(). You want to inflate your xml within onCreateView and then use that view to get the id of your other views. For example:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view;
if (container == null) {
return null;
}
view = inflater.inflate(R.layout.tab0fragment, container, false);
Spinner scouterName = (Spinner) view.findViewById(R.id.choose_scouter_name);
}

Related

How to link two xml pages in Android app when a button is clicked?

I am making a simple app in which on home page, a button is placed. When the button is clicked, it must display a new page (xml in layout). How to do that ..
My app contains in src directory, There are two java files.
1. Activity2
2. Main_activity
and two xml files in layout:
1. fragment_main.xml
2. Activity.xml
I want that when i click "Technical button", it should display Activity.xml page from layout..
My codes:
Main_Activity.java
package com.example.vit;
import java.util.Locale;
import android.util.Log;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a {#link FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this
* becomes too memory intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// 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);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#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);
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* 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_main, container,
false);
return rootView;
}
}
public void onClick(View v)
{
Intent intent = new Intent (v.getContext(),Activity.class);
startActivityForResult (intent,0);
}
}
2.Activity2.java
package com.example.vit;
import android.app.Activity;
public class Activity2 extends Activity
public void onCreate(Bundle, savedInstanceState)
{
{
super.onCreate(savedInstanceState);
setContentView(R.layout.Activity);
}
}
3. fragment_main.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: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"
tools:context="com.example.vit.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="31dp"
android:onClick="doSomething"
android:text="Technical" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Non Technical" />
</LinearLayout>
Activity.xml
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your request is being processed"
android:textAppearance="?android:attr/textAppearanceLarge" />
Intent intent = new Intent(this, ActivityTwo.class);
this.startActivity ( intent );
Note : #Don already provided a correct answer, but (sorry) lack of information. Accept his answer, i only help to add some informations (which is quite long if i put in comment)
In Android, a page/screen in your apps refer to the subclass of Activity. An Activity always have a xml layout.
So, if you want to change from one layout (or screen/page) to others, you should change the Activity, with the help of Intent class. This will automatically change the layout (as your question refer) because an Activity has a layout.
No offense, but i suggest you to search some videos/books/tutorials. I suggest Commonsware's book which is free (the old version, but still the best book in my opinion) :
http://commonsware.com/Android/4-2-free
all is going right but u have to include the following code
Intent intent = new Intent(this, ActivityTwo.class);
this.startActivity ( intent );

setOnClickListener(this) crashes my app

I have a problem with btn.setOnClickListener(this). I have a simple project that works good, but when I add an action to the button I get the message:
unfortunatelay (app name) has stopped
When I comment btn.setOnClickListener(this) out the project works without any problem.
Here is my code:
package com.example.hello;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
public static final Context PlaceholderFragment = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().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 implements OnClickListener {
Button btn;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
btn=(Button)rootView.findViewById(R.id.Entrer);
btn.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
// here is the problem error: no eclosing istance of the type MainActivityis accessible in scope
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
}
}
My layout is as follows:
<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="com.example.hello.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="190dp"
android:text="#string/hello_world"
android:textSize="16dp" />
<Button
android:id="#+id/Entrer"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="61dp"
android:text="Entrer" />
</RelativeLayout>
I dont know if I have simple things that are not go correctly. I'm new to Android programming. Thank you!
btn is null, so when you set onClickListener you get NullPointerException. It's null because it's located in fragment_main.xml, not activity_main.xml. You should move this code from onCreate()
btn = (Button) findViewById(R.id.Entrer);
btn.setOnClickListener(this);
to PlaceholderFragment() as follows:
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);
btn=(Button) rootView.findViewById(R.id.Entrer);
btn.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), SecondActivity.class);
startActivity(intent);
}
});
return rootView;
}
}
btn=(Button)findViewById(R.id.Entrer);
btn.setOnClickListener(this);
Most likely, findViewById above is returning null. btn.setOnClickListener is crashing on a null pointer exception. (Because btn is null).
It is extremely likely, since you are using the default fragment structure created by the Eclipse solution, that the Button is really in the fragment layout file (fragment_main.xml) and not in activity_main.xml. (Hence, the button is not in the Activity view, it's in the fragment view).
If that's the case, then move the above two lines into the onCreateView method of the PlaceholderFragment.

Populate a Listview NOT in the current layout

I'm using the popular SlidingMenu library, and the only thing in it is a listview. So I tried using an array adapter to populate it with an ArrayList that I have, but it gives me a NullPointer Exception. So I had a gut feeling that I should try to set the layout of the activity to the layout with the listview, and sure enough, it worked. but that doesn't solve my problem because I need the listview in the DRAWER. Can someone help?
package josh.hutchins.frcmatchscouter2014;
import java.util.ArrayList;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
BlueAllianceHandler bah = new BlueAllianceHandler("sc");
FileIoHandler fih = new FileIoHandler(/*maybe pass in folder path here?*/);
ArrayList<String> testTeams = new ArrayList<String>();
ListView drawerListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerListView = (ListView) findViewById(R.id.drawerListView);
setupSlidingMenu();
//Toast.makeText(this, bah.pullData(), Toast.LENGTH_LONG).show();
pullTeamData();
}
#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;
}
void setupSlidingMenu(){
SlidingMenu menu = new SlidingMenu(this);
menu.setMode(SlidingMenu.LEFT);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
menu.setShadowWidthRes(R.dimen.shadow_width);
menu.setShadowDrawable(R.drawable.shadow);
menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
menu.setFadeDegree(0.35f);
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
menu.setMenu(R.layout.menu);
}
void pullTeamData(){
//JUST FOR TESTING PURPOSES
testTeams.add("2655");
testTeams.add("1533");
testTeams.add("900");
testTeams.add("4451");
testTeams.add("2200");
testTeams.add("3301");
testTeams.add("2059");
testTeams.add("5010");
testTeams.add("1747");
testTeams.add("2641");
testTeams.add("4231");
fih.createTeamRecords(testTeams);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
testTeams );
drawerListView.setAdapter(arrayAdapter);
}
}
Just follow these steps :
1.Extend SlidingFragmentActivity in your MainActivity instead of just Activity.
2.Make two layouts of FrameLayout type in your layout folder, like this
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/menu_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
name layouts as menu_frame, content_frame ,menu_frame will hold the list view that you require and content_frame will hold the content.
3.In your MainActivity , do this.
SlidingMenu menu;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setBehindContentView(R.layout.menu_frame);
getSupportFragmentManager().beginTransaction()
.replace(R.id.menu_frame, new MenuFragment()).commit();
setContentView(R.layout.content_frame);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, new ShockFeedsFragment()).commit();
ab=getActionBar();
menu = getSlidingMenu();
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
menu.setShadowWidthRes(R.dimen.shadow_width);
menu.setShadowDrawable(R.drawable.shadow);
menu.setBehindOffset(200);
menu.setMode(SlidingMenu.LEFT_RIGHT );
}
Now design the layout for your left menu , just simply include a listview in a linear layout and name your layout as left_menu.
Make a fragment named MenuFragment , extend ragment class , in onCreateView Method , setup your menu list view as shown below
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v=inflater.inflate(R.layout.left_menu, container, false);
lv=(ListView)v.findViewById(R.id.menuListView);
iv=(ImageView)v.findViewById(R.id.imageMenuProfile);
tv=(TextView)v.findViewById(R.id.textViewProfileName);
LeftMenuAdapter adap=new LeftMenuAdapter(getActivity(), list);
//lv.setAdapter(new ArrayAdapter<String>(getActivity().getApplicationContext(),R.layout.ledt_en_row,R.id.textList,new String[] {"H","R","S","B","C","W"}));
lv.setAdapter(adap);
lv.setOnItemClickListener(new MenuListListener());
return v;
}
I have implemented the same library , did it this way , working perfectly , hope it does same for you :)... good luck.

using actionbar tabs to switch between fragments

A week later, I am still trying without success to create a tabbed action bar with v7 support to be able to switch between fragments. This is my first effort at an android app in native code and I am new to Java.
My Main.Activity.java looks like this
package com.example.appcompattest;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBarActivity;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setup action bar for tabs
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(true);
Tab tab = actionBar.newTab()
.setText(R.string.grammar)
.setTabListener(new TabListener<GrammarFragment>(
this, "GRAMMAR", GrammarFragment.class));
actionBar.addTab(tab);
tab = actionBar.newTab()
.setText(R.string.lexis)
.setTabListener(new TabListener<LexisFragment>(
this, "LEXIS", LexisFragment.class));
actionBar.addTab(tab);
}
#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;
}
public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
private Fragment mFragment;
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
/** Constructor used each time a new tab is created.
* #param activity The host Activity, used to instantiate the fragment
* #param tag The identifier tag for the fragment
* #param clz The fragment's Class, used to instantiate the fragment
*/
public TabListener(Activity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
}
/* The following are each of the ActionBar.TabListener call backs */
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
// Commit the transaction
ft.add(R.id.fragment_holder, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach( mFragment);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// User selected the already selected tab. Usually do nothing.
}
}
}
Apart from this, I have a Framelayout called fragment_holder in my activity_main.xml to swap the tabs in and out of, and separate xml files for my two fragments. I also have two classes, LexisFragment.java and GrammarFragment.java which are basically the same (with Grammar/grammar substituted for Lexis/lexis) and look like this.
public class LexisFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.lexisfragment, container, false);
}
When I run the activity, the first fragment is added. Selecting the other tab causes the the second fragment to be added but without destroying the first. On subsequent tab changes the fragments just remain superimposed.
After logging the variables (mTag and mFragment) at each step and experimenting with ft.remove(), I am pretty sure that what is happening is as follows:
On the first tab change onTabUnselected fails to detach / remove anything while onTabSelected adds the new fragment. Then, on sucessive tab changes, the tab which should be added is removed while the tab which should be removed is added. I am grateful for any suggestions.
Hope this helps you..
public class AboutActivity extends Activity {
boolean mIsFromMem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mIsFromMem=savedInstanceState!=null;
}}

Android ImageView not showing in SherlockFragment

I'm trying to make an ImageView, in the Graphical view it shows up but when I run it on my device and the emulator the image doesn't show up. Here's my XML code.
<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" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:scaleType="fitXY"
android:src="#drawable/map_mockup" />
and here's my Fragment1 code (I am using Fragment1 as the Fragment to display this ImageView)
import com.actionbarsherlock.app.SherlockFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import android.app.*;
import android.content.Intent;
public class Fragment1 extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
return rootView;
}
}
I hope this is enough, but if you need more code of the application I'll post it.
This is the first time I'm asking a question on Stack Overflow so if I do something wrong PLEASE tell me so I can correct it, so that in the future my questions layout is correct.
Here's the code for the activity I am adding the fragment to.
import android.app.Activity;
import android.os.Bundle;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.content.res.Configuration;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.support.v4.view.GravityCompat;
public class MainActivity extends SherlockFragmentActivity {
// Declare Variable
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
MenuListAdapter mMenuAdapter;
String[] title;
String[] subtitle;
int[] icon;
Fragment fragment1 = new Fragment1();
Fragment fragment2 = new Fragment2();
Fragment fragment3 = new Fragment3();
Fragment fragment4 = new Fragment4();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_main);
// Generate title
title = new String[] { "Main", "Nick Honegger",
"Discounts", "About" };
// Generate subtitle
subtitle = new String[] { "Check nearby markets", "View your profile",
"Coupons and deals!", "Find out more!" };
// Generate icon
icon = new int[] { R.drawable.action_about, R.drawable.profile_pic,
R.drawable.collections_cloud, R.drawable.action_about };
// Locate DrawerLayout in drawer_main.xml
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// Locate ListView in drawer_main.xml
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// Pass results to MenuListAdapter Class
mMenuAdapter = new MenuListAdapter(this, title, subtitle, icon);
// Set the MenuListAdapter to the ListView
mDrawerList.setAdapter(mMenuAdapter);
// Capture button clicks on side menu
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
// TODO Auto-generated method stub
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
// The click listener 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) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Locate Position
switch (position) {
case 0:
ft.replace(R.id.content_frame, fragment1);
break;
case 1:
ft.replace(R.id.content_frame, fragment2);
break;
case 2:
ft.replace(R.id.content_frame, fragment3);
break;
case 3:
ft.replace(R.id.content_frame, fragment4);
}
ft.commit();
mDrawerList.setItemChecked(position, true);
// Close drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
#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 toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
I've tried using Log.d and it shows that Fragment1 is being loaded. I'm stumped, I don't know what to do and am completely lost right here.
If it matters, the resolution for the PNG is 900x1429.
Two things I can think of.
First, I'm not sure if your layout code shows us the whole file or a snippet. If it's the whole file, you're missing a closing tag on the relativeLayout. If it's a snippet then ignore me.
Second, can you post the code for the Activity that you are adding this Fragment to?
Did you try to add the in the onCreateView instead of the xml?That would be the first thing I'd try.Btw I used the same tutorial as you did and consider yourself lucky,mine doesnt even show the image on my device -.-
Please would you try this:
ft.replace(android.R.id.content, fragment1, "frag1");
instead of
ft.replace(R.id.content_frame, fragment1);
?
If this doesn't change anything, I suggest you use Log.d to confirm that your fragment1 is actually being loaded.
Edit:
Good, then follow Arkan's line or reasoning or place a textview in your xml like this, to determine whether or not the xml is being loaded:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="if you can see me the problem must be with my image"
/>

Categories