I have been trying to call an async task using httpurlconnection. I want the Json data to be fed into an adapter which is creating a custom list view. But my app is crashing. I have tried a lot of different code that have been discussed on this stack overflow, but I just cant figure it out. I am not sure if it is the code that is incorrect or my logic in general.I am an amateur when it comes to Android development so I would really appreciate the help.
this is the class where the async function is declared, it is part of a fragment.
public class Movies extends Fragment {
ListView List;
ListAdapter ladapter;
ArrayList<info> data;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_movies, container, false);
movielist mv=new movielist();
Toast.makeText(getContext(), "calling", Toast.LENGTH_LONG).show();
mv.execute("myurl");
return view;
}
public class movielist extends AsyncTask<String, Void, String> {
HttpURLConnection urlConnection;
@Override
protected String doInBackground(String... args) {
String result = null;
try {
URL myurl=new URL(args[0]);
HttpURLConnection urlConnection = (HttpURLConnection) myurl
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
InputStream is=urlConnection.getInputStream();
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
} finally {
is.close();
}
result = sb.toString();
}
}catch (Exception e){
result=null;
}
return result;
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(getContext(), "In post ex", Toast.LENGTH_SHORT).show();
try {
String data1 = result;
JSONObject jobj = new JSONObject(data1);
JSONArray jArray = jobj.getJSONArray("actors");
for (int i = 0; i < jArray.length(); i++) {
info information = new info();
JSONObject jrealobj = jArray.getJSONObject(i);
information.setTitle(jrealobj.getString("name"));
information.setPoster_path(jrealobj.getString("image"));
data.add(information);
}
} catch (JSONException e) {Toast.makeText(getContext(), "Not working", Toast.LENGTH_SHORT).show();
}
try {
ladapter = new Listadapter(getContext(), data);
List.setAdapter(ladapter);}catch (NullPointerException e){Toast.makeText(getContext(), "Null", Toast.LENGTH_SHORT).show();}
}
}
}