OnMenuButton 未将数据发布到 google 个电子表格

OnMenuButton not posting data to google spreadsheets

大家好,我遇到这个问题已经有一段时间了,我不知道为什么它不起作用。当我使用我在 YouTube 上遵循的教程提供的代码时,它工作正常,即在应用程序启动后立即 posting 该数据。然而,我想要做的是 post 在菜单中按下 "Save Register" 按钮后立即显示数据,但它不起作用并且 returns 日志目录中显示的消息。

我觉得我应该为此创建一个异步任务,但是因为我的 android 编程非常有限,我不确定我将如何创建它。

我的主activityClass:

public class MainActivity extends Activity{

boolean wasApEnabled = false;
static AccessPoint wifiAP;
private WifiManager wifi;
static Button apButton;
static TextView textView;
final String myTag = "DocsUpload";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    apButton = (Button) findViewById(R.id.toggleBtn);
    textView = (TextView) findViewById(R.id.wifiClients);

    apButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            wifiAP.toggleWifiAP(wifi, MainActivity.this);
        }
    });

    /*Log.i(myTag, "OnCreate()");
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            postData();

        }
    });*/
    //t.start();

    wifiAP = new AccessPoint(this);
    wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    postData();
    scan();
    //getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|WindowManager.LayoutParams.FLAG_DIM_BEHIND);

}

private void scan(){
    wifiAP.getClientList(false, new FinishScanListener() {

        @Override
        public void onFinishScan(final ArrayList<ClientScanResult> clients) {
            textView.setText("WifiApState:" + wifiAP.getWifiApState()+ "\n\n");
            textView.append("Clients: \n");
            for (ClientScanResult clientScanResult : clients){
                textView.append("====================\n");
                textView.append("ipAddress: " + clientScanResult.getIpAddress() + "\n");
                textView.append("Device: " + clientScanResult.getDevice() + "\n");
                textView.append("macAddress: " + clientScanResult.getMacAddress() + "\n");
                textView.append("isReachable: " + clientScanResult.isReachable() + "\n");

            }
        }
    });
}

public void postData() {

    String fullUrl = "https://docs.google.com/forms/d/1yipuuXd5V53Ol12U24Cl2H4RIdYtm622jIk13Zo26cM/formResponse";
    HttpRequest mReq = new HttpRequest();
    String col1 = "Hello";
    String col2 = "World";

    String data = "entry_272641491=" + URLEncoder.encode(col1) + "&" +
            "entry_130393492=" + URLEncoder.encode(col2);
    String response =mReq.sendPost(fullUrl, data);
   // Log.i(myTag, response);
}

@Override
public void onResume() {
    super.onResume();
    if (wasApEnabled) {
        if (wifiAP.getWifiApState() != wifiAP.WIFI_STATE_ENABLED && wifiAP.getWifiApState() != wifiAP.WIFI_STATE_ENABLING) {
            wifiAP.toggleWifiAP(wifi, MainActivity.this);
        }
    }
    updateStatusDisplay();
}

@Override
public void onPause() {
    super.onPause();
    boolean wifiApIsOn = wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLED || wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLING;
    if (wifiApIsOn){
        wasApEnabled = true;
        wifiAP.toggleWifiAP(wifi, MainActivity.this);
    }else {
        wasApEnabled = false;
    }
    updateStatusDisplay();
}

public static void updateStatusDisplay(){
    if (wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLED || wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLING){
        apButton.setText("Turn Off");
    }else {
        apButton.setText("Turn on");
    }
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(0,0,0, "Get Clients");
    menu.add(0,1,0, "Save Register");
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return super.onCreateOptionsMenu(menu);
}

public boolean onMenuItemSelected(int featureId, MenuItem item) {
    switch (item.getItemId()){
        case 0:
            scan();
            break;
        case 1:
            postData();
            break;
    }
    return super.onMenuItemSelected(featureId, item);
}
}

这是我用过的助手 class,感谢这个 stack overflow 用户创建了这个 class

这是我得到的日志猫

    03-12 15:06:27.428    3096-3096/com.example.gavin.wifiattendance D/Your App Name Here﹕ https://docs.google.com/forms/d/1yipuuXd5V53Ol12U24Cl2H4RIdYtm622jIk13Zo26cM/formResponse?entry_272641491=Hello&entry_130393492=World
03-12 15:06:27.428    3096-3096/com.example.gavin.wifiattendance E/WifiAttendance﹕ HttpUtils: android.os.NetworkOnMainThreadException
03-12 15:06:27.428    3096-3096/com.example.gavin.wifiattendance D/WifiAttendance﹕ Returning value:null

I am getting the feeling that i am supposed to create an Async task for this

正确。当您尝试在主线程(UI 线程)上进行网络调用时抛出 NetworkOnMainThreadException

您可以在 AsyncTask 上找到很好的教程 here

教程中的示例:

private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        String response = "";

        //Do your network calls here

        return response;

    }

    @Override
    protected void onPostExecute(String result) {

        //When you are done, this method runs on the UI thread so you can update the UI from here

        textView.setText(result);
    }
}

你终于这样执行了

DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.vogella.com" });

感谢@Marcus 提供的有用链接,我设法使用以下代码使其正常工作:

 public class PostDataTask extends AsyncTask<String, Void, Integer>{

    @Override
    protected Integer doInBackground(String... params) {
        HttpRequest mReq = new HttpRequest();
        String data = "entry_272641491=" + URLEncoder.encode(params[1]) + "&" +
                "entry_130393492=" + URLEncoder.encode(params[2]);
        String response = mReq.sendPost(params[0], data);
        return 200;
    }
}