在java中访问类变量时,将局部变量的值传递给类变量会产生NullPointer

时间:2014-09-12 18:25:20

标签: java nullpointerexception

我获得了一个访问令牌作为响应,并尝试将其保存在类变量中。但是当我从getter访问变量时,我得到空指针异常。这是代码片段。 由于我将局部变量的值赋给类变量,所以我不太明白这个原因。所以即使变量是私有的,我也应该可以通过类的任何成员方法来访问它。

public class Login {
private String access_token;
public String doLogin(String uName) throws Exception {
    BaseClass bc = new BaseClass();
    String loginUrl = "http://www.example.com/login";
    bc.setUrl(loginUrl);
    bc.REQUEST_METHOD="POST";
    bc.CONTENT_TYPE="application/json";
    //System.out.println(url);
    System.out.println(bc.getUrl());
    bc.openConnection();
    bc.con.setDoOutput(true);
    JSONObject loginRequest = new JSONObject();
    loginRequest.put("userName", uName);
    loginRequest.put("password", "password");
    System.out.println(loginRequest);

    DataOutputStream dos = new DataOutputStream(bc.con.getOutputStream());
    dos.writeBytes(loginRequest.toString());
    dos.flush();
    dos.close();
    int responseCode = bc.con.getResponseCode();
    System.out.println(responseCode);
    BufferedReader login = new BufferedReader(new InputStreamReader(bc.con.getInputStream()));
    String inputLine;
    StringBuffer loginResponse = new StringBuffer();
    while((inputLine=login.readLine())!=null){
        loginResponse.append(inputLine);
    }
    login.close();
    System.out.println("#####BEGIN LOGIN RESPONSE#####");
    System.out.println(loginResponse.toString());
    //setAccess_token(access_token);
    JSONObject jobj= new JSONObject(loginResponse.toString());
    JSONArray jArray = jobj.getJSONArray("respList");
    String access_token = jArray.getJSONObject(0).getString("ticket");
    token = jArray.toString();
    //access = new JSONObject(response);
    System.out.println("printing token"+token);
    access_token = token;
    System.out.println("printint access token"+access_token);
    return access_token;
}

public String getToken(){
    System.out.println("printing return token"+access_token);// I GET NULL POINTER EXCEPTION HERE
    return access_token;
}

1 个答案:

答案 0 :(得分:1)

这是你的问题:

String access_token = jArray.getJSONObject(0).getString("ticket");

将该行更改为:

this.access_token = jArray.getJSONObject(0).getString("ticket");

请考虑重构。这种方法做了很多。