//////////////////////////////////////////////////////////////////////////////// /////////
嗨,伙计们,我是第一次制作 android 应用程序,只是测试它是否有效,所以我的问题是:我在 iOS 中制作了一个应用程序,将某人的参数发送到我返回 Json String 值的 URL,仅一个价值链,我的 iOS 代码是:
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:&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=%@&email=%@&lang=%@&country=%@",name,mail,language,country];
return PushToURL;
}
它运行良好,但在 Android 中,我在我的活动中使用此代码:
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+"&email="+textMail+"&lang="+Idioma+"&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();
}
我不知道我是否做错了什么或者应该从我创建的 url 接收 json,代码都在 Ibaction 和 OnClickListener 中运行,但有什么问题?应用程序崩溃并显示:
Logcat 给我看这个,是因为是 URL 吗?来自http请求?:
请从 Url 获得的简单 Json 提供任何帮助?我所基于的 Java Android Eclipse 的代码在本教程中,形式为 android hive:http ://www.androidhive.info/2012/01/android-json-parsing-tutorial/
//------------------------------------------//
// THANKS StackOverFlow //
// GRETTINGS FROM BOLIVIA //
// ROCK ON!!!! n_n' //
//------------------------------------------//
///////////////////////////// 编辑 //////////////////// ///////////////
////////////////////////第二次尝试,第二次尝试://////////// /////////
好吧,有些人推荐我使用 AsyncTask 并更改我的代码,并且是:
registrarseBtn.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
new Registration().execute();
}
class Registration extends AsyncTask<Void,String, JSONObject> {
@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() <= 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+"&email="+textMail+"&lang="+Idioma+"&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();
}
});
}
问题是一样的应用程序崩溃并且我不知道出了什么问题,如果我要更改我的代码中的某些内容?logcat 给我看这个?
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.<init>(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
请帮忙!
//////////////////////////////////////////////////////////////////////////////////////////////////// /////////
谢谢:
@popovitsj, @Phil, @printemps, @aegean, @Wang,
但我补充说
<uses-permission android:name="android.permission.INTERNET" />
到我的 manifest.xml 文件,应用程序也崩溃了,logcat 现在向我显示:
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
OK 寄存器终于运行了,所以,现在问题出在 onPostExecute 中,问题是当我在 URL 中插入数据时,它返回错误代码或者只是 JSON 中记录的 id,如下所示:
{
error:1
}
或者
{
id:123
}
但是在我的 asyncTask 中出了什么问题???请帮助伙计们!!!