This code shows the exception when it reach the get sentence (line commented on the code).
The code is the next, consist on get a comments list from Http get Request:
public class ObtencionComentariosPerfil extends AsyncTask<String, Integer, List<Comment>>{
#Override
protected List<Comment> doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
URI url;
List<Comment> listaComentarios = new ArrayList<Comment>();
try {
url = new URI(params[1]);
HttpGet del = new HttpGet(url);
del.setHeader("content-type", "application/json");
del.setHeader("X-Auth-Token", params[0]);
System.out.println("El token params es: "+params[0]);
HttpResponse resp = httpClient.execute(del);// THE EXCEPTION shows here
StatusLine estatus = resp.getStatusLine();
if (estatus.getStatusCode() == 200) {
InputStream is = resp.getEntity().getContent();
CommentsParser parser= new CommentsParser();
listaComentarios = parser.parseoComentarios(is.toString());
} else {
System.out.println("Error");
listaComentarios = null;
}
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listaComentarios;
}
#Override
protected void onPostExecute(List<Comment> lista){
}
}
Here is called from main code:
public List<Comment> obtieneComentariosPerfil(long idUsuario, String aut){
List<Comment> listaComentarios = new ArrayList<Comment>();
String url= "http://"+ip+":8080/api/users/"+idUsuario+"/comments";
String[] params= new String[2];
params[0]=aut;
params[1]=url;
ObtencionComentariosPerfil du = new ObtencionComentariosPerfil();
listaComentarios = du.doInBackground(params);
return listaComentarios;
}
I think it have to be a stupid failure but i cant find the error. Thanks.
Because you call du.doInBackground(params);
you should call du.excute(params) instead
listaComentarios = du.doInBackground(params);
You submit async tasks for execution in a background thread by calling execute(), not by directly calling the doInBackground() callback in the current thread.
Communicate the result back to UI thread in onPostExecute().
Related
Unfortunately android application has been stopped. At Http Post while attempting to call server at post activity please help
HttpClient cli = new DefaultHttpClient();
//HttpPost post = new HttpPost("http://" + sp.getString("ip", "localhost") + "/attendance/cliLogin.php");
HttpPost post = new HttpPost("localhost/attendance/");
// seting post data
List<NameValuePair> loginData = new ArrayList<NameValuePair>(2);
loginData.add(new BasicNameValuePair("uname", uname));
loginData.add(new BasicNameValuePair("pass", pass));
post.setEntity(new UrlEncodedFormEntity(loginData));
// executing login
HttpResponse res = cli.execute(post);
HttpEntity resent = res.getEntity();
String result = EntityUtils.toString(resent);
// reading response
if(result.equals("NoParams"))
Commons.showToast("Something went wrong", true);
else if(result.equals("Login"))
{
navi = new Intent(this, HomeActivity.class);
startActivity(navi);
}
else
Commons.showToast(result, true);
}
catch (HttpHostConnectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Commons.showToast("Can't reach server, check the Hostname", true);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
Commons.showToast("Username/Password can't be empty", true);
}
}
Could you please share your logcat to see the error? I think that your are calling the php script in your main thread (that is your activity thread) and you may have NetworkOnMainThreadException
If that is the case:
Create a class that extends the AsyncTask.
Override its methods.
In the creator of this class pass the variables and assign them to the fields (variables) of your class.
Make your post in an AsyncTask inside the doInBackground method
And call the AsyncTask execute. Like this:
public class MyTask extends AsyncTask<String,String,String>{
private short errorType = -1;
private String result;
private String uname;
private String pass;
public MyTask(String uname, String pass){
this.uname = uname;
this.pass = pass;
}
#Override
protected String onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (errorType == 1){
Commons.showToast("Can't reach server, check the Hostname", true);
}
if(result.equals("NoParams")) {
Commons.showToast("Something went wrong", true); }
else if(result.equals("Login")) {
Intent navi = new Intent(this, HomeActivity.class); startActivity(navi);
}
else {
Commons.showToast(result, true);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try
{
HttpClient cli = new DefaultHttpClient();
HttpPost post = new HttpPost("localhost/attendance/");
List<NameValuePair> loginData = new ArrayList<NameValuePair>(2);
loginData.add(new BasicNameValuePair("uname", uname));
loginData.add(new BasicNameValuePair("pass", pass));
post.setEntity(new UrlEncodedFormEntity(loginData));
// executing login
HttpResponse res = cli.execute(post);
HttpEntity resent = res.getEntity();
return result = EntityUtils.toString(resent);
}
catch (HttpHostConnectException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
errorType = 1;
return null;
}
catch (ParseException e) {
// TODO Auto-generated catch block e.printStackTrace();
errorType = 2;
return null;
}
catch (IOException e) {
// TODO Auto-generated catch block e.printStackTrace();
errorType = 3;
return null;
}
catch(Exception e){
errorType = 4;
return null;
}
}
}
And inside the activity make your call like this:
MyTask new MyTask(uname, pass).execute();
Again. All this is applicable only if you have
NetworkOnMainThreadException
Please share your logcat for further help.
I have a method that need to update its status periodically to the server.
I am using AsyncTask to run the HTTP call in background.
PROBLEM: In onPostExecute method upon checking AsyncTask.getStatus, It show the previous task still running which is causing the error.
ERROR: java.lang.IllegalStateException: Cannot execute task: the task is already running.
DIFFERENT STRATEGIES USED TO SOLVE THE PROBLEM BUT NONE IS WORKING
1. Before Relaunching AsyncTask, checked the status, it is showing the thread is RUNNING.
2. Called the AsyncTask.cancel(true), immediately before calling the AsyncTask.execute if it is still running. It turns out AsyncTask still RUNNING and taking more than 3 mins to get cancel.
NOTE: I have checked many similar questions here, but haven't found helpful.
I would really appredicae if any one of you guys give me an example to solve this issue, Thanks a Million in advance......
public class MainActivity extends Activity implements AsyncResponse{
ConnectServer asyncTask =new ConnectServer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
asyncTask.delegate = this;
setContentView(R.layout.activity_main);
//Start updating server using below method
loop();
}
public void processFinish(String output){
//this you will received result fired from async class of onPostExecute(result) method.
//Log.v(TAG, output);
if(output != null){
//not using this at this point
}
}
//Method that will call Async method to reach server
public void loop(){
TextView b = (TextView) findViewById(R.id.mField);
String str;
try {
str = asyncTask.execute(true).get();
b.setText(str);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// START SERVER CONNECTION
class ConnectServer extends AsyncTask<Boolean, String, String> {
public AsyncResponse delegate=null;
public int i = 0;
private Activity activity;
public void MyAsyncTask(Activity activity) {
this.activity = activity;
}
#Override
protected String doInBackground(Boolean... params) {
String result = null;
StringBuilder sb = new StringBuilder();
try {
// http post
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://192.168.0.21:8080");
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("GPSApp", "Server encountered an error");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF8"));
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result) {
TextView mField = (TextView) findViewById(R.id.mField);
mField.setText(result+i);
try {
Thread.sleep(10000);
//asyncTask =new ConnectServer();
i++;
String str = asyncTask.execute(true).get();
mField.setText(str+i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void onPreExecute() {}
}
}
Call getStatus() to get the status of AsyncTask. If the status is AsyncTask.Status.RUNNING, cancel it.
I am trying to get an HttpResponse in xml but Im not getting the whole response, what is courious is that if I loop the request the response ends in different parts but is never full.
I use the same code to request things from different Urls but I only get problems with one.
Here is the code of the AsyncTask:
public class NetworkTask extends AsyncTask<String, Void, HttpResponse> {
private AsyncTaskListener listener;
#Override
protected HttpResponse doInBackground(String... params) {
String link = params[0];
HttpGet request = new HttpGet(link);
AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
try {
HttpResponse httpResponse = client.execute(request).;
return httpResponse;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
client.close();
}
}
#Override
protected void onPostExecute(HttpResponse result) {
if (result != null){
try {
String sRes = EntityUtils.toString(result.getEntity());
listener.onNTCompleted(sRes);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public NetworkTask(AsyncTaskListener listener){
this.listener=listener;
}
}
I am not sure if this helps you but you have a problem because EntityUtils.toString() reads data from the network stream, which should not be done on UI thread (onPostExecute). Try moving EntityUtils.toString() to doInBackground() first. This may not help solve your problem, but it is the right thing to do.
Here is the class where i get JSON objects. In this code I get only one object and I don't really know how to return from the method, there is a Protected Void method where it is a settext method called and there is where the only JSON object goes.
public class ConnectMySql extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://79.114.48.119/RadarsMySql.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
httpStuff = (TextView) findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
new Read().execute("latitude");
}
public JSONObject lastTweet(String username) throws ClientProtocolException, IOException,JSONException{
StringBuilder url = new StringBuilder(URL);
url.append(username);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
//if(status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
data = data.substring(data.indexOf("["));
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
//}else{
//Toast.makeText(ConnectMySql.this, "error", Toast.LENGTH_LONG);
//return null;
//}
}
public class Read extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet("");
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(String result) {
// TODO Auto-generated method stub
httpStuff.setText(result);
int myNum = 0;
try {
myNum = Integer.parseInt(result);
httpStuff.setText(myNum);
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
}
}
}
What I want to do is to have an array where i could store three kind of objects (exemple Latitude[1], Longitude [1], Description[1]; Latitude[2] etc... I would like the latitude and longitude to be as integers ). After this I will use a for loop to call a function with this 3 parameters. Could anyone help me or could give me some tips ?
Thank you!
Dont use AsyncTask, as it executes in background, and this is why it causes some problems for you.
And when you have your twitter arser working, integrate it in a AsyncTask. Code below is not tested.
public class ConnectMySql extends Activity {
TextView httpStuff;
HttpClient client;
int i;
JSONObject json;
final static String URL = "http://localhost/RadarsMySql.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
httpStuff = (TextView) findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
for(i=0;i<2;i++){
new Read().execute("latitude");
try {
json = lastTweet("",i);
String result = json.getString(params[i]);
httpStuff.setText(result);
int myNum = 0;
try {
myNum = Integer.parseInt(result);
httpStuff.setText(myNum);
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public JSONObject lastTweet(String username,int i) throws ClientProtocolException, IOException,JSONException{
StringBuilder url = new StringBuilder(URL);
url.append(username);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
//if(status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
data = data.substring(data.indexOf("["));
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(i);
return last;
//}else{
//Toast.makeText(ConnectMySql.this, "error", Toast.LENGTH_LONG);
//return null;
//}
}
}
I'm trying to use HttpClient to connect to a php page that logs in and passes back a sessionid and then goes to a new page, using that sessionid and obtains a mySQL datafield associated with that sessionid.
On the first request, HttpClient can take 1.5 seconds, 6 seconds, or 2 minutes. If the first request was slow, subsequence requests seem to be faster, and visaversa.
The HttpClient request occurs when a Button view is clicked
Here's my code:
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
name = (TextView)findViewById(R.id.name);
user = (EditText) findViewById(R.id.user);
pass = (EditText) findViewById(R.id.pass);
submit = (Button) findViewById(R.id.button1);
submit.setOnClickListener(this);
HttpParams params1 = new BasicHttpParams();
params1.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
client = new DefaultHttpClient(params1);
httpclient = new DefaultHttpClient();
// Create a local instance of cookie store
cookieStore = new BasicCookieStore();
// Create local HTTP context
}
public void onClick(View v) {
if (v.getId() == R.id.button1) {
//submit.setClickable(false);
String username = user.getText().toString();
String password = pass.getText().toString();
String targetURL = "<<<<LOGIN PHP URL>>>>";
post = new HttpPost(targetURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("params","params added");
try {
post.setEntity(new UrlEncodedFormEntity(params));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d("entity added","entityadded");
Log.d("preex","PRE EXECUTION");
localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//submit.setText("Logging In...");
new Thread(new Runnable(){
public void run(){
try {
Log.d("pre","pre execute");
response = client.execute(post,localContext);
Log.d("post","post execute");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Log.d("post","FIANLLY");
try {
input = response.getEntity().getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("response: ",convertStreamToString(input));
getFullName(localContext);
}
}
}).start();}
}
private void getFullName(final HttpContext context){
Log.d("called","called");
String targetURL = "<<<<SESSION CHECKER PHP URL>>>>";
//client1 = new DefaultHttpClient();
post1 = new HttpPost(targetURL);
Log.d("","about to call runable....");
// submit.setText("Obtaining Full Name...");
try {
Log.d("pre","CALLING!");
response = client.execute(post1,context);
Log.d("post","called..");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Log.d("post","FIANLLY");
try {
//submit.setText("Full Name Obtained!...");
input = response.getEntity().getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Log.d("response: ",convertStreamToString(input));
outputResponse(input);
}
}
private void outputResponse(final InputStream in) {
name.post(new Runnable(){
public void run(){
String fullname=convertStreamToString(in);
name.setText("Full Name is: "+fullname);
}
});
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Before I set Http version 1.1 it took double the time, but for my application, the speed cannot be unreliable. This is all on a pretty fast WiFi connections -- can you image Edge or 3G speeds??
So what can I optimize?
Thanks everyone:)
EDIT: I did a new test with: http://www.posttestserver.com/ and it happened pretty fast. The urls I'm using currently aren't my final server urls, they are for a different site on a different server -- shared hosting, so could it be that contacting my shared hosting site is just slow and will be compared to my .net server?
Thanks again !