마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

json파싱을 이용해서 php로 id체크를 해서 DB 정보를 읽어오는 거 질문합니다.

0 추천
<?
   // 데이터베이스 접속 문자열. (db위치, 유저 이름, 비밀번호)
   $hostname_localhost ="localhost";
   $database_localhost ="mydatabase";
   $username_localhost ="root";
   $password_localhost ="apmsetup";
   $localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
        or
   trigger_error(mysql_error(),E_USER_ERROR);
 
   mysql_select_db($database_localhost, $localhost);
 
   $userID = $_POST['userID'];
 
   // 쿼리 실행 결과를 $result에 저장
   $query_search = "select * from tbl_user where userID = '$userID'";
   $result = mysql_query($query_search) or die(mysql_error());
   $rows = mysql_num_rows($result);

   // JSONArray 형식으로 만들기 위해서...
   echo "{\"status\":\"OK\",\"num_results\":\"$rows\",\"results\":[";
 
   // 반환된 각 레코드별로 JSONArray 형식으로 만들기.
   if($rows!=0)                    
   {
      // 가져올 레코드로 위치(포인터) 이동       
      $row = mysql_fetch_array($result);
      echo "\"Name\":$row[userName],\"Gender\":$row[userGender],\"Height\":\"$row[userHeight]\",\"Weight\":\"$row[userWeight]\"}";
 
      // 마지막 레코드 이전엔 ,를 붙인다. 그래야 데이터 구분이 되니깐.  
   }

   // JSONArray의 마지막 닫기
   echo "]}";
?>


public class Userpage extends Activity {

    ImageView imView;
    TextView txtView;
    phpDown task;
    String ID = Gloval.getID();
    List<NameValuePair> nameValuePairs;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_userpage);
        task = new phpDown();    
        txtView = (TextView)findViewById(R.id.txtView);
        task.execute("http://164.125.69.83:80/read.php");
    }
   
private class phpDown extends AsyncTask<String, Integer,String>{
        @Override
        protected String doInBackground(String... urls) {
          HttpClient httpclient = new DefaultHttpClient(); 
             StringBuilder builder = new StringBuilder();
             HttpPost httppost = new HttpPost(urls[0]); 
             try { 
              nameValuePairs = new ArrayList<NameValuePair>(2);
                 // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar, 
                 nameValuePairs.add(new BasicNameValuePair("userID",ID.toString().trim()));  // $Edittext_value = $_POST['Edittext_value'];
                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
              HttpResponse response = httpclient.execute(httppost); 
                 StatusLine statusLine = response.getStatusLine();
              int statusCode = statusLine.getStatusCode();
              if (statusCode == 200) {
               HttpEntity entity = response.getEntity();
               InputStream content = entity.getContent();
               BufferedReader reader = new BufferedReader(new InputStreamReader(content));
               String line;
               while ((line = reader.readLine()) != null) {
                builder.append(line);
               }
              } 
             } catch (Exception e) {
              e.printStackTrace();
             }    
             return builder.toString();          
        }
        protected void onPostExecute(String result) {
         String state="";
            String stateInfo="";
            try{
             JSONArray countriesArray = new JSONArray(result);        
                   for (int i =0 ; i<countriesArray.length();i++) {
                       JSONObject jObject = countriesArray.getJSONObject(i);
                       state = jObject.getString("state"); 
                       stateInfo+="Name: "+jObject.getString("userName")+"\n"; 
                       stateInfo+="Gender: "+jObject.getString("userGender")+"\n"; 
                       stateInfo+="Height: "+jObject.getString("userHeight")+"\n"; 
                       stateInfo+="Weight: "+jObject.getString("userWeight")+"\n"; 
                   }
            }
             catch (JSONException e) { 
                 e.printStackTrace(); 
                 } 
            if(stateInfo.trim().length() >0 )
             txtView.setText(stateInfo);    
            else
               txtView.setText("Sorry no match found");
        }
    }
}

메인 액티비티에서 저장된 글로벌 ID 값을 String ID에 넣어서 이걸 read.php 파일에 전달해 DB에서 똑같은 아이디의 정보를 가져와 JSON 파서로 출력하려고 합니다. 그런데 계속 Sorry no match found만 뜨네요...

sd156 (200 포인트) 님이 2014년 5월 22일 질문

1개의 답변

0 추천
단계적으로 확인해 보세요...

POST 방식을 사용하셨으니 ..POST Man 같은 걸로.. 웹브라우져에서 서버에서

보내주는 내용을 확인 하시던지...

아니면..Fiddler 를 통해서 확인하시던지..

 

확인할 내용은 서버쪽에서 제대로 Json 타입의 데이터를 내려주는지..

클라이언트에서 제대로 파씽하는지..확인하셔야 됩니다.
아즈라엘 (4,010 포인트) 님이 2014년 5월 22일 답변
...