NetworkOnMainThreadException - android

Trying to read and parse some json data in my app. I implemented Parser class extending AsyncTask as follows:
public class JSONParser extends AsyncTask<Void, Void, String> {
private String strUrl;
private List<NameValuePair> params;
private String result;
private String response;
public static final String RESULT_SUCCESS = "success";
public static final String RESULT_FAILED = "failed";
public JSONParser(String strUrl, List<NameValuePair> params) {
this.strUrl = strUrl;
this.params = params;
}
private void parse() {
try {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(strUrl);
// Add parameters
if (params != null) {
httppost.setEntity(new UrlEncodedFormEntity(params));
}
// Execute HTTP Post Request
HttpResponse httpResponse = httpclient.execute(httppost);
// return by response
result = RESULT_SUCCESS;
this.response = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (Exception e) {
result = RESULT_FAILED;
this.response = null;
e.printStackTrace();
}
}
#Override
public String doInBackground(Void... params) {
parse();
return response;
}
public String getResult() {
return result;
}
public String getResponse() {
return response;
}
}
It works well in later android versions, but unfortunately it throws NetworkOnMainThreadException in older versions.
I've searched and found that I should use Strict mode in my app, but performance of threads became very bad! when I click parse button it freezes!
can you help me with more better solution?

Call you class like this, it will solve your issue !!
new JSONParser().execute();

Related

HTTP Request POST JSON Object in Body

Hey guys I'm struggeling with HTTP Requests in Java/Android. I want to create a new Github issue. So I've looked it up, and almost everybody did it the same way, but I have the problem that AndroidStudio tells me, that all the classes (HttpClient, HttpPost, ResponseHandler) doesn't exist, did I something wrong or why I don't have them?
private class GithubPostIssues extends AsyncTask<String, Void, String> {
private View view;
public GithubPostIssues(View view) {
this.view = view;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(FeedbackActivity.this, "Feedback/Hilfe gesendet", Toast.LENGTH_SHORT).show();
finish();
}
#Override
protected String doInBackground(String... params) {
return addIssue(view);
}
private String addIssue(View view) {
//here I'm getting some values from the user input and pass them in to the execute method
return execute(title, body, bug, help, question, feature, enhancement, design);
}
private String execute (String title, String body, boolean bug,
boolean help, boolean question, boolean feature,
boolean enhancement, boolean design) {
//Building the JSONOBject to pass in to the Request Body
JSONObject issue = new JSONObject();
JSONArray labels = new JSONArray();
try {
issue.put("title", title);
issue.put("body", body);
labels.put("0 - Backlog");
if (bug) {
labels.put("bug");
}
if (help) {
labels.put("help");
}
if (question) {
labels.put("question");
}
if (feature) {
labels.put("feature");
}
if (enhancement) {
labels.put("enhancement");
}
if (design) {
labels.put("design");
}
issue.put("labels", labels);
return makeRequest("http://requestb.in/uwwzlwuw", issue);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private String makeRequest (String uri, JSONObject issue) {
//all these clases aren't found by Android Studio
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(issue));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
return httpClient.execute(httpPost, responseHandler);
}
}
Try adding this inside gradle:
android {
useLibrary 'org.apache.http.legacy'

How to Retrieve two or more json from multiple Url in MainActivity class Android

I've made a GetJSONTask class which extend AsynkTaskClass. In the onPostExecute method I get the result if I pass single URL in onCreate. like
newCustomAsync().execute("http://abcd.com/fetch/Service1.svc/GetStates?"+
"CCode=" +country+ "");
I want to call multiple URL and retrieve multiple JSON in different variables.
private class CustomAsync extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... URL) {
HttpClient Client = new DefaultHttpClient();
try{
String SetServerString = "";
HttpGet httpget = new HttpGet(URL[0]);
ResponseHandler<String> responseHandler =
new BasicResponseHandler();
SetServerString = Client.execute(httpget, responseHandler);
JSONArray myListsAll= new JSONArray(SetServerString);
for(int i=0;i<myListsAll.length();i++){
JSONObject jsonobject= (JSONObject) myListsAll.get(i);
String states = jsonobject.optString("states");
}
return SetServerString;
}catch(Exception e){}
return null;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
JSONArray myListsAll = null;
try {
myListsAll = new JSONArray(result);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jsonobject= null;
try {
jsonobject = (JSONObject) myListsAll.get(0);
} catch (JSONException e) {
e.printStackTrace();
}
String msg =jsonobject.optString("states");
}
}
call all the url's in your doInbackground() and get the result. For passing multiple results to your onPostExecute(), use a wrapper class, you've to pass the object of the wrapper class.
public class CustomAsync extends AsyncTask<String, Integer, Wrapper> {
#Override
protected Wrapper doInBackground(String... params) {
String url1 = params[0];
String url2 = params[1]
Wrapper wrapper = new Wrapper();
wrapper.result1 = Get(url1);
wrapper.result2 = Get(url2);
return wrapper;
}
#Override
protected void onPostExecute(Wrapper wrapper) {
String result1 = wrapper.result1;
String result2 = wrapper.result2;
// Do your operation
}
public class Wrapper {
public String result1;
public String result2;
}
}
define Get() as separate function. Code is more clean that way
public static synchronized String Get(String url){
HttpClient Client = new DefaultHttpClient();
try{
String SetServerString = "";
HttpGet httpget = new HttpGet(url);
ResponseHandler<String> responseHandler =
new BasicResponseHandler();
SetServerString = Client.execute(httpget, responseHandler);
JSONArray myListsAll= new JSONArray(SetServerString);
for(int i=0;i<myListsAll.length();i++){
JSONObject jsonobject= (JSONObject) myListsAll.get(i);
String states = jsonobject.optString("states");
}
return SetServerString;
}catch(Exception e){}
return null;
}

Nullpoint exception even after getting data from json response

I'm trying to get data by calling webservices, for that I'm using a Async task class. As I have shon in the screen shot I'm getting json response successfully. But it crashes in listener.onTaskCompletedObject(responseJson); inside the onPostExecute().
Can anyone spot the reason wht this is not working for me.
Activity.java
new AddressAsyncTask(getBaseContext(), new OnTaskCompletedObject() {
#Override
public void onTaskCompletedObject(JSONObject responseJson) {
Constants.dataAddress = responseJson.toString();
loaddata();
}
}).execute(email);
OnTaskCompletedObject.java
public interface OnTaskCompletedObject {
void onTaskCompletedObject(JSONObject responseJson);
}
AddressAsyncTask.java
public class AddressAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private OnTaskCompletedObject listener;
private JSONObject responseJson = null;
private Context contxt;
private Activity activity;
String email;
public AddressAsyncTask(Context context, OnTaskCompletedObject onTaskCompletedObject) {
this.contxt = context;
}
// async task to accept string array from context array
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the email and password
Log.i("Email", params[0]);
try {
path = "http://xxxxxxxxxxxxxxxxx/MemberDetails";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("Email"), params[0]);
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
listener.onTaskCompletedObject(responseJson);
}
}
Screenshot of the exception
Screenshot of the jsonresponse
NullPointerException exception even after getting data from json
response
Because listener is null.
Initialize listener as :
public AddressAsyncTask(Context context, OnTaskCompletedObject listener) {
this.contxt = context;
this.listener=objListener;
}
Try changing
listener.onTaskCompletedObject(responseJson);
to
listener.onTaskCompletedObject(result);
You have forgotten to initialize your listener in the asyn task constructor.
You have forgotten to initialize your listener in AddressAsyncTask constructor.
public AddressAsyncTask(Context context, OnTaskCompletedObject onTaskCompletedObject) {
this.contxt = context;
this.listener=onTaskCompletedObject;
}

Android: how to use webservices with AsyncTasks

This is my first post on this site, i have a problem with my app, i can't find the reason which my app stops. I am sending a request to Despegar to get a json of the countries but happens these. I would be very greatfull if you could help me. Here is my code:
public class MainActivity extends Activity {
final TextView txtResultado = (TextView) findViewById(R.id.txtResultado);
String JSONRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new TareaConexion().execute("http://api.despegar.com/countries");
}
class TareaConexion extends AsyncTask<String, Void, String>{
protected void onPreExecute() {
}
protected String doInBackground(String... urls) {
httpHandler httphandler = new httpHandler();
JSONRequest = httphandler.Post(urls[0]);
return JSONRequest;
}
protected void onProgressUpdate () {
}
protected void onPostExecute() {
txtResultado.setText(JSONRequest);
}
}
and the class httpHandler:
public class httpHandler {
public String Post (String PostURL)
{
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(PostURL);
HttpResponse resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();
String Respuesta = EntityUtils.toString(ent);
return Respuesta;
} catch (Exception e) {
return "error";
}
}
}
can anybody find the reason which do my app stops? what am i doing wrong?
i'm argentinian so excuse me if i make a mistake with the lenguage, ajja. Thanks
Try this code
MyAsyncTask extends AsyncTask<String, Void, HttpResponse>
{
#Override
protected HttpResponse doInBackground(String... param)
{
String url = param[0];
HttpResponse response = null;
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter("http.connection-manager.timeout", 15000);
try {
if (type == Constants.TYPE_POST)
{
HttpPost httppost = new HttpPost(url);
response = httpclient.execute(httppost);
}
else if (type == Constants.TYPE_DELETE)
{
HttpDelete httpdelete = new HttpDelete(url);
response = httpclient.execute(httpdelete);
}
else
{
HttpGet httppost = new HttpGet(url);
response = httpclient.execute(httppost);
}
} catch (ClientProtocolException es)
{
Log.e("x" , es.getMessage());
} catch (IOException e)
{
Log.e("aasx" , e.getMessage());
}
return response;
}
#Override
protected void onPostExecute(HttpResponse response)
{
if (response != null)
{
JSONObject obj = new JSONObject(Utilities.convertStreamToString(response.getEntity().getContent()));
//Whatever you want to do
}
}
}

android http post asynctask

Please can anyone tell me how to make an http post to work in the background with AsyncTask and how to pass the parameters to the AsyncTask? All the examples that I found were not clear enough for me and they were about downloading a file.
I'm running this code in my main activity and my problem is when the code sends the info to the server the app slows down as if it is frozen for 2 to 3 sec's then it continues to work fine until the next send. This http post sends four variables to the server (book, libadd, and time) the fourth is fixed (name)
Thanks in advance
public void SticketFunction(double book, double libadd, long time){
Log.v("log_tag", "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SticketFunction()");
//HttpClient
HttpClient nnSticket = new DefaultHttpClient();
//Response handler
ResponseHandler<String> res = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("http://www.books-something.com");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("book", book+""));
nameValuePairs.add(new BasicNameValuePair("libAss", libass+""));
nameValuePairs.add(new BasicNameValuePair("Time", time+""));
nameValuePairs.add(new BasicNameValuePair("name", "jack"));
//Encode and set entity
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
//Execute
//manSticket.execute(postMethod);
String response =Sticket.execute(postMethod, res).replaceAll("<(.|\n)*?>","");
if (response.equals("Done")){
//Log.v("log_tag", "!!!!!!!!!!!!!!!!!! SticketFunction got a DONE!");
}
else Log.v("log_tag", "!!!!!!!?????????? SticketFunction Bad or no response: " + response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
//Log.v("log_tag", "???????????????????? SticketFunction Client Exception");
} catch (IOException e) {
// TODO Auto-generated catch block
//Log.v("log_tag", "???????????????????? IO Exception");
}
}
}
At first,
You put a class like following:
public class AsyncHttpPost extends AsyncTask<String, String, String> {
interface Listener {
void onResult(String result);
}
private Listener mListener;
private HashMap<String, String> mData = null;// post data
/**
* constructor
*/
public AsyncHttpPost(HashMap<String, String> data) {
mData = data;
}
public void setListener(Listener listener) {
mListener = listener;
}
/**
* background
*/
#Override
protected String doInBackground(String... params) {
byte[] result = null;
String str = "";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);// in this case, params[0] is URL
try {
// set up post data
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
Iterator<String> it = mData.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
result = EntityUtils.toByteArray(response.getEntity());
str = new String(result, "UTF-8");
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (Exception e) {
}
return str;
}
/**
* on getting result
*/
#Override
protected void onPostExecute(String result) {
// something...
if (mListener != null) {
mListener.onResult(result)
}
}
}
Now.
You just write some lines like following:
HashMap<String, String> data = new HashMap<String, String>();
data.put("key1", "value1");
data.put("key2", "value2");
AsyncHttpPost asyncHttpPost = new AsyncHttpPost(data);
asyncHttpPost.setListener(new AsyncHttpPost.Listener(){
#Override
public void onResult(String result) {
// do something, using return value from network
}
});
asyncHttpPost.execute("http://example.com");
First i would not recommend do a Http request in a AsyncTask, you better try a Service instead. Going back to the issue on how to pass parameter into an AsyncTask when you declared it you can defined each Object class of the AsyncTask like this.
public AsyncTask <Params,Progress,Result> {
}
so in your task you should go like this
public MyTask extends<String,Void,Void>{
public Void doInBackground(String... params){//those Params are String because it's declared like that
}
}
To use it, it's quite simple
new MyTask().execute("param1","param2","param3")

Categories

Resources