You see, I have an App with a Bottom bar with 5 buttons corresponding to 5 fragments, and when entering the application, of course, it loads the first fragment which is a database. The code of said fragment is the following:
public class First_fragment extends Fragment {
ListView lstCursos;
String recuperado;
public final static String CLAVE_EXTRA_PASAR2 = "true";
private ListView mylist;
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_tab, container, false);
//De este modo cambiamos el tema para cada uno de los layout
getActivity().setTheme(R.style.Barra);
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Bundle recupera = getActivity().getIntent().getExtras ();
if (recupera != null) {
recuperado = recupera.getString ( "cod" );
}
Thread tr2 = new Thread () {
@Override
public void run() {
final String resultado = enviarGET ( recuperado ); //LINEA 55
getActivity().runOnUiThread ( new Runnable () {
@Override
public void run() {
////////////////////////////////////////
cargarListView ( ArregloLista ( resultado ) );
////////////////////////////////////////
}
} );
}
};
tr2.start ();
return v;
}
public String enviarGET(String id){
URL url = null;
String linea = "";
int respuesta = 0;
StringBuilder resul = null;
try {
//url = new URL ("http://192.168.1.41/WebService/llenarnoticias.php?id="+id);
url = new URL ("http://rudeboys.esy.es/ramiroconnect/llenarnoticias.php?id="+id);
//Ahora enviamos el dato
HttpURLConnection conection = (HttpURLConnection) url.openConnection ();
//Guardamos la respuesta en el entero, porque sera un uno o un cero
//Esto es lo que devuelve la BD una vez hacemos la consulta
respuesta = conection.getResponseCode ();
//Inicializamos resul
resul = new StringBuilder ();
if (respuesta == HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(conection.getInputStream());
BufferedReader reader = new BufferedReader (new InputStreamReader(in));
while ((linea = reader.readLine ()) != null){
resul.append (linea);
}
}
} catch (Exception e) {
Intent intencion = new Intent(getActivity(),Federaciones.class);
intencion.putExtra(CLAVE_EXTRA_PASAR2, "true");
startActivity(intencion);
}
return resul.toString (); // LINEA 101
}
//Metodo que permite crear un arraylista para llena el listview
public ArrayList<String> ArregloLista(String response){
ArrayList<String> listado = new ArrayList<String> ();
try {
JSONArray json = new JSONArray (response);
String texto = "";
String texto2 = "";
for(int i=0;i<json.length ();i++){
texto = json.getJSONObject(i).getString("titulo");
texto2 = json.getJSONObject(i).getString("descripcion");
listado.add("\n" + texto + "\n\n" +texto2 + "\n");
}
} catch (Exception e) {}
return listado;
}
//Aquí es donde va TODA LA CHICHA
public void cargarListView(ArrayList<String> datos){
ArrayAdapter<String> adaptador = new ArrayAdapter<String> (getActivity(), android.R.layout.simple_list_item_1, datos);
lstCursos = (ListView) getActivity().findViewById (R.id.listCursos);
lstCursos.setAdapter (adaptador);
}
}
Lo que sucede que si la uso sin Wi-Fi o sin datos, es decir, sin Internet, la App crashea al iniciarla, supongo que será porque como no hay Internet no puede accedes a la data base. Por tanto intenté poner en el **Main Activity un try-catch donde llamo al 1º fragment para que no crasheara sin éxito alguno** :
``if (i == R.id.one) {`` // AQUI CARGO EL PRIMER FRAGMENT
First_fragment f1 = new First_fragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame, f1).commit();
currentFragment = 1;
}
if (i == R.id.two) { // AQUI CARGO EL SEGUNDO FRAGMENT
//Second_fragment f2 = new Second_fragment();
Second_renovado_fragment f2 = new Second_renovado_fragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame, f2).commit();
currentFragment = 2;
}
if (i == R.id.three) { AQUI CARGO EL TERCER FRAGMENT
Three_fragment f3 = new Three_fragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame, f3).commit();
currentFragment = 3;
}
if (i == R.id.four) { // AQUI CARGO EL CUARTO FRAGMENT
Four_fragment_list f4 = new Four_fragment_list();
getSupportFragmentManager().beginTransaction().replace(R.id.frame, f4).commit();
currentFragment = 4;
}
if (i == R.id.five) { // AQUI CARGO EL QUINTO FRAGMENT
Map_fragment f5 = new Map_fragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame, f5).commit();
// startActivity(new Intent(MainActivity1.this, MapActivity.class));
currentFragment = 5;
}
}
});
mBottomBar.mapColorForTab(0, "#c92029");
mBottomBar.mapColorForTab(1, "#c92029");
mBottomBar.mapColorForTab(2, "#c92029");
mBottomBar.mapColorForTab(3, "#c92029");
mBottomBar.mapColorForTab(4, "#c92029");
// seems this is working to highlist tab
mBottomBar.selectTabAtPosition(0, true);
try { ////////ESTE ES EL TRY-CATCH DEL QUE HABLO//////////
// Loading first Fragment to FrameLayout manually
First_fragment f1 = new First_fragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame, f1).commit();
}catch (Exception e){}
What I can do ?
What appears in the log:
01-24 11:30:01.345 18876-18981/com.test.rudeboys.rudeboys1 E/AndroidRuntime: FATAL EXCEPTION: Thread-4172 java.lang.NullPointerException at com.test.rudeboys.rudeboys1.First_fragment.sendGET(First_fragment.java :101) at com.test.rudeboys.rudeboys1.First_fragment$1.run(First_fragment.java:55)
I have commented lines 55 and 101 that give errors in the log in the above code to easily locate them
Inside the method
enviarGET()
you return a String value from aStringBuilder
callresul
, but this sometimes has a null value so you can't call the methodtoString()
:As a solution, validate the value of
resul
:if the value of
resul
is not null, it returns the valueresul.toString()
, if the value is null, it returns an empty String "".Posteriormente esta respuesta va a ser parseada por medio del método
ArregloLista(String response)
, pero al realizar la validación anterior y en el caso de no tener valor, simplemente retornara unArrayList<String>
vacio.No veo necesario validar la conexión ya que si no existe es obvio que no puedas obtener datos en la petición.
It is clear that your variable
resul
does not get to initialize, and an Exception occurs before, that's why it throws aNullPointerException
You should check the following:If you put in
catch
which hereturn
isnull
. You can check:Applied to your example:
After, before
cargarListView
checking if elresultado
is null. If you trycargarListView
with a null object, the exception is thrown.