Java 在android中使用改型库生成异步请求

Java 在android中使用改型库生成异步请求,java,android,retrofit,Java,Android,Retrofit,我拥有的内容::我有一个简单的异步任务,它使用Http获取JSON 我试图学习的内容::如何将其转换为使用改装库的项目 我在下面提到了这门课 SplashActivity.java public class SplashActivity extends Activity { /** Called when the activity is first created. */ JSONObject jsonobject; JSONArray jsonarray;

我拥有的内容::我有一个简单的异步任务,它使用Http获取JSON

我试图学习的内容::如何将其转换为使用
改装
库的项目

我在下面提到了这门课


SplashActivity.java

public class SplashActivity extends Activity {
    /** Called when the activity is first created. */

    JSONObject jsonobject;  
    JSONArray jsonarray;
    ArrayList<HashMap<String, String>> arraylist;
    private String Content;
    DatabaseHandler db;
    //TextView txtSplashTitle,txtSplashDesc;

    @InjectView(R.id.txtSplashDesc) TextView txtSplashDesc=null;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ButterKnife.inject(this);//using ButterKnife library for viewInjection

        String serverURL = "";
        db = new DatabaseHandler(this);
        new LongOperation().execute(serverURL);

        freeMemory();
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();

        //Setting fonts for textviews
        setCustomFontForTextViews();

    }



    private void setCustomFontForTextViews() {
        Typeface typeFace = Typeface.createFromAsset(getAssets(), "royalacid.ttf");
        txtSplashDesc.setTypeface(typeFace);
    }



    // Class with extends AsyncTask class
    private class LongOperation  extends AsyncTask<String, Void, Void> {

        private final HttpClient Client = new DefaultHttpClient();
        private String Error = null;
        private ProgressDialog Dialog = new ProgressDialog(SplashActivity.this);


        protected void onPreExecute() {
            // NOTE: You can call UI Element here.
            Dialog.setMessage("Downloading source..");
            Dialog.show();
        }

        // Call after onPreExecute method
        protected Void doInBackground(String... urls) {
            try {
                // NOTE: Don't call UI Element here.
                HttpGet httpget = new HttpGet("http://10.0.2.2:3009/findmybuffet/?storedproc=get_app_tables&flag=sudhakar");
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                Content = Client.execute(httpget, responseHandler);
                jsonobject = new JSONObject(Content);
                jsonobject = jsonobject.getJSONObject("findmybuffet");
                jsonarray = jsonobject.getJSONArray("buffets");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put("buf_off_id", jsonobject.getString("buf_off_id"));
                    map.put("from_time", jsonobject.getString("from_time"));
                    map.put("to_time", jsonobject.getString("to_time"));
                    map.put("online_price", jsonobject.getString("online_price"));
                    map.put("reserved_price", jsonobject.getString("reserved_price"));
                    map.put("buf_image", jsonobject.getString("buf_image"));
                    map.put("res_name", jsonobject.getString("res_name"));
                    map.put("rating", jsonobject.getString("rating"));
                    map.put("latitude", jsonobject.getString("latitude"));
                    map.put("longitude", jsonobject.getString("longitude"));
                    map.put("buf_type_name", jsonobject.getString("buf_type_name"));
                    map.put("from_date", jsonobject.getString("from_date"));
                    map.put("to_date", jsonobject.getString("to_date"));
                    map.put("city_id", jsonobject.getString("city_id"));
                    map.put("city_name", jsonobject.getString("city_name"));
                    map.put("meal_type_id", jsonobject.getString("meal_type_id"));
                    map.put("meal_type_name", jsonobject.getString("meal_type_name"));
                    map.put("buf_desc", jsonobject.getString("buf_desc"));
                    map.put("distance", jsonobject.getString("distance"));

                    Log.d("----$$$----", map.toString());

                    //Calling database 
                    db.addContact(map);

                    //findCityName();
                    //String result=getAddress(12.918286,77.669493);
                   // Log.d("----result$$$$$-----", result);
                }           
            } catch (IOException|JSONException e) {
                Error = e.getMessage();
                cancel(true);
            }
            return null;
        }

        private String getAddress(double latitude, double longitude) {
            StringBuilder result = new StringBuilder();
            try {
                Geocoder geocoder = new Geocoder(SplashActivity.this, Locale.getDefault());
                List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
                if (addresses.size() > 0) {
                    Address address = addresses.get(0);
                    result.append(address.getLocality()).append("\n");
                    result.append(address.getCountryName());
                }
            } catch (IOException e) {
                Log.e("tag", e.getMessage());
            }

            return result.toString();
        }

        /*private void findCityName() {
            // TODO Auto-generated method stub
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
        }
*/
        protected void onPostExecute(Void unused) {     
            // Close progress dialog
            Dialog.dismiss();   
        }
    }

    private void freeMemory() {
        jsonobject=null;
        jsonarray=null;
        arraylist=null;
        Content=null;
    }

}
公共类SplashActivity扩展活动{
/**在首次创建活动时调用*/
JSONObject JSONObject;
JSONArray JSONArray;
ArrayList ArrayList;
私有字符串内容;
数据库处理程序数据库;
//text查看txtSplashTitle,txtSplashDesc;
@InjectView(R.id.txtSplashDesc)TextView txtSplashDesc=null;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.injection(this);//使用ButterKnife库进行视图注入
字符串serverURL=“”;
db=新的DatabaseHandler(此);
新建LongOperation().execute(服务器URL);
freemory();
}
@凌驾
受保护的void onStart(){
//TODO自动生成的方法存根
super.onStart();
//设置文本视图的字体
setCustomFontForTextViews();
}
私有void setCustomFontForTextViews(){
Typeface-Typeface=Typeface.createFromAsset(getAssets(),“royalacid.ttf”);
txtSplashDesc.setTypeface(字体);
}
//使用扩展的AsyncTask类初始化
私有类LongOperation扩展了异步任务{
私有最终HttpClient客户端=新的DefaultHttpClient();
私有字符串错误=null;
private ProgressDialog=新建ProgressDialog(SplashActivity.this);
受保护的void onPreExecute(){
//注意:您可以在这里调用UI元素。
setMessage(“下载源…”);
Dialog.show();
}
//在onPreExecute方法之后调用
受保护的Void doInBackground(字符串…URL){
试一试{
//注意:这里不要调用UI元素。
HttpGet HttpGet=新的HttpGet(“http://10.0.2.2:3009/findmybuffet/?storedproc=get_app_tables&flag=sudhakar");
ResponseHandler ResponseHandler=新BasicResponseHandler();
Content=Client.execute(httpget、responseHandler);
jsonobject=新的jsonobject(内容);
jsonobject=jsonobject.getJSONObject(“findmybuffet”);
jsonarray=jsonobject.getJSONArray(“自助餐”);
for(int i=0;i0){
地址=地址。获取(0);
result.append(address.getLocality()).append(“\n”);
append(address.getCountryName());
}
}捕获(IOE异常){
Log.e(“tag”,e.getMessage());
}
返回result.toString();
}
/*私有void findCityName(){
//TODO自动生成的方法存根
Geocoder Geocoder=新的Geocoder(这个,Locale.getDefault());
列表地址=地理编码器。getFromLocation(lat,lng,1);
}
*/
受保护的void onPostExecute(void unused){
//关闭进度对话框
Dialog.dismise();
}
}
私有void freemory(){
jsonobject=null;
jsonarray=null;
arraylist=null;
内容=空
@GET("/findmybuffet/?storedproc=get_app_tables&flag={name}")  
void findBuffet(@Path("name") String name, Callback cb);
RestAdapter restAdapter = new RestAdapter.Builder()
            .setServer("http://10.0.2.2:3009")     
            .build();
ClientInterface service = restAdapter.create(ClientInterface.class);

Callback callback = new Callback() {
    @Override
    public void success(Object o, Response response) {
        // Read response here
    }

    @Override
    public void failure(RetrofitError retrofitError) {
        // Catch error here
    } }; 
    service.findBuffet("sudhakar", callback);