JSON对象返回空指针

时间:2011-09-28 12:46:44

标签: java android json android-manifest

我想在数据库中插入一些项目。在主要活动中,我从用户检索信息并将其传递给另一个类进行一些解析。我的JSONObject一直显示为NULL。

如果我不清楚这个问题,我很抱歉。我试图尽可能地解释它。

以下是您欢迎输入的代码

public class MainActivity extends Activity {
/** THE FOLLOWING STRINGS WILL BE DISPLAYED IN LOGCAT */

final String TAG = "########-------MAIN ACTIVITY: LOGIN--------######";
final String URL = "http://46.51.193.32/timereport/ses/sessions";
UserHelper userAdapter;
UserHelper db;
EditText edit_password,edit_username,edit_company;
String regName;
int duration = Toast.LENGTH_LONG;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    db = new UserHelper(this);
    userAdapter = new UserHelper(this);
     edit_password = (EditText)findViewById(R.id.password);
     edit_username = (EditText)findViewById(R.id.user_name);
     edit_company = (EditText)findViewById(R.id.company_string);
    Button login = (Button)findViewById(R.id.login_button);
    login.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
           JSONObject jsonobj = new JSONObject();
            try{

                JSONObject subJson = new JSONObject();
                subJson.put("username", edit_username.getText().toString());
                subJson.put("password", edit_password.getText().toString());
                subJson.put("company", edit_company.getText().toString());
                jsonobj.put("user", subJson);
            }
            catch(JSONException e) {
                Log.i("","#####-----error at catch jsonexception-----#####");

            }
HandleJSON.SendHttpPost(URL, jsonobj);
                String regNameSplit[] = regName.split("-");
            try{
                userAdapter.openDatabase();
                long id = db.insertIntoDatabase(edit_username.getText().toString(),edit_company.getText().toString(), edit_password.getText().toString(),regNameSplit[0], regNameSplit[2]);
                Toast.makeText(getApplicationContext(), "You have successfully logged in as: " +"\n" +regNameSplit[0], duration).show();
                Log.i(TAG, "Printing value of id which will be inserted only to remove warnings "+id);
                userAdapter.closeDatabase();
            }
            catch(SQLiteException e){
                e.printStackTrace();
            } 
        }
    });
}

}

这是我要发送要解析的JSON对象的类

public class HandleJSON{

UserHelper userAdapter;
private static final String TAG = "&&----HTTPClient-----**";
public static String SendHttpPost (String URL, JSONObject jsonobj) {
String regName = "";

try{    

        Log.v("Json object request is ",jsonobj.toString());
        DefaultHttpClient httpClientInstance = GetHttpClient.getHttpClientInstance();
        HttpPost httpPostRequest = new HttpPost(URL);
        Log.v(TAG,"The url is "+URL);

        StringEntity se;
        se = new StringEntity(jsonobj.toString());

        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");

        long t = System.currentTimeMillis();
        HttpResponse response = (HttpResponse) httpClientInstance.execute(httpPostRequest);
        Log.i(TAG, "HTTPRESPONSE RECIEVED" +(System.currentTimeMillis()-t) + "ms");

            String resultString = convertStreamToString(response.getEntity().getContent());
            Log.v(TAG , "The response is " +resultString);
            JSONObject jsonObj = new JSONObject(resultString);
            JSONObject sessionJson = jsonObj.getJSONObject("session");
            String sessionId = sessionJson.getString("sessionid");
            String name = sessionJson.getString("name");
            Log.v(TAG,"The session ID is "+sessionId);
            Log.v(TAG,"The name is "+name);
            regName = name+"-"+sessionId+"-"+URL;

} catch (Exception e){
    e.printStackTrace();
}
return regName;
}

 private static String convertStreamToString(InputStream is) {

BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();

String line = null;
try{
    while((line = reader.readLine()) !=null ){
        sb.append(line + "\n");
    }
}
    catch (IOException e){
        e.printStackTrace();
    } finally{
        try {
            is.close();
        } catch (IOException e){
            e.printStackTrace();
        }
    }
    return sb.toString();
 }
 }

我刚刚添加了一些MainActivity中缺少的代码,

String regNameSplit[] = regName.split("-");

一直显示为空

2 个答案:

答案 0 :(得分:2)

  1. 尝试使用提供的系统EntityUtils.toString(entity),而不是convertStreamToString()方法。

  2. 重要提示:不要捕获泛型Exception,这会隐藏未经检查的(运行时)异常。您可能隐藏JSONObject constructor中发生的JSONException

  3. <强>更新

    您正在调用SendHttpPost而不是将结果分配给变量:

    HandleJSON.SendHttpPost(URL, jsonobj);
    

    应该是:

    regName = HandleJSON.SendHttpPost(URL, jsonobj);
    

答案 1 :(得分:1)

我没有看到这个有什么问题,你能告诉我regname有什么用吗?

在您的主动活动中,只需更改以下内容:

regname = HandleJSON.SendHttpPost(URL, jsonobj);

您没有回拨的regname被分配给您在sendhttppost返回的name和sessionid。