I am creating an android app that depends on data that the app gets from the database. To get this data I have the following class (this class gets data from the database in JSON, translates it and returns it):
public class Json {
public String jsonResult;
private Activity activity;
private String url = "http://json.example.org/json.php";
private String db, query;
public Json(Activity activity) {
this.activity = activity;
}
public String accessWebService(String db, String query) {
JsonReadTask task = new JsonReadTask();
this.db = db;
this.query = query;
task.execute(new String[] { url });
try {
task.get();
} catch (InterruptedException e) {
Toast.makeText(activity.getApplicationContext(), "FATAL ERROR: The thread got interrupted",
Toast.LENGTH_LONG).show();
} catch (ExecutionException e) {
Toast.makeText(activity.getApplicationContext(), "FATAL ERROR: The thread wasn't able to execute",
Toast.LENGTH_LONG).show();
}
return jsonResult;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
private final ProgressDialog dialog = new ProgressDialog(activity);
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
// add post data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("db", db));
nameValuePairs.add(new BasicNameValuePair("query", query));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
if (jsonResult.isEmpty()) {
Toast.makeText(activity.getApplicationContext(),
"Error, connection is up but didn't receive data. That's strange...", Toast.LENGTH_LONG)
.show();
this.cancel(true);
}
} catch (ClientProtocolException e) {
// Toast.makeText(activity.getApplicationContext(),
// "Error, Client Protocol Exception in JSON task",
// Toast.LENGTH_LONG).show();
Log.i("Json", "Error, Client Protocol Exception in JSON task");
this.cancel(true);
} catch (IOException e) {
// Toast.makeText(activity.getApplicationContext(),
// "Error, Please check your internet connection",
// Toast.LENGTH_LONG).show();
Log.i("Json", "Error, Please check your internet connection");
this.cancel(true);
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
Toast.makeText(activity.getApplicationContext(), "Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
}// end async task
}
I noticed that my app freezes while accessing the database. After some googling, I found out it was the .get() method in the accessWebService() method caused this. I tried to implement a progressDialog like so (I also deleted the .get() method):
private final ProgressDialog dialog = new ProgressDialog(activity);
protected void onPreExecute() {
super.onPreExecute();
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(false);
this.dialog.show();
}
protected void onPostExecute(String result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
but the dialog didn't show up and I got NullPointerException because the app only works when there is data:
result = json.accessWebService(db, query);
(maybe an important thing to mention: I also use this method in for loops)
So now my question is: How can I change my app so that I get a ProgressDialog while accessing the database and without getting NullPointerException? I fear that I have to rearchitect my whole app and if I have to do this, how do I do this? I hope you guys understand my question and have a fix for this because I really need help. Thanks in advance.
P.S. Sorry if my English is not that good, I'm not a native speaker.
... I found out it was the .get() method in the accessWebService() method caused this. I tried to implement a progressDialog...
That is right. get() is a blocking call and simply adding a ProgressDialog won't fix it. You need to remove .get() and that will probably fix the issue of your ProgressDialog not showing.
An AsyncTask must be executed on the main Thread so make sure you are doing that.
Another problem you have is Toast.LENGTH_LONG).show(); runs on the UI and you have it in doInBackground() which cannot happen. You need to send the result to onPostExecute() and you can display your Toast there if need. This could also be done in onProgressUpdate().
This null pointer exception happens because of result value was null. put the condition before
if(result != null ) {
// CODE FOR PARSING
} else {
return;
}
You can start showing progress bar before asyncTask is started and finish showing when asyncTask is finished.
Pass handler to asyncTask and sendMessage onPostExecute method. Then handle message on UI thread and hide progress bar
For example there is handler field in UI (mainActivity). There you should handle hiding progress bar:
public Handler refreshChannelsHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case EPGManager.ERROR_MESSAGE:
//do some stuff
break;
case EPGManager.SUCCESS_MESSAGE:
//do some stuff
break;
}
super.handleMessage(msg);
}
};
Then you can call asyncTask with your handler
epgManager.loadChannels(refreshChannelsHandler);
AsyncTask is inside the method so it looks like this:
public void loadChannels(Handler handler) {
AsyncTask task = new AsyncTask() {
#Override
protected Object doInBackground(Object[] params) {
try {
//do AsyncTask Job
} catch (Exception e) {
return new LoadingResult((Handler) params[0], false);
}
return new LoadingResult((Handler) params[0], false);
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
LoadingResult loadingResult = ((LoadingResult)o);
sendMessageToHandler(loadingResult.handler, loadingResult.isSuccess);
}
};
task.execute(handler);
}
Here is method:
private void sendMessageToHandler(Handler handler, boolean isSuccess) {
handler.sendEmptyMessage(isSuccess ? SUCCESS_MESSAGE : ERROR_MESSAGE);
}
And finally inner class
private class LoadingResult {
private Handler handler;
private boolean isSuccess;
public LoadingResult(Handler handler, boolean isSuccess) {
this.handler = handler;
this.isSuccess = isSuccess;
}
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this.handler = handler;
}
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean isSuccess) {
this.isSuccess = isSuccess;
}
}
Ow, and don't forget constants
public static final int SUCCESS_MESSAGE = 1;
public static final int ERROR_MESSAGE = -1;
Hope it helps :)
Related
I have a AsyncTask<Task, Void, Boolean> thread in my Android application. And I want to show message through Toast.makeText() when this thread completes its execution. For this I have added Toask.makeText() inside if as well as inside else of doInBackground method. The thread is completing its execution succesfully but the toast's message does not appears. So what can be the problem?
Code:
#Override
protected Boolean doInBackground(Task... arg0) {
try {
Task task = arg0[0];
QueryBuilder qb = new QueryBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(qb.buildContactsSaveURL());
StringEntity params =new StringEntity(qb.createTask(task));
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
if(response.getStatusLine().getStatusCode()<205)
{
/*this is the message inside if*/
Toast.makeText(context, "inside -IF", Toast.LENGTH_SHORT).show();
return true;
}
else
{
/*this is the message inside else*/
Toast.makeText(context, "inside -ELSE", Toast.LENGTH_SHORT).show();
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
Toast work in Main thread you are trying to show Toast in Background Thread (doInBackground). Move your toast code to onPostExecution callaback and you will be able to see Toasts.
The Task it is doing is in background, it won't show toast as it is in background.
Background tasks don't affect your UI or main thread.
The thread is completing its execution succesfully but the toast's
message does not appears
Because doInBackground method run on non-ui-Thread. and application only show Alert,Toast and update UI elements from UI-Thread only.
To show Toast from doInBackground wrap Toast related code inside runOnUiThread method
OR
return response from doInBackground method and use onPostExecute method to show Toast.
As mentioned by other people, you shouldn't have any UI related changes/activities on the background thread. Do it on the main thread which onPostExecute method does. Here's an example
private class DoSomethingTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
//Do background process here. Make sure there are no UI related changes here
return null;
}
protected void onPostExecute(Void x)
{
//Do UI related changes here
}
}
Using your code:
private class DoSomethingTask extends AsyncTask<Void, Void, Void> {
int statusCode;
#Override
protected Void doInBackground(Task... arg0) {
try {
Task task = arg0[0];
QueryBuilder qb = new QueryBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(qb.buildContactsSaveURL());
StringEntity params =new StringEntity(qb.createTask(task));
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
statusCode = response.getStatusLine().getStatusCode();
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
protected void onPostExecute(Void x)
{
//Do UI related changes here
if(statusCode < 205)
{
/*this is the message inside if*/
Toast.makeText(context, "inside -IF", Toast.LENGTH_SHORT).show();
return true;
}
else
{
/*this is the message inside else*/
Toast.makeText(context, "inside -ELSE", Toast.LENGTH_SHORT).show();
return false;
}
}
}
Hope this helps!
i created the following activity and it loads well if i add comment to getData() method. If i remove comment then i connect to remote url to fetch and parse json data. This seems to make slower the load of the activity.
It loads instantly if i add comment to GetData() call; it loads in 4-5 seconds if it use GetData(). Here is my activity:
public class MyActivity extends Activity implements OnItemSelectedListener {
Spinner method;
EditText amount;
EditText address;
EditText email;
EditText total;
Button sendButton;
List<String> methods;
String selected_method;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
method = (Spinner) findViewById(R.id.spinnerBuy); // Spinner element
amount = (EditText) findViewById(R.id.editImporto);
address = (EditText) findViewById(R.id.editAddress);
email = (EditText) findViewById(R.id.editEmail);
total = (EditText) findViewById(R.id.editTotale);
sendButton = (Button) findViewById(R.id.button);
method.setOnItemSelectedListener(this);
methods = new ArrayList<String>();
methods.add("Method 1");
methods.add("Method 2");
methods.add("Method 3");
methods.add("Method 4");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.layout.my_simple_spinner_item, methods);
dataAdapter.setDropDownViewResource(R.layout.my_simple_spinner_dropdown_item);
method.setAdapter(dataAdapter);
try {
getData();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData() throws JSONException {
int timeout = 10;
String jsonString = null;
BasicHttpParams basicParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(basicParams, timeout * 1000);
HttpConnectionParams.setSoTimeout(basicParams, timeout * 1000 );
DefaultHttpClient client = new DefaultHttpClient(basicParams);
HttpGet request = new HttpGet("https://www.example.com/data.json");
request.addHeader("Cache-Control", "no-cache");
try {
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStreamReader in = new InputStreamReader(entity.getContent());
BufferedReader reader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
jsonString = stringBuilder.toString();
} catch (SocketTimeoutException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
What could be the problem and how to fix it?
You have to run network operation using an async class. Async classhas a method which you override called doInBackground which does not run on the UI Thread.
private class MyAsyncTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
//Here write your network request
//to obtain result instead of returning null..return the String reply
return reply;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//This part runs after the async is ready, and yes this is back to the UI thread
//s is the reply from the doInBackgroud returned value
}
}
Then you run the task like so
new MyAsyncTask().execute();
UPDATE - PROGRESS BAR
To include a progress bar you have to also override the onPreExecute method..which also runs in the ui thread and it runs before the doInBackground method..so on the preExecute you display progress bar..
first declare a global progress bar
ProgressDialog progress;
Then the Pre Execute Method
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = ProgressDialog.show(this, "dialog title",
"dialog message", true);
}
and in the postExecute add
progress.dismiss();
to remove the progress bar
UPDATE!! - Network Connection
You can check for the network with this method..
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
To Use
if(isNetworkAvailable(context)){
new MyAsyncTask().execute();
}else{
//No Internet don't run task
}
This is because all network operation must be done in non-UI thread. You can use async classes for Network operation like this:
private class GetDataAsync extends AsyncTask<Void, Void, Void > {
#Override
protected Void doInBackground(Void... voids) {
//Get Data
getData();
return null;
}
#Override
protected void onPostExecute(void result) {
//anything you want to do it on UI
}
}
I need to do some HTTP requests from my android app.
I use AsyncTask as needed, with the network part in doInBackground.
Here is my request class :
public class AsyncRequest extends AsyncTask<Void, Integer, HttpResponse>{
private ProgressDialog dialog;
private Activity activity;
private HttpUriRequest query;
private HttpClient client;
private HttpResponse response;
private String dialogMsg;
private String uri;
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public AsyncRequest(Activity a, HttpUriRequest q, HttpClient c, String m) {
query = q;
client = c;
activity = a;
dialog = new ProgressDialog(a);
dialogMsg = m;
}
#Override
protected void onPostExecute(HttpResponse res) {
if (dialog.isShowing())
dialog.dismiss();
}
protected void onPreExecute() {
this.dialog.setMessage(dialogMsg);
this.dialog.show();
}
#Override
protected HttpResponse doInBackground(Void... arg0) {
try {
response = client.execute(query);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
protected HttpResponse getResponse() {
return response;
}
}
And, in my UI thread, I use it this way :
AsyncRequest request;
HttpClient httpClient = new DefaultHttpClient();
HttpGet getQuery = new HttpGet("Here goes my url");
HttpResponse response = null;
String rt = "Null";
getQuery.setHeader("Authorization", getIntent().getExtras().getString("token"));
request = new AsyncRequest(this, getQuery, httpClient, "Loading events...");
try {
response = request.execute().get(3, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
try {
rt = EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
return ;
}
So, I'm an android beginner, but I guess this exception is caught when network related code is executed in main thread. But I run client.execute() in my doInBackground() method. Is it the call to execute().get() (in ui thread) that causes the problem ?
You have this
response = request.execute().get(3, TimeUnit.SECONDS);
Calling get() makes AsyncTask no more Asynchronous. It blocks the ui thread waiting for the response. This leads to NetworkOnMainThreadException.
Get rid of get(3, TimeUnit.SECONDS);
Just use request.execute(). You can update ui in onPostExecute. You can also use interface as a callback to the Activity.
Check the answer by blackbelt in the below link
How do I return a boolean from AsyncTask?
I am running into a problem. I need to use asynctask to retrieve JSON data and I need that data before I moved to the next part of the program. However, when using the get() method of AsyncTask I have 5 to 8 sec black screen before I see the data is displayed. I would like to display a progress dialog during the data retrieval but I cannot do this due to the black screen. Is there a way to put into another thread? here is some code
AsyncTask
public class DataResponse extends AsyncTask<String, Integer, Data> {
AdverData delegate;
Data datas= new Data();
Reader reader;
Context myContext;
ProgressDialog dialog;
String temp1;
public DataResponse(Context appcontext) {
myContext=appcontext;
}
#Override
protected void onPreExecute()
{
dialog= new ProgressDialog(myContext);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setMessage("Retrieving...");
dialog.show();
};
#Override
protected Data doInBackground(String... params) {
temp1=params[0];
try
{
InputStream source = retrieveStream(temp1);
reader = new InputStreamReader(source);
}
catch (Exception e)
{
e.printStackTrace();
}
Gson gson= new Gson();
datas= gson.fromJson(reader, Data.class);
return datas;
}
#Override
protected void onPostExecute(Data data)
{
if(dialog.isShowing())
{
dialog.dismiss();
}
}
private InputStream retrieveStream(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
try {
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(),
"Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
}
catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
}
DisplayInfo
public class DisplayInfo extends Activity implements AdverData {
public static Data data;
public ProjectedData attup;
public ProjectedData attdown;
public ProjectedData sprintup;
public ProjectedData sprintdown;
public ProjectedData verizionup;
public ProjectedData veriziondown;
public ProjectedData tmobileup;
public ProjectedData tmobiledown;
public ProjectedAll transfer;
private ProgressDialog dialog;
public DataResponse dataR;
Intent myIntent; // gets the previously created intent
double x; // will return "x"
double y; // will return "y"
int spatial; // will return "spatial"
//public static Context appContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
dialog= new ProgressDialog(DisplayInfo.this);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setMessage("Retrieving...");
dialog.show();
myIntent= getIntent(); // gets the previously created intent
x = myIntent.getDoubleExtra("x",0); // will return "x"
y = myIntent.getDoubleExtra("y", 0); // will return "y"
spatial= myIntent.getIntExtra("spatial", 0); // will return "spatial"
String URL = "Some URL"
dataR=new DataResponse().execute(attUp).get();
#Override
public void onStart()
{more code}
When you are using get, using Async Task doesn't make any sense. Because get() will block the UI Thread, Thats why are facing 3 to 5 secs of blank screen as you have mentioned above.
Don't use get() instead use AsyncTask with Call Back check this AsyncTask with callback interface
I am getting the exception android.os.NetworkOnMainThreadException when I tried to use the following codes:
public class CheckServer extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Runnable runn = null;
HttpTask.execute(runn);
}
private class HttpTask extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpURLConnection urlConnection = null;
URL theURL = null;
try {
theURL = new URL("http://192.168.2.8/parkme/Client/clientquery.php?ticket=66t");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
urlConnection = (HttpURLConnection) theURL.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String response = null;
try {
response = readInputStream(urlConnection.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
private String readInputStream(InputStream is) {
// TODO Auto-generated method stub
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return total.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}}
If possible can someone tell me how to use it inside an Async Task and get the output? I tried but can't seem to get anywhere.
NetworkOnMainThread Exception occurs because you are running a network related operation on the main UI Thread.This is only thrown for applications targeting the Honeycomb SDK or higher
You should be using asynctask.
http://developer.android.com/reference/android/os/AsyncTask.html
In onCreate()
new TheTask().execute();
You can also pass parameters like url to the constructor of AsyncTask and use the same in doInBackground()
class TheTask extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute()
{ super.onPreExecute();
//display progressdialog.
}
protected void doInBackground(Void ...params)//return result here
{
//http request. do not update ui here
return null;
}
protected void onPostExecute(Void result)//result of doInBackground is passed a parameter
{
super.onPostExecute(result);
//dismiss progressdialog.
//update ui using the result returned form doInbackground()
}
}
When an asynchronous task is executed, the task goes through 4 steps:
onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
Ok, lets do it step by step ...
1) create private class extending AsyncTask
private class HttpUrlConnectionTask extends AsyncTask {
2) Override the doInBackground() method, this will do the heavy load
#Override
protected Object doInBackground(Object... params) {
// your HttpUrlConnection code goes here
return response;
3) Once the job is done and returns, the onPostExecute() method will be called. The result parameter contains the return value of doInBackground() - so response.
#Override
protected void onPostExecute(Object result) {
Within this method you can update your UI.
4) Finally lets have a look onto the HttpUrlConnection code
HttpURLConnection urlConnection = null;
URL theURL = new URL(url);
urlConnection = (HttpURLConnection) theURL.openConnection();
String response = readInputStream(urlConnection.getInputStream());
return response;
Hope this helps. Happy coding!
#Raghunandan comes with a really good explanation of how AsyncTask works
Here you go:
public static class InitializeTask extends MyAsyncTask<String, String, String> {
private Activity activity;
private ProgressDialog dialog;
public InitializeTask(Activity activity) {
this.activity = activity;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(activity, result, Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://192.168.2.8/localhost/parkme/Client/clientquery.php?ticket=");
try {
HttpResponse response = httpclient.execute(httpget);
if(response != null) {
String line = "";
InputStream inputstream = response.getEntity().getContent();
return convertStreamToString(inputstream);
} else {
return "Unable to complete your request";
}
} catch (ClientProtocolException e) {
return "Caught ClientProtocolException";
} catch (IOException e) {
return "Caught IOException";
}
}
private String convertStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (Exception e) {
return "Stream Exception";
}
return total.toString();
}
}
A little side note, it is generally considered bad code to catch just Exception, since this will catch anything, and you are not accounting for what it is.
To use the AsyncTask in the Activity do this:
InitializeTask task = new InitializeTask(this)
task.execute()
Exactly as it says, network activity isn't allowed on the thread the activity ran in. Moving your code to an Asynctask is the way to do it properly. Though if you're just trying to get your concept working still you can do this...
//lazy workaround with newer than gingerbread
//normally UI thread can't get Internet.
if(Build.VERSION.SDK_INT >= 9){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
And then the UI thread actually can. I wouldn't release anything like this however, I haven't even tried infact. It's just my lazy debugging move I use a lot.