java - E/AndroidRuntime(2835) : java. lang.NullPointerException异常

标签 java android json import

调用 Web 服务时出现空指针异常。该服务提供 Json 数组,如下所示:

[{"userid":210,
  "name" :"Karan",
  "email":"ka@gmail.com",
  "password":"ka123456",
  "created_at":"17-Oct-2013",
  "success" : 1
  }] 

这是完成解析的类:

package library;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;

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

List<NameValuePair> postparams = new ArrayList<NameValuePair>();
    String URL = null;

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



public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
     this.URL = url;
     this.postparams = params;
     return null;

}

@Override
protected JSONObject doInBackground(String... params) {
     // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(URL);
        httpPost.setEntity(new UrlEncodedFormEntity(postparams));

        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();
    }

    return jObj;

}

protected JSONObject onPostExecute(String json) {
    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.e("JSON", json);
     } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj  = new JSONArray(json).getJSONObject(0);

      } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
  // return JSON String
  return jObj;
}
}

出现空指针异常错误的Registration类

              else
              {
                  erName.setText("");
                  erPass.setText("");
                  erEmail.setText("");
                  erCopass.setText("");
                  UserFunction userFunction = new UserFunction();
                  JSONObject jObj = userFunction.registerUser(name, email, password);

                  // check for login response
                  try {
                      if (jObj.getString(KEY_SUCCESS) != null) {
                          String res = jObj.getString(KEY_SUCCESS); 
                          if(Integer.parseInt(res) == 1){
                              // user successfully registred
                              // Store user details in SQLite Database
                              Databasehandler db = new Databasehandler(getApplicationContext());
                              JSONObject json_user = jObj.getJSONObject("userid");

                              // Clear all previous data in database
                              userFunction.logoutUser(getApplicationContext());
                              db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json_user.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));                        
                              // Launch Dashboard Screen
                              Intent login = new Intent(getApplicationContext(), LoginActivity.class);
                              // Close all views before launching Dashboard
                              login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                              startActivity(login);
                              // Close Registration Screen
                              Toast.makeText(RegisterActivity.this,"You are Registered successfully",Toast.LENGTH_SHORT).show();
                              finish();
                          }else{
                              // Error in registration
                              Toast.makeText(RegisterActivity.this,"User Allready Registered!!!",Toast.LENGTH_LONG).show();
                          }
                      }
                  } catch (JSONException e) {
                      e.printStackTrace();
                  }
              }

错误发生在以下行: 如果 (jObj.getString(KEY_SUCCESS) != null)

这是使用解析器作为后台任务的相关类

package library;

import java.util.ArrayList;
import java.util.List; 
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject; 
import android.content.Context;

public class UserFunction {

private JSONParser jsonParser;

// Testing in localhost using wamp or xampp 
// use http://10.0.2.2/ to connect to your localhost ie http://localhost/
private static String loginURL = "http://192.168.1.120/rvAndroidServices.ashx";
private static String registerURL = "http://192.168.1.120/rvAndroidServices.ashx";
private static String name1 = "http://192.168.1.120/rvAndroidServices.ashx";

private static String login_tag = "login";
private static String register_tag = "register";
private static String name_tag = "name";

// constructor
public UserFunction(){
    jsonParser = new JSONParser();
}

/**
 * function make Login Request
 * @param email
 * @param password
 * */
public JSONObject loginUser(String email, String password){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", login_tag));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("password", password));
    JSONObject jObj = jsonParser.getJSONFromUrl(loginURL, params);
    // return json
    // Log.e("JSON", json.toString());
    return jObj;
}

/**
 * function make Login Request
 * @param name
 * @param email
 * @param password
 * */
public JSONObject registerUser(String name, String email, String password){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", register_tag));
    params.add(new BasicNameValuePair("name", name));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("password", password));

    // getting JSON Object
    JSONObject jObj = jsonParser.getJSONFromUrl(registerURL, params);
    // return json
    return jObj;
}


/**
 * Function get Login status
 * */
public boolean isUserLoggedIn(Context context){
    Databasehandler db = new Databasehandler(context);
    int count = db.getRowCount();
    if(count > 0){
        // user logged in
        return true;
    }
    return false;
}

public String getAppCategorydetail(Context context){
    Databasehandler db = new Databasehandler(context);
    String count = db.getAppCategorydetail();

        return count;

}
/**
 * Function to logout user
 * Reset Database
 * */
public boolean logoutUser(Context context){
    Databasehandler db = new Databasehandler(context);
    db.resetTables();
    return true;
}

public JSONObject chname(String name) 
{
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", name_tag));
    params.add(new BasicNameValuePair("name", name));
     JSONObject jObj = jsonParser.getJSONFromUrl(name1, params);
    return jObj;

}

请对这个问题给出正确的建议。

最佳答案

你必须根据 json 数组创建一个 for 循环,然后从 json 数组中获取 json 对象作为字符串,然后在你检查你的条件后......

关于java - E/AndroidRuntime(2835) : java. lang.NullPointerException异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19424299/

相关文章:

java - 用Jackson写yaml?

java - 如何在 JOptionPane 上添加文本区域

java - 如何使用注解在 Spring 中执行基于构造函数的依赖注入(inject)?

java - 通过 Java 实现 Ackermann 函数并支持 BigInteger

android - 如何禁用 ListView 中的子项目(使其颜色变为灰色且不可点击)

Android - 拍照 - onActivityResult 立即返回

java - 我如何告诉 Wicket 正在通过带有 SSL 终止的 Apache 访问它,以便在加载脚本时避免混合内容错误?

java - 使用 Microsoft Graph API 仅按标题搜索 OneDrive 文件

javascript - 数据和时间中缺少前导 0

json - Scala 解析递归 JSON