VideoView preventing other fragments in a ViewPager from showing up? - java

I have a simple Android program which uses ViewPager to swipe between two tabs. Each tab has its own fragment. One fragment plays video while the other simply shows some text. The problem is when the video plays and I swipe to the information tab there is no text and it is completely black. I know it must be because of the video layout. Reason being is I have tested it with two information tabs instead and the information shows up perfectly on each tab. Here's my code.
MainActivity.java
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBarActivity;
public class MainActivity extends ActionBarActivity implements android.support.v7.app.ActionBar.TabListener{
private ViewPager tabsviewPager;
private ActionBar mActionBar;
private TabsAdapter mTabsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabsviewPager = (ViewPager) findViewById(R.id.tabspager);
mTabsAdapter = new TabsAdapter(getSupportFragmentManager());
tabsviewPager.setAdapter(mTabsAdapter);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab friendstab = getSupportActionBar().newTab().setText("Daily Video").setTabListener(this);
Tab publicprofiletab = getSupportActionBar().newTab().setText("Video Details").setTabListener(this);
getSupportActionBar().addTab(friendstab);
getSupportActionBar().addTab(publicprofiletab);
//This helps in providing swiping effect for v7 compat library
tabsviewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
getSupportActionBar().setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab selectedtab, FragmentTransaction arg1) {
// TODO Auto-generated method stub
tabsviewPager.setCurrentItem(selectedtab.getPosition()); //update tab position on tap
}
#Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
TabsAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class TabsAdapter extends FragmentStatePagerAdapter{
private int TOTAL_TABS = 2;
public TabsAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int index) {
// TODO Auto-generated method stub
switch (index) {
case 0:
return new VideoFragment();
case 1:
return new InfoFragment();
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return TOTAL_TABS;
}
}
VideoFragment.java
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.VideoView;
public class VideoFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.video_layout, container, false);
VideoView vView = (VideoView) view.findViewById(R.id.videoViewLoop);
vView.setVideoPath("/sdcard/Snapchat/Hansen.mp4");
vView.setOnPreparedListener (new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
}
});
vView.start();
return view;
}
}
InfoFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class InfoFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.info_layout, container, false);
return view;
}
}
activity_main.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tabspager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
info_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="This Will Show Details of Video Location and Also the Amount of User Viewings"
android:textSize="30sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
video_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<VideoView
android:id="#+id/videoViewLoop"
android:layout_width="fill_parent"
android:layout_alignParentRight="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_height="fill_parent"/>
</RelativeLayout>

Related

Google Map in Tabs Initialize failed

main class
package com.android.takemethere;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.TargetApi;
import android.app.ActionBar;
import com.android.takemethere.backend.ClassLogin;
import com.android.takemethere.backend.Database_GetAllReports;
import com.android.takemethere.objects.*;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.wearable.internal.ac;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
private ActionBar actionbar;
private ViewPager viewpager;
private FragmentPageAdapter ft;
private Resources res;
private ActionBar bar;
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabhome);
bar = getActionBar();
getActionBar().setDisplayHomeAsUpEnabled(true);
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FE2E2E")));
viewpager=(ViewPager) findViewById(R.id.pager);
ft=new FragmentPageAdapter(getSupportFragmentManager());
InitalizeMap();
actionbar=getActionBar();
viewpager.setAdapter(ft);
actionbar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FE2E2E")));
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionbar.addTab(actionbar.newTab().setTabListener(this)
.setIcon(R.drawable.ic_home));
actionbar.addTab(actionbar.newTab().setTabListener(this)
.setIcon(R.drawable.ic_newsfeeds));
actionbar.addTab(actionbar.newTab().setText("Profile").setTabListener(this));
viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
actionbar.setSelectedNavigationItem(arg0);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
/// InitalizeMap();
//
}
public void InitalizeMap() {
if (googleMap == null) {
googleMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#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) {
Intent SwitchActivity;
switch (item.getItemId()) {
case R.id.action_search:
SwitchActivity= new Intent(getApplicationContext(),class_search.class);
startActivity(SwitchActivity);
return true;
case R.id.action_report:
SwitchActivity= new Intent(getApplicationContext(),Class_report.class);
startActivity(SwitchActivity);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
viewpager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
the fragementadapter that i used
package com.android.takemethere.objects;
import com.android.takemethere.*;
import android.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class FragmentPageAdapter extends FragmentPagerAdapter {
public FragmentPageAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
switch(arg0){
case 0:
return new class_home();
case 1:
return new class_newsfeeds();
case 2:
return new class_profile();
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
}
}
tab_home.xml that holds the tabs
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</android.support.v4.view.ViewPager>
layout_home.xml that has the map fragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center|left"
android:orientation="vertical" >
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.18"
class="com.google.android.gms.maps.SupportMapFragment" />
</LinearLayout>
</LinearLayout>
class_home.java
package com.android.takemethere;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.android.takemethere.maps.direction.*;
import android.app.ActionBar;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class class_home extends Fragment {
private static View view;
GoogleMap googleMap;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {
view = inflater.inflate(R.layout.layout_home, container, false);
} catch (InflateException e) {
/* map is already there, just return view as it is */
}
return view;
}
}
the error:
12-07 14:07:48.973: E/AndroidRuntime(23264): Caused by: java.lang.NullPointerException
12-07 14:07:48.973: E/AndroidRuntime(23264): at com.android.takemethere.MainActivity.InitalizeMap(MainActivity.java:107)
i have this error it is look it cannot find the map id on run time? please help me to solve this
Looks like you're fetching the map when your fragment's layout was not yet initialized. To confirm that, delay InitializeMap():
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
InitalizeMap();
}
}, 3000); // delayed by 3 seconds
If that works, then I'd suggest you somehow wait for the fragment's layout to be inflated. Perhaps you should InitializeMap() inside of your fragment as the map is a part of it, not the activity.

How to add dynamically several fragments

I create a little app with 3 static fragments and a view pager adapter. But what I want is to create Only one kind of fragment and with a button "add" , add other fragment which will be adapted by the view pager.. here is what i have done
FragmentTab1.java ; FragmentTab2 ; FragmentTab3 have the same code
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentTab2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab2.xml
View view = inflater.inflate(R.layout.fragmenttab2, container, false);
return view;
}
}
here is my MainActivity.java
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends FragmentActivity {
//Button adfg = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
// Locate the viewpager in activity_main.xml
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
// Set the ViewPagerAdapter into ViewPager
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
}
}
ViewPagerAdapter.java
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class ViewPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
// Tab Titles
private String tabtitles[] = new String[] { "Tab1", "Tab2", "Tab3" };
Context context;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
switch (position) {
// Open FragmentTab1.java
case 0:
FragmentTab1 fragmenttab1 = new FragmentTab1();
return fragmenttab1;
// Open FragmentTab2.java
case 1:
FragmentTab2 fragmenttab2 = new FragmentTab2();
return fragmenttab2;
// Open FragmentTab3.java
case 2:
FragmentTab3 fragmenttab3 = new FragmentTab3();
return fragmenttab3;
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabtitles[position];
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:textColor="#000000" />
</android.support.v4.view.ViewPager>
fragmenttab1.xml ; fragmenttab2.xml ; fragmenttab3.xml has the same code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment 1" />
<Button
android:id="#+id/bajou"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ajouter fragment" />
</LinearLayout>
You need to create a method to add the fragment on the subclass of FragmentPagerAdapter, more or less like this :
//use those lists
private List<Fragment> listFragment = new ArrayList<Fragment>();
private List<String> listFragmentTitle = new ArrayList<String>();
private List<Integer> listFragmentIcon = new ArrayList<Integer>();
public void addTab(Fragment fragment,String title, int icon) {
listFragment.add(fragment);
listFragmentTitle.add(title);
listFragmentIcon.add(icon);
}
#Override
public Fragment getItem(int position) {
// TODO Auto-generated method stub
return listFragment.get(position);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listFragment.size();
}
Then you just need to use it on the subclass of Activity, example :
//create a private method to set a new - dynamic fragment in the ACTIVITY
private Fragment setFragment(int pos)
{
MyFragment myFragment = new MyFragment();
Bundle data = new Bundle();
data.putString("test", "test");
myFragment.setArguments(data);
return myFragment;
}
Finally, add the fragment (for example, inside an onClickListener) :
//INSIDE an onClickListener
pagerAdapter.addTab(setFragment(position), getItem(position).getName(), R.drawable.ic_launcher);
this is my MainActivity.java class #BlazeTama
package com.light.frag;
import com.light.frag.R;
import com.light.frag.ViewPagerAdapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends FragmentActivity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Locate the viewpager in activity_main.xml
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
// Set the ViewPagerAdapter into ViewPager
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
Button ajou = (Button) findViewById(R.id.bajou);
ajou.setOnClickListener(this);
}
private Fragment setFragment(int pos)
{
MyFragment myFragment = new MyFragment();
Bundle data = new Bundle();
data.putString("test", "test");
myFragment.setArguments(data);
return myFragment;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bajou:
ViewPagerAdapter.addTab(setFragment(position), getItem(position).getName(), R.drawable.ic_launcher);
break;
}
}
}

Android Custom ListView with ArrayList How do I open a second activity

I have this Custom ListView with ArrayList and I am trying to Open second Activity Using
the Icon Used is in the folder drawable
setOnItemClickListener(new OnItemClickListener() {}
but it force closes the app when I click on the ListItem
CbMain.java
package com.frostistudios.circuitbasicspro;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
public class CbMain extends Activity {
String[] listItems = {"Menu One","Menu Two","Menu Three"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cb_main);
ListView lv = (ListView) findViewById(R.id.listView); //listview in xml file
List<ListViewItem> items = new ArrayList<CbMain.ListViewItem>();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
if(position == 0){
//call to custom method for opening activity
openItemOneActivity();
}
else if(position == 1){
openItemTwoActivity();
}
else if(position == 2){
openItemThreeActivity();
}
}
});
items.add(new ListViewItem()
{{
ThumbnailResource = R.drawable.ic_action_call;
Title = listItems[0];
SubTitle = "";
}});
items.add(new ListViewItem()
{{
ThumbnailResource = R.drawable.ic_action_call;
Title = listItems[1];
SubTitle = "";
}});
items.add(new ListViewItem()
{{
ThumbnailResource = R.drawable.ic_action_call;
Title = listItems[2];
SubTitle = "";
}});
CustomListViewAdapter adapter = new CustomListViewAdapter(this, items);
lv.setAdapter(adapter);
}
//custom methods to open another activity
public void openItemOneActivity(){
Intent intent = new Intent(this,ItemOneActivity.class);
startActivity(intent);
}
public void openItemTwoActivity(){
Intent intent = new Intent(this,ItemTwoActivity.class);
startActivity(intent);
}
public void openItemThreeActivity(){
Intent intent = new Intent(this,ItemThreeActivity.class);
startActivity(intent);
}
class ListViewItem {
public int ThumbnailResource;
public String Title;
public String SubTitle;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
//getMenuInflater().inflate(R.menu.actionbar, menu);
//return super.onCreateOptionsMenu(menu);
return true;
}
}
CustomListViewAdapter.java
this is the custom list adapter file
package com.frostistudios.circuitbasicspro;
import java.util.List;
import com.frostistudios.circuitbasicspro.CbMain.ListViewItem;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class CustomListViewAdapter extends BaseAdapter
{
LayoutInflater inflater;
List<ListViewItem> items;
public CustomListViewAdapter(Activity context, List<ListViewItem> items) {
super();
this.items = items;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ListViewItem item = items.get(position);
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item_row, null);
ImageView imgThumbnail = (ImageView) vi.findViewById(R.id.imgThumbnail);
TextView txtTitle = (TextView) vi.findViewById(R.id.txtTitle);
TextView txtSubtitle = (TextView) vi.findViewById(R.id.txtSubTitle);
imgThumbnail.setImageResource(item.ThumbnailResource);
txtTitle.setText(item.Title);
txtSubtitle.setText(item.SubTitle);
return vi;
}
}
and this is the XML File that holds the ListView Design
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imgThumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/ic_action_call"
android:layout_marginLeft="10dp"
android:layout_marginTop="2dp"/>
<TextView
android:id="#+id/txtTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imageView1"
android:layout_toRightOf="#+id/imageView1"
android:text="Large Text"
android:layout_marginLeft="60dp"
android:layout_marginTop="6dp"/>
<TextView
android:id="#+id/txtSubTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:text="" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:src="#drawable/arrow" />
</RelativeLayout>
Looking from your log cat, the error seems because the theme you used is not from the compat. Check your manifest, and make sure you use the compat theme.
Example (for ALL acitivities in your apps) :
<application
//other code
android:theme="#style/Theme.AppCompat.Light" >
Or if you only use the action bar on particular activity :
<Activity
//other code
android:theme="#style/Theme.AppCompat.Light" >
TIPS :
Always pay attention to the log cat, especially the caused by. I know the problem from there.
It would help a lot if you posted the error output. Are your other Activities declared in your manifest? You already have a context in the adapter, so you could set it there and try. I also think that View vi is unecessary, you can use convertView.

Error while using ListFragement

I am developing an android app for online payment for which I want to display Lists of restaurants under the tab named Restaurants. Same as this some other tabs will have list below them and a few tabs will have form under them (if possible and not difficult otherwise I will stay with the lists only)
Here is the code I have written. It contains an error in the Adapter class and may be some logical errors which I am not sure about as this is my first ever android app.
Main.java File
package com.example.tabswithswipe;
import com.example.tabsswipe.adapter.TabsPagerAdapter;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "Retaurants", "Super Store", "Fuel Stations"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
acivity_main.xml File
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
items_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView1"
android:layout_width="50dp"
android:layout_height="50dp"
android:contentDescription="#string/app_name" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name" />
</LinearLayout>
TabPagerAdapter.java Adapter File (Error in this file)
package com.example.tabsswipe.adapter;
import com.example.tabsswipe.*;
import android.app.ListFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new SuperStoreFragment();
case 1:
return new FuelStationsFragment();
case 2:
return new RestaurantsFragment(); //Error Here
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
RestaurantsFragment.java
package com.example.tabsswipe.adapter;
//import com.example.MainActivity.MyAdapter;
import com.example.tabswithswipe.R;
import android.app.ListFragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class RestaurantsFragment extends ListFragment {
LayoutInflater inflater;
ViewGroup container;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
this.inflater = inflater;
View rootView = inflater.inflate(R.layout.list_items, container, false);
setListAdapter(new MyAdapter(getActivity(), android.R.layout.simple_list_item_1, R.id.textView1, getResources().getStringArray(R.array.items)));
return rootView;
}
private class MyAdapter extends ArrayAdapter<String>
{
public MyAdapter(Context context, int resource, int textViewResourceId,
String[] strings) {
super(context, resource, textViewResourceId, strings);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_items, container, false);
String [] items = getResources().getStringArray(R.array.items);
ImageView iv = (ImageView) row.findViewById(R.id.imageView1);
TextView tv = (TextView) row.findViewById(R.id.textView1);
tv.setText(items[position]);
if(items[position].equals("kfc"))
{
iv.setImageResource(R.drawable.kfc);
}
else if(items[position].equals("pizzaHut"))
{
iv.setImageResource(R.drawable.pizzahut);
}
else if(items[position].equals("Domino"))
{
iv.setImageResource(R.drawable.dominos);
}
else if(items[position].equals("hardees") )
{
iv.setImageResource(R.drawable.hardees);
}
else if(items[position].equals("TuttiFrutti"))
{
iv.setImageResource(R.drawable.tuttifrutti);
}
else if(items[position].equals("McDonalds"))
{
iv.setImageResource(R.drawable.mcdonalds);
}
else if(items[position].equals("21 Street"))
{
iv.setImageResource(R.drawable.ic_launcher);
}
return row;
}
}
// View rootView = inflater.inflate(R.layout.fragment_movies, container, false);
// return rootView;
// }
}
SuperStoreFragment.java
package com.example.tabsswipe.adapter;
import com.example.tabswithswipe.R;
import android.app.ListFragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SuperStoreFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_super_stores, container, false);
return rootView;
}
}
fragment_super_stores.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#fa6a6a" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Design Super Stores Screen"
android:textSize="20dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
FuelStationsFragment.java
package com.example.tabsswipe.adapter;
import com.example.tabswithswipe.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FuelStationsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fuel_stations, container, false);
return rootView;
}
}
fragment_fuel_stations.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ff8400" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Design Fuel Stations Screen"
android:textSize="20dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
Please tell me how, where and what error occurred. Any kind of help will be really appreciated e.g. Tutorial, code example or even the error resolution of this code. Please ignore my silliness if any. Thank You.

Implementing multiple fragments in a single activity Dynamically

I am working on fragments
Use case i am trying to implement::
I am using dynamic fragments
I am using three fragments in a single activity
my goal is to communicate between all the three fragments
I am using support package for fragments
Each fragment has a single widget
my_fragment1 has edittext
my_fragment2 has button
my_fragment3 has TextView
On click of button the text from the edittext must be displayed in the textview
What i have tried so far i have constructed most of the scenario below
Top_Fragment.java
public class Top_Fragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view=inflater.inflate(R.layout.my_fragment1, container, false);
return view;
}
}
Middle_Fragment.java
package com.example.deleteme;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class Middle_Fragment extends Fragment{
View view;
Button btn;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view=inflater.inflate(R.layout.my_fragment2, container, false);
btn=(Button) view.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
return view;
}
}
Bottom_Fragment.java
public class Bottom_Fragment extends Fragment{
View view;
TextView display_text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view=inflater.inflate(R.layout.my_fragment3, container,false);
display_text=(TextView) view.findViewById(R.id.editText1);
return view;
}
public void setName(String Name){
display_text.setText("Result::" + Name);
}
}
MainActivity.java
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Top_Fragment frg=new Top_Fragment();//create the fragment instance for the top fragment
Middle_Fragment frg1=new Middle_Fragment();//create the fragment instance for the middle fragment
Bottom_Fragment frg2=new Bottom_Fragment();//create the fragment instance for the bottom fragment
FragmentManager manager=getSupportFragmentManager();//create an instance of fragment manager
FragmentTransaction transaction=manager.beginTransaction();//create an instance of Fragment-transaction
transaction.add(R.id.My_Container_1_ID, frg, "Frag_Top_tag");
transaction.add(R.id.My_Container_2_ID, frg1, "Frag_Middle_tag");
transaction.add(R.id.My_Container_3_ID, frg2, "Frag_Bottom_tag");
transaction.commit();
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity"
android:background="#color/black">
<FrameLayout
android:id="#+id/My_Container_1_ID"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:background="#color/yellow">
</FrameLayout>
<FrameLayout
android:id="#+id/My_Container_2_ID"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/My_Container_1_ID"
android:background="#color/Orange" >
</FrameLayout>
<FrameLayout
android:id="#+id/My_Container_3_ID"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/My_Container_2_ID"
android:background="#color/purple" >
</FrameLayout>
</RelativeLayout>
my_fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/green" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:textColor="#000000"
android:singleLine="true" >
<requestFocus />
</EditText>
</RelativeLayout>
my_fragment2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/pink">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#color/black"
android:text="Button"
android:textColor="#FFFFFF" />
</RelativeLayout>
my_fragment3.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="TextView"
android:textColor="#000000"
android:textSize="30dp" />
</RelativeLayout>
My output is Like below ::
What I am having problem in achieving ::
I am not able to set the value obtained from edit text to
textview on click of the button
Any Ideas?
All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.
http://developer.android.com/training/basics/fragments/communicating.html
test.java // in your case its MainActivity
public class test extends FragmentActivity implements textEntered {
String value;
boolean check = false;
BottomFragment frg2;
FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Top_Fragment frg = new Top_Fragment();
frg2 = new BottomFragment();
FragmentManager manager = getSupportFragmentManager();
transaction = manager.beginTransaction();
transaction.add(R.id.My_Container_1_ID, frg, "Frag_Top_tag");
transaction.add(R.id.My_Container_3_ID, frg2, "Frag_Bottom_tag");
transaction.commit();
}
#Override
public void setValue(String editextvalue) {
value = editextvalue;
if (frg2 != null) {
frg2.setName(value);
} else {
Toast.makeText(getApplicationContext(), "fragment 2 is null", 1000).show();
}
}
}
Top_Fragment.java
public class Top_Fragment extends Fragment {
textEntered mCallback;
Button b;
EditText ed;
public interface textEntered {
public void setValue(String editextvalue);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.my_fragment1, container, false);
ed = (EditText) view.findViewById(R.id.editText1);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
b = (Button) getView().findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String s = ed.getText().toString();
mCallback.setValue(s);
}
});
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (textEntered) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() +
" must implement textEntered");
}
}
}
my_fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:textColor="#000000"
android:singleLine="true" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Button" />
</RelativeLayout>
Change to
display_text=(TextView) view.findViewById(R.id.textView1);
// id is textView 1 not editText1
in BottomFragment
snap
Communication between Fragments
There can be many scenarios where communication between fragment is required. You need to pass data between fragments on button click event. You may also use Android toolbar to switch between fragments. When you add buttons to your toolbar, you need to dynamically change screen using fragment.
Create an interface which will help us to communicate
Communicate.java
package com.example.amaanmemon.testfragment;
interface Communicate {
public void sendData();
}
TopFragment.java
package com.example.amaanmemon.testfragment;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class TopFragment extends Fragment {
EditText firstName;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view=inflater.inflate(R.layout.my_fragment1, container, false);
return view;
}
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
firstName = (EditText) getActivity().findViewById(R.id.editText1);
}
public String getData(){
return firstName.getText().toString();
}
}
MiddleFragment.java
package com.example.amaanmemon.testfragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class MiddleFragment extends Fragment implements OnClickListener{
View view;
Button btn;
Communicate cm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view=inflater.inflate(R.layout.my_fragment2, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
cm = (Communicate) getActivity();
btn = (Button) getActivity().findViewById(R.id.button1);
btn.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
cm.sendData();
}
}
BottomFragment.java
package com.example.amaanmemon.testfragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class BottomFragment extends Fragment{
int count;
View view;
TextView display_text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view=inflater.inflate(R.layout.my_fragment3, container,false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
display_text = (TextView)getActivity().findViewById(R.id.textView1);
}
public void incrementData(String displayText){
display_text.setText(displayText);
}
}
MainActivity.java
package com.example.amaanmemon.testfragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class MainActivity extends FragmentActivity implements Communicate{
TopFragment frg;
MiddleFragment frg1;
BottomFragment frg2;
FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frg = new TopFragment();
frg1 = new MiddleFragment();
frg2 = new BottomFragment();
FragmentManager manager=getSupportFragmentManager();
transaction=manager.beginTransaction();
transaction.add(R.id.My_Container_1_ID, frg, "Frag_Top_tag");
transaction.add(R.id.My_Container_2_ID, frg1, "Frag_Middle_tag");
transaction.add(R.id.My_Container_3_ID, frg2, "Frag_Bottom_tag");
transaction.commit();
}
#Override
public void sendData() {
String temp = frg.getData();
frg2.incrementData(temp);
}
}
You can copy xml files from question.
you can watch the output below.
You can use the Activity for that.
in the onClick of the bottom fragment you can do something like
((MainActivity) getActivity()).doIt();
And make a method doIt in your MainActivity maybe something like this
public void doIt(){
frg2.setName(frg.getText())
}
and in the top fragment make a method getText that returns the text of the EditText

Categories

Resources