简体   繁体   中英

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. But I'm having problems with the AsyncTask method. 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. Log.v("RESULT", "Public KEY JSON from OnStart" + 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:

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. Any help with this? How do I implement a callback in the Activity.java to get method from OnRequestSuccess(); in the NQRequest() ? Note: I'm trying to call the method in Activity.java in other multiple Activity.java files

The log from OnStart should return a null value for 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. 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.

i modified the structure for your reference.

Modified of 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:-

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 :)

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;

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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