Errores en la clase SectionsPagerAdapter al hacer referencia a un fragmento específico
Frecuentes
Visto 1,500 equipos
1
Estoy tratando de referirme a fragmentos específicos usando el Método Switch y cuando me refiero al fragmento específico, el IDE (Eclipse) arroja errores.
El error específico es: Tipo de discrepancia: no se puede convertir de GuidelineFragment a Fragment
Mi primera sospecha fue que estaba extendiendo la actividad de GuidelineFragment a ListActivity, pero cuando extendí a ListFragment arrojó muchos más errores y volvió a la extensión ListActivity.
Organicé las importaciones y limpié el proyecto sin éxito.
Desafortunadamente, las siguientes preguntas de StackOverflow no respondieron específicamente a mi pregunta:
Fragmentos de Android para el menú con pestañas
Problemas con las pestañas y el fragmento.
¿Qué estoy haciendo mal?
Los siguientes son los archivos de mi proyecto.
Clase SectionsPagerAdapter
package com.example.perinatologiev2;
import java.util.Locale;
import com.example.perinatologiev2.R;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class SectionsPagerAdapter extends FragmentPagerAdapter {
protected Context mContext;
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public SectionsPagerAdapter(Context context,FragmentManager fm) {
super(fm);
mContext = context;
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page..
switch(position) {
case 0:
return new GuidelineFragment(); //error here
case 1:
return new CentraFragment(); //error here
case 2:
return new UzitecneFragment(); //error here
}
return null;
}
@Override
public int getCount() {
// Showing 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return mContext.getString(R.string.title_section1).toUpperCase(l);
case 1:
return mContext.getString(R.string.title_section2).toUpperCase(l);
case 2:
return mContext.getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
Este es el fragmento al que se refiere la instrucción switch:
Fragmento de directriz
package com.example.perinatologiev2;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.example.perinatologiev2.R;
import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class GuidelineFragment extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guideline_fragment);
try
{
JSONArray jsonArray = parsePostupyJSON();
ArrayList<String> fields = new ArrayList<String>();
for (int index = 0; index < jsonArray.length(); index++) {
//Set both values into the listview
JSONObject jsonObject = jsonArray.getJSONObject(index);
fields.add(jsonObject.getString("title"));
}
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fields));
} catch (FileNotFoundException e) {
Log.e("jsonFile", "file not found");
} catch (IOException e) {
Log.e("jsonFile", "ioerror");
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.guideline, menu);
return true;
}
private JSONArray parsePostupyJSON() throws IOException, JSONException {
//Load File
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(this.getResources().openRawResource(R.raw.guidelines)));
StringBuilder jsonBuilder = new StringBuilder();
for (String line = null; (line = jsonReader.readLine()) != null;) {
jsonBuilder.append(line).append("\n");
}
//Parse Json
JSONTokener tokener = new JSONTokener(jsonBuilder.toString());
JSONArray jsonArray = new JSONArray(tokener);
return jsonArray;
}
//The following is the method that I need to modify to listen to the tap and direct to web view
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
try {
JSONArray jsonArray = parsePostupyJSON();
JSONObject jsonPost = jsonArray.getJSONObject(position);
String guidelineUrl = jsonPost.getString("guidelinepath");
Intent intent = new Intent(this, GuidelineWebActivity.class);
intent.setData(Uri.parse(guidelineUrl));
startActivity(intent);
}
catch (JSONException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Y por último, pero no menos importante... la actividad principal
package com.example.perinatologiev2;
import com.example.perinatologiev2.R;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
public static final String TAG = MainActivity.class.getSimpleName();
/**
* 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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(this,
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.main, menu);
return true;
}
@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) {
}
}
1 Respuestas
1
Si quieres usar GuidelineFragment
(y otras clases) dentro ViewPager
, necesitan extender Fragment
y no Activity
. Estos dos tienen métodos diferentes que se espera que anule y es por eso que obtuvo tantos errores después de cambiar la superclase, por ejemplo, generalmente usa onCreateView
al trabajar con Fragment
s en lugar de Activity
's onCreate
.
Respondido 10 Feb 14, 11:02
De acuerdo, de hecho, el error desapareció cuando cambié la extensión de ListActivity a ListFragment. ¿Algún buen recurso sobre cómo puedo completar un fragmento de lista con un JSON almacenado localmente? Gracias de antemano por la ayuda :)! - stefbmt
@stefbmt "how I can populate a list fragment with a locally stored JSON"
no es una buena pregunta SO. Sea específico cuando pregunte si tiene problemas para analizar o hacer un adaptador para ListView
. ¡Divide y conquistaras! Y diviértete aprendiendo Android. - MaciejGórski
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas android eclipse tabs switch-statement fragment or haz tu propia pregunta.
¿Cuáles son los errores exactamente? - MaciejGórski
Hola @MaciejGórski, ¡perdón por la respuesta tardía! El error exacto es: Tipo de discrepancia: no se puede convertir de GuidelineFragment a Fragment - stefbmt