ace布置小作业: 制作一个简单的电话号码归属地查询软件:JSON解析和Volly发送get请求
大概就这个样子
用到JSON解析和Volly发送Get请求两个知识点
关于Volly的用法请看我的这篇:
http://www.cnblogs.com/AceIsSunshineRain/p/5177713.html
JSON解析请看
http://www.cnblogs.com/AceIsSunshineRain/p/5178305.html
JSON数据是这样
{ "resultcode":"200", "reason":"Return Successd!", "result":{ "province":"河南", "city":"安阳", "areacode":"0372", "zip":"455000", "company":"中国移动", "card":"移动全球通卡" }, "error_code":0 }
下面看代码
MyApplication:
public class MyApplication extends Application { private static RequestQueue mQueue; @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); mQueue = Volley.newRequestQueue(getApplicationContext()); } public static RequestQueue getRequestQueue(){ return mQueue; } }
MainActivity
public class MainActivity extends Activity { private TextView textView; private Button button; private EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.tv_show); button = (Button) findViewById(R.id.button1); editText = (EditText) findViewById(R.id.ed_query); } public void start(View view) { sendStringGet(); } public void sendStringGet() { String number = editText.getText().toString(); String url = "http://apis.juhe.cn/mobile/get?phone=" + number + "&key=f64ff5c4c517da17761f112d6c3c0da0"; StringRequest mRequest = new StringRequest(Method.GET, url, new Listener<String>() { private String province; private String city; private String company; private String card; @Override public void onResponse(String arg0) { // TODO Auto-generated method stub JSONObject jsonObject; try { jsonObject = new JSONObject(arg0); Log.d("ace", arg0); String resultcode =jsonObject.getString("resultcode"); Log.d("ace", resultcode); String reason =jsonObject.getString("reason"); int error_code =jsonObject.getInt("error_code"); if (error_code == 0) { JSONObject result = jsonObject.getJSONObject("result"); province = result.getString("province"); city = result.getString("city"); company = result.getString("company"); card = result.getString("card"); textView.setText("您输入的手机号码归属地是:" + "\n" + province + city + company + card + "\n" + "查询成功"); }else if (error_code == 201102){ textView.setText("您输入的号码有误"); }else if (error_code == 201101){ textView.setText("请输入号码亲~"); }else if (error_code == 201103){ textView.setText("亲~ace查不到啊!"); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }, new Response.ErrorListener(){ @Override public void onErrorResponse(VolleyError arg0) { Toast.makeText(MainActivity.this, arg0.toString(), Toast.LENGTH_LONG).show(); textView.setText(arg0.toString()); } }); MyApplication.getRequestQueue().add(mRequest); } }