0

Android、Json ans Mysqlでログインするコードを開発しました。私のコードはエミュレーター(Android 2.1)で動作しますが、スマートフォン(4.1)でクラッシュし、これはログ猫のエラーです

error in http connection android.os.networkonmainthreadexception

これは私のコードであり、誰かが何かを変更して、アプリケーションがすべての Android バージョンで動作できるようにするのを手伝ってくれるなら、よろしくお願いします。

public class ConnexionmysqlActivity extends Activity {

        private static final String strURL = "http://mercure.comze.com/mercure/logi.php";
    //  private String result ;
        private Button connexion ;
        private EditText Logon ;
        private EditText password ;
        private JSONArray   jArray;
        private JSONObject  json_data;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.login);
            Button connexion = (Button) findViewById(R.id.btn);
            final EditText Logon = (EditText) findViewById(R.id.login);
            final EditText password = (EditText) findViewById(R.id.mdpt);


            connexion.setOnClickListener(new View.OnClickListener() {

                @SuppressWarnings("unused")
                public void onClick(View v) {
                    String result =null;
                    InputStream is = null;
                    StringBuilder sb = new StringBuilder();
                    ArrayList<NameValuePair> nameValuePairs=new ArrayList<NameValuePair> ();
                    nameValuePairs.add(new BasicNameValuePair("user",Logon.getText().toString()));

                    try{

                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost(strURL);
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost);
                        HttpEntity entity = response.getEntity();
                        is = entity.getContent();    
                    }catch(Exception e){
                        Log.e("log_tag", "Error in http connection " + e.toString());
                    } 
                    try{
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);

                        String line = null;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line + "\n");

                        }
                        is.close();
                        result=sb.toString();

                    }catch(Exception e){
                        Log.e("log_tag", "Error in http connection " + e.toString());
                    }
                    String essai=result.substring(0, 4) ;
                    try {
                        if (result.matches("<br >")){
                             essai=result.substring(0, 2) ; 
                        }
                        JSONArray jArray = new JSONArray(result);
                        int b=jArray.length();



                           JSONObject json_data = jArray.getJSONObject(0);


                           String mot_pass =    json_data.getString("mdp").toString();
                           String login =   json_data.getString("login").toString();
                           if (mot_pass.equals(password.getText().toString()) ){

                               Intent principale =new Intent(ConnexionmysqlActivity.this,compte.class);
                               principale.putExtra("login",login);
                               startActivity(principale);

                           }
                           else {

                               Toast.makeText(ConnexionmysqlActivity.this, "mot de pass invalide ", Toast.LENGTH_LONG).show();
                           }


                   }catch(JSONException e){
                     //  Log.e("log_tag", "Error parsing data " + e.toString());
                       Toast.makeText(ConnexionmysqlActivity.this, "Utilisateur Inexistant ", Toast.LENGTH_LONG).show();
                   }

                }
                });

        }
    }

編集:コードに(asyncTaskを使用して)いくつかの変更を加えましたが、今回もコードが機能しません。これは私が行った変更です:

public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.login);
            Button connexion = (Button) findViewById(R.id.btn);
            final EditText Logon = (EditText) findViewById(R.id.login);
            final EditText password = (EditText) findViewById(R.id.mdpt);


            connexion.setOnClickListener(new View.OnClickListener() {

                @SuppressWarnings("unused")
                public void onClick(View v) {


                    new callServiceTask().execute();

                }
                });

        }

            class callServiceTask extends AsyncTask<Void, Void, Void>
            {
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    pDialog = new ProgressDialog(ConnexionmysqlActivity.this);
                    pDialog.setMessage("Loading...");
                    pDialog.setIndeterminate(false);
                    pDialog.setCancelable(true);
                    pDialog.show();
                }
                @Override
                protected Void doInBackground(Void... params) {

                    // call web service
                     ArrayList<NameValuePair> nameValuePairs=new ArrayList<NameValuePair> ();
                        nameValuePairs.add(new BasicNameValuePair("user",Logon.getText().toString()));

                        try{

                            HttpClient httpclient = new DefaultHttpClient();
                            HttpPost httppost = new HttpPost(strURL);
                            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                            HttpResponse response = httpclient.execute(httppost);
                            HttpEntity entity = response.getEntity();
                            is = entity.getContent();    
                        }catch(Exception e){
                            Log.e("log_tag", "Error in http connection " + e.toString());
                        } 
                        try{
                            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);

                            String line = null;
                            while ((line = reader.readLine()) != null) {
                                sb.append(line + "\n");

                            }
                            is.close();
                            result=sb.toString();

                        }catch(Exception e){
                            Log.e("log_tag", "Error in http connection " + e.toString());
                        }
                        String essai=result.substring(0, 4) ;
                        try {
                            if (result.matches("<br >")){
                                 essai=result.substring(0, 2) ; 
                            }
                            JSONArray jArray = new JSONArray(result);
                            int b=jArray.length();



                               JSONObject json_data = jArray.getJSONObject(0);


                               String mot_pass =    json_data.getString("mdp").toString();
                               String login =   json_data.getString("login").toString();
                               if (mot_pass.equals(password.getText().toString()) ){

                                   Intent principale =new Intent(ConnexionmysqlActivity.this,compte.class);
                                   principale.putExtra("login",login);
                                   startActivity(principale);

                               }
                               else {

                                   Toast.makeText(ConnexionmysqlActivity.this, "mot de pass invalide ", Toast.LENGTH_LONG).show();
                               }


                       }catch(JSONException e){
                         //  Log.e("log_tag", "Error parsing data " + e.toString());
                           Toast.makeText(ConnexionmysqlActivity.this, "Utilisateur Inexistant ", Toast.LENGTH_LONG).show();
                       }
                    return null;
                }

                @Override
                protected void onPostExecute(Void resulta) {

                    //bind data in lisview or any other componet
             pDialog.dismiss();
                    super.onPostExecute(resulta);
                }

            } 

logcat :

07-23 08:16:53.028: W/dalvikvm(15420): threadid=11: thread exiting with uncaught exception (group=0x2b542210)
07-23 08:16:53.048: E/AndroidRuntime(15420): FATAL EXCEPTION: AsyncTask #1
07-23 08:16:53.048: E/AndroidRuntime(15420): java.lang.RuntimeException: An error occured while executing doInBackground()
07-23 08:16:53.048: E/AndroidRuntime(15420):    at android.os.AsyncTask$3.done(AsyncTask.java:278)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at java.lang.Thread.run(Thread.java:856)
07-23 08:16:53.048: E/AndroidRuntime(15420): Caused by: java.lang.NullPointerException
07-23 08:16:53.048: E/AndroidRuntime(15420):    at com.project.mercureproject.ConnexionmysqlActivity$callServiceTask.doInBackground(ConnexionmysqlActivity.java:98)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at com.project.mercureproject.ConnexionmysqlActivity$callServiceTask.doInBackground(ConnexionmysqlActivity.java:1)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
07-23 08:16:53.048: E/AndroidRuntime(15420):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
07-23 08:16:53.048: E/AndroidRuntime(15420):    ... 5 more
4

2 に答える 2

2

oncreate メソッドにこのコードを追加します。

StrictMode.ThreadPolicy ポリシー = 新しい StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(ポリシー);

于 2013-07-23T07:40:38.107 に答える
0

メインスレッドでWebサービスを呼び出しています..メインスレッドの実行でネットワークを取得しています..AsyncTaskでWebサービスを呼び出します

class callServiceTask extends AsyncTask<Void, Void, Void>
{
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {

        // call web service
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        //bind data in lisview or any other componet
        super.onPostExecute(result);
    }

} 

このように呼び出します

 new callServiceTask().execute();
于 2013-07-23T05:20:21.047 に答える