1
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class Signin extends Activity {

    EditText edt_mail, edt_password;
    Button btn_login, btn_pass, btn_reg, btn_forget;
    ImageView iv1, iv2;
    String strmail, strpassword, strres;

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

        btn_forget = (Button) findViewById(R.id.btnforget);

        edt_mail = (EditText) findViewById(R.id.edt_Username);
        edt_password = (EditText) findViewById(R.id.edt_Password);

        btn_login = (Button) findViewById(R.id.btnlogin);
        btn_pass = (Button) findViewById(R.id.btncancel);
        btn_reg = (Button) findViewById(R.id.btnReg);
        iv1 = (ImageView) findViewById(R.id.imgfacebook);
        iv2 = (ImageView) findViewById(R.id.imgtwitter);
        btn_forget.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(Signin.this, ForgetPassword.class);
                startActivity(intent);

            }
        });
        iv2.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(Signin.this, Twitter.class);
                startActivity(intent);

            }
        });
        iv1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(Signin.this, Facebook.class);
                startActivity(intent);

            }
        });

        btn_reg.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(Signin.this, Signup.class);
                startActivity(intent);
            }
        });
        btn_pass.setOnClickListener(new OnClickListener() {

            public void onClick(View v) { // TODO Auto-generated method stub

                cleartext();
            }

            public void cleartext() { // TODO Auto-generated method stub

                edt_mail.setText("");
                edt_password.setText("");
            }
        });

        btn_login.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (!edt_mail.getText().toString().equals("")) {

                    if (!edt_password.getText().toString().equals("")) {

                        try {
                            if (CheckConnection()) {
                                // new GetAccess().execute("");
                                getLogin();
                            } else {
                                Toast.makeText(
                                        Signin.this,
                                        "Please check your internet connection",
                                        Toast.LENGTH_LONG).show();
                            }

                        } catch (Exception e) {
                            Toast.makeText(Signin.this,
                                    "Error caught = " + e.toString(),
                                    Toast.LENGTH_LONG).show();
                        }

                    } else {

                        Toast.makeText(Signin.this, "please enter Password",
                                Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(Signin.this, "please enter Username",
                            Toast.LENGTH_LONG).show();

                }

            }

            private boolean CheckConnection() {
                final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
                if (activeNetwork != null
                        && activeNetwork.getState() == NetworkInfo.State.CONNECTED) {
                    // notify user you are online
                    // System.out.println("Internet connected = 1");
                    return true;

                } else {
                    // notify user you are not online
                    // System.out.println("Internet not connected = 0");
                    Toast.makeText(getApplicationContext(),
                            "Please check your internet connection ",
                            Toast.LENGTH_SHORT).show();
                    return false;

                }
            }
        });

    }

    public boolean CheckConnection() {
        final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
        if (activeNetwork != null
                && activeNetwork.getState() == NetworkInfo.State.CONNECTED) {
            // notify user you are online
            // System.out.println("Internet connected = 1");
            return true;
        } else {
            // notify user you are not online
            System.out.println("Internet not connected = 0");
            Toast.makeText(getApplicationContext(),
                    "Please check your internet connection ",
                    Toast.LENGTH_SHORT).show();
            return false;

        }

    }

    private void loadList() {

        /*
         * ArrayAdapter<String> adapter = new ArrayAdapter<String>(
         * MainActivity.this, android.R.layout.simple_list_item_1, eventlist);
         * view.setAdapter(adapter);
         */

        Intent intent = new Intent(Signin.this, MainList.class);
        startActivity(intent);

    }

    public void getLogin() {

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "my link");
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            // nameValuePairs.add(new BasicNameValuePair("id", "12345"));
            nameValuePairs.add(new BasicNameValuePair("email", edt_mail
                    .getText().toString().trim()));
            nameValuePairs.add(new BasicNameValuePair("password", edt_password
                    .getText().toString().trim()));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse httpResponse = httpclient.execute(httppost);
            HttpEntity entity = httpResponse.getEntity();

            InputStream inputStream = entity.getContent();

            // EntityUtils.toString(httpResponse.getEntity());
            String strres = convertStreamToString(inputStream);

            if (!strres.toString().trim().equals("0")) {
                Toast.makeText(Signin.this, "Successfully logged in ",
                        Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Signin.this, NewMainList.class);

                startActivity(intent);
            }

            else if (strres.toString().trim().equals("0")) {
                Toast.makeText(Signin.this, "Invalid login and password",
                        Toast.LENGTH_SHORT).show();
            }
            System.out.println("Response = " + strres);

            // username.setText("");
            // password.setText("");// clear text box
        } catch (ClientProtocolException e) {
            System.out.println(e);
        } catch (IOException e) {
            System.out.println(e);
        }
    }

    public String convertStreamToString(InputStream inputStream)
            throws IOException {
        if (inputStream != null) {
            StringBuilder sb = new StringBuilder();
            String line;
            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } finally {
                inputStream.close();
            }
            return sb.toString();
        } else {
            return "";
        }

    }

    public class GetAccess extends AsyncTask<String, String, String> {
        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(Signin.this);
            dialog.setTitle("Please wait");
            dialog.setMessage("Getting login access");
            dialog.show();
        }

        @Override
        protected String doInBackground(String... params) {
            getLogin();
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            dialog.dismiss();
            setSession();
            loadList();

            // System.out.println(result);

        }

        private void setSession() {
            SharedPreferences preferences = getSharedPreferences("CurrentUser",
                    MODE_WORLD_READABLE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("Save", edt_mail.getText().toString());
            editor.putString("Save1", edt_password.getText().toString());
            editor.putString("Save2", strres.toString().trim());
            System.out.println("Response = " + strres);

            editor.commit();
            edt_mail.setText("");
            edt_password.setText("");

        }
    }

}

注: このコードは、Android 2.3 エミュレーターおよびデバイスで完全に機能します。しかし、Android 4.0以降でこのコードを実行すると。強制終了エラーが発生します。this.in logcatから抜け出すのを手伝ってください、それはandroid.os.NetworkOnMainThreadExceptionエラーを表示します..どうすればこの問題を修正できますか..???

4

4 に答える 4

3

あなたのエラーはそれ自体を説明しています...

古いバージョンの AndroidOS では、UI スレッドでネットワークを実行できましたが、タイムアウトするとアプリが応答しなくなりました。これを解決するには、Android の新しいバージョンでは、UI スレッドでのネットワーク リクエストの実行をサポートしなくなりました。Threads または AsyncTasks で実行する必要があります。

この行: HttpResponse httpResponse = httpclient.execute(httppost);UI を実行していないスレッドにある必要があります。

new Thread(){
    public void run(){
        //TODO Run network requests here.
        getLogin();
    }
}.start();

これが起こる理由... Android は、WatchDog と呼ばれるものを実行します。これは、素人の言葉で言えば、コードを Android にリンクするコードの一部です。このタイマーは、アプリや OS と頻繁に通信して、すべてが正しく実行され、何もクラッシュしていないことを確認します。WatchDog タイマーを実行するのと同じスレッドである UI スレッドでネットワーク リクエストを実行し、応答がタイムアウトすると、アプリ全体がロックされ、Android との通信が停止します。

于 2013-01-29T09:49:20.143 に答える
1
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

            StrictMode.setThreadPolicy(policy);


add this lines after setcontentview(R.layout.main);
于 2013-01-29T10:23:07.270 に答える
1

メイン スレッドにネットワーク接続を確立することはできません。これは、Thread または AsyncTask を介して別の Thread に移動する必要があることを意味します。

これは、getLogin() メソッドに対してこれを行う必要があることを意味します。メイン スレッドでネットワーク接続の処理を呼び出すことは正しくありません

于 2013-01-29T09:48:57.727 に答える
0

これを試して、

私は変わりました。ToastdoInBackground()追加で削除されましたonPostExecute()

  public class Signin extends Activity {

EditText edt_mail, edt_password;
Button btn_login, btn_pass, btn_reg, btn_forget;
ImageView iv1, iv2;
String strmail, strpassword, strres;

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

    btn_forget = (Button) findViewById(R.id.btnforget);

    edt_mail = (EditText) findViewById(R.id.edt_Username);
    edt_password = (EditText) findViewById(R.id.edt_Password);

    btn_login = (Button) findViewById(R.id.btnlogin);
    btn_pass = (Button) findViewById(R.id.btncancel);
    btn_reg = (Button) findViewById(R.id.btnReg);
    iv1 = (ImageView) findViewById(R.id.imgfacebook);
    iv2 = (ImageView) findViewById(R.id.imgtwitter);
    btn_forget.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(MainActivity.this,
                    ForgetPassword.class);
            startActivity(intent);

        }
    });
    iv2.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(MainActivity.this, Twitter.class);
            startActivity(intent);

        }
    });
    iv1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(MainActivity.this, Facebook.class);
            startActivity(intent);

        }
    });

    btn_reg.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(MainActivity.this, Signup.class);
            startActivity(intent);
        }
    });
    btn_pass.setOnClickListener(new OnClickListener() {

        public void onClick(View v) { // TODO Auto-generated method stub

            cleartext();
        }

        public void cleartext() { // TODO Auto-generated method stub

            edt_mail.setText("");
            edt_password.setText("");
        }
    });

    btn_login.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (!edt_mail.getText().toString().equals("")) {

                if (!edt_password.getText().toString().equals("")) {

                    try {
                        if (CheckConnection()) {
                            new GetAccess().execute();
                            // getLogin();
                        } else {
                            Toast.makeText(
                                    MainActivity.this,
                                    "Please check your internet connection",
                                    Toast.LENGTH_LONG).show();
                        }

                    } catch (Exception e) {
                        Toast.makeText(MainActivity.this,
                                "Error caught = " + e.toString(),
                                Toast.LENGTH_LONG).show();
                    }

                } else {

                    Toast.makeText(MainActivity.this,
                            "please enter Password", Toast.LENGTH_LONG)
                            .show();
                }
            } else {
                Toast.makeText(MainActivity.this, "please enter Username",
                        Toast.LENGTH_LONG).show();

            }

        }

        private boolean CheckConnection() {
            final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
            if (activeNetwork != null
                    && activeNetwork.getState() == NetworkInfo.State.CONNECTED) {
                // notify user you are online
                // System.out.println("Internet connected = 1");
                return true;

            } else {
                // notify user you are not online
                // System.out.println("Internet not connected = 0");
                Toast.makeText(getApplicationContext(),
                        "Please check your internet connection ",
                        Toast.LENGTH_SHORT).show();
                return false;

            }
        }
    });

}

public boolean CheckConnection() {
    final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
    if (activeNetwork != null
            && activeNetwork.getState() == NetworkInfo.State.CONNECTED) {
        // notify user you are online
        // System.out.println("Internet connected = 1");
        return true;
    } else {
        // notify user you are not online
        System.out.println("Internet not connected = 0");
        Toast.makeText(getApplicationContext(),
                "Please check your internet connection ",
                Toast.LENGTH_SHORT).show();
        return false;

    }

}

private void loadList() {

    /*
     * ArrayAdapter<String> adapter = new ArrayAdapter<String>(
     * MainActivity.this, android.R.layout.simple_list_item_1, eventlist);
     * view.setAdapter(adapter);
     */

    Intent intent = new Intent(MainActivity.this, MainList.class);
    startActivity(intent);

}

public void getLogin() {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("my link");
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        // nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("email", edt_mail
                .getText().toString().trim()));
        nameValuePairs.add(new BasicNameValuePair("password", edt_password
                .getText().toString().trim()));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse httpResponse = httpclient.execute(httppost);
        HttpEntity entity = httpResponse.getEntity();

        InputStream inputStream = entity.getContent();

        // EntityUtils.toString(httpResponse.getEntity());
        strres = convertStreamToString(inputStream);

        System.out.println("Response = " + strres);

        // username.setText("");
        // password.setText("");// clear text box
    } catch (ClientProtocolException e) {
        System.out.println(e);
    } catch (IOException e) {
        System.out.println(e);
    }
}

public String convertStreamToString(InputStream inputStream)
        throws IOException {
    if (inputStream != null) {
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(inputStream, "UTF-8"));
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } finally {
            inputStream.close();
        }
        return sb.toString();
    } else {
        return "";
    }

}

public class GetAccess extends AsyncTask<String, String, String> {
    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(MainActivity.this);
        dialog.setTitle("Please wait");
        dialog.setMessage("Getting login access");
        dialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        getLogin();
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (dialog.isShowing())
            dialog.dismiss();
        setSession();
        loadList();
        if (!strres.toString().trim().equals("0")) {
            Toast.makeText(MainActivity.this, "Successfully logged in ",
                    Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(MainActivity.this, NewMainList.class);

            startActivity(intent);
        }

        else if (strres.toString().trim().equals("0")) {
            Toast.makeText(MainActivity.this, "Invalid login and password",
                    Toast.LENGTH_SHORT).show();
        }

        // System.out.println(result);

    }

    private void setSession() {
        SharedPreferences preferences = getSharedPreferences("CurrentUser",
                MODE_WORLD_READABLE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("Save", edt_mail.getText().toString());
        editor.putString("Save1", edt_password.getText().toString());
        editor.putString("Save2", strres.toString().trim());
        System.out.println("Response = " + strres);

        editor.commit();
        edt_mail.setText("");
        edt_password.setText("");

    }
}

}
于 2013-01-29T10:17:35.767 に答える