Fragment not attached to a context after asynctask
Hello everyone I have a problem in fragment, I get a null pointer exception in fragment after changing from second to third fragment:On first onCreateView it's working fine, but when i change it, i get null pointer exception. I tryed with getContext(),getActivity(),requireContext() but I always get this exception. Thanks java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
public class GetListaVozila extends AsyncTask<ArrayList<String>, Void, Void> {
protected void onPreExecute() {
/****** NOTE: You can call UI Element here. *****/
// progressDialog = getDialogProgressBar().show();
// progressDialog.setCancelable(false);
}
// Call after onPreExecute method
protected Void doInBackground(ArrayList<String>... urls) {
try {
System.out.println("pozvanooo1");
URL url = new URL("http://example/app/lista_vozila_novo.php");
URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("POST");
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("key", key);
String query = builder.build().getEncodedQuery();
httpConn.connect();
OutputStream os = httpConn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
InputStream is = httpConn.getInputStream();
parsedString = convertinputStreamToString(is);
System.out.println("pozvanooo parsedstring" + parsedString + " - " + key);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused) {
Gson gson = new Gson();
Type type = new TypeToken<List<PozicijaVozila>>() {
}.getType();
listaVozila = gson.fromJson(parsedString, type);
values = new ArrayList<String>();
// ArrayList<PozicijaVozila> array_sort = new ArrayList<PozicijaVozila>(listaVozila);
for (PozicijaVozila p : listaVozila) {
values.add(p.getIme());
}
it = new ArrayList<PozicijaVozila>(listaVozila);
// for (int i = 0; i < it.size(); i++) {
// values.add(it.get(i).getIme());
// }
I got exception here: adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_activated_1, android.R.id.text1, values);
editTextNaziv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Dialog dialog = new Dialog(requireContext());
dialog.setContentView(R.layout.vozila_listview);
dialog.setTitle(requireContext().getResources().getString(R.string.izaberite_vozilo));
listView = (ListView) dialog.findViewById(R.id.list);
dialog.show();
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setItemChecked(selectedIndex, false);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int itemPosition = position;
selectedIndex = position;
String itemValue = (String) listView
.getItemAtPosition(position);
currentSelectedView = view;
editTextNaziv.setText(itemValue);
// Show Alert
view.setBackgroundColor(Color.parseColor("#F8C304"));
dialog.cancel();
}
});
}
});
// progressDialog.dismiss();
// if (selectedIndex == 0 && values.size() > 0) {
// editTextNaziv.setText(values.get(0));
// }
}
}
looks like getActivity()
is null
when AsyncTask
finishes its job. it is placed inside Fragment
, so this means that this Fragment
wasn't attached to any Activity
at that particular moment (job end). you should cancel your AsyncTask
in some of lifecycle methods like onPause
or onDestroyView
for avoiding this problem. but be awared that AsyncTask
won't have a place to print result of its job (as Fragment
- GUI side - was removed from screen). if you want to keep that work for some other Fragment
or just for storing for future use - start and keep AsyncTask
inside Activity
(as you see it is tightened to it anyway by getActivity()
method, not to Fragment
)