0

私のAndroidアプリケーションでは、async-task.thisからアクティビティクラスを開始したいと考えています。これはログイン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

MainMenu クラスのメイン スレッドでネットワークにアクセスしないようにしてください (48 行目のコード用に別の AsyncTask を作成します)。

NetworkOnMainThreadException

アプリケーションがメイン スレッドでネットワーク操作を実行しようとしたときにスローされる例外。

于 2012-10-11T14:25:12.337 に答える
0

ui スレッドでのネットワークの使用を制限しないため、コードは 2.2 で動作する可能性があります。

ネットワーク操作に asynctask を使用する

于 2012-10-11T16:55:17.447 に答える