2016-11-07 214 views
0

我在登錄時遇到問題。如果你解決了這個問題,我將不勝感激。我無法登錄。我不能找出錯誤在此,請告訴我的錯誤,如果任何一個有登錄失敗,錯誤

這是我的登錄代碼:

package com.solodroid.ecommerce; 

import android.app.ActionBar; 



import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.EditText; 
import android.widget.Toast; 

import org.apache.http.NameValuePair; 
import org.apache.http.cookie.Cookie; 
import org.apache.http.message.BasicNameValuePair; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.util.ArrayList; 
import java.util.List; 
import java.util.Map; 
import java.util.Set; 

public class Executive_Login extends Activity { 

    // Progress Dialog 
    private ProgressDialog pDialog; 
    int flag = 1; 
    JSONParser jsonParser = new JSONParser(); 
    EditText inputName; 
    EditText inputPassword; 
    ExecutiveSessionManager session; 


    public static final String EMAIL = "email"; 

    // url to create new product 
    private static String url_create_product = "http://www.topwebdevcompany.com/app/api/executive-login.php"; 

    // JSON Node names 
    private static final String TAG_SUCCESS = "success"; 


    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_executive__login); 

     session = new ExecutiveSessionManager(getApplicationContext()); 


     ActionBar actionBar = getActionBar(); 
     actionBar.hide(); 

     // Edit Text 
     inputName = (EditText) findViewById(R.id.email); 
     inputPassword = (EditText) findViewById(R.id.pass); 

/* 
     // Create button 
     Button btnCreateProduct = (Button) findViewById(R.id.login); 

     // button click event 
     btnCreateProduct.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View view) { 
       // creating new product in background thread 
       new CreateNewProduct().execute(); 
      } 
     }); 
*/ 
    } 

    public void checkLogin(View v) { 

     //if(session.getUserName(LoginActivity.this).length()==0) 
     //{ 
     new CreateNewProduct().execute(); 
     //}// 
     //else 
     // { 
     //Intent i = new Intent(LoginActivity.this,MainActivity.class); 
     // startActivity(i); 
     //} 
    } 


    /** 
    * Background Async Task to Create new product 
    */ 
    class CreateNewProduct extends AsyncTask<String, String, String> { 

     /** 
     * Before starting background thread Show Progress Dialog 
     */ 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(Executive_Login.this); 
      pDialog.setMessage("Logging In.."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
     } 

     /** 
     * Creating product 
     */ 
     protected String doInBackground(String... args) { 
      String name = inputName.getText().toString(); 
      String password = inputPassword.getText().toString(); 


      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 
      params.add(new BasicNameValuePair("gmail", name)); 
      params.add(new BasicNameValuePair("password", password)); 


      // getting JSON Object 
      // Note that create product url accepts POST method 
      JSONObject json = jsonParser.makeHttpRequest(url_create_product, 
        "POST", params); 

      // check log cat fro response 
      Log.d("Create Response", json.toString()); 

      // check for success tag 
      try { 
       int success = json.getInt(TAG_SUCCESS); 

       if (success == 1) { 
        // successfully created product 
        flag = 0; 

        session.createUserLoginSession("Android Example", 
          name); 

        Intent i = new Intent(getApplicationContext(), Dealer.class); 
        i.putExtra("email", name); 
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

        // Add new Flag to start new Activity 
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
        startActivity(i); 

        // closing this screen 
        finish(); 
       } else { 
        flag = 1; 
        // username/password doesn't match& 
        Toast.makeText(getApplicationContext(), 
          "Username/Password is incorrect", 
          Toast.LENGTH_LONG).show(); 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

      return null; 
     } 

     /** 
     * After completing background task Dismiss the progress dialog 
     **/ 
     protected void onPostExecute(String file_url) { 
      // dismiss the dialog once done 
      pDialog.dismiss(); 
      if (flag == 1) 
       Toast.makeText(Executive_Login.this, "Please Enter Correct informations", Toast.LENGTH_LONG).show(); 
     } 

    } 
} 

My executivesessionmanager code is: 
package com.solodroid.ecommerce; 

import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 

import java.util.HashMap; 

/** 
* Created by hp-pc on 10/28/2016. 
*/ 
public class ExecutiveSessionManager { 

    SharedPreferences pref; 
    SharedPreferences.Editor editor; 
    Context _context; 
    int PRIVATE_MODE = 0; 

    private static final String PREFER_NAME = "AndroidExamplePref"; 
    private static final String IS_USER_LOGIN = "IsUserLoggedIn"; 
    public static final String KEY_NAME = "name"; 
    public static final String KEY_EMAIL = "email"; 

    public ExecutiveSessionManager(Context context){ 
     this._context = context; 
     pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE); 
     editor = pref.edit(); 
    } 
    public void createUserLoginSession(String name, String email){ 
     // Storing login value as TRUE 
     editor.putBoolean(IS_USER_LOGIN, true); 

     // Storing name in pref 
     editor.putString(KEY_NAME, name); 

     // Storing email in pref 
     editor.putString(KEY_EMAIL, email); 

     // commit changes 
     editor.commit(); 
    } 

    public boolean checkLogin(){ 
     // Check login status 
     if(!this.isUserLoggedIn()){ 

      // user is not logged in redirect him to Login Activity 
      Intent i = new Intent(_context, Executive_Login.class); 

      // Closing all the Activities from stack 
      i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

      // Add new Flag to start new Activity 
      i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

      // Staring Login Activity 
      _context.startActivity(i); 

      return true; 
     } 
     return false; 
    } 
    public HashMap<String, String> getUserDetails(){ 

     //Use hashmap to store user credentials 
     HashMap<String, String> user = new HashMap<String, String>(); 

     // user name 
     user.put(KEY_NAME, pref.getString(KEY_NAME, null)); 

     // user email id 
     user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null)); 

     // return user 
     return user; 
    } 
/*static SharedPreferences getSharedPreferences(Context ctx) 
{ 
    return PreferenceManager.getDefaultSharedPreferences(ctx); 
} 
    public static void setUserName(Context ctx,String username) 
    { 
     SharedPreferences.Editor ed = getSharedPreferences(ctx).edit(); 
     ed.putString(PREFER_NAME ,username); 
     ed.commit(); 
    } 

    public static String getUserName(Context ctx) { 
     return getSharedPreferences(ctx).getString(PREFER_NAME,""); 
    } 

    { 

    }*/ 
    /** 
    * 
    * Clear session details 
    * */ 
    public void logoutUser(){ 

     // Clearing all user data from Shared Preferences 
     editor.clear(); 
     editor.commit(); 

     // After logout redirect user to Login Activity 
     Intent i = new Intent(_context, Executive_Login.class); 

     // Closing all the Activities 
     i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

     // Add new Flag to start new Activity 
     i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

     // Staring Login Activity 
     _context.startActivity(i); 
    } 


    // Check for login 
    public boolean isUserLoggedIn(){ 
     return pref.getBoolean(IS_USER_LOGIN, true); 
    } 


} 
and my xml file is : 

「如果任何人能告訴什麼是在這個代碼中的錯誤,因爲後點擊登錄按鈕我就出來了應用 的這thorugh我已經做了解析各個文件的JSONParser的代碼....

package com.solodroid.ecommerce; 

import android.util.Log; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.utils.URLEncodedUtils; 
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; 
import java.util.List; 

public class JSONParser { 

    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 

    // constructor 
    public JSONParser() { 

    } 

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

     // Making HTTP request 
     try { 

      // check for request method 
      if(method == "POST"){ 
       // request method is POST 
       // defaultHttpClient 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       HttpPost httpPost = new HttpPost(url); 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 

       HttpResponse httpResponse = httpClient.execute(httpPost); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 

      }else if(method == "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(); 
     } 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; 

    } 

    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; 

    } 
} 
+3

告訴我們一個logcat錯誤 –

+2

您是否檢查logcat.Error/Message? – Jayshree

+2

請提供錯誤日誌 –

回答

0

您可以嘗試解析這樣...發佈兩個POST和GET方法。

import android.content.Context; 

import com.kspl.kard.R; 
import com.kspl.kard.constant.Constants; 
import com.kspl.kard.util.SharedPrefUtil; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.OutputStreamWriter; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.ProtocolException; 
import java.net.SocketException; 
import java.net.URL; 
import java.net.UnknownHostException; 

/** 
* Created by vivek on 17/5/16. 
*/ 
public class HttpServerConnection implements Constants{ 

    private StringBuilder response; 
    private StringBuilder responseOutput; 
    private String uri; 
    private Context context; 
    private String TAG = "HttpServerConnection"; 
    private static HttpURLConnection httpConn; 

    public HttpServerConnection(Context context) 
    { 
     this.context = context; 
     this.response = new StringBuilder(); 
     this.responseOutput = new StringBuilder(); 
    } 

    public String getParsedData(String jsonData, String method_name, String server_method, String header_value) 
    { 
     try 
     { 
      URL url = new URL(BASE_URL + method_name); 
      httpConn = (HttpURLConnection) url.openConnection(); 
      httpConn.setUseCaches(false); 
      httpConn.setConnectTimeout(100000); 
      httpConn.setDoInput(true); 
      httpConn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); 
      if(header_value.equalsIgnoreCase("yes")) 
      { 
       httpConn.setRequestProperty("X-Mobile-No", SharedPrefUtil.getSharedPref(context, "mobile_no", "")); 
       httpConn.setRequestProperty("X-GCM-Id", SharedPrefUtil.getSharedPref(context, context.getResources().getString(R.string.sp_gcm_id), "", "gcm")); 
       httpConn.setRequestProperty("X-Device-Id", SharedPrefUtil.getSharedPref(context, context.getResources().getString(R.string.dev_id), "", "dev_id")); 
      } 
      /**/ 
      httpConn.setRequestMethod(server_method); // This will be based on 

      if (jsonData != null && jsonData.length() > 0) 
      { 
       httpConn.setRequestProperty("Content-Length", Integer.toString(jsonData.length())); 
       OutputStream os = httpConn.getOutputStream(); 
       OutputStreamWriter outputStreamWriter = new OutputStreamWriter(os, "UTF-8"); 
       outputStreamWriter.write(jsonData); 
       outputStreamWriter.close(); 
      } 
      else 
      { 
       httpConn.setRequestProperty("Content-Length", String.valueOf(2)); 
       OutputStream os = httpConn.getOutputStream(); 
       OutputStreamWriter outputStreamWriter = new OutputStreamWriter(os, "UTF-8"); 
       outputStreamWriter.write("{}"); 
       outputStreamWriter.close(); 
      } 

      int responseCode = httpConn.getResponseCode(); 
      if(responseCode == 200) 
      { 
       InputStream inputStream = null; 
       if (httpConn != null) { 
        inputStream = httpConn.getInputStream(); 
       } else { 
        throw new IOException("Connection is not established."); 
       } 

       String line; 
       BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); 
       while ((line = reader.readLine()) != null) { 
        response.append(line); 
       } 
       reader.close(); 
      } 
      else if(responseCode == 401) 
      { 
       response.append("{\"code\":401,\"message\":\" User session expired. Please Re-login.\",\"status\":false}"); 
      } 
      else 
      { 
       InputStream inputStream = null; 
       if (httpConn != null) 
       { 
        inputStream = httpConn.getErrorStream(); 
       } 
       else 
       { 
        throw new IOException("Connection is not established."); 
       } 

       String line; 
       BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); 
       while ((line = reader.readLine()) != null) { 
        response.append(line); 
       } 
       reader.close(); 
      } 
      System.out.println("=========== MAIN SERVER RESPONSE ============== " + response.toString()); 
      if (httpConn != null) 
       httpConn.disconnect(); 
     } catch (UnknownHostException one) { 
      response.append("{\"code\":0,\"message\":\"No internet connection. Please try after some time.\",\"status\":false}"); 
      //response.append("{\"message\":" + context.getResources().getString(R.string.server_1) + ",\"status\":\"error\"}"); 
     } catch (SocketException two) { 
      response.append("{\"code\":0,\"message\":\" Seems like we are not able to sync with server. Please try after some time. \",\"status\":false}"); 
      //response.append("{\"message\":" + context.getResources().getString(R.string.server_2) + ",\"status\":\"error\"}"); 
     } catch (Exception three) { 
      response.append("{\"code\":0,\"message\":\" Server error. Please try after some time. \",\"status\":false}"); 
      //response.append("{\"message\":" + context.getResources().getString(R.string.server_3) + ",\"status\":\"error\"}"); 
     } 
     return response.toString(); 
    } 

    // Get Request 
    public String getParedDatGet(String complete_url, String need_header) 
    { 
     String get_response = null; 
     URL url = null; 
     try 
     { 
     url = new URL(complete_url); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
      connection.setUseCaches(false); 
      connection.setConnectTimeout(100000); 
      connection.setDoInput(true); 
      connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); 


     /*connection.setRequestProperty("USER-AGENT", "Mozilla/5.0"); 
     connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");*/ 

     if(need_header.equalsIgnoreCase("yes")) 
     { 
      connection.setRequestProperty("X-Mobile-No", SharedPrefUtil.getSharedPref(context, "mobile_no", "")); 
      connection.setRequestProperty("X-GCM-Id", SharedPrefUtil.getSharedPref(context, context.getResources().getString(R.string.sp_gcm_id), "")); 
      connection.setRequestProperty("X-Device-Id", SharedPrefUtil.getSharedPref(context, context.getResources().getString(R.string.dev_id), "")); 
     } 

     connection.setRequestMethod("GET"); 

     int responseCode = connection.getResponseCode(); 

     switch (responseCode) 
     { 
      case 200: 
       final StringBuilder output = new StringBuilder("Request URL " + url); 
       output.append(System.getProperty("line.separator") + "Response Code " + responseCode); 
       output.append(System.getProperty("line.separator") + "Type " + "GET"); 
       BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
       String line = ""; 
       responseOutput = new StringBuilder(); 
       System.out.println("output===============" + br); 
       while((line = br.readLine()) != null) { 
        responseOutput.append(line); 
       } 
       br.close(); 

       output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString()); 

       get_response = responseOutput.toString(); 
       System.out.println("========== GET RESPONSE IS ======== " + get_response); 
       break; 

      case 401: 
       responseOutput.append("{\"code\":401,\"message\":\" User session expired. Please Re-login.\",\"status\":false}"); 
       get_response = responseOutput.toString(); 
       break; 
      default: 

       break; 
     } 


     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
      get_response = ""; 
     } catch (ProtocolException e) { 
      e.printStackTrace(); 
      get_response = ""; 
     } catch (IOException e) { 
      e.printStackTrace(); 
      get_response = ""; 
     } 

     return get_response; 
    } 

} // End of server connection class over here ... 

如果需要,您還可以修改代碼。您可能必須更改獲取請求方式的代碼。對於例如:我在這裏以JSON對象的形式提出請求。

乾杯! Vivek

0

正如我所看到的,您已經實現了doInBackground中應該用於onPostExecute方法的一些代碼。我修改了一些你的代碼。使用您的登錄憑據。可能會對你有用。使用您的JSONParser類相同。

public class Executive_Login extends Activity { 

    // Progress Dialog 
    private ProgressDialog pDialog; 
    int flag = 1; 
    JSONParser jsonParser = new JSONParser(); 
    EditText inputName; 
    EditText inputPassword; 
    ExecutiveSessionManager session; 
    String name; 
    String password; 

    public static final String EMAIL = "email"; 

    // url to create new product 
    private static String url_create_product = "http://www.topwebdevcompany.com/app/api/executive-login.php"; 

    // JSON Node names 
    private static final String TAG_SUCCESS = "success"; 


    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_executive__login); 

     session = new ExecutiveSessionManager(getApplicationContext()); 


//  ActionBar actionBar = getActionBar(); 
//  actionBar.hide(); 

     // Edit Text 
     inputName = (EditText) findViewById(R.id.email); 
     inputPassword = (EditText) findViewById(R.id.pass); 

     // Create button 
     Button btnCreateProduct = (Button) findViewById(R.id.login); 

     // button click event 
     btnCreateProduct.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View view) { 
       // creating new product in background thread 
       checkLogin(); 
      } 
     }); 
    } 

    public void checkLogin() { 

     String name = inputName.getText().toString(); 
     String password = inputPassword.getText().toString(); 

     //if(session.getUserName(LoginActivity.this).length()==0) 
     //{ 
     new CreateNewProduct().execute(); 
     //}// 
     //else 
     // { 
     //Intent i = new Intent(LoginActivity.this,MainActivity.class); 
     // startActivity(i); 
     //} 
    } 


    /** 
    * Background Async Task to Create new product 
    */ 
    class CreateNewProduct extends AsyncTask<String, String, String> { 
     JSONObject json; 
     /** 
     * Before starting background thread Show Progress Dialog 
     */ 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(Executive_Login.this); 
      pDialog.setMessage("Logging In.."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
     } 

     /** 
     * Creating product 
     */ 
     protected String doInBackground(String... args) { 
      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 
      params.add(new BasicNameValuePair("gmail", "[email protected]")); 
      params.add(new BasicNameValuePair("password", "abc")); 


      // getting JSON Object 
      // Note that create product url accepts POST method 
      json = jsonParser.makeHttpRequest(url_create_product, 
        "POST", params); 

      // check log cat fro response 
      Log.d("Create Response", json.toString()); 



      return null; 
     } 

     /** 
     * After completing background task Dismiss the progress dialog 
     **/ 
     protected void onPostExecute(String file_url) { 
      // dismiss the dialog once done 
      pDialog.dismiss(); 

      // check for success tag 
      try { 
       int success = json.getInt(TAG_SUCCESS); 

       if (success == 1) { 
        // successfully created product 
        flag = 0; 

        session.createUserLoginSession("Android Example", 
          name); 

//     Intent i = new Intent(getApplicationContext(), Dealer.class); 
//     i.putExtra("email", name); 
//     i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
// 
//     // Add new Flag to start new Activity 
//     i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
//     startActivity(i); 

        // closing this screen 
        finish(); 
       } else { 
        flag = 1; 
        // username/password doesn't match& 
        Toast.makeText(getApplicationContext(), 
          "Username/Password is incorrect", 
          Toast.LENGTH_LONG).show(); 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 


      if (flag == 1) 
       Toast.makeText(Executive_Login.this, "Please Enter Correct informations", Toast.LENGTH_LONG).show(); 
     } 

    } 
} 



/** 
* Created by hp-pc on 10/28/2016. 
*/ 
class ExecutiveSessionManager { 

    SharedPreferences pref; 
    SharedPreferences.Editor editor; 
    Context _context; 
    int PRIVATE_MODE = 0; 

    private static final String PREFER_NAME = "AndroidExamplePref"; 
    private static final String IS_USER_LOGIN = "IsUserLoggedIn"; 
    public static final String KEY_NAME = "name"; 
    public static final String KEY_EMAIL = "email"; 

    public ExecutiveSessionManager(Context context){ 
     this._context = context; 
     pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE); 
     editor = pref.edit(); 
    } 
    public void createUserLoginSession(String name, String email){ 
     // Storing login value as TRUE 
     editor.putBoolean(IS_USER_LOGIN, true); 

     // Storing name in pref 
     editor.putString(KEY_NAME, name); 

     // Storing email in pref 
     editor.putString(KEY_EMAIL, email); 

     // commit changes 
     editor.commit(); 
    } 

    public boolean checkLogin(){ 
     // Check login status 
     if(!this.isUserLoggedIn()){ 

      // user is not logged in redirect him to Login Activity 
      Intent i = new Intent(_context, Executive_Login.class); 

      // Closing all the Activities from stack 
      i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

      // Add new Flag to start new Activity 
      i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

      // Staring Login Activity 
      _context.startActivity(i); 

      return true; 
     } 
     return false; 
    } 
    public HashMap<String, String> getUserDetails(){ 

     //Use hashmap to store user credentials 
     HashMap<String, String> user = new HashMap<String, String>(); 

     // user name 
     user.put(KEY_NAME, pref.getString(KEY_NAME, null)); 

     // user email id 
     user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null)); 

     // return user 
     return user; 
    } 
/*static SharedPreferences getSharedPreferences(Context ctx) 
{ 
    return PreferenceManager.getDefaultSharedPreferences(ctx); 
} 
    public static void setUserName(Context ctx,String username) 
    { 
     SharedPreferences.Editor ed = getSharedPreferences(ctx).edit(); 
     ed.putString(PREFER_NAME ,username); 
     ed.commit(); 
    } 

    public static String getUserName(Context ctx) { 
     return getSharedPreferences(ctx).getString(PREFER_NAME,""); 
    } 

    { 

    }*/ 
    /** 
    * 
    * Clear session details 
    * */ 
    public void logoutUser(){ 

     // Clearing all user data from Shared Preferences 
     editor.clear(); 
     editor.commit(); 

     // After logout redirect user to Login Activity 
     Intent i = new Intent(_context, Executive_Login.class); 

     // Closing all the Activities 
     i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

     // Add new Flag to start new Activity 
     i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

     // Staring Login Activity 
     _context.startActivity(i); 
    } 


    // Check for login 
    public boolean isUserLoggedIn(){ 
     return pref.getBoolean(IS_USER_LOGIN, true); 
    } 
} 
+0

它不工作forme –