0

I'm trying to add getByName to get the IP address of a hostname and use it in my POST command the problem is wherever i insert this code it crashes i tried to insert in doInBackground it also crashes So where should i insert it ??

package com.example.loginad;



import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;







import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Logindb extends Activity {
Button login;
EditText u,p;
TextView res;
String result;
String x="mobile";
String host;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.logindb);

        login=(Button)findViewById(R.id.login);
        u=(EditText)findViewById(R.id.u);
        p=(EditText)findViewById(R.id.p);
        res=(TextView)findViewById(R.id.res);
        login.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                new MyAsyncTask().execute(u.getText().toString(),p.getText().toString());


            }
        });



    }
    private class MyAsyncTask extends AsyncTask<String, Integer, Boolean>{

        @Override
        protected Boolean doInBackground(String... params) {
            // TODO Auto-generated method stub
            boolean success = postData(params[0],params[1]);
             try
          {
                 InetAddress address=null;
           address = InetAddress.getByName("Nicky-PC");
                host=address.getHostAddress();
          }
          catch(Exception e)
          {
             e.printStackTrace();
          } 
            return success;
        }

        protected void onPostExecute(Boolean localres){

             if (localres){
                    res.setText("A Correct Username and Password");
                }else{
                    res.setText("Incorrect Username or Password");
                }
                Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
        }
        protected void onProgressUpdate(Integer... progress){
            //pb.setProgress(progress[0]);
            //Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_LONG).show();

        }
        /*public void ObtainHost()
        {
            try
            {

            }
            catch(Exception e)
            {
                Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
            }

        } */

        public Boolean postData(String a,String b) {
              ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
              postParameters.add(new BasicNameValuePair("username", a));
              postParameters.add(new BasicNameValuePair("password", b));
              postParameters.add(new BasicNameValuePair("mobileid",x));
              // String valid = "1";
              String response = null;
              try {                 


                //  Toast.makeText(getApplicationContext(), host.toString(), Toast.LENGTH_LONG).show();
                 response = CustomHttpClient.executeHttpPost("http://"+host+"/new/check.php",postParameters);
//now in result you will have the response from php file either 0 or 1.                        
   result = response.toString();
                  // res = res.trim();
                  result = result.replaceAll("\\s+", "");
                  // error.setText(res);

              } catch (Exception e) {
                  res.setText(e.toString());
              }

           return result.equals("1");

        }



    }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.logindb, menu);
        return true;
    }

}

Stacktrace

11-26 21:28:37.856: D/libEGL(17150): loaded /system/lib/egl/libEGL_genymotion.so
11-26 21:28:37.876: D/(17150): HostConnection::get() New Host Connection established 0xb8ed35a8, tid 17150
11-26 21:28:37.900: D/libEGL(17150): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
11-26 21:28:37.900: D/libEGL(17150): loaded /system/lib/egl/libGLESv2_genymotion.so
11-26 21:28:37.968: W/EGL_genymotion(17150): eglSurfaceAttrib not implemented
11-26 21:28:37.976: E/OpenGLRenderer(17150): Getting MAX_TEXTURE_SIZE from GradienCache
11-26 21:28:37.996: E/OpenGLRenderer(17150): Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
11-26 21:28:37.996: D/OpenGLRenderer(17150): Enabling debug mode 0
11-26 21:28:44.876: W/dalvikvm(17150): threadid=13: thread exiting with uncaught exception (group=0xa4c1f648)
11-26 21:28:44.920: E/AndroidRuntime(17150): FATAL EXCEPTION: AsyncTask #3
11-26 21:28:44.920: E/AndroidRuntime(17150): java.lang.RuntimeException: An error occured while executing doInBackground()
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at java.lang.Thread.run(Thread.java:841)
11-26 21:28:44.920: E/AndroidRuntime(17150): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:5908)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:837)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:358)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.widget.TextView.checkForRelayout(TextView.java:6524)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.widget.TextView.setText(TextView.java:3771)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.widget.TextView.setText(TextView.java:3629)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.widget.TextView.setText(TextView.java:3604)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at com.example.loginad.Logindb$MyAsyncTask.postData(Logindb.java:130)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at com.example.loginad.Logindb$MyAsyncTask.doInBackground(Logindb.java:70)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at com.example.loginad.Logindb$MyAsyncTask.doInBackground(Logindb.java:1)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-26 21:28:44.920: E/AndroidRuntime(17150):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-26 21:28:44.920: E/AndroidRuntime(17150):    ... 4 more
11-26 21:28:44.932: D/dalvikvm(17150): GC_FOR_ALLOC freed 259K, 5% free 6365K/6660K, paused 8ms, total 8ms
11
  • Where it doesn't crash. Sorry, couldn't resist. Please post the stack trace. NetworkOnMainThreadException? Commented Nov 26, 2013 at 21:12
  • it crashes when you insert the code above the full code that gets the hostname ,the stacktrace how to post it just give me a link that show me the steps Commented Nov 26, 2013 at 21:14
  • No it doesn't. Stack trace or no-one can help. Commented Nov 26, 2013 at 21:15
  • just tell me where to insert it that's what i'm looking for thanks by the way Commented Nov 26, 2013 at 21:20
  • 1
    Good now check my code after inserting and also the stacktrace. You're lucky with such rudeness that I still felt kind enough to help you. Commented Nov 26, 2013 at 21:44

1 Answer 1

1

First if you will use AsyncHttpClient then you do not need AsyncTask but if you will use HttpClient then you need AsyncTask task. the below code is part from working code to execute get and post requests. Modify it as your need

    @Override
protected String doInBackground(String... params) {
    backGroundExecuted = false;
    Log.d("doInBackground", "Start processing doInBackground");     

    HttpClient httpClient = null;
    HttpPost httpPost = null;
    HttpGet httpGet = null;


     if (httpMethodType == null || url == null) {
         Log.d("doInBackground" , "The URL and Method Type is mandatory, cannot be null - httpMethodType =" + httpMethodType + " and url =" + url);
         this.getApiResponse().setSuccess(false);
         this.getApiResponse().setResponseCode(HttpResponseCode.BAD_REQUEST);
         this.getApiResponse().setResponseDescription("The URL and Method Type is mandatory, cannot be null");
         return null;
     }

    try {

         //set timeout
         HttpParams httpParameters = new BasicHttpParams();
         HttpConnectionParams.setConnectionTimeout(httpParameters, TIME_OUT);
         HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIME_OUT);

         httpClient = new DefaultHttpClient(httpParameters);
         HttpResponse httpResponse = null;

        if (httpMethodType.equals(HTTPMethodType.POST.toString())) {
            httpPost = new HttpPost(url);
            //setting json object to request.
            if (postParams != null) {
                AbstractHttpEntity entity = null;
                entity = new ByteArrayEntity(postParams.getBytes("UTF8"));
                if (httpContentType != null) {
                    entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, httpContentType));
                }
                httpPost.setEntity(entity);
            }
            httpResponse = httpClient.execute(httpPost);

        } else  if (httpMethodType.equals(HTTPMethodType.GET.toString()) || httpMethodType.equals(HTTPMethodType.PUT.toString())) {
            if (queryParams != null) {
                url = url + "?" + URLEncodedUtils.format(queryParams, "utf-8");
                Log.d(TAG ,"new URL :" + url);
            }
            httpGet = new HttpGet(url);
            httpResponse = httpClient.execute(httpGet); 
        }

        this.getApiResponse().setResponseCode(httpResponse.getStatusLine().getStatusCode());
        this.getApiResponse().setResponseDescription(httpResponse.getStatusLine().getReasonPhrase());
         if (this.getApiResponse().getResponseCode() != HttpStatus.SC_OK) { 
             this.getApiResponse().setSuccess(false);
             Log.w(getClass().getSimpleName(), 
                 "Error " + this.getApiResponse().getResponseCode() + " for URL " + url); 
             Log.w(getClass().getSimpleName(), 
                     "Error " +  this.getApiResponse().getResponseDescription() + " for URL " + url);
          }

         Log.d("doInBackground", "The API call executed and will check the response");
         HttpEntity entityResp = httpResponse.getEntity();
         if (entityResp != null) {
             this.getApiResponse().setResponse(appHelper.getStringFromInputStream(entityResp.getContent()));
             Log.d("doInBackground","The response is :" + this.getApiResponse().getResponse());
             this.getApiResponse().setSuccess(true);
         }

     } catch (UnsupportedEncodingException e1) {
         Log.e("doInBackground","Exception :" + e1.toString());
         this.getApiResponse().setSuccess(false);
         this.getApiResponse().setResponseCode(HttpResponseCode.BAD_REQUEST);
         this.getApiResponse().setResponseDescription("Exception :" + e1.toString());
            Log.e("doInBackground","Exception :" + e1.toString());
            e1.printStackTrace();
     } catch (Exception e) {
         Log.e("doInBackground","Exception :" + e.toString());
         this.getApiResponse().setSuccess(false);
         this.getApiResponse().setResponseCode(HttpResponseCode.BAD_REQUEST);
         this.getApiResponse().setResponseDescription("Exception :" + e.toString());
         if (httpPost != null && !httpPost.isAborted()) {
             httpPost.abort(); 
         }
     } finally {
         if (httpClient != null) {
             httpClient.getConnectionManager().shutdown();
         }
         backGroundExecuted = true;

     }
    return null;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.