0

PHPとmysqlに接続してAndroidログインを作成しました。プログラムを実行して正しいメールアドレスとパスワードを入力するたびに、EditTextにandroid.os.NetworkOnMainExceptionと表示されます。そのためのコードは何も起こりません。コーディングを間違えたのですか、それとも何かが足りないのですか。さて、これは私のコードの人です。

アンドロイド:

**

public class LoginActivity extends Activity {
/** Called when the activity is first created. */
     EditText inputEmail ;
    EditText inputPassword ;
    Button btnLogin ;
    public void validation()
    {
        if(inputEmail.getText().toString().equals("") || inputPassword.getText().toString().equals(""))
                {
                Toast.makeText( getApplicationContext(),"Fill Empty Fields",Toast.LENGTH_SHORT ).show();
                }
        else
        {
            connectphp();
        }
        }
    public void connectphp()
    {
    // TODO Auto-generated method stub
    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    postParameters.add(new BasicNameValuePair("eadd", inputEmail.getText().toString()));
    postParameters.add(new BasicNameValuePair("password", inputPassword.getText().toString()));
    //Passing Parameter to the php web service for authentication
    //String valid = "1";
    String response = null;
    try {
    response = CustomHttpClient.executeHttpPost("http://10.0.2.2:8080/TheCalling/log_in.php", postParameters);  //Enter Your remote PHP,ASP, Servlet file link
    String res=response.toString();
    res = res.trim();
    res= res.replaceAll("\\s+","");
    //error.setText(res);
    if(res.equals("1"))
    {
        Toast.makeText( getApplicationContext(),"Correct Username or Password",Toast.LENGTH_SHORT ).show();
        Intent i = new Intent(LoginActivity.this,MainMenu.class);
        startActivity(i);
    }
        else
            if(res.equals("0"))
        {
        Toast.makeText( getApplicationContext(),"Sorry!! Incorrect Username or Password",Toast.LENGTH_SHORT ).show();
        }
    } catch (Exception e) {
        inputEmail.setText(e.toString());
    }}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
 inputEmail = (EditText)findViewById(R.id.inputEmail);
 inputPassword = (EditText)findViewById(R.id.inputPassword);
btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{ 
    validation(); 
    //(This is to check empty fields)
}
});
}}

**

ちなみに、このコードはここからスタックオーバーフローでもありました。

CustomHttpClient

**

public class CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
 * Get our single instance of our HttpClient object.
 *
 * @return an HttpClient object with connection parameters set
 */
private static HttpClient getHttpClient() {
    if (mHttpClient == null) {
        mHttpClient = new DefaultHttpClient();
        final HttpParams params = mHttpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
        ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
    }
    return mHttpClient;
}
/**
 * Performs an HTTP Post request to the specified url with the
 * specified parameters.
 *
 * @param url The web address to post the request to
 * @param postParameters The parameters to send via the request
 * @return The result of the request
 * @throws Exception
 */
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
    BufferedReader in = null;
    try {
        HttpClient client = getHttpClient();
        HttpPost request = new HttpPost(url);
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
        request.setEntity(formEntity);
        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();
        String result = sb.toString();
        return result;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
/**
 * Performs an HTTP GET request to the specified url.
 *
 * @param url The web address to post the request to
 * @return The result of the request
 * @throws Exception
 */
public static String executeHttpGet(String url) throws Exception {
    BufferedReader in = null;
    try {
        HttpClient client = getHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(new URI(url));
        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();
        String result = sb.toString();
        return result;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
}

**

そして私のPHPコード。

**

<?php
include("db_config.php");
$eadd=addslashes($_POST['eadd']);
$password=addslashes($_POST['password']);
$sql="SELECT * FROM users WHERE eadd='$eadd' and password='$password'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$count=mysql_num_rows($result);
if($count==1)
    {
    echo "1";
    //(If result found send 1 to android)
    }
else
    {
    echo "0";
    //(If result not found send o to android)
    }
?>

**

お時間をいただきありがとうございます。

4

1 に答える 1

1

新しいバージョンの Android では、厳密モードがデフォルトで有効になっています。基本的にこれが意味することは、UI スレッドでネットワーク操作を実行できないということです。これは、アプリがフリーズしてバグが発生するためです。したがって、あなたは得ますNetworkOnMainThreadException

これを回避するにはAsyncTask、別のスレッドでダウンロード コードを実行できる を使用します。ドキュメントには、サブクラスの作成方法とそれを実行する方法が示されています (ボタンがクリックされたときに実行されます)。

于 2013-01-28T02:49:17.407 に答える