JSON 对象返回空指针
我想将一些项目插入数据库。在主要活动中,我从用户检索信息并将其传递给另一个类进行一些解析。我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试使用系统提供的
EntityUtils.toString(entity)
。重要提示:不要捕获通用
异常
,这会隐藏未经检查的(运行时)异常。您可能隐藏了 JSONObject 构造函数。更新:
您正在调用
SendHttpPost
并且没有将结果分配给变量:应该是:
Instead of your
convertStreamToString()
method try using system providedEntityUtils.toString(entity)
.IMPORTANT: do not catch generic
Exception
, this hides unchecked (runtime) exceptions. You might be hiding theJSONException
that happens in JSONObject constructor.Update:
You are calling
SendHttpPost
and not assigning result to variable:should be:
我不认为这有什么问题,你能告诉我 regname 有什么用吗?
在您的 mainactivity 中,只需更改以下内容:
您不会回调 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:
Your not calling back regname to be assigned to name and sessionid that you are returning at the sendhttppost.