0

在我的 android 应用程序中,我想从 async-task 启动活动类。这是一个登录 pahe 类。else它部分给出错误onPostExecute(String result)(在新活动中开始时)。错误:Android - android.os.NetworkOnMainThreadException我使用了几种方法来解决这个问题,但我无法解决这个问题。请有人帮我

public class Login extends Activity {

private Button btnLogin;
private EditText txtusername;
private EditText txtPassword;
public String username;
public String password;
public boolean doLogin = false;


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

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.login);


    btnLogin = (Button) findViewById(R.id.btnLogin);
    txtusername = (EditText) findViewById(R.id.txtuserName);
    txtPassword = (EditText) findViewById(R.id.txtPassword);
    btnLogin.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {

            username = txtusername.getText().toString();
            password = txtPassword.getText().toString();

            if (username.equals("") || password.equals("")) {

                AlertDialog alert = new AlertDialog.Builder(Login.this)
                        .create();
                alert.setMessage("Username or Password can not be Empty");
                alert.setButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {
                            }
                        });

                alert.setIcon(R.drawable.loginlogo);
                alert.show();

            }

            else {

                HttpAsync httpasync = new HttpAsync();

                httpasync.execute(new String[] { "http://www.diskonbanget.com/bni/login/login.php" });

            }

        }

    });

}

private class HttpAsync extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        String str = null;
        try {

            // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(
                    "http://www.diskonbanget.com/bni/login/login.php");
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                    2);
            nameValuePairs
                    .add(new BasicNameValuePair("username", username));
            nameValuePairs
                    .add(new BasicNameValuePair("password", password));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request

            HttpResponse response = httpclient.execute(httppost);

            str = inputStreamToString(response.getEntity().getContent())
                    .toString();

        } catch (Exception e) {
            return str;
        }
        return str;
    }

    @Override
    protected void onPostExecute(String result) {
        String str = result;

        if (str.toString().equalsIgnoreCase("false")) {

            AlertDialog alert = new AlertDialog.Builder(Login.this)
                    .create();
            alert.setMessage("Please enter valid username & Password");
            alert.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            });

            alert.setIcon(R.drawable.loginlogo);
            alert.show();

        }

        else if (str.toString().equalsIgnoreCase("null")) {
            AlertDialog alert = new AlertDialog.Builder(Login.this)
                    .create();
            alert.setMessage("Can not Connect to the server.please make sure your internet is Switch on  ");
            alert.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            alert.setIcon(R.drawable.loginlogo);
            alert.show();
        }

        else {

            Intent intent = new Intent(Login.this, MainMenu.class);
            intent.putExtra("photo", str);
            intent.putExtra("username", username);  
            startActivity(intent);

        }

    }

}

private StringBuilder inputStreamToString(InputStream is) {
    String line = "";
    StringBuilder total = new StringBuilder();
    // Wrap a BufferedReader around the InputStream
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    // Read response until the end
    try {
        while ((line = rd.readLine()) != null) {
            total.append(line);
        }
        return total;

    } catch (Exception e) {

        return null;
    }

}

这是我的 LogCat

10-11 18:37:52.540: E/AndroidRuntime(2858): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bni.www/com.bni.www.MainMenu}: android.os.NetworkOnMainThreadException



10-11 19:00:45.498: E/AndroidRuntime(2925):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1026)
10-11 19:00:45.498: E/AndroidRuntime(2925):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-11 19:00:45.498: E/AndroidRuntime(2925):     at android.os.Looper.loop(Looper.java:132)

 10-11 19:00:45.498: E/AndroidRuntime(2925):    at java.lang.reflect.Method.invokeNative(Native Method)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at java.lang.reflect.Method.invoke(Method.java:491)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at dalvik.system.NativeStart.main(Native Method)
 10-11 19:00:45.498: E/AndroidRuntime(2925): Caused by: android.os.NetworkOnMainThreadException
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at java.net.InetAddress.lookupHostByName(InetAddress.java:477)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:277)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at java.net.InetAddress.getAllByName(InetAddress.java:249)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:69)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:304)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:292)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:274)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:217)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at java.net.URLConnection.getContent(URLConnection.java:197)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at java.net.URL.getContent(URL.java:613)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at com.bni.www.MainMenu.onCreate(MainMenu.java:48)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at android.app.Activity.performCreate(Activity.java:4411)
  10-11 19:00:45.498: E/AndroidRuntime(2925):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1781)
  10-11 19:00:45.498: E/AndroidRuntime(2925):   ... 11 more 
  10-11 19:01:22.538: I/Process(2925): Sending signal. PID: 2925 SIG: 9
  10-11 19:12:24.357: D/dalvikvm(2998): GC_FOR_ALLOC freed 43K, 3% free 6404K/6595K, paused 111ms
  10-11 19:12:24.377: I/dalvikvm-heap(2998): Grow heap (frag case) to 7.295MB for 1031504-byte allocation
  10-11 19:12:24.489: D/dalvikvm(2998): GC_FOR_ALLOC freed <1K, 3% free 7411K/7623K, paused 86ms
4

2 回答 2

0

您的代码可能适用于 2.2,因为它不会限制我们在 ui 线程上使用网络。

使用 asynctask 进行网络操作

于 2012-10-11T16:55:17.447 回答
0

确保不在 MainMenu 类的主线程中访问网络(在第 48 行为代码创建另一个 AsyncTask)。

NetworkOnMainThreadException

当应用程序尝试在其主线程上执行网络操作时引发的异常。

于 2012-10-11T14:25:12.337 回答