I tried almost all the solution but there's some problem with my Inner AsyncTask class. It seems that doInBackground() is not being executed.
onPreExecute() and onPostExecute()are working. However, doInBackground() does not read the code.
I'm really sure about getJSON() is correct 100% because i used the same code before
this is my class
public class My extends Activity implements Runnable {
public static String s = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
findViewById(android.R.id.content).postDelayed(this, 3000);
getJSON("My link ");
}
#Override
public void run() {
startActivity(new Intent(SplashActivity.this, MainActivity.class));
finish();
}
}
AsyncTask:
private void getJSON(String url) {
class GetJSON extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
s = sb.toString().trim();
return sb.toString().trim();
} catch(Exception e){
return null;
}
}
#Override
protected void onPostExecute(String ss) {
super.onPostExecute(ss);
s = ss;
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}
Thanks
Related
String json_string;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void getJSON (View view){
new BackgroundTask().execute();
}
class BackgroundTask extends AsyncTask <Void, Void, String>{
String json_url;
#Override
protected void onPreExecute() {
json_url = "http://androidtut.comli.com/json_get_data.php";
}
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((json_string = bufferedReader.readLine()) != null) {
stringBuilder.append(json_string + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
}
catch (MalformedURLException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
TextView textView = (TextView) findViewById(R.id.textJSON);
textView.setText(result);
}
}
Error:(31, 5) error: MainActivity.BackgroundTask is not abstract and does not override abstract method doInBackground(Void...) in AsyncTask
Error:(39, 24) error: doInBackground(Void...) in MainActivity.BackgroundTask cannot override doInBackground(Params...) in AsyncTask
return type Void is not compatible with String
where Params,Result are type-variables:
Params extends Object declared in class AsyncTask
Result extends Object declared in class AsyncTask
Error:(38, 9) error: method does not override or implement a method from a supertype
Error:(54, 53) error: incompatible types: String cannot be converted to Void
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.> Compilation failed; see the compiler error output for details.
AsyncTask <Void, Void, String>
The last type here is the return result type.
Your doInBackground is currently defined with Void, not String
Likewise, you cannot return a StringBuilder String result as a Void type.
You may find that the other Android HTTP libraries that deal with JSON are much easier to use.
AFAIK, when you define Void in AsyncTask , you should understand the meaning.
doInBackground is a function with empty argument (the first void), return a String (the last String)
protected String doInBackground()
onProgressUpdate is a function with empty argument (the 2nd void)
protected void onProgressUpdate()
onPostExecute is a function with String argument (value from step 1).
protected void onPostExecute(String)
If you can't understand the function in AsyncTask clearly,you'd better try to generate the function in AndroidStudio.
Here is the code generated by AndroidStudio.
class BackgroundTask extends AsyncTask<Void,Void,String>
{
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(Void... params) {
return null;
}
}
Compare your code with above,I think you would kown the answer.
I found two mistakes here.
1. For task execution,
new BackgroundTask().execute(null);
2. doInBackground return type should match with Result type (i.e. String)
protected String doInBackground(Void... voids)
AsyncTask
String json_string;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void getJSON (View view){
new BackgroundTask().execute(null);
}
class BackgroundTask extends AsyncTask <Void, Void, String>{
String json_url;
#Override
protected void onPreExecute() {
json_url = "http://androidtut.comli.com/json_get_data.php";
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((json_string = bufferedReader.readLine()) != null) {
stringBuilder.append(json_string + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
}
catch (MalformedURLException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
TextView textView = (TextView) findViewById(R.id.textJSON);
textView.setText(result);
}
}
String json_string;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void getJSON (View view){
new AsynsTask(){
String json_url;
#Override
protected void onPreExecute() {
json_url = "http://androidtut.comli.com/json_get_data.php";
}
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((json_string = bufferedReader.readLine()) != null) {
stringBuilder.append(json_string + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
}
catch (MalformedURLException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
TextView textView = (TextView) findViewById(R.id.textJSON);
textView.setText(result);
}
}.execute();
}
I have a mainactivity which extends SampleActivityBase with the following code
public class MainActivity extends SampleActivityBase {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
SlidingTabsBasicFragment fragment = new SlidingTabsBasicFragment();
transaction.replace(R.id.sample_content_fragment, fragment);
transaction.commit();
}
}
}
I have another class
public class SlidingTabsBasicFragment extends Fragment {
and within this class I have another sub class
class SamplePagerAdapter extends PagerAdapter {
after override all the necessary functions i have one more function
public String getJSON(String url) {
class GetJSON extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(SlidingTabsBasicFragment.this.getContext(), "Please Wait...", "Checking", true, true);
}
#Override
protected String doInBackground(String... params) {
Log.d("doInBackground : ", "Function Started");
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
jsonString = sb.toString().trim();
return sb.toString().trim();
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String s) {
if(loading.isShowing()) {
loading.dismiss();
}
super.onPostExecute(s);
jsonString = s;
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
return jsonString;
}
when I am calling this function in the SamplePagerAdapter class every thing work fine except Progress Dialog. it is not showing...
Please tell me what I am doing wrong and how can I show progress dialog. Tabs are showing data from online database, I want to start progress dialog when data is fatching.
Keep adapter class separate try .get() instaed of .execute
Normally I create classes for every web service call that extends with the AsyncTask and it's so hard to maintain the code. So I think to create the One class and get the OUTPUT Json string according to the parameters.
how do I return the JSON string?
UPDATE
Here what I tried
public class WebCallController extends AsyncTask<Void,Void,String>
{
String PassPeram = "";
JSONStringer JSonRequestString;
String URL;
String JSonResponseString;
public WebCallController(String PerameterPass, JSONStringer JSonRequestString, String URL) {
PassPeram = PerameterPass;
this.JSonRequestString = JSonRequestString;
this.URL = URL;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
post.setHeader("Content-type", "application/json");
try {
StringEntity entity = new StringEntity(JSonRequestString.toString());
post.setEntity(entity);
}
catch (Exception Ex)
{
}
try {
HttpResponse response = client.execute(post);
StatusLine status = response.getStatusLine();
int statusCode = status.getStatusCode();
if(statusCode == 400)
{
Log.d("Error", "bad request");
}
else if(statusCode == 505)
{
Log.d("Error","Internal server error");
}
else
{
InputStream jsonStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(jsonStream));
StringBuilder builder = new StringBuilder();
String line;
while((line = reader.readLine()) != null)
{
builder.append(line);
}
JSonResponseString = builder.toString();
}
}
catch (IOException Ex)
{
}
return JSonResponseString;
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
}
}
this may be what you are looking for(get string as result and parse it to json):
YourAsycTask yat=new YourAsycTask();
yat.execute();
String result=yat.get().toString();
I am assuming that you need to write one AsyncTask which can be reusable for every webservice call. You can do something like below example ,
Step-1: Create a abstract class
public abstract class HttpHandler {
public abstract HttpUriRequest getHttpRequestMethod();
public abstract void onResponse(String result);
public void execute(){
new AsyncHttpTask(this).execute();
}
}
2. Sterp-2: Write your AsyncTask code
public class AsyncHttpTask extends AsyncTask<String, Void, String>{
private HttpHandler httpHandler;
public AsyncHttpTask(HttpHandler httpHandler){
this.httpHandler = httpHandler;
}
#Override
protected String doInBackground(String... arg0) {
//do your task and return the result
String result = "";
return result;
}
#Override
protected void onPostExecute(String result) {
httpHandler.onResponse(result); // set it to the onResponse()
}
}
Step-3: Write your Activity code
public class MainActivity extends Activity implements OnClickListener {
private Button btnRequest;
private EditText etResponse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRequest = (Button) findViewById(R.id.btnRequest);
etResponse = (EditText) findViewById(R.id.etRespose);
//check isConnected()...code is on github
btnRequest.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new HttpHandler() {
#Override
public HttpUriRequest getHttpRequestMethod() {
return new HttpGet("http://hmkcode.com/examples/index.php");
// return new HttpPost(url)
}
#Override
public void onResponse(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
etResponse.setText(result);
}
}.execute();
}
// public boolean isConnected(){}
}
reference
http://hmkcode.com/android-cleaner-http-asynctask/
https://github.com/hmkcode/Android/tree/master/android-clean-http-async-task
Try out below code and put it in separate class from where it returns json string to your activity.
Only pass your url to this method and get the response in a string formate.
public static final String GetConnectionInputStream(String strUrl) {
String line = null;
String response = null;
try {
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is
// established.
// The default value is zero, that means the timeout is not used.
HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setSoTimeout(httpParameters, 30000);
// This is the default apacheconnection.
HttpClient mHttpClient = new DefaultHttpClient(httpParameters);
// Pathe of serverside
HttpGet mHttpGet = new HttpGet(strUrl);
// get the valu from the saerverside as response.
HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
HttpEntity mHttpEntity = mHttpResponse.getEntity();
try {
// convert response in to the string.
if (mHttpEntity.getContent() != null) {
BufferedReader mBufferedReader = new BufferedReader(
new InputStreamReader(mHttpEntity.getContent(),
HTTP.UTF_8), 8);
StringBuilder mStringBuilder = new StringBuilder();
while ((line = mBufferedReader.readLine()) != null) {
mStringBuilder.append(line + "\n");
}
response = mStringBuilder.toString();
// mInputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return response;
}
Change your doInBackground method as below:
private class GetParsedResponse extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(Void... params) {
String response=null;
response=GetConnectionInputStream(URL);
return response;
}
#Override
protected void onPostExecute(String result) {
//your response parsing code.
}
}
private class MyAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
return "Executed";
}
#Override
protected String onPostExecute(String result) {
return "json String";
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
I have a custom http class in my android app to handle http post data that is sent to the server. However, I need to convert it to extend asyncTask because I need to 1, show a progress animation while the data is being fetched and 2, refresh/update the ui at the same time.
So what would be the easiest way to do this. Please note that I am already using the class throughout my app to handle httpPOST requests.
Here is the class:
public class Adapter_Custom_Http_Client
{
//<editor-fold defaultstate="collapsed" desc="Class Members">
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
private static HttpClient mHttpClient;
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getHttpClient">
private static HttpClient getHttpClient()
{
if(mHttpClient == null)
{
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="executeHttpPost">
public static String executeHttpPost(String url, ArrayList postParameters) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="executeHttpGet">
public static String executeHttpGet(String url) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
//</editor-fold>
}
Use this Async Class:
public class Albums extends AsyncTask<Void, Void, Void> {
//declarations what u required
#Override
protected void onPreExecute() {
super.onPreExecute();
///declare ur progress view and show it
}
#Override
protected Void doInBackground(Void... params) {
//do ur http work here which is to be done in background
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Update ur UI here...
}
}
Any problem please ask..
EDIT:
Albums alb=new Albums();
alb.execute(null);///u can use different arguments that u need
follow like this:
public class postmethod extends AsyncTask<Void, Void, Void> {
//declarations what u required
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
//do ur work here completly that will runs as background
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
Create new asynch inner class in your activity :
public class InnerClass extends AsyncTask<Void, Void, String>{
ProgressDialog dialog;
#Override
protected String doInBackground(Void... params) {
String result = Adapter_Custom_Http_Client.executeHttpPost(url , param);
return result;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(context, "", "Please wait....");
super.onPreExecute();
}
}
and execute background task using
new InnerClass().execute();
I currently have multiple activity that needs to perform an asynctask for http post and I wish to make the asynctask as another class file so that the different activity can call the asynctask to perform the http post request and onPostExecute, call the method httpResult(result) in the activity that called the asynctask. I have tried to pass the activity in but I am unable to call the method in onPostExecute. How can I do that?
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_MyActivity);
//logic here...
AsyncHttpPost asyncHttpPost = new AsyncHttpPost("someContent", this, dialog);
JSONObject data = new JSONObject();
data.put("key", "value");
try {
asyncHttpPost.execute(data);
}
catch (Exception ex){
ex.printStackTrace();
}
}
public static void httpResult(String result) {
//this method has to get called by asynctask to make changes to the UI
}
}
AsyncHttpPost.java
public class AsyncHttpPost extends AsyncTask<JSONObject, String, String> {
String recvdjson;
String mData="";
private ProgressDialog dialog;
private Activity activity;
public AsyncHttpPost(String data, Activity activity, ProgressDialog dialog) {
mData = data;
this.activity = activity;
this.dialog = dialog;
}
protected void onPreExecute()
{
dialog.show();
}
#Override
protected String doInBackground(JSONObject... params) {
//logic to do http request
return "someStringResult";
}
protected void onPostExecute(String result) {
dialog.dismiss();
activity.httpResult(result); //This line gives me error : The method httpResult(String) is undefined for the type Activity
}
}
Create an Interface called HttpResponseImpl in a seperate file and add the required method httpResult
interface HttpResponseImpl{
public void httpResult(String result);
}
Now implement this interface by you Activity class
public class MyActivity extends Activity implements HttpResponseImpl{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_MyActivity);
//logic here...
AsyncHttpPost asyncHttpPost = new AsyncHttpPost("someContent", this, dialog);
JSONObject data = new JSONObject();
data.put("key", "value");
try {
asyncHttpPost.execute(data);
}
catch (Exception ex){
ex.printStackTrace();
}
}
public void httpResult(String result){
//this method has to get called by asynctask to make changes to the UI
}
}
And your AsyncHttpPost class would be.
public class AsyncHttpPost extends AsyncTask<JSONObject, String, String> {
String recvdjson;
String mData="";
private ProgressDialog dialog;
private HttpResponseImpl httpResponseImpl;
public AsyncHttpPost(String data, HttpResponseImpl httpResponseImpl, ProgressDialog dialog) {
mData = data;
this.httpResponseImpl = httpResponseImpl;
this.dialog = dialog;
}
protected void onPreExecute()
{
dialog.show();
}
#Override
protected String doInBackground(JSONObject... params) {
//logic to do http request
return "someStringResult";
}
protected void onPostExecute(String result) {
dialog.dismiss();
httpResponseImpl.httpResult(result);
}
}
Implements this HttpResponseImpl interface with all you Activity class from which you want to do HttpRequest.
Generic AsyncTask Example
Call it like
new RetrieveFeedTask(new OnTaskFinished()
{
#Override
public void onFeedRetrieved(String feeds)
{
//do whatever you want to do with the feeds
}
}).execute("http://enterurlhere.com");
RetrieveFeedTask.class
class RetrieveFeedTask extends AsyncTask<String, Void, String>
{
String HTML_response= "";
OnTaskFinished onOurTaskFinished;
public RetrieveFeedTask(OnTaskFinished onTaskFinished)
{
onOurTaskFinished = onTaskFinished;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls)
{
try
{
URL url = new URL(urls[0]); // enter your url here which to download
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = br.readLine()) != null)
{
// System.out.println(inputLine);
HTML_response += inputLine;
}
br.close();
System.out.println("Done");
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return HTML_response;
}
#Override
protected void onPostExecute(String feed)
{
onOurTaskFinished.onFeedRetrieved(feed);
}
}
OnTaskFinished.java
public interface OnTaskFinished
{
public void onFeedRetrieved(String feeds);
}