###前提・実現したいこと
ログイン機能作成のためphpとAndroidの連携をしようとしており、idとpassのデータをphpに送り、ログイン結果を返そうとしているのですが、結果が帰ってこないようで困っています。開発はAndroidStudioでしています。
phpはunityの今回のプログラムとは別のものではPC上でもAndroid上でも正常に動作しました。
###ソースコード
###Title.java
public class Title extends Activity { public static TextView err; SpannableStringBuilder id,pass; public static String result = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_title); ImageView imageView2 = (ImageView) findViewById(R.id.imageView); imageView2.setImageResource(R.drawable.title); // ボタンを設定 Button button = (Button) findViewById(R.id.login); // TextView の設定 err = (TextView) findViewById(R.id.err); // リスナーをボタンに登録 button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText edit = (EditText) findViewById(R.id.user_id); id = (SpannableStringBuilder) edit.getText(); EditText edit2 = (EditText) findViewById(R.id.pass); pass = (SpannableStringBuilder) edit2.getText(); String id2 = id.toString(); String pass2 = pass.toString(); asynctask_job(id2,pass2,"example.com"); } }); } // 非同期処理を開始する private void asynctask_job(String id, String pass, String base_url){ final MyAsync Asynctask = new MyAsync(this); //実行 Asynctask.execute(id,pass, base_url); if(result != null && result.equals("[]")){ String tmp = "ID,パスワードが違います。"; // TextView の設定 err = (TextView) findViewById(R.id.err); err.setText(tmp); } } }
###MyAsync.java
public class MyAsync extends AsyncTask<String,String,String> { private Title _main; public MyAsync(Title main) { super(); _main = main; } @Override protected String doInBackground(String...value) { android.os.Debug.waitForDebugger(); String id = value[0]; String pass = value[1]; String base_url = value[2]; BufferedReader reader = null; OutputStream os = null; HttpURLConnection urlCon = null; try { URL url = new URL(base_url); urlCon = (HttpURLConnection) url.openConnection(); urlCon.setReadTimeout(10000); urlCon.setConnectTimeout(20000); urlCon.setRequestMethod("POST"); urlCon.setDoInput(true); urlCon.setDoOutput(true); urlCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlCon.setUseCaches(false); urlCon.connect(); JSONObject jsonObject = new JSONObject(); jsonObject.put("id", id); jsonObject.put("pass", pass); // データを送信する os = urlCon.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(String.valueOf(jsonObject)); writer.flush(); writer.close(); os.close(); int status = urlCon.getResponseCode(); switch (status) { case HttpURLConnection.HTTP_OK: InputStream is = urlCon.getInputStream(); reader = new BufferedReader(new InputStreamReader(is)); String httpSource = new String(); String str; while (null != (str = reader.readLine())) { httpSource = httpSource + str; } is.close(); break; case HttpURLConnection.HTTP_UNAUTHORIZED: break; default: break; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } if (os != null) { os.close(); } if (urlCon != null) { urlCon.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } try { BufferedInputStream inputStream = null; inputStream = new BufferedInputStream(urlCon.getInputStream()); ByteArrayOutputStream responseArray = new ByteArrayOutputStream(); byte[] buff = new byte[1024]; int length; while((length = inputStream.read(buff)) != -1) { if(length > 0) { responseArray.write(buff, 0, length); } } // JSONをパース StringBuilder viewStrBuilder = new StringBuilder(); JSONObject jsonObj = new JSONObject(new String(responseArray.toByteArray())); JSONArray result = jsonObj.getJSONArray("result"); for(int i = 0; i < result.length(); i++) { JSONObject tweet = result.getJSONObject(i); viewStrBuilder.append(tweet.getString("id")); // result } Title.result = viewStrBuilder.toString(); }catch (Exception e) { e.printStackTrace(); } return null; } }
###login.php
<?php header('Content-type:application/json;charset=UTF-8'); define('DB_USERNAME', '???'); define('DB_PASSWORD', '???'); define('DB_DATABASE', '???'); define('PDO_DSN', 'mysql:host=???;dbname='.DB_DATABASE.';charset=utf8'); error_reporting(0); $user_id =$_POST["id"]; $pass = $_POST["pass"]; try{ $db = new PDO(PDO_DSN,DB_USERNAME,DB_PASSWORD); $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); $sql = "select user_id from users where user_id = :user_id and user_pass = :pass"; $stmt = $db->prepare($sql); $stmt->bindParam(":pass",$pass); $stmt->bindParam(":user_id",$user_id); $stmt->execute(); $result= array(); while($row = $stmt->fetch()){ $result[] = array( 'id'=>$row["user_id"] ); } echo json_encode($result); $db = null; }catch(PDOException $e){ exit; } ?>
###補足情報(言語/FW/ツール等のバージョンなど)
AndroidStudio2.2
Nexus5(Android 6.0 Marshmallow)
windows10