Using getSupportFragmentManager() inside AsyncTask - android

I have an Activity which has a Navigation Drawer that has many buttons and one of them is leading to a fragment.
The problem is that I have to make an AsyncTask to get some information from the server but I can't get to use getSupportFragmentManager() inside the AsyncTask.
I tried to use context or activity but I can't get it to work.
I get this error cannot resolve method getSupportFragmentManager()
AsyncTask.java:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
public class AsyncTask extends AsyncTask<Void, Void, String> {
private Context c;
private String urlAddress;
private String token;
private DatabaseHelper db;
private Activity mainActivity;
public AsyncTask(Context c, DatabaseHelper databaseHelper, String urlAddress, Activity activity) {
this.c = c;
this.db = databaseHelper;
this.urlAddress = urlAddress;
this.mainActivity = activity;
//GET token FROM database
this.token = db.getValueFromColumn(0, DatabaseHelper.getTableUser(), DatabaseHelper.getUserToken());
}
#Override
protected String doInBackground(Void... params) {
return this.send();
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if (response != null) {
//SUCCESS
mainActivity.getSupportFragmentManager().beginTransaction()
.add(R.id.content_frame
, new SessionsFragment())
.addToBackStack("back")
.commit();
} else {
//NO SUCCESS
}
}
private String send() {
//CONNECT
HttpURLConnection connection = Connector.connect(urlAddress);
if (connection == null) {
return null;
}
try {
OutputStream outputStream = connection.getOutputStream();
//WRITE
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
bufferedWriter.write(new DataPackager(token).packData());
bufferedWriter.flush();
//RELEASE RES
bufferedWriter.close();
outputStream.close();
//HAS IT BEEN SUCCESSFUL?
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
//GET EXACT RESPONSE
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder buffer = new StringBuilder();
String line;
//READ LINE BY LINE
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONObject secondParentObject = parentObject.getJSONObject("data");
//json getter and adder to database
JSONArray array = secondParentObject.getJSONArray("s");
for (int i = 0; i < array.length(); i++) {
JSONObject finalObject = array.getJSONObject(i);
db.SessionsAddJson(finalObject);
//RELEASE RES
reader.close();
}
return "c";
} else {
}
} catch (IOException | JSONException e) {
e.printStackTrace();
} finally {
connection.disconnect();
}
return null;
}
}
I call the task by:
new $AsyncTask(getApplicationContext(), db, URL, MyActivity.this).execute();
Thank you for your help.

Upd.:
You should pass the AppCompatActivity in constructor, like this:
Replace
private Activity mainActivity;
with
private AppCompatActivity mainActivity;
Also when you use it: replace
new $AsyncTask(getApplicationContext(), db, URL).execute();
with
new $AsyncTask(getApplicationContext(), db, URL, YourCurrentActivity.this).execute();
Notice that YourCurrentActivity should extends AppCompatActivity.
You just confuse AppCompatActivity with Activity. Activity haven't getSupportFragmentManager(), but AppCompatActivity have this.

If you are using an asyntask class then to load fragment you need context,i.e context of particular activity.
So typecast the context to the respective activity where you want to load the fragment and onPostExecute load the fragment using particular activity fragmentManager.
public class sampleAsyncTask extends AsyncTask<Void, Void, Void> {
private YourActivity mActivity;
#Override
protected Void doInBackground(Void... voids) {
return null;
}
public sampleAsyncTask(Context context) {
super();
activity = (YourActivity) context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mActivity.getSupportFragmentManager().beginTransaction()
.add(R.id.content_frame
, new Fragment())
.addToBackStack("back")
.commit();
}
}
EDIT:
In this line of code instead of storing generic reference of activity typecast to particular activity i.e your current activity.
private YOURACTIVITY mainActivity;
public AsyncTask(Context c, DatabaseHelper databaseHelper, String urlAddress, Activity activity) {
this.c = c;
this.db = databaseHelper;
this.urlAddress = urlAddress;
//TypeCast to your particular activity
mainActivity =(YOURACTIVITY) activity;
this.token = db.getValueFromColumn(0, DatabaseHelper.getTableUser(), DatabaseHelper.getUserToken());
}

Your activity should be AppCompatActivity not Activity

try this
getActivity().getFragmentManager().beginTransaction()
.add(R.id.content_frame
, new Fragment())
.addToBackStack("back")
.commit();

Related

AsyncTasck class will not execute after calling execute method

I have a class to download a file (PortParser) class. and after setting the debugger inside doInBackground method. I can see after calling execute, it jumps to the next line in MainActivity instead of going inside doInBackground. what could this be. I can see the program going inside the execute method which in turn calls the AsyncTask execute method. but it never goes inside doInBackground method. Thanks.
this is the calling instance inside main activity class
portParser = new PortParser(this.getApplicationContext());
portParser.execute();
package org.pctechtips.netdroid.classes;
import android.os.AsyncTask;
import android.content.Context;
import android.util.*;
import org.pctechtips.netdroid.dbhelper.*;
import java.util.*;
import java.io.*;
import java.net.*;
import java.util.zip.*;
import javax.net.ssl.*;
/**
* Java class to downloand and parse service-port csv file from iana.org
*/
public class PortParser {
//public static final String PORT_URL = "https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.csv";
public static final String PORT_URL = "http://pctechtips.org/apps/service-names-port-numbers.csv";
org.pctechtips.netdroid.dbhelper.DatabaseHelper dbHelper;
DownloadPortFile downloadFile;
android.database.sqlite.SQLiteDatabase db;
Context context;
public PortParser(Context ctxt) {
dbHelper = new org.pctechtips.netdroid.dbhelper.DatabaseHelper(ctxt);
db = dbHelper.getWritableDatabase();
downloadFile = new DownloadPortFile();
}
public void execute() {
Log.v("DOWNLOADING", "DOWNLOADING PORT FILE");
downloadFile.execute();
}
public class DownloadPortFile extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
BufferedReader in = null;
HttpsURLConnection connection = null;
try {
URL url = new URL(PORT_URL);
connection = (HttpsURLConnection) url.openConnection();
// connection.setRequestProperty("Accept-Encoding", "gzip");
connection.connect();
Log.v("CONNECTION", "CONNECTION OK");
if (connection.getResponseCode() == HttpsURLConnection.HTTP_OK) {
Log.v("CONNECTION", "CONNECTION OK");
}
in = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getInputStream()), "UTF-8"));
String line;
int lineNum = 0;
while ((line = in.readLine()) != null) {
String[] data = line.split(",", -1);
Log.v("DATA", Arrays.toString(data) +" "+ lineNum);
if(data.length != 12) { continue; }
if(data == null) { continue; }
if(!data[2].equalsIgnoreCase("tcp")) { continue; }
String service = (data[0].equals(" ")) ? "null" : data[0];
int portNum = Integer.parseInt(data[1]);
String protocol = data[2];
String desc = data[3];
Log.v("PARSED", service +" "+ portNum +" "+ protocol +" "+ desc +" "+data.length);
long dbInsert = dbHelper.addTableRecord(service, portNum, protocol, service);
}
} catch (Exception e) {
} finally {
/*try {
if (in != null) {
in.close();
}
} catch (IOException ignored) {
}
if (connection != null) {
connection.disconnect();
}*/
}
return null;
}
#Override
protected void onProgressUpdate(Void... voids) {
}
#Override
protected void onPostExecute(Void aVoid) {
}
}
}
I can see after calling execute, it jumps to the next line in MainActivity instead of going inside doInBackground
This is how it should be as there's no reason for main thread flow to be disrupted just because you spawned other asynchronous worker. That would be actually contrary to what async things are for. If you want to debug doInBackground() you should set a breakpoint on that method's code somewhere (+ you may need to call Debug.waitOnDebugger() if just breakpoint won't work).

App Crashes while switching from one Activity to another

Aim: Building app on Google API to fetch the data about the books the user searches
Problem Explanation:
Whenever I hit the submit Button, my app crashes.
This is my first approach in making a network request app and I need guidance.
MainActivityClass
package com.example.vidit.books;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText query = (EditText) findViewById(R.id.query);
Button submit= (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent= new Intent(MainActivity.this,Request.class);
intent.putExtra ( "text", query.getText().toString() );
startActivity(intent);
}
});
}
}
Second Class
package com.example.vidit.books;
import android.content.Intent;
public class Request {
Intent i = getIntent();
String text = i.getStringExtra ("text");
public static final String LOG_TAG = Request.class.getSimpleName();
String APIURL="https://www.googleapis.com/books/v1/volumes?q= " + text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
}
public void UpdateUi(Book book)
{
BookAdapter bookAdapter = new BookAdapter(this,book);
ListView listView= (ListView) findViewById(R.id.listview_all);
}
private class BookAsyncTask extends AsyncTask<URL,Void,Book>
{
#Override
protected Book doInBackground(URL... urls) {
URL url = createUrl(APIURL);
String jsonResponse = "";
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
// TODO Handle the IOException
}
final Book book = extractFeatureFromJson(jsonResponse);
return book;
}
/**
* Make an HTTP request to the given URL and return a String as the response.
*/
private String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.connect();
if(urlConnection.getResponseCode()==200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
} catch (IOException e) {
// TODO: Handle the exception
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// function must handle java.io.IOException here
inputStream.close();
}
}
return jsonResponse;
}
/**
* Convert the {#link InputStream} into a String which contains the
* whole JSON response from the server.
*/
private String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
/**
* Returns new URL object from the given string URL.
*/
private URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException exception) {
Log.e(LOG_TAG, "Error with creating URL", exception);
return null;
}
return url;
}
private Book extractFeatureFromJson(String bookJSON) {
try {
JSONObject baseJsonResponse = new JSONObject(bookJSON);
JSONArray items = baseJsonResponse.getJSONArray("items");
// If there are results in the features array
for(int i=0;i<10;i++)
{
JSONObject firstFeature = items.getJSONObject(i);
JSONArray author=firstFeature.getJSONArray("author");
for(int j=0;j<author.length();j++)
{
JSONObject authorFeature=author.getJSONObject(j);
}
String title = items.getString(Integer.parseInt("title"));
// Create a new {#link Event} object
return new Book(title,author);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the earthquake JSON results", e);
}
return null;
}
}
}
BookAdapter Class:
package com.example.vidit.books;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class BookAdapter extends ArrayAdapter<Book> {
public BookAdapter(Activity context, Book book)
{
super(context,0, (List<Book>) book);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Book cbook=getItem(position);
TextView title = (TextView) listItemView.findViewById(R.id.title);
title.setText(cbook.getmTitle());
TextView author=(TextView) listItemView.findViewById(R.id.author);
author.setText((CharSequence) cbook.getmAuthor());
return listItemView;
}
}
Showing error in statement:
String text = i.getStringExtra ("text");
Need guidance
I don't know how your code gets compiled when you have overridden onCreate() in Request class and the Request class isn't extending Activity or AppCompatActivity.
Secondly, this line :
Intent i = getIntent();
String text = i.getStringExtra ("text");
should be inside the onCreate() method.
Showing error in statement : String text = i.getStringExtra ("text");
Request for Guidance
Well you need to get the data passed inside onCreate like below.
String APIURL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
Bundle bundle = getIntent().getExtras();
String text = bundle.getString("text");
APIURL="https://www.googleapis.com/books/v1/volumes?q= " + text;
}
And although you have the asyncTask class i can't see where exactly you execute the class. You need to do that inside onCreate as well.
Try moving this code to your onCreate method
Intent i = getIntent();
String text = i.getStringExtra ("text");
The intent extras is not available in the constructor for your Request class.

Cannot resolve method getApplicationContext()

This is the code I got from internet which I need it for my own application. I am trying to make an app using the example. The difference is that I made one separate class for this named JSONTask. I am getting error with getApplicationContex() function. Please help me with this.
import android.os.AsyncTask;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import navdrawerexample1.models.MovieModel;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class JSONTask extends AsyncTask<String,String,List<MovieModel>>
{
private ListView lvMovies;
#Override
protected List<MovieModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url= new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line = reader.readLine())!=null){
buffer.append(line);
}
String finalJason = buffer.toString();
JSONObject parentObject = new JSONObject(finalJason);
JSONArray parentArray = parentObject.getJSONArray("movies");
List<MovieModel> movieModelList = new ArrayList<>();
//StringBuffer finalBufferData = new StringBuffer();
for (int i=0; i<parentArray.length();i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
MovieModel movieModel = new MovieModel();
movieModel.setMovie(finalObject.getString("movie"));
movieModel.setYear(finalObject.getInt("year"));
movieModel.setRating((float) finalObject.getDouble("rating"));
movieModel.setDuration(finalObject.getString("duration"));
movieModel.setDirector(finalObject.getString("director"));
movieModel.setTagline(finalObject.getString("tagline"));
movieModel.setImage(finalObject.getString("image"));
movieModel.setStory(finalObject.getString("story"));
List<MovieModel.cast> castList = new ArrayList<>();
for (int j=0; j<finalObject.getJSONArray("cast").length();j++){
MovieModel.cast cast = new MovieModel.cast();
cast.setName(finalObject.getJSONArray("cast").getJSONObject(j).getString("name"));
castList.add(cast);
}
movieModel.setCastList(castList);
//adding the final object in the list
movieModelList.add(movieModel);
}
return movieModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<MovieModel> result) {
super.onPostExecute(result);
//This is where I get the error
MovieAdapter adapter = new MovieAdapter(getApplicationContext(),R.layout.row,result);
lvMovies.setAdapter(adapter);
//TODO need to set data to the list
}
}
The trouble is that you are calling getApplicationContext() inside a Class that does not extend Context or its subclasses (Activity, etc). You should pass Context or its subclass to the JSONTask constructor. Furthermore, I don't see where you are initializing lvMovies - and you are likely to get NullPointerException at lvMovies.setAdapter(adapter); - my suggestion is that you should pass this as well to your JSONTask constructor:
private Context mContext;
private ListView lvMovies;
public JSONTask (Context context, ListView lstView){
this.lvMovies = lstView;
this.mContext = context;
}
so that in the onPostExecute you can do something like:
MovieAdapter adapter = new MovieAdapter(mContext,R.layout.row,result);
lvMovies.setAdapter(adapter);
I hope this helps.
First declare context,
Activity context;
then
MovieAdapter adapter = new MovieAdapter(context.getApplicationContext(),R.layout.row,result);
lvMovies.setAdapter(adapter);
I hope this is helpfull to you......
You cannot access getApplicationContext() from asynTask because getApplicationContext() doesn't exist in AsyncTask.
Make a constructor and pass Context to this class. Use it in your JSONTask class.
I would recommend you to use Volley library instead of AsyncTask.
create a constructor and pass it a Context variable like
public class JSONTask extends AsyncTask<String,String,List<MovieModel>>{
public Context mContext;
public JSONTask(Context context){
this.mContext = context;
}
.
.
.
now create JsonTask object from your activity/service as
JSONTask task = new JSONTask(getApplicationContext());
and now you can use mContext where you need to pass a context.

Android: get as a static String a value from a URL

URL = http://troyka.esy.es/numberofrows.php
if you put that in your browser you'l get a number (currently it's 9)
I'm trying to pull that number to my android app and display it on a textview
I've tried this method but it shows me nothing on the emulator
internet and network permission are set on manifest
textview id = "textView"
What am I doing wrong?
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class MainActivity extends Activity {
public static String ans;
private TextView T1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
T1 = new TextView(this);
T1 = (TextView) findViewById(R.id.textView);
T1.setText(ans);
}
public String getDATA() throws IOException {
String fullString = "";
URL url = new URL("http://troyka.esy.es/numberofrows.php");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
fullString += line;
}
reader.close();
return fullString;
}
public void setAns() throws IOException {
ans = getDATA();
}
}
Try this answer please:
First, create an AsyncTask class like this to do the actual HTTP request for you outside the android main thread:
public class FetchColumnAsync extends AsyncTask<String, Void, String>
{
private Context mContext;
public FetchColumnAsync( Context ctx){
this.mContext = ctx;
}
protected String doInBackground(String... urls)
{
String fullString = "";
try{
URL url = new URL(urls[0]);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
fullString += line;
}
reader.close();
}catch(Exception e ){
e.getMessage();
}
return fullString;
}
#Override
protected void onPostExecute(String value){
try{
((OnValueFetchedListener) mContext).onValueFetched(value);
}catch(ClassCastException e){}
}
public interface OnValueFetchedListener{
void onValueFetched(String columns);
}
}
Then in your activity class, implement the above interface like this;
public class MainActivity extends Activity implements FetchColumnAsync.OnValueFetchedListener{
public static String ans;
private TextView T1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
T1 = (TextView) findViewById(R.id.textView);
//missing piece of code here
new FetchColumnAsync(this).execute("http://troyka.esy.es/numberofrows.php");
}
#Override
public void onValueFetched(String value){
T1.setText(value);
}
}

Display ListView when button Click

I'm new to android and I hope someone could help me here. I have an activity Faculty and a button.
This is my XML layout browse_faculty:
<Button
android:onClick="searchFSTEHandler"
android:id="#+id/bFSTE"
android:layout_width="220dp"
android:layout_height="80dp"
android:layout_alignLeft="#+id/bFBE"
android:layout_below="#+id/bFBE"
android:layout_marginTop="20dp"
android:text="#string/fste" />
and this is my Faculty Activity which displays the buttons:
I use Intent to view ListView
public class Faculty extends Activity{
#Override
protected void onCreate(Bundle BrowseFaculty) {
// TODO Auto-generated method stub
super.onCreate(BrowseFaculty);
setContentView(R.layout.browse_faculty);
}
//on the XML,this is the "searchFSTEHandler" i want to use to show ListView
public void searchFSTEHandler(View target){
Intent courseList = new Intent(this, HttpActivity.class);
startActivity(courseList);
}
}
and below is the "HttpActivity" class is the class that displays my ListView. This class read a php file which gets data from a MySQL server and converts to JSON data then parses it into a array list.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListActivity;
import android.widget.ArrayAdapter;
public class HttpActivity extends ListActivity {
public String f1 = "FSTE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.faculty_course);
new getHttp().execute();
getHttp test =new getHttp();
String strJsonData = test.doInBackground(f1);
// Convert String JSON data to Java class
ArrayList<Courses> arrayCourse= test.parseJsonData(strJsonData);
//Create an ArrayAdapter which shows the ArrayList data
this.setListAdapter(new ArrayAdapter<Courses>(this,android.R.layout.simple_list_item_1,arrayCourse));
}
private class getHttp extends AsyncTask<String, Void, String> {
public getHttp() {
}
#Override
protected String doInBackground(String... faculty) {
InputStream is = null;
try {
URL url = new URL("http://10.0.2.2/sqlWebService.php?faculty=FSTE");
URLConnection con = url.openConnection();
con.setConnectTimeout(10000);
con.setReadTimeout(10000);
is = con.getInputStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
String str;
while ((str = br.readLine()) != null) {
sb.append(str);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
} finally {
try {
if (is != null)
is.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
//------------------------------------------------------
private ArrayList<Courses> parseJsonData(String strJson) {
ArrayList<Courses> Course = new ArrayList<Courses>();
try {
// Generate JSONArray object by JSON String data
JSONArray arr = new JSONArray(strJson);
//from the JSONArray, get one element (row) of JSONData
for (int i = 0; i < arr.length(); i++) {
//Get JSON Object which is one element of the array
JSONObject ob = arr.getJSONObject(i);
Courses exam = new Courses();
//get the value by key, and set to exam class
exam.setCode(ob.optString("code"));
//save exam class to exam array list
Course.add(exam);
}
} catch (JSONException e) {
e.printStackTrace();
}
return Course;
}
}
}
The application crashes as soon as I click on the button and gives a error:
"android.os.NetworkOnMainThreadException"
Help Please !
The problem that you are having is network operation like what you are trying to do cannot and should not be performed on the main UI thread. Doing so will lead to an ANR (Android Not Responding), which is exactly the kind of error you are getting just now. What you want to do is move your code to a separate thread or to an AsyncTask that will perform this action in the background on a different thread using the doInBackground() method which does not have access to your views on the main UI thread. For example,
private class ExampleOperation extends AsyncTask<String, Void, String> {
public ExampleOperation() { //ctor }
#Override
protected void onPreExecute() {
//things that you want to initialize and maybe show dialog to user.
}
#Override
protected String doInBackground(String... params) {
//this is where you perform that network related operation.
}
#Override
protected void onPostExecute(String result) {
//this is where get the results from the network related task.
}
#Override
protected void onProgressUpdate(Void... values) {
//you can update your progressbar if any; otherwise omit method.
}
}
Then all you have to do is call the AsyncTask where ever you want to use it: new ExampleOperation().execute();
You can't make HTTP calls in the main thread, they take too long and would make the UI unresponsive. You need to do it in an AsyncTask.

Categories

Resources