如何从getter setter类中获取数据?

时间:2016-02-01 05:44:34

标签: java android api

我是android开发的初学者,我有一些问题请帮帮我。 我有2个屏幕登录和登录后,我在登录类中设置了用户ID,我想在登录后使用那个user_id如何获取,当我使用get方法找到Null时如何解决这个问题。
这是我的登录代码`公共类LoginActivity扩展了FragmentActivity {

height

} `

这是我的AfterLogin类`公共类AfterLoginActivity扩展了FragmentActivity {

rect

}`

这里是LoginBean`public类LoginBean {     private String user_id;     private String full_name;     private String display_name;     private String user_image;     私人字符串性别;     private String authorization_key;

private EditText userName;
private EditText password;
private TextView forgotPassword;
private TextView backToHome;
private Button login;
private CallbackManager callbackManager;
private ReferanceWapper referanceWapper;
private LoginBean loginBean;
Context context;
String regid;
GoogleCloudMessaging gcm;
String SENDER_ID = "918285686540";

public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
static final String TAG = "GCM";


@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_login);
    Utility.setStatusBarColor(this, R.color.tranparentColor);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/OpenSans_Regular.ttf");
    setupUI(findViewById(R.id.parentEdit));

    userName = (EditText) findViewById(R.id.userName);
    userName.setTypeface(tf);
    userName.setFocusable(false);
    userName.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View view, MotionEvent paramMotionEvent) {
            userName.setFocusableInTouchMode(true);
            Utility.hideSoftKeyboard(LoginActivity.this);
            return false;
        }
    });


    password = (EditText) findViewById(R.id.passwordEText);
    password.setTypeface(tf);
    password.setFocusable(false);
    password.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
            password.setFocusableInTouchMode(true);
            Utility.hideSoftKeyboard(LoginActivity.this);
            return false;
        }
    });


    forgotPassword = (TextView) findViewById(R.id.forgotPassword);
    forgotPassword.setTypeface(tf);
    forgotPassword.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getApplicationContext(),ForgotPasswordActivity.class);
            startActivity(intent);
        }
    });

    backToHome = (TextView) findViewById(R.id.fromLogToHome);
    backToHome.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });
    login = (Button) findViewById(R.id.loginBtn);

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            doLoginTask();
            //  Intent intent = new Intent(getApplicationContext(), AfterLoginActivity.class);
            //  startActivity(intent);

        }
    });
}


private void doLoginTask() {

    String strEmail = userName.getText().toString();
    String strPassword = password.getText().toString();
    if (strEmail.length() == 0) {
        userName.setError("Email Not Valid");
    } else if (!Utility.isEmailValid(strEmail.trim())) {
        userName.setError("Email Not Valid");
    } else if (strPassword.length() == 0) {
        password.setError(getString(R.string.password_empty));
    } else {

        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject();
            jsonObject.putOpt(Constants.USER_NAME, strEmail);
            jsonObject.putOpt(Constants.USER_PASSWORD, strPassword);
            jsonObject.putOpt(Constants.DEVICE_TOKEN, "11");
            jsonObject.putOpt(Constants.MAC_ADDRESS, "111");
            jsonObject.putOpt(Constants.GPS_LATITUDE, "1111");
            jsonObject.putOpt(Constants.GPS_LONGITUDE, "11111");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        final ProgressDialog pDialog = new ProgressDialog(this);
        pDialog.setMessage("Loading...");
        pDialog.show();

        CustomJSONObjectRequest jsonObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, Constants.USER_LOGIN_URL, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                pDialog.dismiss();
                Log.e("LoginPage", "OnResponse =" + response.toString());
                getLogin(response);
                //LoginBean lb = new LoginBean();
                //Toast.makeText(getApplicationContext(),lb.getFull_name()+"Login Successfuly",Toast.LENGTH_LONG).show();
                Intent intent = new Intent(getApplicationContext(),AfterLoginActivity.class);
                startActivity(intent);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(),"Something, wrong please try again",Toast.LENGTH_LONG).show();
                pDialog.dismiss();

            }
        });
        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
                5000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        Log.e("LoginPage", "Url= " + Constants.USER_LOGIN_URL + " PostObject = " + jsonObject.toString());
        AppController.getInstance().addToRequestQueue(jsonObjectRequest);
    }

}

public void getLogin(JSONObject response) {
    LoginBean loginBean = new LoginBean();
    if (response != null){
        try {
            JSONObject jsonObject = response.getJSONObject("data");
            loginBean.setUser_id(jsonObject.getString("user_id"));
            loginBean.setFull_name(jsonObject.getString("full_name"));
            loginBean.setDisplay_name(jsonObject.getString("display_name"));
            loginBean.setUser_image(jsonObject.getString("user_image"));
            loginBean.setGender(jsonObject.getString("gender"));
            loginBean.setAuthorization_key(jsonObject.getString("authorization_key"));

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    Toast.makeText(getApplicationContext(),"User id is "+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
    finish();
}

public void setupUI(View view) {

    //Set up touch listener for non-text box views to hide keyboard.
    if (!(view instanceof EditText)) {

        view.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                Utility.hideSoftKeyboard(LoginActivity.this);
                return false;
            }

        });
    }


}

}`

2 个答案:

答案 0 :(得分:0)

//in your both activity or create class 

    private SharedPreferences mSharedPreferences;


//in your login on getLogin() method ;

    mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
        //save actual drawable id in this way.

       if(mSharedPreferences==null)
            return;

        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putInt("userId", loginBean.getUser_id());
        editor.commit();


// in your after login acvtivity on deliverable method

    private SharedPreferences mSharedPreferences;

mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
if(mSharedPreferences==null)
            return;
string userId = mSharedPreferences.getString("userId", "");

答案 1 :(得分:0)

您可以编写并应用下面提到的步骤(请忽略任何语法错误,我给您简单的逻辑步骤。)

步骤1 - 创建一个全局应用程序级别的loginObject setter和getter,如下所示。确保在清单中定义Application类,就像为LoginActivity执行它一样

公共类ApplicationClass扩展了Application {

private LoginBean loginObject;



public void setLoginBean(LoginBean object) {

    this.loginObject = object;
}

public LoginBean getName() {

   return this.loginObject

}

}

步骤-2在LoginActivity中获取ApplicationClass对象引用的实例以设置此全局loginObject

e.g。你当前的Loginactivity中的setLogin对象就像这样

...

私有ApplicationClass appObject;

...

@覆盖 protected void onCreate(Bundle savedInstanceState){

......

appObject = (ApplicationClass) LoginActivity.this.getApplication();

.......

appObject.setLoginBean(loginObject)

}

步骤-3在任何其他Activity中获取ApplicationClass对象引用的实例获取此全局loginObject,您需要访问此登录数据。

e.g。你的otherActivity中的getLogin对象就像这样

...

私有ApplicationClass appObject;

...

@覆盖 protected void onCreate(Bundle savedInstanceState){

......

appObject = (ApplicationClass) LoginActivity.this.getApplication();

.......

LoginBean loginObject = appObject.getLoginBean();

}