2016-09-24 22 views
1

私はAndroidアプリケーションの開発の初心者です。アプリケーションをサーバーに接続したいので、MySQLからデータを取得できました。だから私はログイン部分を最初にしようとしましたが、いくつかの問題があります。私のコードはJSONを読むためには機能しません。 私のコードは以下の通りです: LoginActivity(MainActivity):アンドロイドアプリケーションのPHPファイルからJSONデータを読み取る

package ir.naserpour.sportclub; 

import android.content.Context; 
import android.graphics.Typeface; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.view.View; 
import android.widget.Button; 
import android.widget.CheckBox; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.io.UnsupportedEncodingException; 

import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; 

public class LoginActivity extends AppCompatActivity { 

    String link; 
    String response; 
     //get values 
     String username,password; 
     @Override 
     protected void attachBaseContext (Context newBase){ 
     super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); 
    } 
     @Override 
     protected void onCreate (Bundle savedInstanceState){ 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_login); 
      //define things 
      TextView menu = (TextView) findViewById(R.id.menu); 
      final EditText login_username = (EditText) findViewById(R.id.login_username); 
      final EditText login_password = (EditText) findViewById(R.id.login_password); 
      Button login_login = (Button) findViewById(R.id.login_login); 
      Button login_register = (Button)findViewById(R.id.login_register); 
      CheckBox rememberme = (CheckBox)findViewById(R.id.login_remeberme); 


     //set icon type face 
     Typeface fonticon = Typeface.createFromAsset(getAssets(), "fonts/icon.ttf"); 
     menu.setTypeface(fonticon); 

     login_login.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       username = login_username.getText().toString(); 
       password = login_password.getText().toString(); 
       //check values 
       if (username.length() <1 || password.length() < 1) { 
        Toast.makeText(getApplicationContext(), "fields cannot be empty", Toast.LENGTH_SHORT).show(); 
       } else { 
        //generate link 
        link = "http://localhost:8080/login.php?username="+username+"&password="+password; 
        login(); 
        if(response=="true"){ 
         Toast.makeText(getApplicationContext(), "true", Toast.LENGTH_SHORT).show(); 
        }else if(response=="false"){ 
         Toast.makeText(getApplicationContext(), "false", Toast.LENGTH_SHORT).show(); 
        }else{ 
         Toast.makeText(getApplicationContext(), "response", Toast.LENGTH_SHORT).show(); 
        } 
       } 
      } 
     }); 


    } 

     @Override 
     protected void onPause() { 
     super.onPause(); 
     finish(); 
    } 

    public String login() { 

     new JSONParse().execute(); 
     return response; 
    } 

    public class JSONParse extends AsyncTask<String, String, JSONObject> { 


     @Override 
     public void onPreExecute() { 
      super.onPreExecute(); 
      Toast.makeText(getApplicationContext(),"getting data ...",Toast.LENGTH_SHORT).show(); 
     } 

     @Override 
     public JSONObject doInBackground(String... args) { 
      JSONParser jParser = new JSONParser(); 
      // Getting JSON from URL 
      JSONObject json = jParser.getJSONFromUrl(link); 
      return json; 
     } 

     @Override 
     public void onPostExecute(JSONObject json) { 
      try { 
       JSONArray result = json.getJSONArray("result"); 
       JSONObject c = result.getJSONObject(0); 
       try { 
        String res = new String(c.getString("response").getBytes("ISO-8859-1"), "UTF-8"); 
        response = res; 
       } catch (UnsupportedEncodingException e) { 
        e.printStackTrace(); 
       } 

      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

     } 
    } 
} 

JSONParser.java:

package ir.naserpour.sportclub; 

import android.util.Log; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 

/** 
* Created by Mohammad Naserpour on 9/22/2016. 
*/ 
public class JSONParser { 
    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 
    // constructor 
    public JSONParser() { 
    } 
    public JSONObject getJSONFromUrl(String url) { 
     // Making HTTP request 
     try { 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(url); 
      HttpResponse httpResponse = httpClient.execute(httppost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 
     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      json = sb.toString(); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 
     // try parse the string to a JSON object 
     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 
     // return JSON String 
     return jObj; 
    } 
} 

とも私のlogin.phpスクリプト:

<?php 
define("HOST","localhost"); 
define("USERNAME","root"); 
define("PASSWORD",""); 
define("NAME","users"); 

$con = mysqli_connect(HOST,USERNAME,PASSWORD,NAME); 

$username = $_GET["username"]; 
$password = $_GET["password"]; 

$sql = "SELECT * FROM userinfo WHERE username ='$username' AND password='$password'"; 

$check = mysqli_fetch_array(mysqli_query($con,$sql)); 


if(isset($check)){ 
echo '{"result":[{"response":"true"}]}'; 
}else{ 
echo '{"result":[{"response":"false"}]}'; 
} 

mysqli_close($con); 

?> 

私はそうだろう私が問題を見つけたらうれしい。ありがとうございました。

+0

ソリューションでは正確には動作しません。あなたのコードをデバッグしようとしましたか? – Egor

+0

@エゴご存じの通り、私は基本的なものだと言った。正直なところいいえ、私はしませんでしたが、私は次の時間に尋ねる前にやります。 –

答えて

0

まず使用してログインプロセスについて、その完全なチュートリアル:そのシンプルで

セカンドを使用して簡単にデバイス側では、使用ボレー、:サーバー上で、{"result":[{"response":"true"}]}

何を

{"result":true}に問題がありますか?

最後にJSONを使用しましたか、このコードはいくつかのチュートリアルから試してエラーコピーの貼り付けですか?

+0

私は2番目の(結果:真)を試みたが、私は答えが得られなかった、私はjson配列でその1つを試みた。最後の1つ:jsonエンコードの必要がなかったので、私はそれを自分で書きます。私は何か悪いことをした? –

+0

まず第一に、単一の応答のためにjsonarrayを使用しないでください。あなたの応答があなたのデバイスでどのように受信されるかが決定されます。あなたがjsonを文字列として渡している場合は、デバイス上の文字列を解析する必要があります。オブジェクトをjsonとして送信すると、デバイス上で直接オブジェクトを受け取ることができます。後者は提案されています。 –

関連する問題