简体   繁体   中英

Need some help to understand what is done in the second line of code?

 public <T> void addToRequestQueue(Request<T> req, String tag) {
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

what is done in this second line? I can't understand what is this (tag) ?TAG :tag.

Here is the full code

{
import android.app.Application;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;

    private static AppController mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

here is the full code now tell me and please explain if you can that what is done in that method second line

TAG must be some constant of type String representing the default value of tag, whatever it is - something like this:

public static final String TAG = "<default-tag>";

The idea here is to tag your request with the value passed as the second parameter, ie String tag . Conditional operator ?: is used to implement the check without using an if / else statement.

When the tag string passed in the call to addToRequestQueue happens to be empty, the method uses the value of TAG instead.

Translation of the second line

public static final String TAG = AppController.class.getSimpleName();

public <T> void addToRequestQueue(Request<T> req, String tag) {
    req.setTag("is tag empty?" yes, so use `TAG` : no, so use `tag`);
    getRequestQueue().add(req);
} 

In another words:

if(tag.isEmpty()){
  res.setTag(TAG)

} else {
  res.setTag(tag)

}

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