Destroy activity containing two fragments after clicking Andorid Back Button - java

Problem SOLVED!
ISSUE:
I have problem, and I can't find any solution. I have Maps_Activity, which contains two fragments. Both fragments show google maps v2 and I display them on screen thanks to two ActionBar tabs.
The problem is appearing when I want to return to previous activity. When I click Android back button, my whole application turns down, shows pupup, that my application was stopped.
What I should add to my code to remove this error?
Solution:
Maps_Activity.java
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import com.google.android.gms.maps.MapFragment;
public class Maps_Activity extends Activity {
public static FragmentManager manager;
Fragment fragmentTab1 = new Medical_Shops_Map();
Fragment fragmentTab2 = new Medical_Clicnics_Map();
Button Medical_Shops_Button, Medical_Clinics_Button;
ActionBar actionBar ;
#Override
public void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_maps_);
manager = getFragmentManager();
actionBar=getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab1=actionBar.newTab();
tab1.setText("Apteki 24H/7");
tab1.setTabListener(new MyTabsListener(fragmentTab1));
ActionBar.Tab tab2=actionBar.newTab();
tab2.setText("Przychodnie Lekarskie");
tab2.setTabListener(new MyTabsListener(fragmentTab2));
actionBar.addTab(tab1);
actionBar.addTab(tab2);
}
protected class MyTabsListener implements ActionBar.TabListener {
private Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
ft = manager.beginTransaction();
ft.replace(R.id.map_container, fragment);
ft.commit();
Log.e("Activity", "Fragment replace");
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
// some people needed this line as well to make it work:
MapFragment mMap2 = ((MapFragment) Maps_Activity.manager.findFragmentById(R.id.map));
ft = manager.beginTransaction();
if(mMap2!=null)
{
ft.remove(mMap2);
ft.commit();
Log.e("Activity", "Mapa_fragment destroy");
}
else
{
MapFragment mMap1 = ((MapFragment) Maps_Activity.manager.findFragmentById(R.id.map1));
ft.remove(mMap1);
ft.commit();
Log.e("Activity", "Mapa_fragment2 destroy");
}
}
}
}
One of the fragments:
import android.os.Bundle;
import android.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class Medical_Clicnics_Map extends Fragment implements OnMapReadyCallback {
private static View view;
private static GoogleMap mMap2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.medical__clicnics__map, container, false);
setUpMapIfNeeded();
return view;
}
public void setUpMapIfNeeded() {
MapFragment mMap2 = ((MapFragment) Maps_Activity.manager
.findFragmentById(R.id.map1));
mMap2.getMapAsync(Medical_Clicnics_Map.this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
Log.d("Activity", "Map ready");
googleMap.setMyLocationEnabled(true);
LatLng sydney = new LatLng(-33.867, 151.206);
googleMap.addMarker(new MarkerOptions()
.title("Sydney")
.snippet("The most populous city in Australia.")
.position(sydney));
}
}
Maybe for someone this code will be helpful ;)

Related

MapFragment on a fragment

Im developing an app that displays a map on a fragment. Everything is set up, but there's small thing that is not letting me finish it.
gMapFragment.java:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class gMapFragment extends Fragment implements OnMapReadyCallback {
public gMapFragment() {
// Required empty public constructor
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_map, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
MapFragment fragment = (MapFragment) getChildFragmentManager().findFragmentById(R.id.map);
fragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng marker = new LatLng(46.33328, 15.38173);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(marker,13));
googleMap.addMarker(new MarkerOptions().title(("HERE WE ARE!")).position(marker));
}
}
I call this fragment from button in another frament and this is the method that calls it:
public void onClick(View view) {
Fragment fragment = null;
switch (view.getId()) {
case R.id.SearchButton:
fragment = new gMapFragment();
replaceFragment(fragment);
break;
}
}
public void replaceFragment(Fragment someFragment) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, someFragment);
transaction.addToBackStack(null);
transaction.commit();
}
I get error "gMapFragment cannot be converted to fragment" Any idea how to fix this? thanks!
First, make sure that you're consistent with your Fragment imports. Use either import android.app.Fragment in all classes or import android.support.v4.app.Fragment; in all classes. Don't mix-and-match.
Then, add this to the Activity:
public void openMapFragment() {
Fragment fragment = new gMapFragment();
replaceFragment(fragment);
}
//moved to Activity from the Fragment
public void replaceFragment(Fragment someFragment) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, someFragment);
transaction.addToBackStack(null);
transaction.commit();
}
Then, in the Fragment onClick() method, just call into the Activity to do the FragmentTransaction:
public void onClick(View view) {
switch (view.getId()) {
case R.id.SearchButton:
MainActivity activity = (MainActivity) getActivity();
if (activity != null) {
activity.openMapFragment();
}
break;
}
}

How to add map to a tabbed activity (Android)

I have a tabbed activity which uses a SectionsPageAdapter. There are two tabs, each uses a different fragment, one of which is a google map. When I attempt to get the SupportMapFragment from the MapFragment it returns null.
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
I have also tried:
SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager()
.findFragmentById(R.id.map);
If I create a new GoogleMapsActivity it works just fine, that confirms that it has nothing to do with my key. the fragment with id map exists.
MainActivity.java
package com.example.frias19o.trackthem2;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 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.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_map, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MapFragment.java
package com.example.frias19o.trackthem2;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONException;
import org.json.JSONObject;
/********************************************************************
* Fragment for Map
*********************************************************************/
public class MapFragment extends Fragment implements OnMapReadyCallback {
private static final String LOGTAG = "MapFragment";
private static final String ARG_SECTION_NUMBER = "section_number";
public static GoogleApiClient mGoogleApiClient;
private GoogleMap mMap;
public MapFragment() {
}
public static MapFragment newInstance(int sectionNumber) {
MapFragment fragment = new MapFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView;
Toast.makeText(getContext(), "fragment_map", Toast.LENGTH_SHORT).show();
rootView = inflater.inflate(R.layout.activity_maps, container, false);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this); // it brakes here because mapFragment is null
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Log.v(LOGTAG, "map is ready");
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
Log.v(LOGTAG, "Added Sydney");
}
}
SectionsPagerAdapter.java
package com.example.frias19o.trackthem2;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/***********************************************************************
* 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 ClusterFragment (defined as a static inner class below).
Fragment fragment = null;
switch (position) {
case 0:
fragment = MapFragment.newInstance(position + 1);
break;
case 1:
fragment = ClusterFragment.newInstance(position + 1);
break;
default:
break;
}
return fragment;
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
}
return null;
}
}
note: The code on the link provided by CoomonsWare in the first comment on the question, led me to a solution.
As pointed out by CommonsWare, the solution was making MapFragment extend SupportMapFragment, that way getMapAsync(this); can be called directly (without having to access the FragmentManager). Then return an instance of this MapFragment in the getItem() of SectionsPagerAdapter. Note that there should NOT be a call/override for onCreateView(), it caused java.lang.NullPointerException: Attempt to invoke interface method 'void maps.ei.bz.o()' on a null object reference
Final Product:
MapFragment.java
package com.example.frias19o.trackthem2;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
/********************************************************************
* Fragment for Map
*********************************************************************/
public class MapFragment extends SupportMapFragment implements OnMapReadyCallback {
private static final String LOGTAG = "MapFragment";
private GoogleMap mMap;
public MapFragment() {
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Log.v(LOGTAG, "map is ready");
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
Log.v(LOGTAG, "Added Sydney");
}
}
SectionsPagerAdapter.java
package com.example.frias19o.trackthem2;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/***********************************************************************
* 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 ClusterFragment (defined as a static inner class below).
Fragment fragment = null;
switch (position) {
case 0:
fragment = new MapFragment();
break;
case 1:
fragment = ClusterFragment.newInstance(position + 1);
break;
default:
break;
}
return fragment;
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
}
return null;
}
}

Why won't Fragment Transaction work?

I'm writing a simple program in which a two fragments and one activity is used. Both Fragments are displayed (one at a time) within the activity's Frame Layout. The first fragment is a listview that lists items from which the user can select, then the main activity should swap the first fragment with a detail fragment according to the item position determined by a listener within the first fragment. Trouble is, my program won't actually commence the swap. Here's the code for the activity:
package com.example.user.monkeys;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
public class ListActivity extends FragmentActivity implements
monkeyListFragment.OnMonkeySelectedListener {
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i("Activity", "onCreate Pre-Fragment 1");
super.onCreate(savedInstanceState);
setContentView(R.layout.monkey_list_frame);
if (findViewById(R.id.fragment_container) != null) {
if (savedInstanceState != null) {
return;
}
monkeyListFragment monkeyList = new monkeyListFragment();
monkeyList.setArguments(getIntent().getExtras());
// Add the fragment to the container
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, monkeyList);
Log.i("Activity", "made it end onCreate");
}
}
#Override
public void onMonkeyItemSelected(int position) {
Log.i("From Activity", "onMonkeyItemSelected");
monkeyDetailsFragment newDetailFrag = new monkeyDetailsFragment();
Bundle args = new Bundle();
args.putInt("itemPosition", position);
newDetailFrag.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newDetailFrag);
transaction.addToBackStack(null);
transaction.commit();
}
}
And the code for the listview fragment:
package com.example.user.monkeys;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class monkeyListFragment extends Fragment{
OnMonkeySelectedListener monkeyCallBack;
private ListView monkeyLV;
private String[] monkeyStrings;
public interface OnMonkeySelectedListener {
public void onMonkeyItemSelected(int position);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i("Fragment 1", "Made it to onCreateView");
View view = inflater.inflate(R.layout.list_fragment, container, false);
monkeyLV = (ListView) view.findViewById(R.id.monkeyListView);
monkeyStrings = getResources().getStringArray(R.array.monkey_data_list);
ArrayAdapter<String> objAdapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, monkeyStrings);
monkeyLV.setAdapter(objAdapter);
AdapterView.OnItemClickListener monkeyListen = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("ListFragment-ClckLstnr", "Made it");
monkeyCallBack.onMonkeyItemSelected(position);
}
};
Log.i("Fragment 1", "Made it past OnItemClick Listener");
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
monkeyCallBack = (OnMonkeySelectedListener) activity;
}
catch (ClassCastException e) {
throw new ClassCastException(activity.toString());
}
}
}
and finally the code for the detail fragment (this isn't fully fleshed out but it should still swap I believe).
package com.example.user.monkeys;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class monkeyDetailsFragment extends Fragment {
ImageView monkeyPicture;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState) {
Log.i("From Detail Fragment", "Got here");
View view = inflater.inflate(R.layout.monkey_detail_fragment, container,
false);
return view;
}
}
I found your missing line of code for the listview fragment:
monkeyLV.setOnItemClickListener(monkeyListen)

pager Cannot resolved as a variable

I'm trying to make action bar tabs, but I got a error:"pager Cannot resolved as a variable..."
Thansk for your help.
Java code;
package olcay.akgn.fibonaccicalculator;
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.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
public class MainActivity extends ActionBarActivity implements TabListener {
android.app.ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
actionBar=getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tab1=actionBar.newTab();
tab1.setText("Hesaplayıcı");
tab1.setTabListener(this);
Tab tab2=actionBar.newTab();
tab2.setText("Bölünme");
tab2.setTabListener(this);
actionBar.addTab(tab1);
actionBar.addTab(tab2);
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Log.d("AKGN","onTabReselected at "+" position"+tab.getPosition()+"name"+tab.getText());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Log.d("AKGN","onTabReselected at "+" position"+tab.getPosition()+"name"+tab.getText());
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Log.d("AKGN","onTabReselected at "+" position"+tab.getPosition()+"name"+tab.getText());
}
}
class MyAdapter extends FragmentPagerAdapter
{
public MyAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int arg0) {
Fragment fragment=null;
if(arg0==0){
fragment=new Hesapla();
}
if(arg0==0){
fragment=new Bolunme ();
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 2;
}
}
Note; I begin this project with this video tutorial;
https://www.youtube.com/watch?v=iEl0ylVvZho
I tried to "Create "pager" in type id " but it did not solved my issue. Please help me.
You need to declare a ViewPager widget on your activity_main layout.
Never edit the R class - it is automatically generated.

Unable to launch app - java.lang.NullPointerException [duplicate]

This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I'm having problems launching my app (crashes), while there is no errors in code.
This happend after i converted code of List View activity to List Fragment...
My main activity:
package com.example.eronetmarket;
import com.preporuceno_app.AppAdapter;
import android.R.drawable;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.itemmenu, menu);
return true;
}
ViewPager viewPager=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
final ActionBar actionBar=getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.RED));
//actionBar.setDisplayShowHomeEnabled(false);
addTabs(actionBar);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
Log.d("VIVZ","onPageScrolled "+i+" "+v+" "+i2);
}
#Override
public void onPageSelected(int i) {
actionBar.setSelectedNavigationItem(i);
Log.d("VIVZ","onPageSelected "+i);
}
#Override
public void onPageScrollStateChanged(int i) {
if(i==ViewPager.SCROLL_STATE_IDLE)
Log.d("VIVZ","onPageScrollStateChanged scroll state idle "+i);
if(i==ViewPager.SCROLL_STATE_DRAGGING)
Log.d("VIVZ","onPageScrollStateChanged scroll state dragging "+i);
if(i==ViewPager.SCROLL_STATE_SETTLING)
Log.d("VIVZ","onPageScrollStateChanged scroll state settling "+i);
}
});
}
private void addTabs(ActionBar actionBar)
{
ActionBar.Tab tab1=actionBar.newTab();
tab1.setText("PREPORUČENO");
tab1.setTabListener(this);
ActionBar.Tab tab2=actionBar.newTab();
tab2.setText("NAJPOPULARNIJE");
tab2.setTabListener(this);
ActionBar.Tab tab3=actionBar.newTab();
tab3.setText("KATEGORIJE");
tab3.setTabListener(this);
actionBar.addTab(tab1);
actionBar.addTab(tab2);
actionBar.addTab(tab3);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
// Log.d("VIVZ","onTabSelected "+tab.getText());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
// Log.d("VIVZ","onTabUnselected "+tab.getText());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// Log.d("VIVZ","onTabReselected "+tab.getText());
}
}
class MyAdapter extends FragmentStatePagerAdapter
{
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment=null;
if(i==0)
{
fragment=new FragmentA();
}
if(i==1)
{
fragment=new Preporuceno();
}
if(i==2)
{
fragment=new FragmentC();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
And my fragment list:
package com.example.eronetmarket;
import java.io.FileNotFoundException;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class Preporuceno extends ListFragment {
private AppAdapter mAdapter;
private ListView siteList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i("mobAppModel", "OnCreate()");
View rootView = inflater.inflate(R.layout.activity_preporuceno, container, false);
siteList = (ListView) getActivity().findViewById(R.id.listView1);
siteList.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
String url = mAdapter.getItem(pos).getstoreURL();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
if(isNetworkAvailable()){
Log.i("mobAppModel", "starting download Task");
AppDownloadTask download = new AppDownloadTask();
download.execute();
}else{
mAdapter = new AppAdapter(getActivity().getApplicationContext(), -1, XMLsourcePullParser.getmobAppModel(getActivity()));
siteList.setAdapter(mAdapter);
}
return rootView;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private class AppDownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
//Download the file
try {
Downloader.DownloadFromUrl("http://minores.info/joomla30/stacksites.xml", getActivity().openFileOutput("XMLsource.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
//setup our Adapter and set it to the ListView.
mAdapter = new AppAdapter(getActivity().getApplicationContext(), -1, XMLsourcePullParser.getmobAppModel(getActivity()));
siteList.setAdapter(mAdapter);
Log.i("mobAppModel", "adapter size = "+ mAdapter.getCount());
}
}
}
Here is my LogCat messages:
In line 38 where LogCat shows error, I have this line public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
I don't understand where I went wrong?
Change this
siteList = (ListView) getActivity().findViewById(R.id.listView1);
to
siteList = (ListView) rootView.findViewById(R.id.listView1);
The view belongs to the inflated layout and you need to use the view object to initialize views.
java.lang.RuntimeException: Your content must have a ListView whose
id attribute is 'android.R.id.list'
ListActivity or ListFragment will have listview which occuppies the entire screen. If you want to have other views in the layout then your layout must have listview with id andorid.R.id.list
http://developer.android.com/reference/android/app/ListFragment.html
QUoting docs
ListFragment has a default layout that consists of a single list view.
However, if you desire, you can customize the fragment layout by
returning your own view hierarchy from onCreateView(LayoutInflater,
ViewGroup, Bundle). To do this, your view hierarchy must contain a
ListView object with the id "#android:id/list" (or list if it's in
code)

Categories