Issue with TabLayout in fragment (android/java) - java

i've tried to add tabLayout in my application. When I open the fragment (where there is my tablayout) for the first time it works fine, but if I close the fragment and I try to re-open it, the tab indicator doesn't follow my swipe and all viewPager became blank... how can I resolve this problem?
my fragment:
package com.gabrielemarcozzi.mycal;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class PercentageFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment PercentageFragment.
*/
// TODO: Rename and change types and number of parameters
public static PercentageFragment newInstance(String param1, String param2) {
PercentageFragment fragment = new PercentageFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public PercentageFragment() {
// Required empty public constructor
}
private FragmentActivity context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_percentage, container, false);
Toolbar mToolbar = (Toolbar)getActivity().findViewById(R.id.toolbar);
mToolbar.setTitle(R.string.percentage);
ViewPager percentagePager = (ViewPager)view.findViewById(R.id.percentage_pager);
percentagePager.setAdapter(new PercentagePagerAdapter(context.getSupportFragmentManager()));
TabLayout percentageTab = (TabLayout)view.findViewById(R.id.percentage_tabs);
percentageTab.setupWithViewPager(percentagePager);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
MainActivity main = (MainActivity) activity;
mListener = main;
context = (FragmentActivity) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
class PercentagePagerAdapter extends FragmentPagerAdapter {
String[] pergentageTabsArray;
public PercentagePagerAdapter(FragmentManager fm) {
super(fm);
pergentageTabsArray = getResources().getStringArray(R.array.percentage_tabs);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
TabsPercentageFragment TabsPercFrag = TabsPercentageFragment.getIstance(position);
return TabsPercFrag;
}
#Override
public CharSequence getPageTitle(int position) {
return pergentageTabsArray[position];
}
#Override
public int getCount() {
return 3;
}
}
public static class TabsPercentageFragment extends android.support.v4.app.Fragment {
public static TabsPercentageFragment getIstance(int position) {
TabsPercentageFragment increaseFrag = new TabsPercentageFragment();
Bundle args = new Bundle();
args.putInt("position", position);
increaseFrag.setArguments(args);
return increaseFrag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view;
Bundle bundle = getArguments();
switch(bundle.getInt("position")) {
case 1:
view = inflater.inflate(R.layout.fragment_discount, container, false);
break;
case 2:
view = inflater.inflate(R.layout.fragment_xofy, container, false);
break;
default:
view =inflater.inflate(R.layout.fragment_increase, container, false);
break;
}
return view;
}
}
}
my fragment xml file:
<LinearLayout
android:id="#+id/percentage_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.gabrielemarcozzi.mycal.PercentageFragment">
<android.support.design.widget.TabLayout
android:id="#+id/percentage_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:tabMode="fixed"
app:tabIndicatorColor="#color/colorUp"
app:tabTextColor="#android:color/white"
app:tabSelectedTextColor="#color/colorUp"/>
<android.support.v4.view.ViewPager
android:id="#+id/percentage_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<!-- TODO: Update blank fragment layout -->
</LinearLayout>

Try to user getChildFragmentManager() instead of getSupportFragmentManager() at:
percentagePager.setAdapter(new PercentagePagerAdapter(context.getSupportFragmentManager()));
and change your import from:
import android.app.Fragment;
to
import android.support.v4.app.Fragment;

Related

How to showing text inside recycleview without restarting the app?

My problem is I can not add text inside of recycleview after pressing the OK button unless i restart the app , every time I am writing a word inside of dialog box then press OK but the word does not appear inside of recycleview only after restart the app ,I want to type the word and then press the OK button Then the word appears directly inside the recycleview
// class Tab1 :
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
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.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import static android.R.attr.fragment;
import static com.example.chirag.slidingtabsusingviewpager.R.id.parent;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link Tab1.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link Tab1#newInstance} factory method to
* create an instance of this fragment.
*/
public class Tab1 extends Fragment {
#Inject
Context mContext_;
View rootView;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
Context context;
SimpleAdapter adapter;// = new SimpleAdapter(generateSimpleList());
RecyclerView recyclerView ;//= (RecyclerView) view.findViewById(R.id.simple_recyclerview);
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private List<Organization>organizationList;
private OnFragmentInteractionListener mListener;
private static Context mContext;
LayoutInflater inflater2;
ViewGroup Container = null;
View vr;
public Tab1(){
// Required empty public constructor
// test ();
//context = getContext();
Organization organization = new Organization();
organizationList = SQLite.select().from(Organization.class).queryList();
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Tab1.
*/
// TODO: Rename and change types and number of parameters
public static Tab1 newInstance(String param1, String param2) {
Tab1 fragment = new Tab1();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_tab1, container,false);
vr = view;//inflater.inflate(R.layout.fragment_tab1, container,false);
initViews();
showInputDialog();
return view;
}
private void initViews(){
adapter = new SimpleAdapter(generateSimpleList());
recyclerView = (RecyclerView)vr.findViewById(R.id.simple_recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString() + "must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private List<SimpleViewModel> generateSimpleList(){
List<SimpleViewModel>simpleViewModelList = new ArrayList<>();
for(int i=0; i<organizationList.size(); i++){
simpleViewModelList.add(new SimpleViewModel(String.format(Locale.US,organizationList.get(i).getName().toString(),""+organizationList.get(i).getName().toString())));
// Toast.makeText(MainActivity.this,"as"+ organizationList.get(i).getName(), Toast.LENGTH_LONG).show();
}
return simpleViewModelList;
}
protected void showInputDialog(){
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
//LayoutInflater layoutInflater = LayoutInflater.from(getContext().getApplicationContext());
final View promptView = layoutInflater.inflate(R.layout.input_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// setup a dialog window
alertDialogBuilder.setCancelable(false).setPositiveButton("OK",new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Organization organization = new Organization();
organization.setId(organizationList.size()+1);
organization.setName(editText.getText().toString());
organization.save();
//initViews();
}}).setNegativeButton("Cancel",new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
//create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
/*
AlertDialog alert = alertDialogBuilder.create();
alert.show();
*/
}
}
/
/Organization class :
import com.raizlabs.android.dbflow.annotation.Column;
import com.raizlabs.android.dbflow.annotation.PrimaryKey;
import com.raizlabs.android.dbflow.annotation.Table;
import com.raizlabs.android.dbflow.structure.BaseModel;
// **Note:** Your class must extend from BaseModel
#Table(database = MyDatabase.class)
public class Organization extends BaseModel {
#Column
#PrimaryKey
int id;
#Column
String name;
private Organization organization;
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
public void setName(String name) {
this.name = name;
}
}
// input_dialog.xml :
<?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="wrap_content"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Enter Name"
android:id="#+id/textView"/>
<EditText
android:id="#+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter text here.."
android:padding="10dp"/>
</LinearLayout>
After you have changed the data you need to call notifyDataSetChanged() on your Adapter in order to update the data in your RecycleView.
Set this wherever you make changes to the source data:
adapter.notifyDataSetChanged()
Note: As a precaution you might want to check that "adapter" is not null.
Add these two lines, inside your onClick of setPositiveButton
(Just after organization.save())
.......
organization.save();
organizationList.add(organization);
adapter.notifyDataSetChanged();

Attempt to invoke virtual method 'android.view.View android.support.v4.widget.NestedScrollView.findViewById(int)' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm trying to put my NestedScrollView on my MapFragment, but when I'm trying to, this error appears :
Attempt to invoke virtual method 'android.view.View android.support.v4.widget.NestedScrollView.findViewById(int)' on a null object reference
Here is my MapFragment.java file
package com.example.alexandre.list.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.alexandre.list.MainActivity;
import com.example.alexandre.list.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link OnMapClickListener} interface
* to handle interaction events.
* Use the {#link MapFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class MapFragment extends Fragment implements OnMapReadyCallback {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private GoogleMap mGoogleMap;
private MapView mMapView;
private OnMapClickListener mListener;
public MapFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MapFragment.
*/
// TODO: Rename and change types and number of parameters
public static MapFragment newInstance(String param1, String param2) {
MapFragment fragment = new MapFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_map, container, false);
bindViews(view, savedInstanceState);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed() {
if (mListener != null) {
mListener.onMapClick();
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnMapClickListener) {
mListener = (OnMapClickListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnTweetListClickListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
private void bindViews(View view, Bundle savedInstanceState) {
mMapView = view.findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this);
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
LatLng castlePos = new LatLng(45.209299, 5.659144);
LatLng treePos = new LatLng(MainActivity.posx, MainActivity.posy);
CameraPosition liberty = CameraPosition.builder().target(castlePos).zoom(17)/*.bearing(0).tilt(0)*/.build();
Marker marker = mGoogleMap.addMarker(new MarkerOptions()
.position(treePos)
.title("Test du cèdre du Liban")
.snippet("Libani"));
marker.hideInfoWindow();
mGoogleMap.setOnMarkerClickListener(
new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
((AppCompatActivity) getActivity()).getSupportActionBar().hide();
NestedScrollView nestedScrollView = null;
nestedScrollView = (NestedScrollView) nestedScrollView.findViewById(R.id.bottom_sheet);
nestedScrollView.setVisibility(View.VISIBLE);
return false;
}
}
);
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(liberty));
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnMapClickListener {
void onMapClick();
}
}
It looks like R.id.nestedScrollView return NULL, but why ?
Thanks !
Move this code NestedScrollView nestedScrollView; to the top, and reference it in your onCreateView() method. Like this:
nestedScrollView = (NestedScrollView) view.findViewById(R.id.bottom_sheet);. Now you can use it in any method in the fragment including your onMarkerClick().
You're getting the NPE error because your code is telling the Dalvik Machine that it should look for NestedScrollView in a null view NestedScrollView nestedScrollView= null.
Hope it helps.

Scrollview is not working in fragment

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context="mcb.myclickbazaar.Fragments.DateTimePlace">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:isScrollContainer="false"
android:fillViewport="true"
android:padding="10dp">
<LinearLayout>
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout...>
<LinearLayout...>
<LinearLayout...>
<LinearLayout...>
</LinearLayout>
</ScrollView>
</RelativeLayout>
The scrollview is not working. I have tried all the answers from stackoverflow, but still can't find a way to solve this issue.
This xml file is a fragment. It is one of the fragment from tabbedView Activity.
EDIT
JAVA FILE
package mcb.myclickbazaar.Activity;
import android.net.Uri;
import android.os.Bundle;
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.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
import mcb.myclickbazaar.Fragments.DateTimePlace;
import mcb.myclickbazaar.Fragments.FinalBill;
import mcb.myclickbazaar.Fragments.ItemSelect;
import mcb.myclickbazaar.R;
public class ProceedingsActivity extends AppCompatActivity implements ItemSelect.OnFragmentInteractionListener,
DateTimePlace.OnFragmentInteractionListener,FinalBill.OnFragmentInteractionListener{
private static final String TAG = "ProceedingsActivity";
private ViewPager mViewPager;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_proceedings);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
viewPager = (ViewPager) findViewById(R.id.viewpager_proceedings);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
#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_proceedings, 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);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new ItemSelect(), "Select");
adapter.addFragment(new DateTimePlace(), "DateTime");
adapter.addFragment(new FinalBill(), "Bill");
viewPager.setAdapter(adapter);
}
#Override
public void onFragmentInteraction(Uri uri) {
Log.e(TAG,"Working: on onFragmentInteraction");
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
Fragment Code
package mcb.myclickbazaar.Fragments;
import android.content.Context;
import android.net.Uri;
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.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import mcb.myclickbazaar.R;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link DateTimePlace.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link DateTimePlace#newInstance} factory method to
* create an instance of this fragment.
*/
public class DateTimePlace extends Fragment implements AdapterView.OnItemSelectedListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private String upcoming_date_1,upcoming_date_2,upcoming_date_3,upcoming_date_4;
private EditText editText_date;
private EditText editText_time;
private Spinner spinner_calendar;
private Spinner spinner_time;
private OnFragmentInteractionListener mListener;
public DateTimePlace() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment DateTimePlace.
*/
// TODO: Rename and change types and number of parameters
public static DateTimePlace newInstance(String param1, String param2) {
DateTimePlace fragment = new DateTimePlace();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
// Spinner element
final View view = inflater.inflate(R.layout.fragment_date_time_place, container, false);
spinner_calendar = (Spinner) view.findViewById(R.id.spinner_calender);
spinner_time = (Spinner) view.findViewById(R.id.spinner_time);
editText_date = (EditText) view.findViewById(R.id.editText_SelectDate_DTP);
editText_time = (EditText) view.findViewById(R.id.editText_SelectTime_DTP);
editText_date.setFocusable(false);
editText_time.setFocusable(false);
editText_date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinner_calendar.setVisibility(View.VISIBLE);
spinner_calendar.performClick();
editText_date.setHint("");
}
});
editText_time.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinner_time.setVisibility(View.VISIBLE);
spinner_time.performClick();
editText_time.setHint("");
}
});
// Spinner click listener
spinner_calendar.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories_calender = new ArrayList<String>();
categories_calender.add("Today");
categories_calender.add("Tomorrow");
categories_calender.add(getUpcoming_Date(2));
categories_calender.add(getUpcoming_Date(3));
categories_calender.add(getUpcoming_Date(4));
categories_calender.add(getUpcoming_Date(5));
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter_calendar = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, categories_calender);
// Drop down layout style - list view with radio button
dataAdapter_calendar.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner_calendar.setAdapter(dataAdapter_calendar);
// Spinner click listener
spinner_time.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories_time = new ArrayList<String>();
categories_time.add("9AM - 11AM");
categories_time.add("11AM - 1PM");
categories_time.add("1PM - 3PM");
categories_time.add("3PM - 5PM");
categories_time.add("5PM - 7PM");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter_time = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, categories_time);
// Drop down layout style - list view with radio button
dataAdapter_time.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner_time.setAdapter(dataAdapter_time);
return view;
}
private String getUpcoming_Date(int upcoming){
Calendar c = Calendar.getInstance();
Date dt = new Date();
c.add(Calendar.DATE, upcoming);
SimpleDateFormat df = new SimpleDateFormat("EEE,dd MMM", Locale.US);
String formattedDate = df.format(c.getTime());
return formattedDate;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
try this :
make hight match_parent for relativeLayout and ScrollView both like below
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="sdsd"/>
</LinearLayout>
</ScrollView>
</RelativeLayout>
Keep scroll view height as match parent and the height of everything inside it as wrap content.

Can't access outer class from fragment class android

When I try to access outer class with this code:
ImageView myView = new ImageView(Logger.this.getActivity().getApplicationContext());
it says:
The method getActivity() is undefined for the tyoe Logger
No enclosing instance of the type Logger is accessible in scope
Here is my Logger.java:
import java.util.Locale;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
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.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageSwitcher;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;
public class Logger extends FragmentActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
static boolean isBoxOpen = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logger);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setTitle("Sosyaaal");
actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.action_bar));
Thread connectivity = new Thread(){
public void run(){
try {
while(true)
{
while(!isBoxOpen)
{
if( !isOnline() )
{
isBoxOpen = true;
// display error
runOnUiThread(new Runnable() {
public void run() {
new AlertDialog.Builder(Logger.this)
.setTitle("Bağlantı Sorunu")
.setMessage("İnternet bağlantısını kontrol edip tekrar deneyin")
.setCancelable(false)
.setPositiveButton(R.string.yeniden, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Logger.isBoxOpen = false;// Try Again
}
})
.show();
}
});
}
}
}
} catch (Exception e) {
}
}
};
connectivity.start();
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.logger, menu);
return true;
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
// Giriş fragment activity
return new GirisFragment();
case 1:
// Kayıt fragment activity
return new KayitFragment();
}
return null;
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class GirisFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public GirisFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_giris,
container, false);
return rootView;
}
}
public static class KayitFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
private ImageSwitcher cinsiyetSwitcher;
public KayitFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_kayit,
container, false);
cinsiyetSwitcher = (ImageSwitcher) getView().findViewById(R.id.cinsiyetSwitcher);
cinsiyetSwitcher.setFactory(new ViewFactory() {
#Override
public View makeView() {
ImageView myView = new ImageView(Logger.this.getActivity().getApplicationContext());
myView.setScaleType(ImageView.ScaleType.FIT_CENTER);
return myView;
}
});
return rootView;
}
}
}
*EDIT*
Changing this line:
ImageView myView = new ImageView(Logger.this.getActivity().getApplicationContext());
to this:
ImageView myView = new ImageView((Logger)getActivity().getApplicationContext());
solved the problem, but that was not what I was looking for. Thanks to Kapil Vij for correct Answer!
Do this
ImageView myView = new ImageView(getActivity());
getActivity() method is accessible in fragment class, and u r trying to access it using FragmentActivity class instance.
change to:
Logger.this.getApplicationContext()
Logger it-self is activity you call getActivity to get the reference of the activity inside a Fragment
EDIT
Saw that you are calling it inside a fragment change you code to:
ImageView myView = new ImageView(KayitFragment.this.getActivity().getApplicationContext());

Launch a activity with button click using a FragmentActivity

Hey guys I need help I'm making a launcher that needs to have a button that when clicked it opens the AllApps.class activity witch shows a list of all installed apps
The other button needs to open a installed app that is on the device
and the last button needs to open the default web browser and open google.com
Here's my code!
Home.java:
package com.dva.schooltoolshome;
import java.util.Locale;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
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.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
public class Home extends FragmentActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayOptions(actionBar.getDisplayOptions()
^ ActionBar.DISPLAY_SHOW_TITLE);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
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++) {
if (mSectionsPagerAdapter.getPageTitle(i).toString()
.equalsIgnoreCase("calc")) {
actionBar.addTab(actionBar.newTab()
.setIcon(R.drawable.calendar)
.setTabListener(this));
} else if (mSectionsPagerAdapter.getPageTitle(i).toString()
.equalsIgnoreCase("home")) {
actionBar.addTab(actionBar.newTab().setIcon(R.drawable.home)
.setTabListener(this));
} else if (mSectionsPagerAdapter.getPageTitle(i).toString()
.equalsIgnoreCase("drive")) {
actionBar.addTab(actionBar.newTab().setIcon(R.drawable.folder)
.setTabListener(this));
}
}
mViewPager.setCurrentItem(1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_SETTINGS));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#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) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new CalcFragment();
break;
case 1:
fragment = new HomeFragment();
break;
case 2:
fragment = new DriveFragment();
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
public static class HomeFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_homebar,
container, false);
return rootView;
}
}
public static class CalcFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public CalcFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_calculator,
container, false);
return rootView;
}
}
public static class DriveFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public DriveFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText("DRIVE");
return rootView;
}
}
}
activity_homebar
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".HomeBar" >
<ImageButton
android:id="#+id/apps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#drawable/appdrawer"
android:src="#drawable/appdrawer" />
<ImageButton
android:id="#+id/wbrowser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignTop="#+id/apps"
android:src="#drawable/browser" />
</RelativeLayout>
AllApps.java:
package com.dva.schooltoolshome;
import android.app.LauncherActivity;
import android.content.Intent;
public class AllApps extends LauncherActivity {
#Override
protected Intent getTargetIntent () {
// just a example, you should replace the method yourself
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
}
I'm am still learning so please don't judge
Thanks in advance
Regards
Rapsong11
You can easily find the answer to your question with a bit of googling. It has been asked many times before. I will point you in the right direction.
To add functionality to a button you have to first make the button (view) aware it can be clicked. This can be done in java programatically (research this yourself) or in the xml like so:
android:onClick="onClickDoStuff"
Then you have to implement the onClickDoStuff method which will look like:
public void onClickDoStuff(View view) {
//Do stuff on click
}
You wanted the button to open a new activity onClick to do that you would require an intent have a look here for futher guidance

Categories

Resources