gpt4 book ai didi

android - 如何使 Asynctask postExecute 将变量发送回主类

转载 作者:行者123 更新时间:2023-11-30 04:11:56 25 4
gpt4 key购买 nike

我有一个名为 Main.java 的类,它运行 UI。我有另一个名为 VerifyCreds.java 的类,它扩展了 AsyncTask。 VerifyCreds 的全部目的是在另一个线程上运行对我的服务器的调用,以免锁定我的 UI。我没有在 Main.java 中将它子类化,因为我将有许多其他类将调用服务器,我希望它们都使用 VerifyCreds 类来完成它。

我需要做的是将数据从 VerifyCreds.java 传回 Main.java。但在使用以下代码时出错。

感谢任何帮助!谢谢!

这是我的 Main.java 代码

    package com.coolprograms.zeal;
<<<imports removed for brevity>>

public class Main extends Activity
{

// Global VAR's
String TAG = "ZEAL";
static Boolean authCode;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login);

//Grab elements
final EditText userName = (EditText)findViewById(R.id.usernameBOX);
final EditText userPWD = (EditText)findViewById(R.id.passwordBOX);
final Button loginBTN = (Button)findViewById(R.id.loginBTTN);

//Button listener
loginBTN.setOnClickListener(new View.OnClickListener()
{

@Override
public void onClick(View v)
{
// Get username and password and add to array
ArrayList<String> creds = new ArrayList<String>();
creds.add(userName.getText().toString());
creds.add(userPWD.getText().toString());

// Call method that will execute AsyncTask to get creds from server
verify(creds);
}
});
}

private void verify (ArrayList<String> creds)
{
// Start AsyncTask to get creds
new VerifyCredentials(this).execute(creds);
}

public interface credsAuth
{
public void authorizedCreds(Boolean authCode);

}

public void verifiedCreds(Context ctx, Boolean serverAuth)
{
if(serverAuth = true)
{
// Move to next screen if we are authorized
Intent i = new Intent(ctx, Items.class);
startActivity(i);
}
}
}

这是 VerifyCreds.java 代码

package com.coolprograms.zeal;
<<<imports removed for brevity>>
public class VerifyCredentials extends AsyncTask<ArrayList<String>, Void, Boolean> {

private Context ctx;
ProgressDialog dialog;

public VerifyCredentials(Context applicationContext)
{
// TODO Auto-generated constructor stub
ctx = applicationContext;
dialog = new ProgressDialog(applicationContext);
}

@Override
protected void onPreExecute()
{
dialog.setTitle("Please wait");
dialog.setMessage("Verifying username and password...");
dialog.show();
}


@Override
protected Boolean doInBackground(ArrayList<String>...creds)
{
//To return
Boolean serverAnwser = false;

//Get the creds
String userID = creds[0].get(0).toString();
Log.i("ZEAL", "Creds[0]: " + creds[0].get(0).toString());
String userPWD = creds[0].get(1).toString();
Log.i("ZEAL", "Creds[1]: " + creds[0].get(1).toString());

//Get creds from server
try {
String serverANW = null;
URL getCreds = new URL("http://XXX.XXX.XXX.XXX/api/api.php?method=getCreds&id=" + userID + "&pwd=" + userPWD);
Log.i("ZEAL", "Webservice URL: " + getCreds.toString());

URLConnection tc = getCreds.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));

// Get JSON Object
JSONArray jArray;
jArray = new JSONArray(in.readLine());

//Log json object returned
Log.i("ZEAL", jArray.toString());

//Check server response
//for (int i = 0; i < jArray.length(); i++)
//{
JSONObject e = jArray.getJSONObject(0);
String s = e.getString("RETURN");
JSONObject jObject = new JSONObject(s);
serverANW = jObject.getString("RESULT");
Log.i("ZEAL", "API Result: " + serverANW);
//}

if(serverANW.equalsIgnoreCase("True"))
{
serverAnwser = true;
Log.i("ZEAL", "ServerANW = " + serverANW.toString());
Log.i("ZEAL", "Setting server anwser to true");
}
else
{
serverAnwser = false;
Log.i("ZEAL", "ServerANW = " + serverANW.toString());
Log.i("ZEAL", "Setting server anwser to false - " + serverAnwser.toString());
}

} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return serverAnwser;
}

@Override
protected void onPostExecute(final Boolean authCode)
{
dialog.dismiss();

// Log what the functions is doing
Log.d("ZEAL","Server Response: " + authCode.toString());
Toast.makeText(ctx, "Server says: " + authCode.toString(), Toast.LENGTH_LONG).show();
Main m = new Main();
m.verifiedCreds(m, authCode);

}
}

错误:

05-23 15:18:57.190: E/AndroidRuntime(25475): FATAL EXCEPTION: main
05-23 15:18:57.190: E/AndroidRuntime(25475): java.lang.NullPointerException
05-23 15:18:57.190: E/AndroidRuntime(25475): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
05-23 15:18:57.190: E/AndroidRuntime(25475): at android.content.ComponentName.<init>(ComponentName.java:75)
05-23 15:18:57.190: E/AndroidRuntime(25475): at android.content.Intent.<init>(Intent.java:3174)
05-23 15:18:57.190: E/AndroidRuntime(25475): at com.coolprograms.zeal.Main.verifiedCreds(Main.java:85)
05-23 15:18:57.190: E/AndroidRuntime(25475): at com.coolprograms.zeal.VerifyCredentials.onPostExecute(VerifyCredentials.java:117)
05-23 15:18:57.190: E/AndroidRuntime(25475): at com.coolprograms.zeal.VerifyCredentials.onPostExecute(VerifyCredentials.java:1)
05-23 15:18:57.190: E/AndroidRuntime(25475): at android.os.AsyncTask.finish(AsyncTask.java:602)
05-23 15:18:57.190: E/AndroidRuntime(25475): at android.os.AsyncTask.access$600(AsyncTask.java:156)
05-23 15:18:57.190: E/AndroidRuntime(25475): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
05-23 15:18:57.190: E/AndroidRuntime(25475): at android.os.Handler.dispatchMessage(Handler.java:99)
05-23 15:18:57.190: E/AndroidRuntime(25475): at android.os.Looper.loop(Looper.java:137)
05-23 15:18:57.190: E/AndroidRuntime(25475): at android.app.ActivityThread.main(ActivityThread.java:4424)
05-23 15:18:57.190: E/AndroidRuntime(25475): at java.lang.reflect.Method.invokeNative(Native Method)
05-23 15:18:57.190: E/AndroidRuntime(25475): at java.lang.reflect.Method.invoke(Method.java:511)
05-23 15:18:57.190: E/AndroidRuntime(25475): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-23 15:18:57.190: E/AndroidRuntime(25475): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-23 15:18:57.190: E/AndroidRuntime(25475): at dalvik.system.NativeStart.main(Native Method)

最佳答案

您可以创建一个接口(interface),让 Main 实现该接口(interface),将 Main 作为构造函数参数传递给 asynctask,并让它使用您要传回的参数调用 Main。

界面:

public interface CredListener() {
void verify(Boolean status);
}

在类定义中声明 Main 实现了 CredListener

class Main extends Activity implements CredListener {
...

VerifyCredentials() 的新构造函数:

public VerifyCredentials(CredListener listener, Context applicationContext) 
{
this.listener = lister; // remember the listener

ctx = applicationContext;
dialog = new ProgressDialog(applicationContext);
}

在 onPostExecute(final Boolean authCode) 中将结果提供给监听器:

listener.verify(authCode);

这是 Main 与 VerifyCredentials 的松散耦合。

关于android - 如何使 Asynctask postExecute 将变量发送回主类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10727362/

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