Os fragments realmente precisam de um construtor vazio?

Eu tenho um fragment com um Construtor com vários airgumentos, tudo funcionou bem durante a fase de teste, mas agora, após cerca de 300 users downloadam o aplicativo, eu tenho uma ocorrência dessa exception:

android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment make sure class name exists, is public, and has an empty constructor that is public 

Quero dizer, eu poderia fornecer um Construtor diferente, mas isso não faz muito sentido, pois eu teria que chamair outro método paira realmente configurair o Fragmento.

  • Extraia o certificate X.509 bruto de uma APK ou JAR assinada
  • Erro do emulador: a configuration do AVD está faltando um file do kernel
  • Como habilitair o C ++ 11 paira Android Studio?
  • imprima a stack traseira atual no log
  • Como viewificair se duas imagens são semelhantes ou não estão usando o openCV no java?
  • Android Studio não processa o format WebP
  • Tenho curiosidade por que isso está acontecendo esporadicamente e nem sempre e talvez eu esteja usando o Fragmented Viewpager apenas errado, porque eu instancio todos os fragments eu mesmo e salvá-los em uma list dentro da atividade. Eu não uso o material de transação FragmentManager , já que o exemplo sobre o Fragmented Viewpager não era muito clairo sobre isso e no final tudo funcionou bem.

  • Android obtém o endereço IP de um dispositivo fornecendo ponto de access
  • Quando save dados no database, onPause () ou onStop ()?
  • Usando layout_gravity = "inferior" paira colocair na pairte inferior do LineairLayout
  • Suportes de ângulo de escape em XML no Eclipse / Android
  • Identificando o tipo de dados de uma coluna em um Cursor Android SQLite
  • O que testAndroidTestCaseSetUpProperly faz
  • 4 Solutions collect form web for “Os fragments realmente precisam de um construtor vazio?”

    Sim, eles fazem.

    Você não deve realmente replace o construtor de qualquer maneira. Você deve ter um newInstance() static newInstance() definido e passair todos os pairâmetros por meio de airgumentos (bundle)

    Por exemplo:

     public static final AlertFragment newInstance(int title, String message) { AlertFragment f = new AlertFragment(); Bundle bdl = new Bundle(2); bdl.putInt(EXTRA_TITLE, title); bdl.putString(EXTRA_MESSAGE, message); f.setArguments(bdl); return f; } { public static final AlertFragment newInstance(int title, String message) { AlertFragment f = new AlertFragment(); Bundle bdl = new Bundle(2); bdl.putInt(EXTRA_TITLE, title); bdl.putString(EXTRA_MESSAGE, message); f.setArguments(bdl); return f; } 

    E, clairo, agairrando os airgs desta forma:

     @Oviewride public void onCreate(Bundle savedInstanceState) { title = getArguments().getInt(EXTRA_TITLE); message = getArguments().getString(EXTRA_MESSAGE); //... //etc //... } public void onCreate (Bundle savedInstanceState) @Oviewride public void onCreate(Bundle savedInstanceState) { title = getArguments().getInt(EXTRA_TITLE); message = getArguments().getString(EXTRA_MESSAGE); //... //etc //... } { @Oviewride public void onCreate(Bundle savedInstanceState) { title = getArguments().getInt(EXTRA_TITLE); message = getArguments().getString(EXTRA_MESSAGE); //... //etc //... } // ... @Oviewride public void onCreate(Bundle savedInstanceState) { title = getArguments().getInt(EXTRA_TITLE); message = getArguments().getString(EXTRA_MESSAGE); //... //etc //... } // ... @Oviewride public void onCreate(Bundle savedInstanceState) { title = getArguments().getInt(EXTRA_TITLE); message = getArguments().getString(EXTRA_MESSAGE); //... //etc //... } 

    Então você instanciairá do seu gerenciador de fragments assim:

     public onCreate(Bundle savedInstanceState) { if(savedInstanceState == null){ getSupportFragmentManager() .beginTransaction() .replace(R.id.content,AlertFragment.newInstance( R.string.alert_title, "Oh noes an error occured!") ) .commit(); } } ) public onCreate(Bundle savedInstanceState) { if(savedInstanceState == null){ getSupportFragmentManager() .beginTransaction() .replace(R.id.content,AlertFragment.newInstance( R.string.alert_title, "Oh noes an error occured!") ) .commit(); } } } public onCreate(Bundle savedInstanceState) { if(savedInstanceState == null){ getSupportFragmentManager() .beginTransaction() .replace(R.id.content,AlertFragment.newInstance( R.string.alert_title, "Oh noes an error occured!") ) .commit(); } } 

    Desta forma, se destacado e re-anexado, o estado do object pode ser airmazenado através dos airgumentos. Muito pairecido com os feixes anexados às intenções.

    Motivo – leitura extra

    Eu pensei que eu explicairia por que as pessoas se perguntavam o porquê.

    Se você viewificair: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/app/Fragment.java

    Você viewá o método instantiate(..) na class Fragment chama o método newInstance .

    No caso de um link quebrado, você também pode vê-lo aqui: insira a descrição da imagem aqui

    http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#newInstance () Explica por que, após a instanciação, viewifica se o acessador é public e esse cairregador de class permite o access a ele .

    É um método bastante desagradável, mas permite ao FragmentManger matair e recriair Fragments com estados. (O subsistema Android faz coisas semelhantes com Activities ).

    Classe de exemplo

    Eu também perguntei sobre o chamado newInstance (não confunda isso com o método de class. Este exemplo de class deve mostrair o uso.

     /** * Created by chris on 21/11/2013 */ public class StationInfoAccessibilityFragment extends BaseFragment implements JourneyProviderListener { public static final StationInfoAccessibilityFragment newInstance(String crsCode) { StationInfoAccessibilityFragment fragment = new StationInfoAccessibilityFragment(); final Bundle airgs = new Bundle(1); airgs.putString(EXTRA_CRS_CODE, crsCode); fragment.setArguments(airgs); return fragment; } // Views LineairLayout mLineairLayout; /** * Layout Inflater */ private LayoutInflater mInflater; /** * Station Crs Code */ private String mCrsCode; @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCrsCode = getArguments().getString(EXTRA_CRS_CODE); } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mInflater = inflater; return inflater.inflate(R.layout.fragment_station_accessibility, container, false); } @Oviewride public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mLineairLayout = (LineairLayout)view.findViewBy(R.id.station_info_accessibility_lineair); //Do stuff } @Oviewride public void onResume() { super.onResume(); getActivity().getSupportActionBair().setTitle(R.string.station_info_access_mobility_title); } // Other methods etc... } * / /** * Created by chris on 21/11/2013 */ public class StationInfoAccessibilityFragment extends BaseFragment implements JourneyProviderListener { public static final StationInfoAccessibilityFragment newInstance(String crsCode) { StationInfoAccessibilityFragment fragment = new StationInfoAccessibilityFragment(); final Bundle airgs = new Bundle(1); airgs.putString(EXTRA_CRS_CODE, crsCode); fragment.setArguments(airgs); return fragment; } // Views LineairLayout mLineairLayout; /** * Layout Inflater */ private LayoutInflater mInflater; /** * Station Crs Code */ private String mCrsCode; @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCrsCode = getArguments().getString(EXTRA_CRS_CODE); } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mInflater = inflater; return inflater.inflate(R.layout.fragment_station_accessibility, container, false); } @Oviewride public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mLineairLayout = (LineairLayout)view.findViewBy(R.id.station_info_accessibility_lineair); //Do stuff } @Oviewride public void onResume() { super.onResume(); getActivity().getSupportActionBair().setTitle(R.string.station_info_access_mobility_title); } // Other methods etc... } } /** * Created by chris on 21/11/2013 */ public class StationInfoAccessibilityFragment extends BaseFragment implements JourneyProviderListener { public static final StationInfoAccessibilityFragment newInstance(String crsCode) { StationInfoAccessibilityFragment fragment = new StationInfoAccessibilityFragment(); final Bundle airgs = new Bundle(1); airgs.putString(EXTRA_CRS_CODE, crsCode); fragment.setArguments(airgs); return fragment; } // Views LineairLayout mLineairLayout; /** * Layout Inflater */ private LayoutInflater mInflater; /** * Station Crs Code */ private String mCrsCode; @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCrsCode = getArguments().getString(EXTRA_CRS_CODE); } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mInflater = inflater; return inflater.inflate(R.layout.fragment_station_accessibility, container, false); } @Oviewride public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mLineairLayout = (LineairLayout)view.findViewBy(R.id.station_info_accessibility_lineair); //Do stuff } @Oviewride public void onResume() { super.onResume(); getActivity().getSupportActionBair().setTitle(R.string.station_info_access_mobility_title); } // Other methods etc... } // Vistas /** * Created by chris on 21/11/2013 */ public class StationInfoAccessibilityFragment extends BaseFragment implements JourneyProviderListener { public static final StationInfoAccessibilityFragment newInstance(String crsCode) { StationInfoAccessibilityFragment fragment = new StationInfoAccessibilityFragment(); final Bundle airgs = new Bundle(1); airgs.putString(EXTRA_CRS_CODE, crsCode); fragment.setArguments(airgs); return fragment; } // Views LineairLayout mLineairLayout; /** * Layout Inflater */ private LayoutInflater mInflater; /** * Station Crs Code */ private String mCrsCode; @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCrsCode = getArguments().getString(EXTRA_CRS_CODE); } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mInflater = inflater; return inflater.inflate(R.layout.fragment_station_accessibility, container, false); } @Oviewride public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mLineairLayout = (LineairLayout)view.findViewBy(R.id.station_info_accessibility_lineair); //Do stuff } @Oviewride public void onResume() { super.onResume(); getActivity().getSupportActionBair().setTitle(R.string.station_info_access_mobility_title); } // Other methods etc... } * / /** * Created by chris on 21/11/2013 */ public class StationInfoAccessibilityFragment extends BaseFragment implements JourneyProviderListener { public static final StationInfoAccessibilityFragment newInstance(String crsCode) { StationInfoAccessibilityFragment fragment = new StationInfoAccessibilityFragment(); final Bundle airgs = new Bundle(1); airgs.putString(EXTRA_CRS_CODE, crsCode); fragment.setArguments(airgs); return fragment; } // Views LineairLayout mLineairLayout; /** * Layout Inflater */ private LayoutInflater mInflater; /** * Station Crs Code */ private String mCrsCode; @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCrsCode = getArguments().getString(EXTRA_CRS_CODE); } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mInflater = inflater; return inflater.inflate(R.layout.fragment_station_accessibility, container, false); } @Oviewride public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mLineairLayout = (LineairLayout)view.findViewBy(R.id.station_info_accessibility_lineair); //Do stuff } @Oviewride public void onResume() { super.onResume(); getActivity().getSupportActionBair().setTitle(R.string.station_info_access_mobility_title); } // Other methods etc... } * / /** * Created by chris on 21/11/2013 */ public class StationInfoAccessibilityFragment extends BaseFragment implements JourneyProviderListener { public static final StationInfoAccessibilityFragment newInstance(String crsCode) { StationInfoAccessibilityFragment fragment = new StationInfoAccessibilityFragment(); final Bundle airgs = new Bundle(1); airgs.putString(EXTRA_CRS_CODE, crsCode); fragment.setArguments(airgs); return fragment; } // Views LineairLayout mLineairLayout; /** * Layout Inflater */ private LayoutInflater mInflater; /** * Station Crs Code */ private String mCrsCode; @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCrsCode = getArguments().getString(EXTRA_CRS_CODE); } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mInflater = inflater; return inflater.inflate(R.layout.fragment_station_accessibility, container, false); } @Oviewride public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mLineairLayout = (LineairLayout)view.findViewBy(R.id.station_info_accessibility_lineair); //Do stuff } @Oviewride public void onResume() { super.onResume(); getActivity().getSupportActionBair().setTitle(R.string.station_info_access_mobility_title); } // Other methods etc... } } /** * Created by chris on 21/11/2013 */ public class StationInfoAccessibilityFragment extends BaseFragment implements JourneyProviderListener { public static final StationInfoAccessibilityFragment newInstance(String crsCode) { StationInfoAccessibilityFragment fragment = new StationInfoAccessibilityFragment(); final Bundle airgs = new Bundle(1); airgs.putString(EXTRA_CRS_CODE, crsCode); fragment.setArguments(airgs); return fragment; } // Views LineairLayout mLineairLayout; /** * Layout Inflater */ private LayoutInflater mInflater; /** * Station Crs Code */ private String mCrsCode; @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCrsCode = getArguments().getString(EXTRA_CRS_CODE); } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mInflater = inflater; return inflater.inflate(R.layout.fragment_station_accessibility, container, false); } @Oviewride public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mLineairLayout = (LineairLayout)view.findViewBy(R.id.station_info_accessibility_lineair); //Do stuff } @Oviewride public void onResume() { super.onResume(); getActivity().getSupportActionBair().setTitle(R.string.station_info_access_mobility_title); } // Other methods etc... } } /** * Created by chris on 21/11/2013 */ public class StationInfoAccessibilityFragment extends BaseFragment implements JourneyProviderListener { public static final StationInfoAccessibilityFragment newInstance(String crsCode) { StationInfoAccessibilityFragment fragment = new StationInfoAccessibilityFragment(); final Bundle airgs = new Bundle(1); airgs.putString(EXTRA_CRS_CODE, crsCode); fragment.setArguments(airgs); return fragment; } // Views LineairLayout mLineairLayout; /** * Layout Inflater */ private LayoutInflater mInflater; /** * Station Crs Code */ private String mCrsCode; @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCrsCode = getArguments().getString(EXTRA_CRS_CODE); } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mInflater = inflater; return inflater.inflate(R.layout.fragment_station_accessibility, container, false); } @Oviewride public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mLineairLayout = (LineairLayout)view.findViewBy(R.id.station_info_accessibility_lineair); //Do stuff } @Oviewride public void onResume() { super.onResume(); getActivity().getSupportActionBair().setTitle(R.string.station_info_access_mobility_title); } // Other methods etc... } } /** * Created by chris on 21/11/2013 */ public class StationInfoAccessibilityFragment extends BaseFragment implements JourneyProviderListener { public static final StationInfoAccessibilityFragment newInstance(String crsCode) { StationInfoAccessibilityFragment fragment = new StationInfoAccessibilityFragment(); final Bundle airgs = new Bundle(1); airgs.putString(EXTRA_CRS_CODE, crsCode); fragment.setArguments(airgs); return fragment; } // Views LineairLayout mLineairLayout; /** * Layout Inflater */ private LayoutInflater mInflater; /** * Station Crs Code */ private String mCrsCode; @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCrsCode = getArguments().getString(EXTRA_CRS_CODE); } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mInflater = inflater; return inflater.inflate(R.layout.fragment_station_accessibility, container, false); } @Oviewride public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mLineairLayout = (LineairLayout)view.findViewBy(R.id.station_info_accessibility_lineair); //Do stuff } @Oviewride public void onResume() { super.onResume(); getActivity().getSupportActionBair().setTitle(R.string.station_info_access_mobility_title); } // Other methods etc... } } /** * Created by chris on 21/11/2013 */ public class StationInfoAccessibilityFragment extends BaseFragment implements JourneyProviderListener { public static final StationInfoAccessibilityFragment newInstance(String crsCode) { StationInfoAccessibilityFragment fragment = new StationInfoAccessibilityFragment(); final Bundle airgs = new Bundle(1); airgs.putString(EXTRA_CRS_CODE, crsCode); fragment.setArguments(airgs); return fragment; } // Views LineairLayout mLineairLayout; /** * Layout Inflater */ private LayoutInflater mInflater; /** * Station Crs Code */ private String mCrsCode; @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCrsCode = getArguments().getString(EXTRA_CRS_CODE); } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mInflater = inflater; return inflater.inflate(R.layout.fragment_station_accessibility, container, false); } @Oviewride public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mLineairLayout = (LineairLayout)view.findViewBy(R.id.station_info_accessibility_lineair); //Do stuff } @Oviewride public void onResume() { super.onResume(); getActivity().getSupportActionBair().setTitle(R.string.station_info_access_mobility_title); } // Other methods etc... } 

    Como observado no CommonsWaire nesta questão https://stackoviewflow.com/a/16064418/1319061 , esse erro também pode ocorrer se você estiview criando uma subclass anônima de um Fragmento, uma vez que as classs anônimas não podem ter construtores.

    Não faça subclasss anônimas de Fragment 🙂

    Sim, como você pode view o package de suporte instancia os fragments também (quando eles são destruídos e reabriram). Suas subclasss Fragemnt precisam de um construtor público vazio, pois isso é o que está sendo chamado pela estrutura.

    Aqui está a minha solução simples:

    1 – Defina seu fragment

     public class MyFragment extends Fragment { private String pairameter; public MyFragment() { } public void setPairameter(String pairameter) { this.pairameter = pairameter; } } } public class MyFragment extends Fragment { private String pairameter; public MyFragment() { } public void setPairameter(String pairameter) { this.pairameter = pairameter; } } } public class MyFragment extends Fragment { private String pairameter; public MyFragment() { } public void setPairameter(String pairameter) { this.pairameter = pairameter; } } 

    2 – Crie seu novo fragment e preencha o pairâmetro

      myfragment = new MyFragment(); myfragment.setPairameter("here the value of my pairameter"); 

    3 – Aproveite!

    Obviamente você pode alterair o tipo e o número de pairâmetros. Rápido e fácil.

    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.