无法解析并在Toast(Android)中显示结果?
问题描述:
我是Android新手,所以我在JSON解析HTTP请求时遇到问题。让我简单介绍一下。其实我试图做一个登录,从用户将输入“电子邮件”作为用户名和“密码”作为passsword,只要他点击登录按钮一个http请求将在url http://excoflare.com/dev2010/bb_snet/baranzan/index.php?json=json&UM_email="+sUserName+"&UM_password="+sPassword
,如果成功了吐司消息将在同一个布局上到达“欢迎用户名”。我有两个(i)类HelloAndroid.java及(ii)RestJsonClient.java无法解析并在Toast(Android)中显示结果?
HelloAndroid.java
public class HelloAndroid extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Button login = (Button)findViewById(R.id.login_button);
login.setOnClickListener(this);
}
public void onClick(View v) {
EditText usernameEditText = (EditText) findViewById(R.id.txt_username);
EditText passwordEditText = (EditText) findViewById(R.id.txt_password);
String sUserName = usernameEditText.getText().toString();
String sPassword = passwordEditText.getText().toString();
String address = "http://excoflare.com/dev2010/bb_snet/baranzan/index.php?json=json&UM_email="+sUserName+"&UM_password="+sPassword+"";
JSONObject json = RestJsonClient.connect(address);
/* is something missing here if yes Please HELP*/
next();
}
private void next(){
Toast.makeText(HelloAndroid.this, "Welcome username", Toast.LENGTH_SHORT).show();
}
}
RestJsonClient
public class RestJsonClient {
public static JSONObject connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
JSONObject json = new JSONObject();
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
json=new JSONObject(result);
instream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
/**
*
* @param is
* @return String
*/
public 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();
}
}
现在我只用正确的努力/有效的电子邮件和密码,现在只有我想要。 请帮助。 非常感谢
答
JSONObject json = RestJsonClient.connect(address);
/* is something missing here if yes Please HELP*/
next();
在这里,你应该有一个的if-else条件检查你是从JSON响应获取数据。在你的情况下,你应该检查用户认证。如果用户认证,那么你应该显示其他的不是。
检查你是否在logcat中获得任何exeception .... – Dinash 2011-05-06 05:21:32
convertStreamToString方法返回什么? – 2011-05-06 06:50:12