I have a method name Request() in the onCreate method of the activity.
private void Request() {
new PostDataAsyncTask(textEmail, tValue).execute();
}
Iam passing two strings in it and the async class is as follows:
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
GameActivity game= new GameActivity();
private String data,data1;
public PostDataAsyncTask(String textEmail, String hello) {
data = textEmail;
data1= hello;
}
long date = System.currentTimeMillis();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM MM dd, yyyy h:mm a");
String dateString = simpleDateFormat.format(Long.valueOf(date));
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
postText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String lenghtOfFile) {
}
private void postText(){
try{
String postReceiverUrl = "http://techcube.pk/game/game.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(postReceiverUrl);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", data));
nameValuePairs.add(new BasicNameValuePair("score", data1));
nameValuePairs.add(new BasicNameValuePair("datetime", dateString));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v("SuccesS", "Response: " + responseStr);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now what i want is that i want to get the value of responseStr in my MainActivity that is generated when posttext method called.
How to show this responseStr value in the MainActivity?
Remember there is a new class that i made named as PostDataAsyncTask so how to access responseStr from this class and show it in my mainActivity as a Toast or Textview?
Please Help
You can create an interface that you pass into the method in question. For example
public interface INetworkResponse {
void onResponse(String response);
void onError(Exception e);
}
You would then need to create a concrete implementation of the interface. perhaps as a child class inside the activity that calls the AsyncTask.
public class MyActivity extends Activity {
private void Request() {
NetworkResponse response = new NetworkResponse();
new PostDataAsyncTask(textEmail, tValue, response).execute();
}
public class NetworkResponse implements INetworkResponse {
public void onResponse(String response) {
// here is where you would process the response.
}
public void onError(Exception e) {
}
}
}
Then change the async task constructor to include the new interface.
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
GameActivity game= new GameActivity();
private String data,data1;
private INetworkResponse myResponse;
public PostDataAsyncTask(String textEmail, String hello, INetworkResponse response) {
data = textEmail;
data1 = hello;
myResponse = response
}
private void postText() {
// do some work
myResponse.onResponse(myResultString);
}
}
You can create a Handler as an Inner class inside your Activity to send data between your thread and UIthread:
public class YourHandler extends Handler {
public YourHandler() {
super();
}
public synchronized void handleMessage(Message msg) {
String data = (String)msg.obj;
//Manage the data
}
}
Pass this object in the header of PostDataAsyncTask
public PostDataAsyncTask(String textEmail, String hello, YourHandler mYourHandler) {
data = textEmail;
data1= hello;
this.mYourHandler = mYourHandler;
}
and send the data in postText() to the Activity:
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
msg = Message.obtain();
msg.obj = responseStr;
mYourHandler.sendMessage(msg);
Log.v("SuccesS", "Response: " + responseStr);
}
Related
My scenario is i have 5 threads parallel call to happen in splash activity but i need to wait for one specific thread( which is DashBoardCallable) exectuion so that i can load dashboard data, show the splash screen untill dashboard data gets loaded and once dashboard data get loaded change the activity meanwhile in parallel i load some more data related to that user in background(which is thread util class will do ).
or you can understand this way i have a ExecutorService of 5 threads for parallel calls and Splashscreen is based on one thread execution out of 5. Once this thread execution is done change the activity leaving rest other thread execution in background.
below is splash activity code :
ExecutorService executor = Executors.newFixedThreadPool(5);
SharedPreferences sharedpreferences = getSharedPreferences(getResources().getString(R.string.mypreference_key), Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedpreferences.edit();
ThreadUtil datatype1 = new ThreadUtil(editor,3504,"URL","DATATYPE1","DATATYPE1");
ThreadUtil datatype2 = new ThreadUtil(editor,3504,"URL","DATATYPE2","DATATYPE2");
ThreadUtil datatype3 = new ThreadUtil(editor,3504,"URL","DATATYPE3","DATATYPE3");
ThreadUtil datatype4 = new ThreadUtil(editor,3504,"Different URL","DATATYPE1","DATATYPE1");
DashBoardCallable dashBoardCallable = new DashBoardCallable(SplashScreenActivity.this,3504);
FutureTask<String> dashboardFuture = new FutureTask<String>(dashBoardCallable);
executor.execute(datatype1);
executor.execute(datatype2);
executor.execute(datatype3);
executor.execute(datatype4);
executor.execute(dashboardFuture);
String response =dashboardFuture.get();
This is dashboaord callable :
public class DashBoardCallable implements Callable<String> {
private Context context;
private int user_id;
public DashBoardCallable(Context context,int user_id){
this.context = context;
this.user_id = user_id;
}
#Override
public String call() throws Exception {
HttpUtil httpUtil = new HttpUtil();
httpUtil.setUrl("URL");
httpUtil.setType("GET");
return httpUtil.getStringResponse();
}
}
this is threadUtil class:
public class ThreadUtil implements Runnable {
private int user_id;
private String url,type,stored_name;
private SharedPreferences.Editor editor;
public ThreadUtil( SharedPreferences.Editor editor, int user_id, String url, String type,String stored_name){
this.editor = editor;
this.user_id = user_id;
this.url = url;
this.type = type;
this.stored_name = stored_name;
}
#Override
public void run() {
HttpUtil httpUtil = new HttpUtil();
httpUtil.setUrl(url);
httpUtil.setType("GET");
String jsonresponse =httpUtil.getStringResponse();
Gson gson = new Gson();
switch (type){
case "DATATYPE1":
saveDATATYPE1(jsonresponse,gson,editor);
break;
case "DATATYPE2":
saveDATATYPE2(jsonresponse,gson,editor);
break;
case "DATATYPE3":
saveDATATYPE3(jsonresponse,gson,editor);
break;
}
}
private void saveDATATYPE1(String jsonresponse, Gson gson,SharedPreferences.Editor editor) {
if(!jsonresponse.equalsIgnoreCase("null")){
editor.putString(stored_name, jsonresponse);
editor.apply();
editor.commit();
}
}
private void saveDATATYPE2(String jsonresponse, Gson gson, SharedPreferences.Editor editor) {
try {
Type listType = new TypeToken<List<AssessmentPOJO>>() {}.getType();
ArrayList<AssessmentPOJO> dashboardCards = (ArrayList<AssessmentPOJO>) gson.fromJson(jsonresponse, listType);
for(AssessmentPOJO assessmentPOJO:dashboardCards){
System.out.println("XXBBXBXBXBXB -> "+assessmentPOJO.getName());
if(assessmentPOJO != null){
editor.putString(stored_name+assessmentPOJO.getId(), gson.toJson(assessmentPOJO));
editor.apply();
editor.commit();
}
}
}catch (JsonSyntaxException jse){
jse.printStackTrace();
}catch (Exception e){
}
}
private void saveDATATYPE3(String jsonresponse, Gson gson,SharedPreferences.Editor editor) {
if(!jsonresponse.equalsIgnoreCase("null")) {
Type listType = new TypeToken<List<CoursePOJO>>() {}.getType();
ArrayList<CoursePOJO> coursePOJOs = (ArrayList<CoursePOJO>)gson.fromJson(jsonresponse, listType);
for(CoursePOJO coursePOJO:coursePOJOs){
if(coursePOJO != null){
editor.putString(stored_name+coursePOJO.getId(), gson.toJson(coursePOJO));
editor.apply();
editor.commit();
}
}
}
}
}
this is HttpUtil class:
public class HttpUtil {
private String url;
private String type;
private HashMap<String,String> param;
private String postrequest;
public HttpUtil(){}
private int socketTimeOut=0, connectionTimeOut=0;
public HttpUtil(String url, String type, HashMap<String, String> param,String postrequest) {
this.url = url;
this.type = type;
this.param = param;
this.postrequest = postrequest;
}
public String getStringResponse(){
String jsonresponse="";
try {
System.out.println("url "+url);
System.out.println("type "+type);
HttpResponse httpResponse = getHttpResponse();
if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
HttpEntity httpEntity = httpResponse.getEntity();
jsonresponse = EntityUtils.toString(httpEntity);
if(jsonresponse.equalsIgnoreCase("[]")){
jsonresponse="";
}
System.out.println("HttpUtil Response is .... " + jsonresponse);
} else {
return "null";
}
} catch (IOException e) {
e.printStackTrace();
}
return jsonresponse;
}
public void getVoidResponse(){
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public HashMap<String, String> getParam() {
return param;
}
public void setParam(HashMap<String, String> param) {
this.param = param;
}
private HttpResponse getHttpResponse(){
HttpResponse httpResponse = null;
HttpClient httpclient = new DefaultHttpClient();
try{
switch(type){
case "GET":
if(socketTimeOut != 0 && connectionTimeOut != 0){
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeOut);
HttpConnectionParams.setSoTimeout(httpParameters, socketTimeOut);
httpclient = new DefaultHttpClient(httpParameters);
}
httpResponse = httpclient.execute(new HttpGet(url));
break;
case "POST":
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if(param != null) {
for (String key : param.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, param.get(key)));
}
}
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpResponse = httpclient.execute(httpPost);
break;
case "PUT":
HttpPut httpPut = new HttpPut(url);
if(postrequest != null){
StringEntity se = new StringEntity(postrequest);
se.setContentType("application/json;charset=UTF-8");//text/plain;charset=UTF-8
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
httpPut.setEntity(se);
httpPut.setHeader("Accept", "application/json");
httpPut.setHeader("Content-type", "application/json");
}
httpResponse = httpclient.execute(httpPut);
break;
default:
httpResponse = httpclient.execute(new HttpGet(url));
break;
} }catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}catch (JsonSyntaxException jse) {
jse.printStackTrace();
return null;
}catch (Exception e){
e.printStackTrace();
return null;
}
return httpResponse;
}
public String getPostrequest() {
return postrequest;
}
public void setPostrequest(String postrequest) {
this.postrequest = postrequest;
}
public int getSocketTimeOut() {
return socketTimeOut;
}
public void setSocketTimeOut(int socketTimeOut) {
this.socketTimeOut = socketTimeOut;
}
public int getConnectionTimeOut() {
return connectionTimeOut;
}
public void setConnectionTimeOut(int connectionTimeOut) {
this.connectionTimeOut = connectionTimeOut;
}
}
Based on the use of your threads I can tell you should be better to use AsyncTask.
Every AsyncTask must have a Callback and the Activity implement them so, after the task was completed, the Activity can keep control of the operations and take decisions.
For the tasks:
public class SplashScreenTask extends AsyncTask<Void, Void, Void> {
private Context context;
private SplashScreenTaskCallback listener = null;
public SplashScreenTask (Context context) {
this.context = context;
}
#Override
protected Void doInBackground (Void... params) {
// Do your tasks
return null;
}
#Override
public void onPreExecute () {
}
#Override
public void onPostExecute (Void v) {
if (listener != null) {
listener.OnSplashScreenTaskCompleted ();
}
}
public void setListener (SplashScreenTaskCallback listener) {
this.listener = listener;
}
public interface SplashScreenTaskCallback {
void OnSplashScreenTaskCompleted ();
}
}
And your activity:
public class SplashScreenActivity extends Activity implements SplashScreenTask.SplashScreenTaskCallback {
protected Runnable postDelayedAction;
private final Handler handler = new Handler();
#Override
public void onCreate (Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
handler.postDelayed(startBackgroundTasks, splashScreenDelay);
}
private Runnable startBackgroundTasks = new Runnable() {
#Override
public void run () {
// Do initial background tasks like sounds load
SplashScreenTask task = new SplashScreenTask (SplashScreenActivity.this);
task.setListener (SplashScreenActivity.this);
task.execute ();
}
};
#Override
public void OnSplashScreenTaskCompleted () {
// Here you take decisions
}
}
I would use the Rx zip operator to determine when all of your backgrounds tasks have completed. Determining the completion of multiple parallel jobs is a huge headache with the Android framework.
There is a best practice for showing a splash screen with no initial delay wherein you set the background drawable using themes. In order to do that and transition into your Activity (not your splash screen) where you can actually fire off all of this logic, simply duplicate the visuals of your splash screen in your Activity, and transition out of showing those visuals once your jobs have completed.
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 want to create an class file for Async task operation and from creating the object of that class file i want to access these method of async task with no of different class files with different parameters.
Methods of Async task include:-
OnPreExecute()-Want to start progress dialog same for each class.
doInbackground()-Want to perform background operation(like getting data from server) means passing parameter different for each class.
onPostExecute()-Dismiss the progress dialog and update the UI differnt for each class.
Now I'm writing the async task in my every class as inner class like the following:-
class loaddata extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddNewLineitem.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
}
});
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url_foralldropdowns,
"GET", params1);
compoment = json.getJSONArray(COMPONENT_CODE);
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
loadSpinnerData();
pDialog.dismiss();
}
}
And JSON parser class is as follows:-
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
And in oncreate() I call this and it works fine:-
new loaddata().execute();
We can reuse Aysntask with different parameters. For this
1.Create an Interface so that we can reuse,pass and receive parameters
public interface BackgroundListener {
public Object[] startBackgroundWork(Object... objs);
public void endBackgroundWork(Object... objs);
public void beforeBackgroundWork();
}
2.Create a Class Extending Asyntask
BackgroundHandler.java
import android.os.AsyncTask;
public class BackgroundHandler extends AsyncTask<Object, Object[], Object[]>{
BackgroundListener backgroundListener;
public void setBackgroundListener(BackgroundListener aBackgroundListener)
{
this.backgroundListener = aBackgroundListener;
}
#Override
protected void onPreExecute() {
backgroundListener.beforeBackgroundWork();
}
#Override
protected Object[] doInBackground(Object... objs) {
return backgroundListener.startBackgroundWork(objs);
}
#Override
protected void onPostExecute(Object result[]) {
backgroundListener.endBackgroundWork(result);
}
}
Using in Activity
A.java
Class A extends Activity implements BackgroundListener
{
...onCreate()
{
BackgroundHandler backgroundHandler = new BackgroundHandler()
backgroundHandler.setBackgroundListner(this);
backgroundHandler.execute(new Object[]{url1});//pass any number of parameters of any object type
// show loading bar
}
public void beforeBackgroundWork()
{
pDialog = new ProgressDialog(A.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
.....
}
public Object[] startBackgroundWork(Object... objs)
{
// access and type convert the passed parameters like objs[0], objs[1]
//.... some time consuming stuff
//.... some time consuming stuff
String url_foralldropdowns = objs[0].toString();
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url_foralldropdowns,
"GET", params1);
JSONArray compoment = json.getJSONArray(COMPONENT_CODE);
//Create new list_compoment here instead of global declaration
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
retrun new Object[]{list_compoment};
}
public void endBackgroundWork(Object ...obj)
{
pDialog.dismiss();// hide loading bar
//access resultant parameters like objs[0], objs[1]
//user list_component will be in obj[0]
}
}
Similarly we can reuse in B.java
Class B extends Activity implements BackgroundListener
{
...
....
public void beforeBackgroundWork()
{
pDialog = new ProgressDialog(B.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
.....
}
public Object[] startBackgroundWork(Object... objs)
{
// access and type convert the passed parameters like objs[0], objs[1]
//.... some time consuming stuff
//.... some time consuming stuff
String url2 = objs[0].toString();
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url2,
"GET", params1);
JSONArray compoment = json.getJSONArray(COMPONENT_CODE);
//Create new list_compoment here instead of global declaration
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
retrun new Object[]{list_compoment};
}
public void endBackgroundWork(Object ...obj)
{
pDialog.dismiss();
.....
//user list_component will be in obj[0]
}
}
Asyntask is just a class like others. Apart from the main inhertited methods of AsyncTask you can create your own methods, constructor etc. So just create a separate class in separate file. pass the context as parameter of the constructor. you can pass other values also to define the tasks.
class Loaddata extends AsyncTask<String, String, String> {
public Loaddata( pass the params){
... set the params
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Loading Data. Please wait...");
pDialog.show();
}
protected void onPostExecute() {
// pDialog.dismiss();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
}
I am attempting to write an Android app which casts JSON input. This is my sample input.
I have the following class to serve as the data container:
public class DATA {
public Long id;
public String title;
public String author;
public String url;
public String date;
public String body;
public DATA() {
// TODO Auto-generated constructor stub
}
#Override
public String toString(){
return "DATA-Oblect: ID=> " + id + "/nTITLE=> " + title;
}
}
Using the following code:
protected void doInBackground(String... url) {
try{
//create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://kylewbanks.com/rest/posts");//url[0]);
//perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200){
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
content = entity.getContent();
try{
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
List<DATA> Data = new ArrayList<DATA>();
Data = Arrays.asList(gson.fromJson(reader, DATA[].class));
content.close();
}catch(Exception ex){
Log.e(TAG, "JSON parse failed due to: " + ex);
}
}else{
Log.e(TAG, "Server response code: " + statusLine.getStatusCode());
}
}catch(Exception ex){
Log.e(TAG, "HTTP-Post failed due to: " + ex);
}
}
I get the following exception error:
JSON parse failed due to: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
What am I doing wrong?
Update
The following the the my main activity code:
public class MainActivity extends Activity {
private List<DATA> Data;
public static final String jsonSource = "http://kylewbanks.com/rest/posts";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// DataRetriever("http://kylewbanks.com/rest/posts");
new DataRetriever(this.getApplicationContext()).execute(jsonSource);
}
/**
* Callback function for handling retrieved data from the
* DATARetrieve class
* #param Data
*/
public void DataListDrop(List<DATA> Data){
this.Data = Data;
Toast.makeText(MainActivity.this, "Testing ... testing!", Toast.LENGTH_SHORT).show();
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
for(DATA data : MainActivity.this.Data){
Toast.makeText(MainActivity.this, data.title, Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Callback function for responding no-data return from the
* DATARetrieve class
*/
private void NoData(){
runOnUiThread(new Runnable() {
#Override
public void run(){
Toast.makeText(MainActivity.this, "No data to process! Checkout LogCat.", Toast.LENGTH_SHORT).show();
}
});
}
}
I'm working on one project and I need to call one AsyncTask, but the onPostExecute method is not called.
This is my class:
public class WebService extends AsyncTask<String, String, String> {
private ArrayList<SimpleObserver> listeners;
private int responseCode;
private String message;
private String response;
private String URL;
public WebService() {
listeners = new ArrayList<SimpleObserver>();
}
public void addListener(SimpleObserver obs) {
listeners.add(obs);
}
public void removeListener(SimpleObserver obs) {
listeners.remove(obs);
}
public void notifyListener(String s) {
for (SimpleObserver listener : listeners)
listener.onChange(s);
}
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
#Override
protected void onPreExecute() {
//notifyListener("A calcular");
}
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
HttpParams my_httpParams = new BasicHttpParams();
final String proxyHost = android.net.Proxy.getDefaultHost();
final int proxyPort = android.net.Proxy.getDefaultPort();
if(proxyPort != -1)
{
my_httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort));
}
DefaultHttpClient client = new DefaultHttpClient(my_httpParams);
HttpGet httpGet = new HttpGet(url);
Log.d("URL serviço HttpGet", url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
Log.d("RESPOSTA do web service", response);
} catch (Exception e) {
e.printStackTrace();
response = e.getMessage();
Log.e("ERRO de respota", e.getMessage());
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
Log.d("onPostExecute Serviço", result);
notifyListener(result);
}
}
I have created this method:
public void executeService(String param) {
try {
Log.d("Entrar", "no serviço");
s.execute(new String [] {URL+param});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Erro ao aceder ao web service", e.getMessage());
}
}
to call the task.
these are the results of Log
08-28 17:47:21.936: D/URL serviço HttpGet(2055): http://192.168.56.1:8080/pt.Agile21.Acerola.WebService/rest/acerola?id=g;ana#eu.com
08-28 17:47:22.456: D/RESPOSTA do web service(2055): ana;ana#eu.com;pass;0
08-28 17:47:22.456: D/RESPOSTA do web service(2055): ana;ana#eu.com;pass;0
As you can see I have all the results of doInBackground(). :S
Someone can help me to understand which is the problem?
Something that I saw now looking for the Log files.. my onPostExeute method returns when I finish my app on purpose.. it is not normal.. :S can someone help me?