我是 android 初学者并尝试使用 json 获取 pnr 状态,这是我的代码不起作用,请帮助我。 还告诉我哪种解析方法是goo xml parse或json parse。当你提出问题时,多用一些词来描述你的问题总是有帮助的。如果真的没什么好说的,就从网上随便抄一段,但一定要把它们标记为虚拟文本,这样人们就不会注意到它们。
public class JSON extends Activity {
String completeData="";
TextView tv;
EditText et;
Button bt;
HttpClient client;
JSONObject jsonobj;
final static String URI="http://pnrapi.alagu.net/api/v1.0/pnr/";
String pnr_no=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json);
tv=(TextView) findViewById(R.id.textView1);
et=(EditText) findViewById(R.id.editText1);
bt=(Button) findViewById(R.id.button1);
client=new DefaultHttpClient();
}
public void showpnr(View v){
pnr_no=et.getText().toString();
if(pnr_no.equals("")){
Toast.makeText(this, "Enter the Valid Pnr", Toast.LENGTH_LONG).show();
return;
}
GetPNR pnr=new GetPNR();
pnr.execute("train-name");
completeData="";
}
public JSONArray pnr(String username){
JSONArray jarray=null;
try
{
StringBuilder builder=new StringBuilder(URI);
builder.append(username);
HttpGet get=new HttpGet(builder.toString());
HttpResponse response=client.execute(get);
int status =response.getStatusLine().getStatusCode();
if(status==200){
HttpEntity entity=response.getEntity();
String data=EntityUtils.toString(entity);
jarray=new JSONArray(data);
}
else{
Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
}
}catch(ClientProtocolException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
catch(JSONException e){
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
return jarray;
}
JSONObject js_pnr=new JSONObject();
public class GetPNR extends AsyncTask<String, Integer, ArrayList<String>>
{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
tv.setText("Loading Pnr status");
super.onPreExecute();
}
@Override
protected ArrayList<String> doInBackground(String... params) {
// TODO Auto-generated method stub
ArrayList<String> al_texts=new ArrayList<String>();
try{
JSONArray data =pnr(pnr_no);
if(data==null){
return null;
}
int count=data.length();
JSONObject jobj=new JSONObject();
for(int i=0;i<count;i++){
jobj=data.getJSONObject(i);
al_texts.add(jobj.getString("train-name").toString());
}
return al_texts;
}catch(JSONException e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(ArrayList<String> al_pnrText) {
if(al_pnrText==null){
tv.setText("Pnr not found");
return;
}
for(String string:al_pnrText){
completeData+=string+System.getProperty("line.seperator")
+System.getProperty("line.seperator");
}
tv.setText("pnr status:"+System.getProperty("line.seperator")+completeData);
}
}
}