[MT] Specify the article category from Android with Data API

DataAPI wants to post articles on Android! It is a very important API at that time. This time, I would like to briefly explain the specification of categories from among them.

Get article category

MainActivity.java

package com.example.mtapply01;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;

import com.loopj.android.http.*;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.json.*;

import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity  {
    MainActivity act;
    Button btnSend;
    TextView txtTitle, txtBody;

    String cgi_url  = "http://path/to/mt-data-api.cgi";
    String blog_id  = "id";
    String username = "username";
    String password = "password";
    String token;
    ArrayList<String>  categoryLabel;
    ArrayList<Integer> categoryId;
    AsyncHttpClient    client;


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

        setContentView(R.layout.activity_main);
        act = this;
        btnSend = (Button) findViewById(R.id.btnSend);
        txtTitle = (TextView) findViewById(R.id.txtTitle);
        txtBody = (TextView) findViewById(R.id.txtBody);

        categoryLabel        = new ArrayList<String>();
        categoryId           = new ArrayList<Integer>();
        client               = new AsyncHttpClient();
        RequestParams params = new RequestParams();

        params.put("username", username);
        params.put("password", password);
        params.put("clientId", "test");

        String url = cgi_url.concat("/v2/authentication");
        client.post(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(JSONObject res) {
                try {
                    token = res.getString("accessToken");
                    Toast.makeText(act, "You are now logged", Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    Toast.makeText(act, "Login error", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Throwable e, JSONObject res) {
                Toast.makeText(act, "Login error", Toast.LENGTH_LONG).show();
            }
        });

        url = cgi_url.concat("/v2/sites/2/categories");
        client.get(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(JSONObject json) {
                try {
                    //To get the title
                    JSONArray datas = json.getJSONArray("items");
                    for (int i = 0; i < datas.length(); i++) {
                        categoryLabel.add(datas.getJSONObject(i).getString("label"));
                        categoryId.add(Integer.parseInt(datas.getJSONObject(i).getString("id")));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable e, JSONObject res) {
                Toast.makeText(act, "Login error", Toast.LENGTH_LONG).show();
            }
        });



        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Post entry
                try {
                    uploadText();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }


    private void uploadText() throws JSONException {
        CharSequence  title  = "title";
        CharSequence  body   = "body";
        JSONObject    entry  = new JSONObject();
        RequestParams params = new RequestParams();
        JSONArray categories = new JSONArray();
        JSONObject category;
        for(int i=0; i<categoryLabel.size(); i++) {
            category = new JSONObject();
            category.put("id",categoryId.get(i));
            categories.put(category);
        }
        try {
            entry.put("title", title);
            entry.put("body", body);
            entry.put("categories",categories);
            entry.put("status", "Draft");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.put("entry", entry.toString());
        String url = cgi_url.concat("/v2/sites/").concat(blog_id).concat("/entries");
        Header[] headers = new Header[1];
        headers[0] = new BasicHeader("X-MT-Authorization", "MTAuth accessToken=".concat(token));
        client.post(getBaseContext(), url, headers, params, "application/x-www-form-urlencoded", new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(JSONObject res) {
                Toast.makeText(act, "send completely", Toast.LENGTH_LONG).show();
            }
            public void onFailure(Throwable e, JSONObject res) {
                Toast.makeText(act, "sending error", Toast.LENGTH_LONG).show();
            }
        });

    }


    private void setButtonEnable(boolean flagEnable){
        btnSend.setEnabled(flagEnable);
    }

    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#eeeeee"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="title" />

    <EditText
        android:id="@+id/txtTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:background="#ffffff"
        android:ems="10"
        android:inputType="text"
        android:padding="3dp" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/txtTitle"
        android:layout_marginTop="16dp"
        android:text="Text"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <EditText
        android:id="@+id/txtBody"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView2"
        android:background="#ffffff"
        android:ems="10"
        android:gravity="center_vertical|top"
        android:inputType="textMultiLine"
        android:padding="3dp"
        android:layout_above="@+id/btnSend" />

    <Button
        android:id="@+id/btnSend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Send"
        />


</RelativeLayout>

Declare cgi_url: DataAPI endpoint, blog_id: blog ID, ʻusername: username, password: password` in the member area.

Get articles in ʻonCreate`.

To log in, insert the member variables ʻusername and passwordintoRequestParams and ** post ** to cgi_url + / v2 / authentication with ʻAsyncHttpClient.

If you log in successfully, you will enter ʻonSuccess and JSONObject will be returned, so save ʻaccessToken.

To get the article category, ** post ** the RequestParams created earlier to cgi_url + / v2 / sites / 2 / categories with ʻAsyncHttpClient`.

If the category is successfully acquired, it will enter ʻonSuccess, so insert the element of ʻitems into JSONArray.

JSONArray datas = json.getJSONArray("items");

Get the label and ʻid of the registered category from the obtained ʻitems.

for(int i=0; i<datas.length(); i++) {
    categoryLabel.add(datas.getJSONObject(i).getString("label"));
    categoryId.add(Integer.parseInt(datas.getJSONObject(i).getString("id")));
}

Now you can get the article category.

Post an article

If you can do this, all you have to do is post.

    private void uploadText() throws JSONException {
        CharSequence  title  = "title";
        CharSequence  body   = "body";
        JSONObject    entry  = new JSONObject();
        RequestParams params = new RequestParams();
        JSONArray categories = new JSONArray();
        JSONObject category;
        for(int i=0; i<categoryLabel.size(); i++) {           
            category = new JSONObject();
            category.put("id",categoryId.get(i));
            categories.put(category);
        }
        try {
            entry.put("title", title);
            entry.put("body", body);
            entry.put("categories",categories);
            entry.put("status", "Draft");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.put("entry", entry.toString());
        String url = cgi_url.concat("/v2/sites/").concat(blog_id).concat("/entries");
        Header[] headers = new Header[1];
        headers[0] = new BasicHeader("X-MT-Authorization", "MTAuth accessToken=".concat(token));
        client.post(getBaseContext(), url, headers, params, "application/x-www-form-urlencoded", new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(JSONObject res) {
                Toast.makeText(act, "send completely", Toast.LENGTH_LONG).show();
            }
            public void onFailure(Throwable e, JSONObject res) {
                Toast.makeText(act, "sending error", Toast.LENGTH_LONG).show();
            }
        });

    }

First, create the entry element JSONObject and RequestParams to send the article request. After that, prepare JSONArray for inserting multiple categories and JSONObject for inserting individual categories. The category entry is id and the category group entry is categories. When ** post **, send by inserting category inside categories. After that, if you enter the endpoint of ʻurlandheaders set as params with ʻAsyncHttpClient and send it, you can create an article with the category registered.

Supplement

Since it uses the internet, it's in Android Manifest <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> Don't forget to declare!

Impressions

Would you like to make it from your boss? I posted it on Qiita for the first time when I was asked! I'm sorry that the content is too shabby. .. .. I will do my best the next time I write!

Recommended Posts

[MT] Specify the article category from Android with Data API
[MT] Specify the article category from Android with Data API
Try using the Emotion API from Android
Compatible with Android 10 (API 29)
Vibrate the wristband device with Bluetooth from the Android app
Android development-WEB access (GET) Try to get data by communicating with the outside. ~
Call the Microsoft Emotion API by sending image data directly from Java.
SetCookie from the client side with OkHttp3
Data processing using stream API from Java 8
Hit the Salesforce REST API from Java
Find Raspberry Pi from Android with mDNS
Android development-WEB access (POST) Try to communicate with the outside and send data. ~