2013-04-26 2 views
0

EDIT : 마침내 문제가 어디인지 알아 냈습니다. 이 줄에 IOException이 계속 발생합니다. response = httpClient.execute (httpPost).사용자로부터 서버로 데이터를 보내주고 있습니다.

그러나이 오류의 원인이되는 정상적인 문제 (URL이 잘못되어 온라인에서 검색 한 것과 같은 문제)는 여기에서 문제가되지 않습니다. URL이 정확합니다. 누구든지이 오류가 발생할 수있는 모든 이유를 도울 수 있습니다. 고맙습니다.


이 질문을 여러 번 요청되었습니다 알고, 사실 원래이 작업을 수행하는 방법을 파악하기 위해 그 질문에 주어진 대답 보았다하지만 어떤 이유로 작동하지 않습니다와 나는하지 않습니다 왜 그런지 안다.

사용자가 가입해야하는 앱이 있습니다. 그들이 가입 한 후에 나는 그들이 입력 한 정보를 서버에 보낸다.

안드로이드 코드 :

//This is the method called when user presses submit button. The variables not declared 
//are global 
public void registerUser(View v){ 
    context = getApplicationContext(); 

    username = ((EditText) this.findViewById(R.id.username)).getText().toString(); 
    email = ((EditText) this.findViewById(R.id.email)).getText().toString(); 
    password=((EditText)this.findViewById(R.id.password)).getText().toString(); 

    String[] params = {username,email,password}; 
    (new SendRegisterInfo(this.getApplicationContext())).execute(params); 

    Toast t = Toast.makeText(context, "Thank you for Signing up "+username, Toast.LENGTH_SHORT); 
    t.show(); 
    //Start Main Page Activity. Page they'll see everytime they login 
    Intent i = new Intent(this,HomeActivity.class); 
    startActivity(i); 

} 


public class SendRegisterInfo extends AsyncTask<String,Void,Void>{ 

private String tag = "SendRegisterInfo"; 
private InputStream is; 
private Context c; 

@Override 
protected void onPostExecute(Void result) { 
    // TODO Auto-generated method stub 
    super.onPostExecute(result); 
} 

public SendRegisterInfo(Context c){ 
    this.c = c; 
} 

@Override 
protected Void doInBackground(String... params) { 
    String URI="http://www.mysite.com/registerUser.php"; 

    HttpClient httpClient = new DefaultHttpClient(); 
    HttpPost httpPost = new HttpPost(URI); 
    HttpResponse response; 

    String username,email,password; 
    username = params[0]; 
    email = params[1]; 
    password = params[2]; 


    try { 

     ArrayList<NameValuePair> submit = new ArrayList<NameValuePair>(2); 
     submit.add(new BasicNameValuePair("username",username)); 
     submit.add(new BasicNameValuePair("email",email)); 
     submit.add(new BasicNameValuePair("password",password)); 
     httpPost.setEntity(new UrlEncodedFormEntity(submit)); 

     response = httpClient.execute(httpPost); 
     Log.i(tag,response.getStatusLine().toString()); 

    } catch (ClientProtocolException e) { 
     Log.e(tag, "Error in http connection "+e.toString()); 

     e.printStackTrace(); 
    } catch (IOException e) { 
     Log.e(tag, "Error in http connection "+e.toString()); 

     e.printStackTrace(); 
    }catch (Exception e){ 
     Log.e(tag, "Error in http connection "+e.toString()); 

     e.printStackTrace(); 
    } 

    return null; 
} 


} 

매니페스트 파일 :

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> 
<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 

PHP 코드 :

<?php 
$username = $_POST["username"]; 
$email = $_POST["email"]; 
$pswrd = $_POST["password"]; 
$score = 0; 

$user = "root"; 
$password="pword"; 
$database = "databasename"; 

mysql_connect(localhost,$user,$password); 

mysql_select_db($database) or die("Unable to Select Database"); 

$query="INSERT INTO Players VALUES ('','$username','$email','$pswrd','','$score')"; 

mysql_query($query); 

mysql_close(); 

?> 
+0

귀하는이 작동 말하고 그 이유를 몰라? – Jordan

+0

무엇이 작동하지 않습니까? 간단한 양식을 만들고 데이터를 게시하는 경우 코드를 디버깅 해보십시오. PHP 스크립트가 작동합니까? Android가 실제로 콘텐츠를 전송합니까? 오류가 있습니까? – YuviDroid

+1

코드를 빠르게 살펴보면 유일한 문제는 전체 코드를 게시하지 않는 한 UI 스레드에서 네트워크 활동을 수행한다는 것입니다. – YuviDroid

답변

0

오류 판독 (문자열 ... PARAMS)가의 인수 doInBackground() 메소드. 당신은 AsyncTask를 시작하면

은 :이 작품이 아닌 경우는 인수

String username,email,weight,password; 
username = params[0]; 
email = params[1]; 
password = params[3]; // should be: password = params[2]; 

을 읽을 때

String[] params = {username,email,password}; 

을, PHP는 프로그램의 마지막 삽입 ID를 요청하는 MySQL의 쿼리를 추가 결과를 인쇄하여 클라이언트에서 응답을 얻으십시오.

response = httpclient.execute(httppost); 
HttpEntity entity = response.getEntity();  
Log.i(tag,EntityUtils.toString(entity).toString()); 

그래서 당신은 볼 수 있습니다. 삽입하거나 데이터베이스에 없습니다. 당신은 토스트를 표시하도록 설계되지 않은 클래스의 토스트를 보여주기 위해 시도하고

RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 

:

+0

답변 해 주셔서 감사합니다. 처음에 나열한 오류는 실제로 내 부분의 오타였습니다. 또한 오류가 실제로 발생한 위치에 있으며 질문을 다시 편집했습니다. – evthim

0

이 문제입니다. 또는, 아마, tost를 보여줄 준비가되어 있지 않습니다. 방법이 포함 된 클래스는 무엇입니까 registerUser

+0

답변 해 주셔서 감사 드리며 실제로 오류 중 하나입니다. 나는 그것을 고정하고 응용 프로그램이 충돌을 멈추지 만, 데이터는 여전히 서버로 전송되지 않습니다. 분명히 주요한 문제는이 라인 응답 = httpClient.execute (httpPost)로, IOException을 제공합니다. 질문을 업데이트했습니다. – evthim

0

아래 코드를 확인하십시오.

  • 데이터와 함께 기능 이름과 키를 요청에 추가하십시오.

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3); 
    
    nameValuePairs.add((NameValuePair) new BasicNameValuePair("f", "yourFunctionName."+methodName)); 
    
    nameValuePairs.add((NameValuePair) new BasicNameValuePair("u", "a0ff8a6a0a831ec25cf4de6c730be54c")); 
    
    //u is the key used by server to identify valid request. 
    
관련 문제