3

我正在 onoptionitemselected 函数内建立一个 htpp 连接。这是功能:

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.logout:
            startActivity(new Intent(UserPage.this,HelloUser.class));
            finish();
            return true;
        case R.id.go:
            if(!mode)
            {runOnUiThread(new Runnable() 
            {
                public void run()
                     {
                docheck();
                     }});
            }

这是 docheck 函数:

public void docheck()
{
namepair2=new ArrayList<NameValuePair>(2);
DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://mobileattendance.eu.pn/checkcon.php");
try
{
namepair2.add(new BasicNameValuePair("check",pid));
namepair2.add(new BasicNameValuePair("check1",pid));

 jParser12=new JSONParser();
 httppost.setEntity(new UrlEncodedFormEntity(namepair2));
    HttpResponse response = httpclient.execute(httppost);
    StringBuilder sb = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    for (String line; null != (line = reader.readLine());) {
        sb.append(line);
    }
    String output = sb.toString();

这是我收到的信息:

     05-18 04:06:18.656: D/libc-netbsd(15077): getaddrinfo: mobileattendance.eu.pn  return error = 0x8 >>
   05-18 04:06:18.696: I/System.out(15077): Exception : null
  05-18 04:06:18.713: W/System.err(15077): android.os.NetworkOnMainThreadException
  05-18 04:06:18.729: W/System.err(15077):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
  05-18 04:06:18.730: W/System.err(15077):  at java.net.InetAddress.lookupHostByName(InetAddress.java:392)
  05-18 04:06:18.730: W/System.err(15077):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:243)
  05-18 04:06:18.730: W/System.err(15077):  at java.net.InetAddress.getAllByName(InetAddress.java:221)
  05-18 04:06:18.730: W/System.err(15077):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
  05-18 04:06:18.730: W/System.err(15077):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
  05-18 04:06:18.730: W/System.err(15077):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
  05-18 04:06:18.730: W/System.err(15077):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:363)
  05-18 04:06:18.730: W/System.err(15077):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
  05-18 04:06:18.730: W/System.err(15077):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
  05-18 04:06:18.731: W/System.err(15077):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
  05-18 04:06:18.731: W/System.err(15077):  at com.example.attendence.UserPage.docheck(UserPage.java:648)
  05-18 04:06:18.731: W/System.err(15077):  at com.example.attendence.UserPage.onOptionsItemSelected(UserPage.java:312)
  05-18 04:06:18.731: W/System.err(15077):  at android.app.Activity.onMenuItemSelected(Activity.java:2516)
  05-18 04:06:18.731: W/System.err(15077):  at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:968)
  05-18 04:06:18.731: W/System.err(15077):  at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
  05-18 04:06:18.732: W/System.err(15077):  at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
  05-18 04:06:18.732: W/System.err(15077):  at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
  05-18 04:06:18.732: W/System.err(15077):  at com.android.internal.view.menu.IconMenuView.invokeItem(IconMenuView.java:468)
  05-18 04:06:18.732: W/System.err(15077):  at com.android.internal.view.menu.IconMenuItemView.performClick(IconMenuItemView.java:126)
  05-18 04:06:18.733: W/System.err(15077):  at android.view.View$PerformClick.run(View.java:14155)
  05-18 04:06:18.733: W/System.err(15077):  at android.os.Handler.handleCallback(Handler.java:605)
  05-18 04:06:18.733: W/System.err(15077):  at android.os.Handler.dispatchMessage(Handler.java:92)
  05-18 04:06:18.733: W/System.err(15077):  at android.os.Looper.loop(Looper.java:154)
  05-18 04:06:18.734: W/System.err(15077):  at android.app.ActivityThread.main(ActivityThread.java:4624)
  05-18 04:06:18.734: W/System.err(15077):  at java.lang.reflect.Method.invokeNative(Native Method)
  05-18 04:06:18.734: W/System.err(15077):  at java.lang.reflect.Method.invoke(Method.java:511)
  05-18 04:06:18.735: W/System.err(15077):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
  05-18 04:06:18.735: W/System.err(15077):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
  05-18 04:06:18.735: W/System.err(15077):  at dalvik.system.NativeStart.main(Native Method)
  05-18 04:07:10.318: D/dalvikvm(15077): GC_EXPLICIT freed 996K, 10% free 11692K/12919K, paused 1ms+2ms
  05-18 04:07:10.318: D/ActivityThread(15077): LOW_MEMORY handled : 0 / null

我在使用 printstacktrace() 方法后发布了错误日志。

4

1 回答 1

1

这是示例:

主类

public class MainActivity extends Activity implements OnWorkDone {

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

        doCheck();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private void doCheck(){
        MyAsyncTask task = new MyAsyncTask();
        task.setListener(this);
        task.execute();
    }

    @Override
    public void handleResponse(String resp) {
        //Do something with response
        Log.d("TAG", resp);
    }

}

我的异步任务

public class MyAsyncTask extends AsyncTask<Void, Void, String> {

    public interface OnWorkDone {
        public void handleResponse(String resp);
    }

    private OnWorkDone listener;

    public void setListener(OnWorkDone l) {
        this.listener = l;
    }

    @Override
    protected String doInBackground(Void... params) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://mobileattendance.eu.pn/checkcon.php");

        List<NameValuePair> pairs = new ArrayList<NameValuePair>(2);
        pairs.add(new BasicNameValuePair("check", "value1"));
        pairs.add(new BasicNameValuePair("check1", "value2"));
        String result = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(pairs));

            HttpResponse response = client.execute(post);
            result = EntityUtils.toString(response.getEntity());

        } catch (UnsupportedEncodingException e) {
            //Should never be thrown
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if (listener != null) {
            listener.handleResponse(result);
        }
    }

}

请注意,只有当您需要根据服务器的响应更改 UI(即在 TextView 中设置文本)时,您才需要侦听器部分。或者您可以将MyAsyncTask类设为内部的,否则您可以简单地在方法MainClass中处理响应。onPostExecute

于 2013-05-17T23:06:11.527 回答