简体   繁体   English

从活动中的异步任务获取价值

[英]Get value from Async task in Activity

I have a class as shown below. 我有一个如下所示的课程。 It is in a .java file called NQRequestHandler.java and I want to call this from an Activity.java. 它在一个名为NQRequestHandler.java的.java文件中,我想从Activity.java调用它。 But I'm having problems with the AsyncTask method. 但是我在使用AsyncTask方法时遇到问题。 When I run it in the Activity.java file it returns a null value when I try to log the value of Globals.PUBLIC_KEY from the Activity. 当我在Activity.java文件中运行它时,当我尝试从Activity记录Globals.PUBLIC_KEY值时,它返回一个空值。 Log.v("RESULT", "Public KEY JSON from OnStart" + Globals.PUBLIC_KEY); Log.v(“ RESULT”,“来自OnStart的公钥JSON” + Globals.PUBLIC_KEY);

public class NQRequestHandler {

    private static NQRequestHandler instance;
    public static final String TAG = NQRequestHandler.class.getSimpleName();
    private Context mContext;


public NQRequestHandler(Context context) {
    mContext = context;
}

public static synchronized NQRequestHandler getInstance(Context context) {

    if (instance == null)
        instance = new NQRequestHandler(context);

    return instance;
}

public class requestHandler extends AsyncTask<String, Void, JSONArray> {

    RequestListener requestListener;
    public JSONArray requestResult;

    public requestHandler() {

    }

    public void setRequestListener(RequestListener requestListener) {
        this.requestListener = requestListener;
    }

    @Override
    protected JSONArray doInBackground(String... params) {

        try {
            String url = "http://www.someurl.com";

            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);

            List<NameValuePair> urlParameters = requestHandlerHelper(params);
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(urlParameters);

            entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8"));
            post.setEntity(entity);

            HttpResponse response = client.execute(post);
            System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

            Reader reader = new InputStreamReader(response.getEntity().getContent());

            int contentLength = (int) response.getEntity().getContentLength();
            Log.v(TAG, "Content Length DATA" + contentLength);
            char[] charArray = new char[contentLength];
            reader.read(charArray);

            String responseData = new String(charArray);
            JSONArray jsonResponse = new JSONArray(responseData);

            return jsonResponse;

        } catch (ClientProtocolException e) {
            Log.i(TAG, "ClientProtocolException: ", e);
        } catch (UnsupportedEncodingException e) {
            Log.i(TAG, "UnsupportedEncodingException: ", e);
        } catch (IOException e) {
            Log.i(TAG, "IOException: ", e);
        } catch (JSONException e) {
            Log.i(TAG, "JSONException: ", e);
        }
        return null;
    }

    @Override
    protected void onPostExecute(JSONArray results) {
        if (results != null) {
            requestListener.onRequestSuccess(results);
        } else {
            requestListener.onRequestFailed();
        }
    }

}

public interface RequestListener {
    JSONArray onRequestSuccess(JSONArray data);

    void onRequestFailed();
}

public void NQRequest(String... params) {
    if (isNetworkAvailable()) {
        requestHandler handler = new requestHandler();
        RequestListener listener = new RequestListener() {
            @SuppressWarnings("unchecked")
            @Override
            public JSONArray onRequestSuccess(JSONArray data) {
                //TODO: Switch set data here

                Log.v(TAG, "JSON FROM NQRequest" + data);
                Globals.PUBLIC_KEY = String.valueOf(data);
                return data;
            }

            @Override
            public void onRequestFailed() {
                Toast.makeText(mContext, "Network is unavailable. Request failed", Toast.LENGTH_LONG).show();
            }
        };
        handler.setRequestListener(listener);
        handler.execute(params);
    } else {
        Toast.makeText(mContext, "Network is unavailable", Toast.LENGTH_LONG).show();
    }
}

private static List<NameValuePair> requestHandlerHelper(String... params) {

    //Declare URL Parameter values
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    String[] requestActionArray = Globals.REQUEST_ACTION_ID;
    int actionSwitch = -1;
    String[] requestActionHeaders = null;

    //Find URL Parameter Action Switch
    for (int i = 0; i < requestActionArray.length; i++) {
        if (requestActionArray[i].equalsIgnoreCase(params[params.length - 1])) {
            actionSwitch = i;
        }
    }

    //Set Action Switch ID Parameters
    requestActionHeaders = NQActionHeader(actionSwitch);

    //Set URL Parameters
    for (int i = 0; i < requestActionHeaders.length; i++) {
        urlParameters.add(new BasicNameValuePair(requestActionHeaders[i], params[i]));
    }

    return urlParameters;
}

private boolean isNetworkAvailable() {
    ConnectivityManager manager =
            (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();

    return networkInfo != null && networkInfo.isConnected() ? true : false;
}

private static String[] NQActionHeader(int actionSwitch) {
    /* some code goes here */
    }
}

In the Activity class looks like this: 在Activity类中如下所示:

public class Application extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    try {
        String message = "Hello World from Android";
            Context mContext = getBaseContext();
            NQRequestHandler.requestHandler handler = new     NQRequestHandler.requestHandler();
            NQRequestHandler requestHandler = NQRequestHandler.getInstance(mContext);
            requestHandler.NQRequest(message, "sendPublicKey");

        Log.v("RESULT", "Public KEY JSON from OnStart" + Globals.PUBLIC_KEY);
        //Start Activity
        Intent intent = new Intent(this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    } catch (Exception e) {
        e.printStackTrace();
    }
  }
}

The call to NQRequest in the Activity initiates the call to AsyncTask in the Activity. 在Activity中对NQRequest的调用会在Activity中发起对AsyncTask的调用。 Any help with this? 有什么帮助吗? How do I implement a callback in the Activity.java to get method from OnRequestSuccess(); 如何在Activity.java中实现回调以从OnRequestSuccess();获取方法OnRequestSuccess(); in the NQRequest() ? NQRequest() Note: I'm trying to call the method in Activity.java in other multiple Activity.java files 注意:我正在尝试在其他多个Activity.java文件中的Activity.java中调用方法

The log from OnStart should return a null value for Globals.PUBLIC_KEY. 来自OnStart的日志应为Globals.PUBLIC_KEY返回空值。 You have just set an asynchronous task to run to set that value. 您刚刚设置了一个异步任务来运行以设置该值。 It has not run yet by the time that log statement executes. 在执行log语句时尚未运行。 You should receive the log input from the 您应该从

Log.v(TAG, "JSON FROM NQRequest" + data);

call. 呼叫。 That will mostly happen after your activity has finished onCreate, as it is an asynchronous call. 这通常会在您的活动完成onCreate之后发生,因为它是异步调用。

i modified the structure for your reference. 我修改了结构供您参考。

Modified of requestHandler :- 修改了requestHandler:-

//**** e.g.
class requestHandler extends AsyncTask<Object, Void, JSONArray> {
    // define a caller

    String requester;
    Application caller;
    YourEachActivityClass1 caller1;

    //create a Constructor for caller;
    public requestHandler (Application caller) {
        // TODO Auto-generated constructor stub
         this.caller = caller;
    }

    public requestHandler (YourEachActivityClass1 caller1) {
        // TODO Auto-generated constructor stub
         this.caller1 = caller1;
    }

    ///&& method doInBackground
    @Override
    protected JSONArray doInBackground(Object... params) {
          .....
          //your process is here
         //custom your returning jsonarray

    try {

    Context context = (Context) params[0];
    Log.i(TAG, "context :"+context.getClass().getSimpleName());

    requester = (Integer) params[1];

    String message = (String) params[2];

    String public= (String) params[3]

        String url = "http://www.someurl.com";

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);

        List<NameValuePair> urlParameters = requestHandlerHelper(params);
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(urlParameters);

        entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8"));
        post.setEntity(entity);

        HttpResponse response = client.execute(post);
        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

        Reader reader = new InputStreamReader(response.getEntity().getContent());

        int contentLength = (int) response.getEntity().getContentLength();
        Log.v(TAG, "Content Length DATA" + contentLength);
        char[] charArray = new char[contentLength];
        reader.read(charArray);

        String responseData = new String(charArray);
        JSONArray jsonResponse = new JSONArray(responseData);

        Globals.PUBLIC_KEY = String.valueOf(jsonResponse);

        return jsonResponse;

    } catch (ClientProtocolException e) {
        Log.i(TAG, "ClientProtocolException: ", e);
    } catch (UnsupportedEncodingException e) {
        Log.i(TAG, "UnsupportedEncodingException: ", e);
    } catch (IOException e) {
        Log.i(TAG, "IOException: ", e);
    } catch (JSONException e) {
        Log.i(TAG, "JSONException: ", e);
    }
    return null;

    }

    ////&& return JSONArray back to ur activity class here by pass in caller
    protected void onPostExecute(JSONArray jsonarray) {

        if(requester.equals("IM_Application"))
            caller.onBackgroundTaskCompleted(jsonarray);
        else if(requester.equals("IM_ACTIVITY_1"))
            caller1.onBackgroundTaskCompleted(jsonarray);
    }

}

Application.class get ur json object:- Application.class获取您的json对象:-

public class Application extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {
            String message = "Hello World from Android";
             new requestHandler(this).execute(getActivity(), "IM_Application", message, "sendPublicKey");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

        //your returning result
public void onBackgroundTaskCompleted(JSONArray jsonarray) {
        Log.i("TAG", jsonarray:"+jsonarray);

        if(jsonarray!=null){
            //process your jsonarray to get the Globals.PUBLIC_KEY)here

                    Log.v("onBackgroundTaskCompleted", "Public KEY JSON from OnStart" + Globals.PUBLIC_KEY);
                    //Start Activity
                    Intent intent = new Intent(this, LoginActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);


         }else{
         Toast.makeText(mContext, "Network is unavailable. Request failed", Toast.LENGTH_LONG).show();
         }

}

}

Gd Luck :) GD运气:)

Fixed it works now. 已修复,现在可以使用。

public class HQHandler extends AsyncTask<String, Void, JSONArray> {

    public static final String TAG = HQHandler.class.getSimpleName();
    private static HQHandler instance;
    RequestListener requestListener;
    JSONArray requestResult;
    Context mContext;

    public HQHandler(Context context) {
        this.mContext = context;
    }

    public static synchronized HQHandler getInstance(Context context) {

        if (instance == null)
            instance = new HQHandler(context);

        return instance;
    }

    public void setRequestListener(RequestListener requestListener) {
        this.requestListener = requestListener;
    }

    public JSONArray getRequestResult() {
        return this.requestResult;
    }

    @Override
    protected JSONArray doInBackground(String... params) {

        try {
            String url = "http://www.someurl.com";

            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);

            List<NameValuePair> urlParameters = requestHandlerHelper(params);
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(urlParameters);

            entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8"));
            post.setEntity(entity);

            HttpResponse response = client.execute(post);
            System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

            Reader reader = new InputStreamReader(response.getEntity().getContent());

            int contentLength = (int) response.getEntity().getContentLength();
            Log.v(TAG, "Content Length DATA" + contentLength);
            char[] charArray = new char[contentLength];
            reader.read(charArray);

            String responseData = new String(charArray);
            JSONArray jsonResponse = new JSONArray(responseData);

            return jsonResponse;

        } catch (ClientProtocolException e) {
            Log.i(TAG, "ClientProtocolException: ", e);
        } catch (UnsupportedEncodingException e) {
            Log.i(TAG, "UnsupportedEncodingException: ", e);
        } catch (IOException e) {
            Log.i(TAG, "IOException: ", e);
        } catch (JSONException e) {
            Log.i(TAG, "JSONException: ", e);
        }
        return null;
    }

    @Override
    protected void onPostExecute(JSONArray results) {
        if (results != null) {
            requestListener.onRequestSuccess(results);
        } else {
            requestListener.onRequestFailed();
        }
    }

    public interface RequestListener {
        JSONArray onRequestSuccess(JSONArray data);

        void onRequestFailed();
    }

    public JSONArray HQRequest(String... params) throws ExecutionException, InterruptedException, JSONException {
        JSONArray result;

        if (!isNetworkAvailable()) {
            Toast.makeText(mContext, "Network is unavailable", Toast.LENGTH_LONG).show();
            return null;
        }

        HQHandler handler = new HQHandler(this.mContext);
        RequestListener listen = new RequestListener() {
            @SuppressWarnings("unchecked")
            @Override
            public JSONArray onRequestSuccess(JSONArray data) {
                return data;
            }

            @Override
            public void onRequestFailed() {
                Toast.makeText(mContext, "Network is unavailable. Request failed", Toast.LENGTH_LONG).show();
            }
        };
        handler.setRequestListener(listen);
        result = this.requestResult = handler.execute(params).get();

        return result;

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM