-1

Hey guys i have got this problem for a while now and i cannot figure out as to why it is not working. when i use the code provided by the tutorial that i have followed on YouTube it works fine, which is posting that data as soon as the application starts. However what i am trying to do is post the data as soon as the "Save Register" button is pressed in the menu but the it doesnt work and returns the message as shown in Log Cat.

I am getting the feeling that i am supposed to create an Async task for this however because my android programming is very limited i am not to sure how i would go about creating this.

My Main activity Class:

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);
}
}

This is the helper class that i have used, Credit goes to this stack overflow user for creating this class

Secure HTTP Post in Android

This is the log cat that i am getting

    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
Community
  • 1
  • 1
hero8110
  • 259
  • 4
  • 5
  • 14

2 Answers2

0

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

Correct. NetworkOnMainThreadException is thrown when you are trying to make network calls on your Main Thread (UI thread).

You can find a good tutorial on AsyncTask here.

Example from the tutorial:

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);
    }
}

Finally you execute it like so

DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.vogella.com" });
Marcus
  • 6,697
  • 11
  • 46
  • 89
  • Would i create this Async task in the Main Activity Class or would it be more appropriate to put it in my Access Point Class? – hero8110 Mar 12 '15 at 15:42
  • That depends where you intend to use it. If you use it in your MainActivity, then put it there. If you use it in AccessPointClass, then put in there. @hero8110 – Marcus Mar 12 '15 at 15:43
  • I really dont understand the concept of Async task, i appreciate the link you sent me but im struggling to apply it to my application. Im not sure if this is right http://gyazo.com/d63b4c54b86176bc5c27b9b6954ceb37 – hero8110 Mar 12 '15 at 16:17
  • [here](http://stackoverflow.com/questions/9671546/asynctask-android-example) is another good example. And [here](http://programmerguru.com/android-tutorial/android-asynctask-example/) is another. I would also suggest having a look at the [official documentation](http://developer.android.com/reference/android/os/AsyncTask.html). @hero8110 – Marcus Mar 12 '15 at 16:24
  • thank you but i dont think the official documentation would be of any help to me, they explain it too complicated. I need pure simple english if it is going to get through my head im afraid, thank you for the help and the links ill see what i can make of it – hero8110 Mar 12 '15 at 16:30
  • Well, as a final hint, try [this](https://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/) for a more simpler explanation. @hero8110 – Marcus Mar 12 '15 at 16:31
0

Thank you for the @Marcus for the helpful links i managed to get it working using this code:

 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;
    }
}
hero8110
  • 259
  • 4
  • 5
  • 14