Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在json中成功登录?_Java_Android_Json - Fatal编程技术网

Java 如何在json中成功登录?

Java 如何在json中成功登录?,java,android,json,Java,Android,Json,我试图在Android中使用post方法,借助JSON实现登录和注册表单。当我注册并输入详细信息时,它已成功注册,数据已显示在我的本地主机服务器中;当我登录时,输入错误的用户名和密码,它在toast中显示错误的详细信息,输入正确的详细信息,它在toast中显示登录成功;但当我输入正确的详细信息时,它将转到另一个活动。输入错误的详细信息只显示toast。代码如下:- MainActivity.java public class MainActivity extends Activity {

我试图在Android中使用post方法,借助JSON实现登录和注册表单。当我注册并输入详细信息时,它已成功注册,数据已显示在我的本地主机服务器中;当我登录时,输入错误的用户名和密码,它在toast中显示错误的详细信息,输入正确的详细信息,它在toast中显示登录成功;但当我输入正确的详细信息时,它将转到另一个活动。输入错误的详细信息只显示toast。代码如下:-

MainActivity.java

public class MainActivity extends Activity {
    public static HashMap<Sound, MediaPlayer> SOUND_MAP=
            new HashMap<Sound, MediaPlayer>();
    public static int userScore= 0, computerScore=0,
            buddyBoxId = 1, computerBoxId = 1;
    public static Context CTX;
    Button play;
    private static final String TAG = "LoginActivity";
    String URL = "http://10.0.2.2/test_android/index.php";
    JSONParser jsonParser=new JSONParser();
    ProgressDialog progressDialog;
    TextView register_caption;
    AdView adView = null;
    private AdView mAdView;
    EditText username, password;
    Button btnSignIn, btnRegister;
    ImageView fb;
    int i=0;
    private AdRequest adRequest;
    InterstitialAd mInterstitialAd;

    static MediaPlayer media;
    static Handler mediaHandler;
    public static int stat=0, totTurn = 0, maxEnd = 100;
    public static SharedPreferences configs;
    public static SharedPreferences.Editor configuration;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        username = (EditText) findViewById(R.id.email);
        password = (EditText)findViewById(R.id.passwordd);
        btnSignIn = (Button) findViewById(R.id.play);
        register_caption = (TextView) findViewById(R.id.register_caption);
        fb = (ImageButton) findViewById(R.id.btnfb);
        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);



        btnSignIn.setOnClickListener(new View.OnClickListener() {
                                         @Override
                                         public void onClick(View view) {
                                             AttemptLogin attemptLogin = new AttemptLogin();
                                             attemptLogin.execute(username.getText().toString(), password.getText().toString(), "");
                                         }
                                     });

        register_caption.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent in = new Intent(MainActivity.this,Registration.class);
                startActivity(in);


            }
        });

        CTX = getApplicationContext();
        configs = CTX. getSharedPreferences("snake_n_ladder", 0);
        configuration = configs.edit();
        loadConfig();
        loadMedia();
    }
    private class AttemptLogin extends AsyncTask<String, String, JSONObject> {

        @Override

        protected void onPreExecute() {

            super.onPreExecute();

        }

        @Override

        protected JSONObject doInBackground(String... args) {


            String email = args[2];
            String password = args[1];
            String name = args[0];

            ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", name));
            params.add(new BasicNameValuePair("password", password));
            if (email.length() > 0)
                params.add(new BasicNameValuePair("email", email));

            JSONObject json = jsonParser.makeHttpRequest(URL, "POST", params);


            return json;

        }

        protected void onPostExecute(JSONObject result) {

            // dismiss the dialog once product deleted
            //Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
            try {
                if (result != null) {
                    Toast.makeText(getApplicationContext(), result.getString("message"), Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Unable to retrieve any data from server", Toast.LENGTH_LONG).show();

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

            }


        }

    }
公共类MainActivity扩展活动{
公共静态哈希映射声音映射=
新的HashMap();
公共静态int userScore=0,computerScore=0,
buddyBoxId=1,computerBoxId=1;
公共静态上下文;
按钮播放;
私有静态最终字符串TAG=“LoginActivity”;
字符串URL=”http://10.0.2.2/test_android/index.php";
JSONParser JSONParser=新的JSONParser();
进行对话进行对话;
文本视图寄存器标题;
AdView AdView=null;
私人顾问马德维尤;
编辑文本用户名、密码;
按钮btnSignIn,BTN注册表;
ImageView fb;
int i=0;
私人信件;
间质间隙;
静态媒体播放器媒体;
静态处理程序mediaHandler;
公共静态int stat=0,totTurn=0,maxEnd=100;
公共静态SharedReferences配置;
公共静态SharedReferences.Editor配置;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u登录);
用户名=(编辑文本)findViewById(R.id.email);
密码=(EditText)findViewById(R.id.passwordd);
btnSignIn=(按钮)findviewbyd(R.id.play);
register\u caption=(TextView)findViewById(R.id.register\u caption);
fb=(ImageButton)findViewById(R.id.btnfb);
progressDialog=新建progressDialog(此);
progressDialog.setCancelable(假);
setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
AttemptLogin AttemptLogin=新的AttemptLogin();
attemptLogin.execute(username.getText().toString(),password.getText().toString(),“”);
}
});
register\u caption.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
Intent in=新的Intent(MainActivity.this,Registration.class);
星触觉(in);
}
});
CTX=getApplicationContext();
configs=CTX.getSharedReferences(“蛇梯”,0);
configuration=configs.edit();
loadConfig();
loadMedia();
}
私有类AttemptLogin扩展异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
}
@凌驾
受保护的JSONObject doInBackground(字符串…args){
字符串email=args[2];
字符串密码=args[1];
字符串名称=args[0];
ArrayList params=新的ArrayList();
添加(新的BasicNameValuePair(“用户名”,名称));
添加(新的BasicNameValuePair(“密码”,password));
如果(email.length()>0)
参数添加(新的BasicNameValuePair(“电子邮件”),电子邮件);
JSONObject json=jsonParser.makeHttpRequest(URL,“POST”,参数);
返回json;
}
受保护的void onPostExecute(JSONObject结果){
//删除产品后关闭对话框
//Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG.show();
试一试{
如果(结果!=null){
Toast.makeText(getApplicationContext(),result.getString(“消息”),Toast.LENGTH_LONG.show();
}否则{
Toast.makeText(getApplicationContext(),“无法从服务器检索任何数据”,Toast.LENGTH_LONG.show();
}
}捕获(JSONException e){
e、 printStackTrace();
}
}
}
JsonParser.java

public class JSONParser {


    static InputStream is = null;
    static JSONObject jObj = null;
    static JSONArray jArr = null;
    static String json = "";
    static String error = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
                                      ArrayList<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method.equals("POST")){
                // request method is POST
                // defaultHttpClient
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));
                try {
                    Log.e("API123", " " +convertStreamToString(httpPost.getEntity().getContent()));
                    Log.e("API123",httpPost.getURI().toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                HttpResponse httpResponse = httpClient.execute(httpPost);
                Log.e("API123",""+httpResponse.getStatusLine().getStatusCode());
                error= String.valueOf(httpResponse.getStatusLine().getStatusCode());
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method.equals("GET")){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                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();
            Log.d("API123",json);
        } 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);
            jObj.put("error_code",error);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }

    private String convertStreamToString(InputStream is) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        is.close();
        return sb.toString();
    }

}
公共类JSONParser{
静态InputStream为空;
静态JSONObject jObj=null;
静态JSONArray jArr=null;
静态字符串json=“”;
静态字符串错误=”;
//建造师
公共JSONParser(){
}
//函数从url获取json
//通过使用HTTP POST或GET方法
公共JSONObject makeHttpRequest(字符串url、字符串方法、,
ArrayList参数){
//发出HTTP请求
试一试{
//检查请求方法
if(方法等于(“POST”)){
//请求方法为POST
//defaultHttpClient
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
setEntity(新的UrlEncodedFormEntity(参数));
试一试{
Log.e(“API123”,“convertStreamToString(httpPost.getEntity().getContent()));
Log.e(“API123”,httpPost.getURI().toString());
}捕获(例外e){
e、 printStackTrace();
}
HttpResponse HttpResponse=httpClient.execute(httpPost);
Log.e(“API123”,“”+httpResponse.getStatusLine().getStatusCode());
error=String.valueOf(httpResponse.getStatusLine().getStatusCode());
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}else if(method.equals(“GET”)){
//请求方法是
    protected void onPostExecute(JSONObject result) {

 try {
if (result != null) 
{
        if(result.getString("message").equals("Successfully logged in"))
        {
           Intent intent = new Intent(ThisActivity.this,NewActivity.class);
            startActivity(intent);
            finish();
        }
        else
        {
        Toast.makeText(this,"Invalid credentials",Toast.LENGTH_LONG).show();
        } 
} 
else 
{
   Toast.makeText(getApplicationContext(), "Unable to retrieve any data from 
server", Toast.LENGTH_LONG).show();
}
 } catch (JSONException e) {
            e.printStackTrace();
        }
    }