gpt4 book ai didi

java - 问题,如何修复android中从URL获取JSON?,Onclicklistener?异步任务?执行后?

转载 作者:行者123 更新时间:2023-12-01 13:51:15 25 4
gpt4 key购买 nike

/////////////////////////////第一次尝试,第一次尝试://///////////////////////

大家好,我是第一次制作 Android 应用程序,只是测试一下它是否有效,所以我的问题是这样的:我在 iOS 中创建了一个应用程序,将某人的参数发送到一个 URL,我返回一个 Json 字符串值,只有一个值链,我的 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 中我在我的 Activity 中使用此代码:

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 中运行,但是出了什么问题?应用程序崩溃并显示:

enter image description here

Logcat 向我展示了这个,是 URL 吗?来自http请求?:

enter image description here

请从 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' //
//------------------------------------------//

//////////////////////////////编辑////////////////////////////////////

/////////////////////////////第二次尝试,第二次尝试://///////////////////////

好吧,有些 Commrads 推荐我使用 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

好的,寄存器终于运行了,所以,现在的问题出在 onPostExecute 中,问题是当我在 URL 中插入数据时,它返回错误代码或只是 JSON 中记录的 id,如下所示:

{
error:1
}

{
id:123
}

但是在我的 asyncTask 中出了什么问题???请帮助大家!!!

最佳答案

Logcat 应该显示一些内容。尝试重新连接设备并检查您是否在 DDMS 视角中选择了正确的设备。

//编辑

您正在尝试在 UI 线程上运行网络调用。尝试使用 AsyncTask 进行后台调用。 AsyncTask

类似这样的事情:

new AsyncTask<JSONURL, Integer, JSONObject> {
protected JSONObject doInBackground(JSONURL... urls) {
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();
}
}
}.execute(JSONURL);

这只是一个例子。代码中可能存在一些错误。

关于java - 问题,如何修复android中从URL获取JSON?,Onclicklistener?异步任务?执行后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19941136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com