can you please tell me how to call json web service using how to call json webservice using asynctask android .I call like that and got the response.But I need to do like that before calling i need to show "please wait " do some async task in background.and remove that pop up when response come.
public static String getMethod(String url) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(url));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
// Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
// TODO Handle problems..
} catch (IOException e) {
// TODO Handle problems..
}
return responseString;
}
WebServiceRequestManager wb=new WebServiceRequestManager();
String ss= wb.getMethod("htoard?crsCode=add");
System.out.println("String"+ss);
My suggestion would to use AndroidAsyncHttp(LoopJ) for the following reasons.
1) Code structure will be small and elegant.
2) Easy to use.
3) Performance ,it is really fast
DO this way
This is your WebServiceRequestManager.java
public class WebServiceRequestManager {
public String getMethod(String url) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(url));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
// Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
// TODO Handle problems..
} catch (IOException e) {
// TODO Handle problems..
}
return responseString;
}
}
How to call it from Activity from asynctask?
public class MainActivity extends Activity {
private ProgressDialog progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTask<Void, Void, String>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialog("Please Wait...");
}
#Override
protected String doInBackground(Void... params) {
WebServiceRequestManager manager = new WebServiceRequestManager();
return manager.getMethod("http://50.57.145.165:8080/FirstGroupRailApps/jservices/rest/a/destinationdashboard?crsCode=add");
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Respose : " + result);
hideProgressDialog();
}
}.execute();
}
public void showProgressDialog(final String msg) {
runOnUiThread(new Runnable() {
public void run() {
if (progress == null || !progress.isShowing()) {
progress = ProgressDialog.show(MainActivity.this, "", msg);
}
}
});
}
public void hideProgressDialog() {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
if (progress.isShowing())
progress.dismiss();
} catch (Throwable e) {
}
}
});
}
}
Related
I have an AsyncTask which acts as a client and get a string from a server and puts it in a String. After the task I use the response from the server but the data haven't changed yet - it's null.
connectBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
Client myClient = new Client(responseTV);
myClient.execute();
if (responseStr.charAt(0) == '1') { <----- responseStr is null
changeBrightness(Integer.parseInt(responseStr.substring(1)));
}
}
});
I assume the code keeps going after .execute() which is not very good in my situation.
Update: Added code for Client class.
public class Client extends AsyncTask<Void, Void, Void> {
String response = "";
TextView responseTV;
public Client(TextView responseTV) {
this.responseTV = responseTV;
}
#Override
protected Void doInBackground(Void... params) {
Socket socket = null;
try {
socket = new Socket(IP, PORT);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
InputStream inputStream = socket.getInputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e) {
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
e.printStackTrace();
response = "IOException: " + e.toString();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
//Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
responseTV.setText(response);
responseStr = response;
super.onPostExecute(aVoid);
}
}
if (responseStr.charAt(0) == '1') { <----- responseStr is null
changeBrightness(Integer.parseInt(responseStr.substring(1)));
}
Use this code in onPostExecute() method of AsyncTask. It runs on the UI thread and is exactly the method you need after finishing work in doInBackground().
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
While executing Async Task in android and getting Json response and while converting response into JSONArray,i am getting NUll pointer Exception.
I am trying fron two days Please help me.
Here is the code to get the Json String.
error is at task.get().
DownloadTask task=new DownloadTask();
task.execute(new String[]{"URL"});
try {
jsonArr=new JSONArray(task.get());
Toast.makeText(getApplicationContext(), jsonArr.toString(), Toast.LENGTH_LONG).show();
for (int i = 0; i < jsonArr.length(); i++) {
obj = jsonArr.getJSONObject(i);
name = obj.getString("name");
phno = obj.getString("phone");
dcount = obj.getString("count");
}
} catch (JSONException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Here Is the Async task code.
class DownloadTask extends AsyncTask<String,Void,String>{
private ProgressDialog mProgressDialog=new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute(){
mProgressDialog.setMessage("Processing");
mProgressDialog.show();
}
#Override
protected String doInBackground(String... targetURL) {
URL url;
HttpURLConnection connection = null;
try {
url = new URL(targetURL[0]);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type",
"application/json");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
/* //Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes("BID1");
wr.flush();
wr.close();*/
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(),result, Toast.LENGTH_SHORT);
mProgressDialog.dismiss();
}
}
You are forgot to call the super method of the onPostExecute
It should be like this
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(),result, Toast.LENGTH_SHORT);
mProgressDialog.dismiss();
super.onPostExecute(result);
}
Other Solution
You can use an interface for your callback
ICallback.java
public interface ICallback {
void onResult(String result);
}
DownloadTask
class DownloadTask extends AsyncTask<String, Void, String> {
private ProgressDialog mProgressDialog = new ProgressDialog(MainActivity.this);
private ICallback callback;
public DownloadTask(ICallback callback) {
this.callback = callback;
}
#Override
protected void onPreExecute() {
//Your Codes Here
}
#Override
protected String doInBackground(String... targetURL) {
//Your Codes Here
}
#Override
protected void onPostExecute(String result) {
//Your Codes Here
callback.onResult(result)
}
}
How to use it
DownloadTask task = new DownloadTask(new ICallback() {
#Override
public void onResult(String result) {
try {
jsonArr=new JSONArray(result);
Toast.makeText(getApplicationContext(), jsonArr.toString(), Toast.LENGTH_LONG).show();
for (int i = 0; i < jsonArr.length(); i++) {
obj = jsonArr.getJSONObject(i);
name = obj.getString("name");
phno = obj.getString("phone");
dcount = obj.getString("count");
}
} catch (JSONException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
task.execute(new String[]{"URL"});
I have used an asyncTask to make an http request and hence i have used progress bar to indicate the progress of ongoings in that thread. Everything works fine till the onPostexecute() method is called, i have displayed the response string in the Logcat but my progress bar doesn't quit.
There was similar questions asked but i didn't get the required solution for the problem.
Please help.
Here is my code:
class RequestTask extends AsyncTask<String, Integer, String> {
#SuppressWarnings("static-access")
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
prgDialog=new ProgressDialog(getActivity());
prgDialog.setCancelable(true);
prgDialog.show(getActivity(), null, "Loading...");
}
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
// Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
// TODO Handle problems..
} catch (IOException e) {
// TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("result", result);
prgDialog.dismiss();
// Do anything with response..
}
}
You're not calling dismiss() on the ProgressDialog instance you think(or want)you do. You create a ProgressDialog and assign it to the prgDialog reference only to call:
prgDialog.show(getActivity(), null, "Loading...");
which will create a new instance of ProgressDialog which you don't dismiss because prgDialog points to another not showing ProgressDialog. Try:
protected void onPreExecute() {
super.onPreExecute();
prgDialog = ProgressDialog.show(getActivity(), null, "Loading...");
}
This is why you should call static methods on the class and not some instance of that class.
I have some errors when I read a web page content on the main thread
public class WebReader extends AsyncTask<String, String, String> {
private String result;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result;
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(params[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
System.out.println(params[0]);
try {
result = client.execute(request, responseHandler);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.result = result;
return result;
}
protected void onProgressUpdate(String... progress) {
}
#Override
protected void onPostExecute(String result) {
this.result = result;
}
public String getResult(){
return result;
}
}
And I use this in :
public static void testAsync(){
String result = null;
WebReader wr = new WebReader();
wr.execute("http://www.google.fr");
result = wr.getResult();
while(result==null){
try {
Thread.sleep(1000);
result = wr.getResult();
} catch (InterruptedException e) {
result = "";
}
}
System.out.println(result);
}
I don't realy find the soltion to return a String
Thanks
I think the problem is the line
this.result = result;
in
protected void onPostExecute(String result) {
because I don't see how onPostExecute gets passed the result parameter, so you are assigning NULL. I removed the line and it worked.
I am trying to hit a url through asynctask class and some times, url might not be reachable, in such cases application crashes, how do i prevent this from happening, I would like to display an error message/Toast on UI..I tried to implement runOnUiThread(), but was not successful.
This is my asynctask class: In this case I will be gettin IOException.
public class SelectedEmployeeAsyncTask extends AsyncTask<String, Void, ArrayList<Employee>>{
private CaptureActivity captureActivity;
public SelectedEmployeeAsyncTask(CaptureActivity activity) {
this.captureActivity = activity;
}
#Override
protected ArrayList<Employee> doInBackground(String... url) {
ArrayList<Employee> employees = null;
for(String employeeUrl : url){
employees = fetch(employeeUrl);
}
return employees;
}
private ArrayList<Employee> fetch(String url) {
ArrayList<Employee> employees = null;
String response = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
employees = EmployeeXMLParser.selectedEmployeeParser(response);
System.out.println("Size in fetch "+employees.size());
//System.out.println("Employee Name :: " + employees.get(0).getFirstName() + " " + employees.get(0).getLastName());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /*catch (XmlPullParserException e) {
// TODO Auto-generated catch block
System.out.println("Error parsing the response :: " + response);
e.printStackTrace();
}*/
return employees;
}
#Override
public void onPostExecute(ArrayList<Employee> employees){
super.onPostExecute(employees);
System.out.println("in post execxute "+employees.size());
//progressDialog.dismiss();
captureActivity.display(employees);
//activity.showEmployees(employees);
//activity.setContentView(R.layout.activity_capture);
}
}
This is my activity class, where asynctask would be called:
public class CaptureActivity extends Activity {
//private String url = "http://192.168.3.140:8080/EmployeeXmlDemo/EmployeeList.xml";
private String url = "http://192.168.2.223:8680/capture/clientRequest.do?r=employeeList&cid=0";
FetchEmployeeAsyncTask employeeAsyncTask;
private ArrayList<Employee> employees = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("");
//if(employees!=null){
employeeAsyncTask = new FetchEmployeeAsyncTask(this);
//selectedEmployeeAsyncTask = new SelectedEmployeeAsyncTask(this);
employeeAsyncTask.execute(url);
setContentView(R.layout.activity_capture);
System.out.println("Status "+employeeAsyncTask.getStatus());
//}
}
try this,
catch (final Exception e) {if (e != null) {
e.printStackTrace();
Temes.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
}
});
}