JSON 对象返回空指针

发布于 2024-12-06 23:30:20 字数 4672 浏览 2 评论 0原文

我想将一些项目插入数据库。在主要活动中,我从用户检索信息并将其传递给另一个类进行一些解析。我的 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("-");

一直显示为 null

I want to insert some items into the database. In the main activity, I retrieve information from the user and pass it to the another class to do some parsing. My JSONObject keeps showing up as NULL.

I am sorry if I am not clear with the question . I've tried to explain it as much as possible.

Below is the code your inputs are welcome

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

}

This is the class to which I am sending the JSON object to be parsed

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

I've just added some of the code that was missing at the MainActivity,

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

keeps showing up as null

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我是男神闪亮亮 2024-12-13 23:30:20
  1. 尝试使用系统提供的 EntityUtils.toString(entity)

  2. 重要提示:不要捕获通用异常,这会隐藏未经检查的(运行时)异常。您可能隐藏了 JSONObject 构造函数

更新:

您正在调用SendHttpPost并且没有将结果分配给变量:

HandleJSON.SendHttpPost(URL, jsonobj);

应该是:

regName = HandleJSON.SendHttpPost(URL, jsonobj);
  1. Instead of your convertStreamToString() method try using system provided EntityUtils.toString(entity).

  2. IMPORTANT: do not catch generic Exception, this hides unchecked (runtime) exceptions. You might be hiding the JSONException that happens in JSONObject constructor.

Update:

You are calling SendHttpPost and not assigning result to variable:

HandleJSON.SendHttpPost(URL, jsonobj);

should be:

regName = HandleJSON.SendHttpPost(URL, jsonobj);
探春 2024-12-13 23:30:20

我不认为这有什么问题,你能告诉我 regname 有什么用吗?

在您的 mainactivity 中,只需更改以下内容:

regname = HandleJSON.SendHttpPost(URL, jsonobj);

您不会回调 regname 来分配给您在 sendhttppost 返回的 name 和 sessionid。

I don't see anything wrong with this, could you tell me what is the use of regname ?

at your mainactivity just change the following:

regname = HandleJSON.SendHttpPost(URL, jsonobj);

Your not calling back regname to be assigned to name and sessionid that you are returning at the sendhttppost.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文