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
user1928775
  • 355
  • 1
  • 5
  • 15
  • Where it doesn't crash. Sorry, couldn't resist. Please post the stack trace. NetworkOnMainThreadException? – Simon Nov 26 '13 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 – user1928775 Nov 26 '13 at 21:14
  • No it doesn't. Stack trace or no-one can help. – Simon Nov 26 '13 at 21:15
  • just tell me where to insert it that's what i'm looking for thanks by the way – user1928775 Nov 26 '13 at 21:20
  • No. Copy and paste the stack trace from your debugger – Bizmarck Nov 26 '13 at 21:22
  • Good now check my code after inserting and also the stacktrace :D – user1928775 Nov 26 '13 at 21:33
  • `Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.` and later, `at com.example.loginad.Logindb$MyAsyncTask.postData(Logindb.java:130)`, At line 130, you are trying to set the text of a text view from a thread which is not the main thread. It doesn't matter where you put this code, it will not work. Please learn about AsyncTask, Handler and threading in Android. – Simon Nov 26 '13 at 21:42
  • 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. – Simon Nov 26 '13 at 21:44
  • I was asking for help and you asked me to post the stacktrace and i did .And now you're being rude , if you don't know the answer just don't comment i can give anyone the answer you just gave me look and learn.correct my mistake or just don't comment. – user1928775 Nov 26 '13 at 21:47
  • You clearly can't give the answer or you would not have asked "where should I insert it". If you know that you cannot update the UI from a thread which is not the main thread (the answer I gave), then why did you ask the question? Learning is the best solution to most porgramming questions. – Simon Nov 26 '13 at 21:52
  • by the way my major is not programming at all and not related in anyway ,what i asked was specific you knew where to insert and you told me it worked then why would you make wait if you have it just give it .don't wait me to beg you for it (there is big difference between learning and correcting what i was asking for is correcting ) – user1928775 Nov 26 '13 at 21:55

1 Answers1

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;
}
Mina Tadros
  • 514
  • 6
  • 18