title: issue, how Fix get JSON from URL in android?, Onclicklistener? AsyncTask? OnPostExecute?
body: <p>/////////////////////////////FIRST TRY, first attempt:////////////////////////</p>
  
  <p>hi guys is my first time making an android application, and is only a test to see if it works, so my problem is this:
    I made an application in iOS that sending someones parameters to a URL that me returns a Json String value, only a value chain, my iOS code is:</p>
  
  <pre><code> URL = [[self replaceRealURL:[self GetUrlForRegisterWithName:NameValue Mail:MailValue Language:Language Country:Country]]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
      NSURL *Filtro = [NSURL URLWithString:URL];
  
      NSLog(@"%@",URL);
  
  
      dispatch_async(HILO_REGISTRO, ^{
  
          NSData *data = [[NSData alloc] initWithContentsOfURL:Filtro];
  
          [self performSelectorOnMainThread:@selector(fetchedData:)withObject:data waitUntilDone:YES];
          //[self fetchedData:data];
      });
  
  - (void)fetchedData:(NSData *)responseData {
  
  NSError* error;
  
  NSDictionary* json = [NSJSONSerialization
  
                        JSONObjectWithData:responseData
  
                        options:kNilOptions
  
                        error:&amp;error];
  
  
  NSString *CodigoDeError = [json objectForKey:@"error"];
  
  if ([CodigoDeError isEqualToString:@"1"])
  {
      // Existe
      NSLog(@"%@",json);
      [progressUpload hide:YES];
      UIAlertView *YaExiste = [[UIAlertView alloc] initWithTitle:@"Usuario registrado"
                                                         message:@"Este usuario ya ha sido registrado"
                                                        delegate:self
                                               cancelButtonTitle:@"OK"
                                               otherButtonTitles:nil];
      [YaExiste show];
  }
  else if ([CodigoDeError isEqualToString:@"2"])
  {
      // Argumentos Invalidos
      NSLog(@"%@",json);
      [progressUpload hide:YES];
      UIAlertView *NoValidos = [[UIAlertView alloc] initWithTitle:@"Su email no es válido"
                                                          message:@"Por favor ingrese un email válido"
                                                         delegate:self
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles:nil];
      [NoValidos show];
  }    }
  -(NSString*)GetUrlForRegisterWithName:(NSString*)name Mail:(NSString*)mail Language:(NSString*)language Country:(NSString*)country
  {
  NSString *PushToURL = [NSString stringWithFormat:@"http://MIPAGINA.com/PRUEBA/regiphone/?name=%@&amp;email=%@&amp;lang=%@&amp;country=%@",name,mail,language,country];
  return PushToURL;
   }
  </code></pre>
  
  <p>and it works perfectly, but in Android I am using this code in my activity:</p>
  
  <pre><code>textNombre = URLEncoder.encode(textNombre,"utf-8");
                      textMail = URLEncoder.encode(textMail,"utf-8");
                      Idioma = URLEncoder.encode(Idioma,"utf-8");
                      Pais = URLEncoder.encode(Pais,"utf-8");
  
  
                      JSONUrl = "http://MIPAGINA.com/PRUEBA/regiphone/?name="+textNombre+"&amp;email="+textMail+"&amp;lang="+Idioma+"&amp;country="+Pais;
  
                  /*  Toast msg = Toast.makeText(getBaseContext(),
                               JSONUrl, Toast.LENGTH_LONG);
                              msg.show();*/
                      JSONParser jParser = new JSONParser();
  
                      // getting JSON string from URL
                      JSONObject json = jParser.getJSONFromUrl(JSONUrl);
  
                      Toast msg = Toast.makeText(getBaseContext(),
                               JSONUrl, Toast.LENGTH_LONG);
                              msg.show();
  
                              try {
  
  
                                  String CodigoDeError = jsonobject.getString("error");
  
                                  if(CodigoDeError.equals("1"))
                                  {
                                      String Mensaje = "Este usuario ya ha sido registrado";
                                      Toast msge = Toast.makeText(getBaseContext(),
                                               Mensaje, Toast.LENGTH_LONG);
                                              msge.show();
                                  }
                                  else if (CodigoDeError.equals("2")) 
                                  {
                                      String Mensaje = "Por favor ingrese un email válido";
                                      Toast msge = Toast.makeText(getBaseContext(),
                                               Mensaje, Toast.LENGTH_LONG);
                                              msge.show();
                                  }
                                  else
                                  {
                                      CodigoDeError = jsonobject.getString("id");
                                      String NSLOG = "Nslog";
                                      Log.i(NSLOG, CodigoDeError.toString());
                                      String Mensaje = "Muchas gracias por registrarse";
                                      Toast msge = Toast.makeText(getBaseContext(),
                                               Mensaje, Toast.LENGTH_LONG);
                                              msge.show();
                                  }
  
  
                              } catch (JSONException e) {
                                  Log.e("Error", e.getMessage());
                                  e.printStackTrace();
                              }
  </code></pre>
  
  <p>I dont know if I'm doing something wrong or should receive json from url I did create, the code for both run in Ibaction and in a OnClickListener, but what is wrong? the app crash and show:</p>
  
  <p><img src="https://i.stack.imgur.com/BEEa5.png" alt="enter image description here"></p>
  
  <p>And the Logcat show me this, is for is the URL? from http request?:</p>
  
  <p><img src="https://i.stack.imgur.com/2qsX2.png" alt="enter image description here"></p>
  
  <p>Please any help from a simple Json get from Url? the code for Java Android Eclipse in which I base is in this tutorial form android hive :<a href="http://www.androidhive.info/2012/01/android-json-parsing-tutorial/" rel="nofollow noreferrer">http://www.androidhive.info/2012/01/android-json-parsing-tutorial/</a></p>
  
  <pre><code>               //------------------------------------------//
                 //           THANKS StackOverFlow           //
                 //          GRETTINGS FROM BOLIVIA          //
                 //             ROCK ON!!!! n_n'             //
                 //------------------------------------------//
  </code></pre>
  
  <p>/////////////////////////////          EDIT           ///////////////////////////////////</p>
  
  <p>/////////////////////////////SECOND TRY, second attempt:////////////////////////</p>
  
  <p>well someons commrads recommended me using AsyncTask and change my code so and is:</p>
  
  <pre><code>  registrarseBtn.setOnClickListener(new OnClickListener()
      {
      public void onClick(View v)
      {
          new Registration().execute();
      }
  
    class Registration extends AsyncTask&lt;Void,String, JSONObject&gt; {
  
          @Override
          protected void onPreExecute() {
              super.onPreExecute();
              // Create a progressdialog
              mProgressDialog = new ProgressDialog(MainActivity.this);
              // Set progressdialog title
              mProgressDialog.setTitle("Auto Venta");
              // Set progressdialog message
              mProgressDialog.setMessage("Registrando...");
              mProgressDialog.setIndeterminate(false);
              // Show progressdialog
              mProgressDialog.show();
          }
  
  
          @Override
          protected JSONObject doInBackground(Void... params) 
          {
              String textNombre;
              String textMail;
              String Idioma;
              String Pais;
              //-------Validando Nombre -----//
               // String textNombre;
  
                if (nombreTextField.getText().toString().length() &lt;= 0) 
                {
                  nombreTextField.setError("Accept Alphabets Only.");
                  textNombre = null;
              } else if (!nombreTextField.getText().toString().matches("[a-zA-Z ]+")) 
              {
                  nombreTextField.setError("Accept Alphabets Only.");
                  textNombre = null;
              } else 
              {
                  textNombre=nombreTextField.getText().toString();
              }
                //-------- Validando eMail --------//
  
                //String textMail;
                if (mailTextField.getText().toString() == null) {
                  mailTextField.setError("Invalid Email Address");
                  textMail = null;
              } else if (isEmailValid(mailTextField.getText().toString()) == false) {
                  mailTextField.setError("Invalid Email Address");
                  textMail = null;
              } else {
                  textMail = mailTextField.getText().toString();
              }
  
              //-------Armando Cadena para URL------// 
  
  
                Idioma = Locale.getDefault().getLanguage();
                TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
                Pais = tm.getSimCountryIso();
  
                          try {
  
                              textNombre = URLEncoder.encode(textNombre,"utf-8");
                              textMail = URLEncoder.encode(textMail,"utf-8");
                              Idioma = URLEncoder.encode(Idioma,"utf-8");
                              Pais = URLEncoder.encode(Pais,"utf-8");
  
  
                              JSONUrl = "http://MIPAGINA.com/PRUEBA/websites/regiphone/?name="+textNombre+"&amp;email="+textMail+"&amp;lang="+Idioma+"&amp;country="+Pais;
  
                          } catch (UnsupportedEncodingException e1) {
                              // TODO Auto-generated catch block
                              e1.printStackTrace();
                          }
  
              JSONParser jParser = new JSONParser();
  
               // getting JSON string from URL
               JSONObject json = jParser.getJSONFromUrl(JSONUrl);
  
               return json;
          }
          protected void onPostExecute(JSONObject json) 
          {
  
              Toast msg = Toast.makeText(getBaseContext(),
                      JSONUrl, Toast.LENGTH_LONG);
                     msg.show();
  
                     try {
  
  
                         String CodigoDeError = jsonobject.getString("error");
  
                         if(CodigoDeError.equals("1"))
                         {
                             String Mensaje = "Este usuario ya ha sido registrado";
                             Toast msge = Toast.makeText(getBaseContext(),
                                      Mensaje, Toast.LENGTH_LONG);
                                     msge.show();
                         }
                         else if (CodigoDeError.equals("2")) 
                         {
                             String Mensaje = "Por favor ingrese un email válido";
                             Toast msge = Toast.makeText(getBaseContext(),
                                      Mensaje, Toast.LENGTH_LONG);
                                     msge.show();
                         }
                         else
                         {
                             CodigoDeError = jsonobject.getString("id");
                             String NSLOG = "Nslog";
                             Log.i(NSLOG, CodigoDeError.toString());
                             String Mensaje = "Muchas gracias por registrarse";
                             Toast msge = Toast.makeText(getBaseContext(),
                                      Mensaje, Toast.LENGTH_LONG);
                                     msge.show();
                         }
  
  
                     } catch (JSONException e) {
                         Log.e("Error", e.getMessage());
                         e.printStackTrace();
                     }
          }
      }
  
      boolean isEmailValid(CharSequence email)
      {
          return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
      } 
       });
  
  
  
  }
  </code></pre>
  
  <p>the problem is the same the app crashes and Idont know what is wrong, if I would change something in my code? the logcat show me this? </p>
  
  <pre><code> 11-13 09:37:42.840: E/AndroidRuntime(1200): FATAL EXCEPTION: AsyncTask #1
  11-13 09:37:42.840: E/AndroidRuntime(1200): Process: com.example.prototipo, PID: 1200
  11-13 09:37:42.840: E/AndroidRuntime(1200): java.lang.RuntimeException: An error occured while executing doInBackground()
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at java.lang.Thread.run(Thread.java:841)
  11-13 09:37:42.840: E/AndroidRuntime(1200): Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at com.example.prototipo.JSONParser.getJSONFromUrl(JSONParser.java:38)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at com.example.prototipo.MainActivity$1$Registration.doInBackground(MainActivity.java:153)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at com.example.prototipo.MainActivity$1$Registration.doInBackground(MainActivity.java:1)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     ... 4 more
  11-13 09:37:42.840: E/AndroidRuntime(1200): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at libcore.io.Posix.getaddrinfo(Native Method)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     ... 18 more
  11-13 09:37:42.840: E/AndroidRuntime(1200): Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied)
  11-13 09:37:42.840: E/AndroidRuntime(1200):     ... 21 more
  11-13 09:37:45.580: E/WindowManager(1200): android.view.WindowLeaked: Activity com.example.prototipo.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b4150488 V.E..... R......D 0,0-480,243} that was originally added here
  11-13 09:37:45.580: E/WindowManager(1200):  at android.view.ViewRootImpl.&lt;init&gt;(ViewRootImpl.java:346)
  11-13 09:37:45.580: E/WindowManager(1200):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
  11-13 09:37:45.580: E/WindowManager(1200):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
  11-13 09:37:45.580: E/WindowManager(1200):  at android.app.Dialog.show(Dialog.java:286)
  11-13 09:37:45.580: E/WindowManager(1200):  at com.example.prototipo.MainActivity$1$Registration.onPreExecute(MainActivity.java:89)
  11-13 09:37:45.580: E/WindowManager(1200):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
  11-13 09:37:45.580: E/WindowManager(1200):  at android.os.AsyncTask.execute(AsyncTask.java:535)
  11-13 09:37:45.580: E/WindowManager(1200):  at com.example.prototipo.MainActivity$1.onClick(MainActivity.java:73)
  11-13 09:37:45.580: E/WindowManager(1200):  at android.view.View.performClick(View.java:4424)
  11-13 09:37:45.580: E/WindowManager(1200):  at android.view.View$PerformClick.run(View.java:18383)
  11-13 09:37:45.580: E/WindowManager(1200):  at android.os.Handler.handleCallback(Handler.java:733)
  11-13 09:37:45.580: E/WindowManager(1200):  at android.os.Handler.dispatchMessage(Handler.java:95)
  11-13 09:37:45.580: E/WindowManager(1200):  at android.os.Looper.loop(Looper.java:137)
  11-13 09:37:45.580: E/WindowManager(1200):  at android.app.ActivityThread.main(ActivityThread.java:4998)
  11-13 09:37:45.580: E/WindowManager(1200):  at java.lang.reflect.Method.invokeNative(Native Method)
  11-13 09:37:45.580: E/WindowManager(1200):  at java.lang.reflect.Method.invoke(Method.java:515)
  11-13 09:37:45.580: E/WindowManager(1200):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
  11-13 09:37:45.580: E/WindowManager(1200):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
  11-13 09:37:45.580: E/WindowManager(1200):  at dalvik.system.NativeStart.main(Native Method)
  11-13 09:37:46.390: I/Process(1200): Sending signal. PID: 1200 SIG: 9
  </code></pre>
  
  <p>please help!</p>
  
  <p>/////////////////////////////THIRD TRY, third attempt:////////////////////////</p>
  
  <p>Thanks: </p>
  
  <pre><code>@popovitsj, @Phil, @printemps, @aegean, @Wang, 
  </code></pre>
  
  <p>but I added </p>
  
  <pre><code> &lt;uses-permission android:name="android.permission.INTERNET" /&gt; 
  </code></pre>
  
  <p>to my manifest.xml file and the app crashes too, and the logcat now show me this:</p>
  
  <pre><code>11-13 10:06:03.450: E/AndroidRuntime(1256): FATAL EXCEPTION: main
  11-13 10:06:03.450: E/AndroidRuntime(1256): Process: com.example.prototipo, PID: 1256
  11-13 10:06:03.450: E/AndroidRuntime(1256): java.lang.NullPointerException
  11-13 10:06:03.450: E/AndroidRuntime(1256):     at com.example.prototipo.MainActivity$1$Registration.onPostExecute(MainActivity.java:167)
  11-13 10:06:03.450: E/AndroidRuntime(1256):     at com.example.prototipo.MainActivity$1$Registration.onPostExecute(MainActivity.java:1)
  11-13 10:06:03.450: E/AndroidRuntime(1256):     at android.os.AsyncTask.finish(AsyncTask.java:632)
  11-13 10:06:03.450: E/AndroidRuntime(1256):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
  11-13 10:06:03.450: E/AndroidRuntime(1256):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
  11-13 10:06:03.450: E/AndroidRuntime(1256):     at android.os.Handler.dispatchMessage(Handler.java:102)
  11-13 10:06:03.450: E/AndroidRuntime(1256):     at android.os.Looper.loop(Looper.java:137)
  11-13 10:06:03.450: E/AndroidRuntime(1256):     at android.app.ActivityThread.main(ActivityThread.java:4998)
  11-13 10:06:03.450: E/AndroidRuntime(1256):     at java.lang.reflect.Method.invokeNative(Native Method)
  11-13 10:06:03.450: E/AndroidRuntime(1256):     at java.lang.reflect.Method.invoke(Method.java:515)
  11-13 10:06:03.450: E/AndroidRuntime(1256):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
  11-13 10:06:03.450: E/AndroidRuntime(1256):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
  11-13 10:06:03.450: E/AndroidRuntime(1256):     at dalvik.system.NativeStart.main(Native Method)
  11-13 10:06:06.000: I/Process(1256): Sending signal. PID: 1256 SIG: 9
  </code></pre>
  
  <p>OK The register runs finally,SO, the problem now is in the onPostExecute, the problem is that when I insert the data in the URL, it returns me error code or just an id of the record in JSON like this:</p>
  
  <pre><code>{
    error:1
  }
  </code></pre>
  
  <p>or </p>
  
  <pre><code>{
   id:123
  }
  </code></pre>
  
  <p>but in my asyncTask what is wrong???? please help Guys!!!</p>