One of the basic methods of use

Posted by itsmani1 on Sat, 25 May 2019 00:53:44 +0200

Today I'll give you a basic introduction to XUtils 3. The cases in this article are all based on the API grammar of XUtils 3. I believe you have also known about this framework. Here is a brief introduction to some basic knowledge of XUtils 3.  
XUtils 3 has four functions: annotation module, network module, image loading module and database module.  
To use XUtils, you only need to add a jar package to the libs folder. If you encapsulate the data returned by the server, you need to import a Gson jar package.  
Required permissions:

<uses-permission android:name="android.permission.INTERNET" />  
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  • 1
  • 2

Annotation module

Annotations to Activity
1. Add the following code to the oncreate method of Application:
x.Ext.init(this); 
2. Add the following code to Activity's oncreate method:
x.view().inject(this); 
3. Loading the current Activity layout requires the following annotations:
@ ContentView is added to the top of Activity
4. Initialization of View requires the following annotations:
@InjectView 
5. Processing the various response events of the control requires the following annotations:
@Envent 
Examples are as follows:

    @ContentView(R.layout.activity_main)
public class MainActivity extends ActionBarActivity {

    @ViewInject(R.id.btn_get)
    Button btn_get;
    @ViewInject(R.id.btn_post)
    Button btn_post;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);

        btn_get.setText("Send out get request");
        btn_post.setText("Send out post request");
    }
    //Equivalent to @Event(value={R).id.btn_get,R.id.btn_post},type=View.OnClickListener.class)
    @Event(value={R.id.btn_get,R.id.btn_post})
    private void getEvent(View view){
        switch(view.getId()){
        case R.id.btn_get:
            Toast.makeText(MainActivity.this, btn_get.getText().toString().trim(), 0).show();
            break;
        case R.id.btn_post:
            Toast.makeText(MainActivity.this, btn_post.getText().toString().trim(), 0).show();
            break;
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

Through the test, we found that when we clicked the btn_get button, the effect of "sending get request" popped up. At this point, you have a basic understanding of XUtils annotations. I would like to emphasize that the @Event annotation defaults to View.OnClickListener.class. If you want to achieve the rest of the click events, you just need to modify the type value.  
Another point to note is that the click event of the button must be modified with private.

Notes to Fragment:

@ContentView(R.layout.fragment_first)  
public class FirstFragment extends Fragment{  
    private MyAdapter adapter;
    private List<Person> list=new ArrayList<>();  
    private List<String> listUrl=new ArrayList<>();  
    private List<String> listName=new ArrayList<>();    

    @ViewInject(R.id.btn_test)
    Button btn_test;
    @ViewInject(R.id.listView)
    ListView listView;

    @Override
    public View onCreateView(LayoutInflater inflater,
            @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return  x.view().inject(this, inflater, container);
    } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

ViewHolder's annotations:

    public class MyAdapter extends  BaseAdapter{
    private Context context;
    private List<Person> list;
    private LayoutInflater mInflater;
    private ImageOptions options;
    public ViewHolder holder;
    public MyAdapter(Context context, List<Person> list) {
        this.context = context;
        this.list = list;
        this.mInflater=LayoutInflater.from(context);
        options=new ImageOptions.Builder().setLoadingDrawableId(R.drawable.ic_launcher)
                .setLoadingDrawableId(R.drawable.ic_launcher).setUseMemCache(true).setCircular(true).build();
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        holder=null;
        if(convertView==null){
            convertView=mInflater.inflate(R.layout.itemone, null);
            holder=new ViewHolder();
            x.view().inject(holder,convertView);
            convertView.setTag(holder);
        }
        else{
            holder=(ViewHolder) convertView.getTag();
        }
        Person bean=list.get(position);
        holder.tv_name.setText(bean.getName());
        x.image().bind(holder.iv_image, bean.getImgUrl(), options);
        return convertView;
    }

    class ViewHolder{
        @ViewInject(R.id.tv_name)
        private TextView tv_name;
        @ViewInject(R.id.iv_image)
        private ImageView iv_image;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53

The above code is the standard mode for annotating ViewHolder, and I believe you can see it clearly. Here I use XUtils 3 to load network images. I'll explain it in detail later.

Network module

The network request method of XUtils is very similar to the usage of some network request frameworks. I did some simple encapsulation.  
There are three files encapsulated, namely, the network request tool class XUtil, the request response data parsing class, and an interface callback class with a successful request.  
The code is as follows:

public class XUtil {
    /**
     * Send get request
     * @param <T>
     */
    public static <T> Cancelable Get(String url,Map<String,String> map,CommonCallback<T> callback){
        RequestParams params=new RequestParams(url);
        if(null!=map){
            for(Map.Entry<String, String> entry : map.entrySet()){
                params.addQueryStringParameter(entry.getKey(), entry.getValue());
            }
        }
        Cancelable cancelable = x.http().get(params, callback);
        return cancelable;
    }

    /**
     * Send a post request
     * @param <T>
     */
    public static <T> Cancelable Post(String url,Map<String,Object> map,CommonCallback<T> callback){
        RequestParams params=new RequestParams(url);
        if(null!=map){
            for(Map.Entry<String, Object> entry : map.entrySet()){
                params.addParameter(entry.getKey(), entry.getValue());
            }
        }
        Cancelable cancelable = x.http().post(params, callback);
        return cancelable;
    }


    /**
     * Upload files
     * @param <T>
     */
    public static <T> Cancelable UpLoadFile(String url,Map<String,Object> map,CommonCallback<T> callback){
        RequestParams params=new RequestParams(url);
        if(null!=map){
            for(Map.Entry<String, Object> entry : map.entrySet()){
                params.addParameter(entry.getKey(), entry.getValue());
            }
        }
        params.setMultipart(true);
        Cancelable cancelable = x.http().post(params, callback);
        return cancelable;
    }

    /**
     * Download File
     * @param <T>
     */
    public static <T> Cancelable DownLoadFile(String url,String filepath,CommonCallback<T> callback){
        RequestParams params=new RequestParams(url);
        //Setting Breakpoint Continuation
        params.setAutoResume(true);
        params.setSaveFilePath(filepath);
        Cancelable cancelable = x.http().get(params, callback);
        return cancelable;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
public class JsonResponseParser implements ResponseParser {
    //Check the response header information returned by the server
    @Override
    public void checkResponse(UriRequest request) throws Throwable {
    }

    /**
     * Objects that convert result to resultType
     *
     * @param resultType  Return value type (possibly with generic information)
     * @param resultClass return type
     * @param result      String data
     * @return
     * @throws Throwable
     */
    @Override
    public Object parse(Type resultType, Class<?> resultClass, String result) throws Throwable {
        return new Gson().fromJson(result, resultClass);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
public class MyCallBack<ResultType> implements Callback.CommonCallback<ResultType>{

    @Override
    public void onSuccess(ResultType result) {
        //Successful logical processing of unified requests based on the needs of the company
    }

    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        //Unified logic processing of request network failure can be performed according to the company's requirements
    }

    @Override
    public void onCancelled(CancelledException cex) {

    }

    @Override
    public void onFinished() {

    }


}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

1. Send an example get request:

//This get request comes from the free test interface: http://www.k780.com/api/entry.baidu
String url="http://api.k780.com:88/?app=idcard.get";
        Map<String,String> map=new HashMap<>();
        map.put("appkey", "10003");
        map.put("sign", "b59bc3ef6191eb9f747dd4e83c99f2a4");
        map.put("format", "json");
        map.put("idcard", "110101199001011114");
        XUtil.Get(url, map, new MyCallBack<PersonInfoBean>(){

            @Override
            public void onSuccess(PersonInfoBean result) {
                super.onSuccess(result);
                Log.e("result", result.toString());
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);


            }

        });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

2. Send a post request

String url="http://api.k780.com:88/?app=idcard.get";
        Map<String,Object> map=new HashMap<>();
        map.put("appkey", "10003");
        map.put("sign", "b59bc3ef6191eb9f747dd4e83c99f2a4");
        map.put("format", "json");
        map.put("idcard", "110101199001011114");
        XUtil.Post(url, map, new MyCallBack<PersonInfoBean>(){

            @Override
            public void onSuccess(PersonInfoBean result) {
                super.onSuccess(result);
                Log.e("result", result.toString());
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);

            }
        });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

3. Upload files

/**
     * Upload files (support multiple file uploads)
     */
    private void uploadfile() {
        //Picture upload address
        String url="";
        Map<String,Object> map=new HashMap<>();
        //Pass in your own parameters
        //map.put(key, value);
        //map.put(key, value);
        XUtil.UpLoadFile(url, map, new MyCallBack<String>(){

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }

        });

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

4. Download files

private void downloadfile() {
        //File download address
        String url="";
        //Files are saved locally
        String filepath="";
        XUtil.DownLoadFile(url, filepath,new MyCallBack<File>(){
            @Override
            public void onSuccess(File result) {
                super.onSuccess(result);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);

            }
        });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

5. Download File Belt Progress Bar

private void downloadprogressfile() {
        //File download address
        String url="";
        //Files are saved locally
        String filepath="";
        XUtil.DownLoadFile(url, filepath,new MyProgressCallBack<File>(){

            @Override
            public void onSuccess(File result) {
                super.onSuccess(result);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);

            }
            @Override
            public void onLoading(long total, long current,
                    boolean isDownloading) {
                super.onLoading(total, current, isDownloading);

            }
        });
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

6. Send get request (server returns in xml format)

private void getxml() {
        String url="http://flash.weather.com.cn/wmaps/xml/china.xml";
        XUtil.Get(url, null, new MyCallBack<String>(){

            @Override
            public void onSuccess(String xmlString) {
                super.onSuccess(xmlString);
                try{
                    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();  
                    XmlPullParser xmlPullParser = factory.newPullParser();  
                    xmlPullParser.setInput(new StringReader(xmlString));  
                    int eventType = xmlPullParser.getEventType();  
                    while (eventType != XmlPullParser.END_DOCUMENT) {  
                        switch (eventType) {  
                        case XmlPullParser.START_TAG:  
                            String nodeName = xmlPullParser.getName();  
                            if ("city".equals(nodeName)) {  
                                String pName = xmlPullParser.getAttributeValue(0);  
                                Log.e("TAG", "city is " + pName);  
                            }  
                            break;  
                        }  
                        eventType = xmlPullParser.next();  
                    }  
                }catch(Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }

        });
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

Picture Loading Module

Usage:

x.image().bind(imageView, url, imageOptions);
x.image().bind(imageView, "file:///sdcard/test.gif", imageOptions);
x.image().bind(imageView, "assets://test.gif", imageOptions);
x.image().bind(imageView, url, imageOptions, new Callback.CommonCallback<Drawable>() {...});
x.image().loadDrawable(url, imageOptions, new Callback.CommonCallback<Drawable>() {...});
x.image().loadFile(url, imageOptions, new Callback.CommonCallback<File>() {...});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Xutils3's api is still relatively simple, I believe you can understand, the first parameter into a View, the second parameter into a picture's network address, the third parameter is generally the configuration of loading the picture.  
Let's look at the ImageOptions class.

ImageOptions options=new ImageOptions.Builder()
//Setting up pictures during loading
.setLoadingDrawableId(R.drawable.ic_launcher)
//Set the picture after loading failure
.setFailureDrawableId(R.drawable.ic_launcher)
//Setting Use Cache
.setUseMemCache(true)
//Set up to display circular pictures
.setCircular(true)
//Setting up gif support
.setIgnoreGif(false)
.build();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Refer to the source code for some of the remaining configurations

If you need to manipulate the loaded image, you can use:

x.image().loadDrawable(url, imageOptions, new Callback.CommonCallback<Drawable>() {...});
  • 1

Through the returned Drawable object for image processing, to meet the personalized requirements of the project.

Having said so much, I think you will at least have a basic understanding of XUtils 3. Because there are many uses of XUtils 3 database, this article will not touch on it. In the next article, I will explain the database module of XUtils 3 in detail. Let's do it now. All the examples mentioned in this article will be covered in the demo below. Please refer to them for your own reference.

XUtils3.zip

Topics: network Android Database xml