getting FATAL EXCEPTION in MAIN when doing a callback,asyntask android - android

After reading over android asynctask sending callbacks to ui My goal is :
dialog box will show when you are waiting for the authentication from
the server and as long as the process is done, a call back will be
invoked and dialog box will be dismissed.
My structure is ( asyntask and log in activity are separated classes )
Log in activity
Class A extends Aysnctask
A call back interface.
Partial of my codes :
public class SpalshScreenActivity extends Activity implements LogInCallBack{
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
logInButton = (Button) findViewById(R.id.btnLogin);
logInButton.setBackgroundDrawable(getResources() .getDrawable(R.drawable.button));
logInButton .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog = new ProgressDialog(SpalshScreenActivity.this);
dialog.setMessage("waiting......");
dialog.show();
Service client = new Service(new SpalshScreenActivity(), email.getText().toString(), password.getText().toString());
String logInURL = "my url goes here";
client.execute(logInURL);
}
});
}
}
#Override
public void successfullyLogIn() {
Log.d("SPLASH","successfullyLogIn");
dialog.dismiss(); // **<--------crash is at here**
}
#Override
public void failedToLogIn() {
}
}
Service.java :
public class Service extends AsyncTask<String, Integer, String> {
private LogInCallBack callBack;
String userName;
String password;
public Service(LogInCallBack callBack, String userName, String password) {
this.callBack = callBack;
this.userName = userName;
this.password = password;
}
// Handling ssl connection
protected String doInBackground(String... arg) {
// validation and accept all type of self signed certificates
SimpleSSLSocketFactory simpleSSLFactory;
String logInURL = arg[0];
try {
simpleSSLFactory = new SimpleSSLSocketFactory(null);
simpleSSLFactory .setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
// Enable HTTP parameters
params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
// Register the HTTP and HTTPS Protocols. For HTTPS, register our
// custom SSL Factory object.
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory .getSocketFactory(), 80));
registry.register(new Scheme("https", simpleSSLFactory, 443));
// Create a new connection manager using the newly created registry
// and then create a new HTTP client
// using this connection manager
ccm = new ThreadSafeClientConnManager(params, registry);
} catch (KeyManagementException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (UnrecoverableKeyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (KeyStoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// TODO Auto-generated method stub
HttpClient client = new DefaultHttpClient(ccm, params);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("user_session[email]", "lenanguyen#hotmail.ca"));
nameValuePair.add(new BasicNameValuePair("user_session[password]","2congato"));
// Create http GET method
HttpPost logIn = new HttpPost(logInURL);
try {
logIn.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Fire a request
try {
HttpResponse response = client.execute(logIn);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
this.result = convertStreamToString(is);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("ClientProtocolException is ", e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("IOException is ", e.toString());
}
return result;
}
// called after doInBackground finishes
protected void onPostExecute(String result) {
Log.e("result, yay!", this.result);
this.callBack.successfullyLogIn();
}
}
and my call back interface is
public interface LogInCallBack {
void successfullyLogIn ();
void failedToLogIn();
}
However after the dialog shows up for a few seconds, my app is crashing and FATAL Exception in MAIN is thrown in the cat log. Any ideas about this guys.
PS :
log cat i here

Change
Service client = new Service(new SpalshScreenActivity(), email.getText().toString(), password.getText().toString());
into
Service client = new Service(SpalshScreenActivity.this, email.getText().toString(), password.getText().toString());
and
public FlipGiveClient(LogInCallBack callBack, String userName, String password) {
this.callBack = callBack;
this.userName = userName;
this.password = password;
}
into
public FlipGiveClient(Activity activity, String userName, String password) {
this.callBack = (LogInCallBack) activity;
this.userName = userName;
this.password = password;
}

Related

unfortunately android application has been stopped. At Http Post while attempting to call server

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.

Android NetworkOnMainThreadException inside Asyntask class

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().

Android Strict Mode

I have written a simple code on JSON Parsing using AsyncTask. I'm just displaying the response in TextView. I don't know whether it is right or wrong. Its working on GingerBread and showing NetworkOnMainThreadException on JellyBean. If I use StrictMode, its working on JellyBean and getting force close on GingerBread. How to write the code which support above Android 3.0 and below Android 3.0.
public class MainActivity extends Activity {
TextView tv;
Button b;
InputStream is = null;
DefaultHttpClient client;
HttpGet get;
HttpResponse response;
HttpEntity entity;
StringBuffer buffer;
#SuppressLint("NewApi")
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
// StrictMode.setThreadPolicy(policy);
tv = (TextView) findViewById(R.id.texty);
b = (Button) findViewById(R.id.buttonGET);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyOperation mytask = new MyOperation();
mytask.execute();
}
});
}
private class MyOperation extends AsyncTask<String, Void, String> {
ProgressDialog dialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.setMessage("Loading...");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
client = new DefaultHttpClient();
get = new HttpGet("http://www.google.com");
try {
response = client.execute(get);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
entity = response.getEntity();
try {
is = entity.getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = null;
do {
try {
line = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buffer.append(line);
} while (line != null);
tv.setText(buffer);
}
}
}
public class MainActivity extends Activity {
TextView tv;
Button b;
InputStream is = null;
DefaultHttpClient client;
HttpGet get;
HttpResponse response;
HttpEntity entity;
StringBuffer buffer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//StrictMode.ThreadPolicy policy = new
// StrictMode.setThreadPolicy(policy);
tv = (TextView) findViewById(R.id.texty);
b = (Button) findViewById(R.id.buttonGET);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyOperation mytask = new MyOperation();
mytask.execute();
}
});
}
private class MyOperation extends AsyncTask<String, Void, String> {
ProgressDialog dialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.setMessage("Loading...");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
StringBuffer buffer = new StringBuffer();
// TODO Auto-generated method stub
client = new DefaultHttpClient();
get = new HttpGet("http://www.google.com");
try {
response = client.execute(get);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
entity = response.getEntity();
try {
is = entity.getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
String line = null;
do {
try {
line = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buffer.append(line);
} while (line != null);
return buffer.tostring();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
tv.setText(result);
}}
}
otherwise you are running the read line operation in main thread
Make the InputStream is and Entity entity local field variables in the doInBackground() as return as result the string that you wanna set on the TextView...and on the onPostExecute() you just get the result (the string) and set it in the TextView straight on.
You should read inputStream data in doInBackground function, not in the onPostExecute. So construct StringBuffer in doInBackground append all lines to it and return StringBuffer.toString as result. In onPostExecute you will get what string as parameter.

Android app stopped working - servlets and Httpget

I have a problem. I am starting my adventure with servlets and Android and I designed a simple servlet which writes "Hello world". Now I want to receive this message in my Android app. My code:
public class MyServlet extends Activity implements OnClickListener{
Button button;
TextView outputText;
public static final String URL = "http://10.0.2.2:8080/ServletExample/HelloServletExample";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsById();
button.setOnClickListener(this);
}
private void findViewsById() {
button = (Button) findViewById(R.id.button);
outputText = (TextView) findViewById(R.id.outputTxt);
}
public void onClick(View view) {
String output = null;
HttpClient httpclient = new DefaultHttpClient();
try {
HttpResponse response = httpclient.execute(new HttpGet(URL));
HttpEntity httpEntity = response.getEntity();
output = EntityUtils.toString(httpEntity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
//} catch (IOException e) {
// TODO Auto-generated catch block
//}
outputText.setText(output);
}
My servlet:
#WebServlet("/HelloServletExample")
public class HelloServletExample extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HelloServletExample() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
I don't know why but my app crashes. I tried commenting out some lines and it turns out that what is the problem is this line:
HttpEntity httpEntity = response.getEntity();
Why?
if you are using API level >= 9 then no need to use AsyncTask for making network request from Ui Thread just add StrictMode.ThreadPolicy in Activity onCreate method as:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().
permitAll().build();
StrictMode.setThreadPolicy(policy);

Android - HttpClient execute has a mind of its own - 1 second or 200 seconds

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 !

Categories

Resources