I have a Fragment (PokedexFragment.java) which contains a GridView (via Custom Recyclerview) with a few items. When I click on an item the current Fragment will be replaced by another fragment (SinglePokemonFragment.java) with the details from the selected item.
The user would like to go to the last or next item in the gridview directly (pressing Forward- / Backbutton). When he presses the Hardware "Backbutton" the old Fragment (SinglePokemonFragment.java) is still visible!
I do not like to use addBackStack, because there should not be any backstacks.
What part of the code is wrong or has to be updated and why?
I thought replace means replace...
SinglePokemonFragment.java (Buttons)
cLayBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create new fragment and transaction
Fragment newFragment = new SinglePokemonFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Bundle bundle = new Bundle();
bundle.putInt("POKEMON_ID", Integer.parseInt(db.getPokemonID(intPokeDexID-1)));
bundle.putInt("ARRAY_ID", intPokeArrayID-1);
bundle.putInt("POKEMON_ID_MAX", getIntPokemonIDMax);
bundle.putInt("POKEDEX_ID", intPokeDexID-1);
newFragment.setArguments(bundle);
transaction.replace(R.id.frame_container, newFragment);
// Commit the transaction
transaction.commit();
}
});
cLayForward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create new fragment and transaction
Fragment newFragment = new SinglePokemonFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Bundle bundle = new Bundle();
bundle.putInt("POKEMON_ID", Integer.parseInt(db.getPokemonID(intPokeDexID+1)));
bundle.putInt("ARRAY_ID", intPokeArrayID+1);
bundle.putInt("POKEMON_ID_MAX", getIntPokemonIDMax);
bundle.putInt("POKEDEX_ID", intPokeDexID+1);
newFragment.setArguments(bundle);
transaction.replace(R.id.frame_container, newFragment);
// Commit the transaction
transaction.commit();
}
});
MainFragment.java (with ViewPager)
public class MainFragment extends Fragment {
private TextView titleTxtView;
private static final String ARG_PARAM1 = "param1";
private String mParam1;
TabLayout tabLayout;
ViewPager viewPager;
private FragmentActivity myContext;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
tabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
viewPager = (ViewPager) view.findViewById(R.id.pager);
if (viewPager != null) {
Log.v("ViewPager", "IS NOT NULL");
setupViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_pokedex);
tabLayout.getTabAt(1).setIcon(R.drawable.pokedex_kanto);
tabLayout.getTabAt(2).setIcon(R.drawable.pokedex_johto);
tabLayout.getTabAt(3).setIcon(R.drawable.pokedex_hoenn);
}else{
Log.v("ViewPager", "ISNULL");
}
return view;
}
#Override
public void onAttach(Activity activity) {
myContext=(FragmentActivity) activity;
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
}
private void setupViewPager(ViewPager viewPager) {
PagerAdapter adapter = new PagerAdapter(getChildFragmentManager(), getActivity());
adapter.addFragment(new PokedexFragment().newInstance(0, 9999), "Alle");
adapter.addFragment(new PokedexFragment().newInstance(1, 151), "Kanto");
adapter.addFragment(new PokedexFragment().newInstance(152, 251), "Johto");
adapter.addFragment(new PokedexFragment().newInstance(252, 386), "Hoenn");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
}
}
PokedexFragment.java
package com.spicysoftware.goexpert;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
import static android.content.ContentValues.TAG;
public class PokedexFragment extends Fragment{
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
MySQLiteHelper db;
// TODO: Rename and change types of parameters
private int param1, param2;
public PokedexFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
param1 = getArguments().getInt(ARG_PARAM1);
param2 = getArguments().getInt(ARG_PARAM2);
}
}
public static PokedexFragment newInstance(int intDexFrom, int intDexTo) {
PokedexFragment fragment = new PokedexFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, intDexFrom);
args.putInt(ARG_PARAM2, intDexTo);
fragment.setArguments(args);
Log.d(TAG, "newInstance: 2F");
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_pokedexall, container, false);
db = new MySQLiteHelper(getActivity());
RecyclerView recyclerView = (RecyclerView)myView.findViewById(R.id.rvPokedex);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(),4);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemViewCacheSize(20);
recyclerView.setDrawingCacheEnabled(true);
recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
CustomRecyclerAdapterPokedexGrid adapter = new CustomRecyclerAdapterPokedexGrid(getActivity(), db.getPokemon(param1,param2));
recyclerView.setAdapter(adapter);
return myView;
}
}
CustomRecyclerAdapterPokedexGrid.java (ItemClickListener)
viewHolder.setClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
if (isLongClick) {
} else {
String test = strPokemonInfo.get(i);
String[] separated = test.split("/");
intPokemonID = Integer.parseInt(separated[0]);
pokeDexID = Integer.parseInt(separated[1]);
Fragment myFragment = new SinglePokemonFragment();
Bundle bundle = new Bundle();
bundle.putInt("POKEMON_ID", intPokemonID);
bundle.putInt("ARRAY_ID", i);
bundle.putInt("POKEMON_ID_MAX", strPokemonInfo.size());
bundle.putInt("POKEDEX_ID", pokeDexID);
myFragment.setArguments(bundle);
AppCompatActivity activity = (AppCompatActivity) view.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, myFragment).addToBackStack(null).commit();
}
}
});
Related
I'm trying to create VeiwPager inside a Fragment using FragmentStatePagerAdapter.
it displays the first fragment but after scrolling to the second fragment there is just white fragment (even on scrolling back to the first fragment)
I've tried to use PagerAdapter and set pictures without fragment but the result is same.
is there RAM problem ? what can I do to solve it?
Home fragment(contains ViewPager) :
private void initSlideShow(View view){
VPImageSlider = (ViewPager16by9) view.findViewById(R.id.VPImageSlider);
sliderDotsPanel = (LinearLayout) view.findViewById(R.id.SliderDots);
VPImageSliderAdapter vpImageSliderAdapter = new VPImageSliderAdapter(getFragmentManager());
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_1);
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_2);
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_3);
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_4);
vpImageSliderAdapter.addSlide(R.drawable.dc_slide_5);
VPImageSlider.setAdapter(vpImageSliderAdapter);
}
ViewPager Fragment:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import iranelab.samsoft.net.iranelab.Classes.ImageView16by9;
import iranelab.samsoft.net.iranelab.R;
public class ViewPagerFragment extends Fragment {
private static final String ARG_PARAM4 = "imageTest";
private int imageTest;
public ViewPagerFragment() {}
public static ViewPagerFragment newInstance(String imageId, String type, String text,int imageTest) {
ViewPagerFragment fragment = new ViewPagerFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM4, imageTest);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
imageTest = getArguments().getInt(ARG_PARAM4);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_view_pager, container, false);
ImageView16by9 image = (ImageView16by9) view.findViewById(R.id.IVSlide);
image.setImageResource(imageTest);
return view;
}
}
ViewPager Adapter :
public class VPImageSliderAdapter extends FragmentStatePagerAdapter {
private int[] slides = {};
public VPImageSliderAdapter(FragmentManager fm){
super(fm);
}
public void addSlide(int drawable){
slides = Arrays.copyOf(slides,slides.length+1);
slides[slides.length-1]=drawable;
}
#Override
public int getCount() {
return slides.length;
}
#Override
public Fragment getItem(int position) {
return ViewPagerFragment.newInstance(slides[position]);
}
}
Change
VPImageSliderAdapter vpImageSliderAdapter = new VPImageSliderAdapter(getFragmentManager());
to
VPImageSliderAdapter vpImageSliderAdapter = new VPImageSliderAdapter(getChildFragmentManager());
it will work
Just needed to add :
ViewPager.setOffscreenPageLimit(5);
My app have one activity A and two fragments F1 and F2.
One clicking button in F1, the F1 is replaced by F2.
I want to transfer data in F1 to F2. For that I implemented the interface in F1 and override its method in A.
But when sending the data from A to F2, my reference(sFragment in code A) to the F2 remains null,due to which data is not sent to F2. I am getting reference to the F2 using TAG provided while replacing F1 by F2.
Does it have something to do with the lifecycle like when I am trying to get reference to the F2 it hasn't yet created?
F1
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.form_fragment1,container,false);
nextB = (Button) v.findViewById(R.id.f1Next);
nextB.setOnClickListener(this);
return v;
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.f1Next:
SFragment fragment = new SFragment();
FragmentManager mManager = getFragmentManager();
FragmentTransaction mTransaction = mManager.beginTransaction();
mTransaction.replace(R.id.fragment_container,fragment,"SecondF"); // SecondF
mTransaction.addToBackStack(null); // this is required to move to the previous fragment
mTransaction.commit();
commListener.PlaceName(data1,data2); //passing value to activity
break;
}
}
interface CommBridge{
void PlaceName(String data1,String data2);
}
#Override
public void onAttach(Context context){
super.onAttach(context);
if (context instanceof CommBridge){
commListener= (CommBridge) context;
}
}
}
A
#Override
public void PlaceName(String data1, String data2) {
SFragment sFragment=(SFragment) getFragmentManager().findFragmentByTag("SecondF");
if (sFragment != null && sFragment.isInLayout()){
Log.d("STATE","1");
sFragment.setPlace(data1,data2);
}else{
Log.d("STATE","2"); // this is always the case
}
F2
public class SFragment extends Fragment {
String Place2,Place1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.form_fragment2,container,false);
return v;
}
void setPlace(String data1, String data2){
place1 = data1;
place2 = data2;
}
}
Let the activity be responsible for handling the onClick event of the Fragment. See the example below.
Activity:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity implements Fragment1.CommBridge {
private Fragment1 fragment1 = new Fragment1();
private Fragment2 fragment2 = new Fragment2();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content, fragment1)
.commit();
}
#Override
public void onButtonClicked(String data1, String data2) {
fragment2.setData(data1, data2);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content, fragment2)
.commit();
}
}
Fragment1:
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class Fragment1 extends Fragment {
interface CommBridge {
void onButtonClicked(String data1, String data2);
}
private CommBridge handler;
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof CommBridge) {
handler = (CommBridge) context;
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1, container, false);
Button button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.onButtonClicked("Data1", "Data2");
}
});
return view;
}
}
Fragment2
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Fragment2 extends Fragment {
private String data1;
private String data2;
public void setData(String data1, String data2) {
this.data1 = data1;
this.data2 = data2;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment2, container, false);
TextView textView = (TextView) view.findViewById(R.id.textView);
textView.setText(data1 + "\n" + data2);
return view;
}
}
I would recommend putting the code for replacing the fragment in your Activity and put the values which should be passed to SFragment() in its arguments directly:
SFragment newFragment = new SFragment();
Bundle args = new Bundle();
args.putString("place1", data1);
args.putString("place2", data1);
newFragment.setArguments(args);
You could get them in SFragment#onCreateView()
String place1 = getArguments().getString("place1");
Also have a look here: https://developer.android.com/training/basics/fragments/communicating.html
I'm having a problem here
i have activity with tablayout viewpager get objects from database and pass them by bundle to the tabs fragment
the problem is bundle getting null in the tab fragment
here is the Activity
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
public class Categorys extends DrawerActivity implements TabLayout.OnTabSelectedListener {
String url,result;
//This is our tablayout
private TabLayout tabLayout;
//This is our viewPager
private ViewPager viewPager;
ProgressDialog progress;
DBhelper db;
Bundle bundle;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categorys);
//Adding toolbar to the activity
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// getSupportActionBar().setDisplayShowHomeEnabled(true);
set();
db = new DBhelper(Categorys.this);
db.open();
List<ProductObj> productslistfromDB = db.getAllProductsUp();
db.close();
ProductObj product = productslistfromDB.get(0);
String namee = product.getName();
String details = product.getDetails();
String category = product.getcategory();
String ownerr = product.getOwner();
String weight = product.getWeight();
String size = product.getSize();
String price = product.getPrice();
String imageurl = product.getimageurl();
String owner_address = product.getOwner_address();
String owner_phone = product.getOwner_phone();
String UID = product.getUID();
productpojo productpoj = new productpojo();
productpoj.setName(namee);
productpoj.setDetails(details);
productpoj.setcategory(category);
productpoj.setOwner(ownerr);
productpoj.setWeight(weight);
productpoj.setSize(size);
productpoj.setPrice(price);
productpoj.setimageurl(imageurl);
productpoj.setOwner_address(owner_address);
productpoj.setOwner_phone(owner_phone);
productpoj.setUID(UID);
ArrayList<productpojo> productlisttosend = new ArrayList<>();
productlisttosend.add(productpoj);
Tab1 fragmentGet1 = new Tab1();
Tab2 fragmentGet2 = new Tab2();
bundle = new Bundle();
bundle.putParcelableArrayList("arraylist", productlisttosend);
fragmentGet1.setArguments(bundle);
fragmentGet2.setArguments(bundle);
//Initializing the tablayout
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
//Adding the tabs using addTab() method
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_clothes));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_electrical));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_hammer));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_cars));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_interior_accesories));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_buid));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
//Creating our pager adapter
Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());
//Adding adapter to pager
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//Adding onTabSelectedListener to swipe views
tabLayout.setOnTabSelectedListener(this);
}
#Override
public void onTabSelected(TabLayout.Tab tab)
{
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
#Override
public void onBackPressed() {
}
}
and here is the first fragment Tab1
import android.content.Intent;
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.AdapterView;
import android.widget.GridView;
import java.util.ArrayList;
/**
* Created by toshiba c660-12T on 16/08/2016.
*/
public class Tab1 extends Fragment {
GridView gv;
int[] clicknums;
ArrayList<productpojo> productarraylist = null;
Bundle bundle;
//Overriden method onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1, container, false);
bundle=this.getArguments();
if (bundle != null) {
productarraylist = bundle.getParcelableArrayList("arraylist");
}
go();
return view;
}
public void go(){
productpojo propoj; = productarraylist.get(0);
String namee = propoj.getName();
String details = propoj.getDetails();
String category = propoj.getcategory();
String ownerr = propoj.getOwner();
String weight = propoj.getWeight();
String size = propoj.getSize();
String price = propoj.getPrice();
String imageurl = propoj.getimageurl();
String owner_address = propoj.getOwner_address();
String owner_phone = propoj.getOwner_phone();
String UID = propoj.getUID();
ProductObj product = new ProductObj();
product.setName(namee);
product.setDetails(details);
product.setcategory(category);
product.setOwner(ownerr);
product.setWeight(weight);
product.setSize(size);
product.setPrice(price);
product.setimageurl(imageurl);
product.setOwner_address(owner_address);
product.setOwner_phone(owner_phone);
product.setUID(UID);
final ArrayList<ProductObj> productlist = new ArrayList<>();
productlist.add(product);
gv = (GridView) getView().findViewById(R.id.grid);
clicknums = new int[productlist.size()];
gv.setAdapter(new CustomGrid(getActivity(), productlist));
gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int clicknum;
clicknums[position] = clicknums[position] + 1;
clicknum = clicknums[position];
String image = productlist.get(position).imageurl;
String text = productlist.get(position).name;
String owenr = productlist.get(position).owner;
Intent intent = new Intent(getActivity(), Product.class);
intent.putExtra("numofclick", clicknum);
intent.putExtra("title", text);
intent.putExtra("owner", owenr);
intent.putExtra("image", image);
//Start details activity
startActivity(intent);
}
});
}
and here is the second fragment Tab2
import android.content.Intent;
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.AdapterView;
import android.widget.GridView;
import java.util.ArrayList;
/**
* Created by toshiba c660-12T on 16/08/2016.
*/
public class Tab2 extends Fragment {
GridView gv;
int[] clicknums;
ArrayList<productpojo> productarraylist = null;
Bundle bundle;
//Overriden method onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab2, container, false);
bundle=this.getArguments();
if (bundle != null) {
productarraylist = bundle.getParcelableArrayList("arraylist");
}
go();
return view;
}
public void go(){
productpojo propoj; = productarraylist.get(0);
String namee = propoj.getName();
String details = propoj.getDetails();
String category = propoj.getcategory();
String ownerr = propoj.getOwner();
String weight = propoj.getWeight();
String size = propoj.getSize();
String price = propoj.getPrice();
String imageurl = propoj.getimageurl();
String owner_address = propoj.getOwner_address();
String owner_phone = propoj.getOwner_phone();
String UID = propoj.getUID();
ProductObj product = new ProductObj();
product.setName(namee);
product.setDetails(details);
product.setcategory(category);
product.setOwner(ownerr);
product.setWeight(weight);
product.setSize(size);
product.setPrice(price);
product.setimageurl(imageurl);
product.setOwner_address(owner_address);
product.setOwner_phone(owner_phone);
product.setUID(UID);
final ArrayList<ProductObj> productlist = new ArrayList<>();
productlist.add(product);
gv = (GridView) getView().findViewById(R.id.grid);
clicknums = new int[productlist.size()];
gv.setAdapter(new CustomGrid(getActivity(), productlist));
gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int clicknum;
clicknums[position] = clicknums[position] + 1;
clicknum = clicknums[position];
String image = productlist.get(position).imageurl;
String text = productlist.get(position).name;
String owenr = productlist.get(position).owner;
Intent intent = new Intent(getActivity(), Product.class);
intent.putExtra("numofclick", clicknum);
intent.putExtra("title", text);
intent.putExtra("owner", owenr);
intent.putExtra("image", image);
//Start details activity
startActivity(intent);
}
});
}
pager class
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by toshiba c660-12T on 16/08/2016.
*/
//Extending FragmentStatePagerAdapter
public class Pager extends FragmentStatePagerAdapter {
//integer to count number of tabs
int tabCount;
//Constructor to the class
public Pager(FragmentManager fm, int tabCount) {
super(fm);
//Initializing tab count
this.tabCount= tabCount;
}
//Overriding method getItem
#Override
public Fragment getItem(int position) {
//Returning the current tabs
switch (position) {
case 0:
Tab1 tab1 = new Tab1();
return tab1;
case 1:
Tab2 tab2 = new Tab2();
return tab2;
default:
return null;
}
}
//Overriden method getCount to get the number of tabs
#Override
public int getCount() {
return tabCount;
}
}
Need to call getArguments() in onCreateView to get Bundle which is send using setArguments :
bundle=this.getArguments();
I am fairly new to developing Android applications. I am trying to create an application that allows you to save a picture in the "Pictures" folder named Property_Picture.jpg using the last (camera) tab. However, both the last two tabs are opening the camera, and the picture is also not being saved once you take a picture. Any help would be greatly appreciated. Thank you!
Here is my code:
package com.example.prcentry02;
import java.io.File;
import java.util.Locale;
import android.app.Activity;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v13.app.FragmentPagerAdapter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
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;
import android.widget.Toast;
public class MainActivity extends Activity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
getFragmentManager();
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position== mSectionsPagerAdapter.getCount()-1)
{
return CameraFragment.newInstance(position);
}
else if (position== 0)
{
return LocationFragment.newInstance(position);
}
else
{
return propertyrecordFragment.newInstance(position);
}
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.PRC_Location).toUpperCase(l);
case 1:
return getString(R.string.PRC_1).toUpperCase(l);
case 2:
return getString(R.string.PRC_2).toUpperCase(l);
case 3:
return getString(R.string.Camera).toUpperCase(l);
}
return null;
}
}
public static class LocationFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static LocationFragment newInstance(int sectionNumber) {
LocationFragment fragment = new LocationFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public LocationFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.location_main, container,false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText("Location" + this.getArguments());
return rootView;
}
}
public static class CameraFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static CameraFragment newInstance(int sectionNumber) {
CameraFragment fragment = new CameraFragment();
Bundle args = new Bundle();
args.putInt(CameraFragment.ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public CameraFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.camera_main, container,false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText("camera" + ARG_SECTION_NUMBER);
Context context = getActivity();
PackageManager packageManager = context.getPackageManager();
if(packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA) == false){
Toast.makeText(getActivity(), "This device does not have a camera.", Toast.LENGTH_SHORT)
.show();
}
Intent imageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File image = new File("~/Pictures/", "Property_Picture.jpg");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent,0);
return rootView;
}
}
public static class propertyrecordFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static propertyrecordFragment newInstance(int sectionNumber) {
propertyrecordFragment fragment = new propertyrecordFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public propertyrecordFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.propertyrecordcard_main, container,false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText("PRC goes here");
return rootView;
}
}
}
I'm trying to build a simple application that displays two fragments. The first fragment is displayed by default. It contains a list of names which you can choose and when you click on one of the items, it supposes to display a second fragment with a text view, displaying the name you have chosen.
The problem is everytime I click one of the names on the list, it throws me a NullPointerException. I really don't know what could be the problem.
Here are the codes( The app contains three class - two fragments and one activity. The FriendsF fragment is the list fragment and it performs well. The second fragment is FeedFragment and onitemclick it should display the name that was clicked)
FriendsF fragment:
package com.example.fragmentsexcersize;
import android.app.Activity;
import android.app.ListFragment;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class FriendsF extends ListFragment {
private static final String[] FRIENDS = { "ladygaga", "msrebeccablack",
"taylorswift13" };
public interface SelectionListener {
public void onItemSelected(int position);
}
private SelectionListener mCallback;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? android.R.layout.simple_list_item_activated_1
: android.R.layout.simple_list_item_1;
setListAdapter(new ArrayAdapter<String>(getActivity().getBaseContext(), layout, FRIENDS));
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (SelectionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement SelectionListener");
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (isInTwoPaneMode()) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
}
#Override
public void onListItemClick(ListView l, View view, int position, long id) {
mCallback.onItemSelected(position);
}
private boolean isInTwoPaneMode() {
return getFragmentManager().findFragmentById(R.id.tweets) != null;
}
}
FeedFragment:
package com.example.fragmentsexcersize;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FeedFragment extends Fragment{
private TextView mTextView;
private static final String[] data = { "ladygaga", "msrebeccablack",
"taylorswift13" };
public FeedFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tweet_view, container, false);
mTextView = (TextView) rootView.findViewById(R.id.tweet_view);
return rootView;
}
public void updateFeedDisplay(int position) {
mTextView.setText(data[position]);
}
}
MainActivity:
package com.example.fragmentsexcersize;
import android.app.Activity;
import android.app.FragmentManager;
import android.os.Bundle;
import android.app.FragmentTransaction;
public class MainActivity extends Activity implements FriendsF.SelectionListener{
private FriendsF mFriendsFragment;
private FeedFragment mFeedFragment;
private FragmentManager fragMana;
private FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFriendsFragment = new FriendsF();
fragMana = getFragmentManager();
transaction = fragMana.beginTransaction();
transaction.add(R.id.friends, mFriendsFragment);
transaction.commit();
}
private boolean isInTwoPaneMode() {
return findViewById(R.id.tweets) == null;
}
public void onItemSelected(int position) {
if (mFeedFragment == null)
mFeedFragment = new FeedFragment();
if (!isInTwoPaneMode()) {
transaction = fragMana.beginTransaction();
transaction.add(R.id.tweets, mFeedFragment);
transaction.commit();
}
mFeedFragment.updateFeedDisplay(position);
}
}
Make the following changes to your source:
MainActivity
public void onItemSelected(int position) {
Bundle bundle = new Bundle();
if (mFeedFragment == null)
mFeedFragment = new FeedFragment();
if (!isInTwoPaneMode()) {
bundle.putInt("POSITION", position);
mFeedFragment.setArguments(bundle);
transaction = fragMana.beginTransaction();
transaction.replace(R.id.tweets, mFeedFragment);
transaction.commit();
}
}
FeedFragment
private TextView mTextView;
private static final String[] data = { "ladygaga", "msrebeccablack",
"taylorswift13" };
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
View rootView = inflater.inflate(R.layout.tweet_view, container, false);
mTextView = (TextView) rootView.findViewById(R.id.tweet_view);
int mPosition = getArguments().getInt("POSITION", 0);
mTextView.setText(data[mPosition]);
return rootView;
}