安卓实习第十一天

- Activity的数据传递到Fragment

Activity.java

fragmentManager = getFragmentManager();
transaction = fragmentManager.beginTransaction();
details = new SearchResultFragment();
Bundle bundle = new Bundle();
bundle.putStringArrayList("cities", (ArrayList<String>) listResult);
details.setArguments(bundle);
transaction.replace(R.id.search_default, details);
transaction.addToBackStack(null);
transaction.commit();

Fragment.java

    List<String> list;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search_result,
                container, false);
        TextView tv = (TextView) view.findViewById(R.id.result);
        Bundle bundle = getArguments();
        list = new ArrayList<>();
        list = bundle.getStringArrayList("cities");
        tv.setText(list.get(0).toString());

        return view;
    }

- 回退按钮重写

    @Override
    public void onBackPressed() {
        finish();
    }

- handler延时处理

public class MainActivity extends Activity implements OnClickListener {
    public static final int UPDATE_TEXT = 1;
    private TextView text;
    private Button changeText;
    private Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case UPDATE_TEXT:
                    // 在这里可以进行UI操作 
                    text.setText("Nice to meet you"); break;
                default:
                    break;
                } 
            }
    };
    ......
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.change_text:
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Message message = new Message();
                    message.what = UPDATE_TEXT; 
                    handler.sendMessage(message); // 将Message对象发送出去
                }
            }).start();
            break;
        default:
            break;
        }
    }
}

首先需要在主线程当中创建一个 Handler 对象,并重写 handleMessage()方法。然后当子线程中需要进行 UI 操作时,就创建一个 Message 对象,并 通过 Handler 将这条消息发送出去。之后这条消息会被添加到 MessageQueue 的队列中等待 被处理,而 Looper 则会一直尝试从 MessageQueue 中取出待处理消息,最后分发回 Handler 的 handleMessage()方法中。由于 Handler 是在主线程中创建的,所以此时 handleMessage()方 法中的代码也会在主线程中运行,于是我们在这里就可以安心地进行 UI 操作了。

- LeanCloud查询及存储数据

SJBSearchLeanCloudDao.java

package com.shijiebang.offlinemap.db.SJBDao;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;

import java.util.concurrent.TimeUnit;

/**
 * Created by zhangkaiyue on 15/7/29.
 */
public class SJBSearchLeanCloudDao {

    //搜索城市
    public AVQuery<AVObject> SJBCitiesQuery(String str){
        AVQuery<AVObject> citiesQuery = new AVQuery<AVObject>("CityMaps");
        citiesQuery.setCachePolicy(AVQuery.CachePolicy.IGNORE_CACHE);
        citiesQuery.whereMatches("searchKeys", ".*" + str + ".*");
        citiesQuery.include("country");
        citiesQuery.include("mapFile");
        citiesQuery.orderByAscending("pinyin");
        return citiesQuery;
    }

    //搜索国家
    public AVQuery<AVObject> SJBCountryQuery(String str){

        AVQuery<AVObject> countriesQuery = new AVQuery<AVObject>("Countries");
        countriesQuery.setCachePolicy(AVQuery.CachePolicy.IGNORE_CACHE);
        countriesQuery.whereMatches("searchKeys", ".*" + str + ".*");

        AVQuery<AVObject> cityMapsQuery = new AVQuery<AVObject>("CityMaps");
        cityMapsQuery.setCachePolicy(AVQuery.CachePolicy.IGNORE_CACHE);
        cityMapsQuery.whereMatchesQuery("country", countriesQuery);
        cityMapsQuery.include("country");
        cityMapsQuery.include("mapFile");
        cityMapsQuery.orderByAscending("pinyin");

        return cityMapsQuery;
    }


    //搜索大洲
    public AVQuery<AVObject> SJBContinentQuery(String str){

        AVQuery<AVObject> continentsQuery = new AVQuery<AVObject>("Continents");
        continentsQuery.setCachePolicy(AVQuery.CachePolicy.IGNORE_CACHE);
        continentsQuery.whereMatches("searchKeys", ".*" + str + ".*");

        AVQuery<AVObject> countriesQuery = new AVQuery<AVObject>("Countries");
        countriesQuery.setCachePolicy(AVQuery.CachePolicy.IGNORE_CACHE);
        countriesQuery.whereMatchesQuery("continent", continentsQuery);

        AVQuery<AVObject> cityMapsQuery = new AVQuery<AVObject>("CityMaps");
        cityMapsQuery.setCachePolicy(AVQuery.CachePolicy.IGNORE_CACHE);
        cityMapsQuery.whereMatchesQuery("country", countriesQuery);
        cityMapsQuery.include("country");
        cityMapsQuery.include("mapFile");
        cityMapsQuery.orderByAscending("pinyin");

        return cityMapsQuery;
    }

    //将搜索传到LeanCloud
    public AVObject SJBToLeanCloud(String str){
        AVObject post = new AVObject("SearchKeywords");
        post.put("keyword", str);
        return post;
    }
}

SJBSearchLeanCloudService.java

package com.shijiebang.offlinemap.db.SJBService;

import android.util.Log;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.shijiebang.offlinemap.db.SJBDao.SJBSearchLeanCloudDao;
import com.shijiebang.offlinemap.ui.Fragment.MapListFragment;
import com.shijiebang.offlinemap.ui.activity.SearchActivity;

import java.util.List;

/**
 * Created by zhangkaiyue on 15/7/29.
 */
public class SJBSearchLeanCloudService {
    SJBSearchLeanCloudDao sjbSearchLeanCloudDao = new SJBSearchLeanCloudDao();
    AVQuery<AVObject> SJBSearch = new AVQuery<>();

    //>>>>>>调用该方法,将查询到的数据传回前端
    public void getSJBCityData(String str,final SearchActivity searchActivity){

        SJBSearch = sjbSearchLeanCloudDao.SJBCitiesQuery(str);
        SJBSearch.findInBackground(new FindCallback<AVObject>() {
            public void done(List<AVObject> cities, AVException e) {
                if (e == null) {
                    Log.e("成功", "查询到" + cities.size() + " 条符合条件的数据");
                    searchActivity.SJBSearchCityCallBack(cities);
                } else {
                    Log.e("失败", "查询错误: " + e.getMessage());
                }
            }
        });
    }

    //>>>>>>调用该方法,将查询到的数据传回前端
    public void getSJBCountryData(String str,final SearchActivity searchActivity){

        SJBSearch = sjbSearchLeanCloudDao.SJBCountryQuery(str);
        SJBSearch.findInBackground(new FindCallback<AVObject>() {
            public void done(List<AVObject> cities, AVException e) {
                if (e == null) {
                    Log.e("成功", "查询到" + cities.size() + " 条符合条件的数据");
                    searchActivity.SJBSearchCountryCallBack(cities);
                } else {
                    Log.e("失败", "查询错误: " + e.getMessage());
                }
            }
        });
    }

    public void getSJBContinentData(String str,final SearchActivity searchActivity){

        SJBSearch = sjbSearchLeanCloudDao.SJBContinentQuery(str);
        SJBSearch.findInBackground(new FindCallback<AVObject>() {
            public void done(List<AVObject> cities, AVException e) {
                if (e == null) {
                    Log.e("成功", "查询到" + cities.size() + " 条符合条件的数据");
                    searchActivity.SJBSearchContinentCallBack(cities);
                } else {
                    Log.e("失败", "查询错误: " + e.getMessage());
                }
            }
        });
    }

    public void setSJBKeyWords(String str,final SearchActivity searchActivity){

        AVObject post = sjbSearchLeanCloudDao.SJBToLeanCloud(str);
        post.saveInBackground(new SaveCallback() {
            public void done( AVException e) {
                if (e == null) {
                    Log.e("成功", "成功");
                    searchActivity.SJBSearchUploadCallBack(e);
                } else {
                    Log.e("失败", "查询错误: " + e.getMessage());
                }
            }
        });
    }
}

SearchActivity.java

public Handler mhandler = new Handler() {
        public void handleMessage(Message msg){
            if(msg.arg1 == 1){

                getData();

                //将数据整理为ArrayList传到ResultFragment
                listResult = new ArrayList<>();
                listCountryResult = new ArrayList<>();
                for(int i = 0;i<list.size();i++){
                    listResult.add((String) list.get(i).get("nameCn"));
                    listCountryResult.add((String) list.get(i).get("country"));
                }

                if(listResult.size()==0){
                    //转到UploadFragment
                    fragmentManager = getFragmentManager();
                    transaction = fragmentManager.beginTransaction();
                    details = new SearchReturnLoginFragment();
                    transaction.replace(R.id.search_default, details);
                    transaction.addToBackStack(null);
                    transaction.commit();
                }else {
                    //转到ResultFragment
                    fragmentManager = getFragmentManager();
                    transaction = fragmentManager.beginTransaction();
                    details = new SearchResultFragment();
                    Bundle bundle = new Bundle();
                    bundle.putStringArrayList("cities", (ArrayList<String>) listResult);
                    bundle.putStringArrayList("country", (ArrayList<String>) listCountryResult);
                    details.setArguments(bundle);
                    transaction.replace(R.id.search_default, details);
                    transaction.addToBackStack(null);
                    transaction.commit();
                }
            }
        }
    };
    …… 

     //将搜索内容传到LeanCloud
     searchCities.setSJBKeyWords(searchContent,this);

     //从LeanCloud进行搜索
     searchCities.getSJBCityData(searchContent, this);
     searchCities.getSJBCountryData(searchContent, this);
     searchCities.getSJBContinentData(searchContent, this);

    //回调函数
    public void SJBSearchCityCallBack(List<AVObject> cities){
        SJBCitiesFragment = cities;
        Message msg = new Message();
        msg.arg1 = 1;
        mhandler.sendMessage(msg);
    }

    //回调函数
    public void SJBSearchCountryCallBack(List<AVObject> cities){
        SJBCountriesFragment = cities;
        Message msg = new Message();
        msg.arg1 = 1;
        mhandler.sendMessage(msg);
    }

    //回调函数
    public void SJBSearchContinentCallBack(List<AVObject> cities){
        SJBContinentsFragment = cities;
        Message msg = new Message();
        msg.arg1 = 1;
        mhandler.sendMessage(msg);
    }

    //回调函数
    public void SJBSearchUploadCallBack(AVException e){
        Message msg = new Message();
        msg.arg1 = 1;
        mhandler.sendMessage(msg);
    }


    //将结果转为ArrayList<Map<String, Object>>
    private List<Map<String, Object>> getData() {
        list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();

        //循环保存查询到的数据到list中
        int i;
        for(i = 0; i < SJBCitiesFragment.size();i++){
            AVObject SJBcountry = SJBCitiesFragment.get(i).getAVObject("country");
            map.put("nameCn",SJBCitiesFragment.get(i).getString("nameCn"));
            map.put("country",SJBcountry.getString("nameCn"));
            list.add(map);
            map = new HashMap<String, Object>();
        }
        for(i = 0; i < SJBCountriesFragment.size();i++){
            for(int j = 0;j<list.size();j++)
            {
                Boolean temp = false;
                if(temp == false){
                    temp = ((String)list.get(j).get("nameCn")).equals(SJBCountriesFragment.get(i).getString("nameCn"));
                }else {
                    break;
                }
            }
            AVObject SJBcountry = SJBCountriesFragment.get(i).getAVObject("country");
            map.put("nameCn",SJBCountriesFragment.get(i).getString("nameCn"));
            map.put("country",SJBcountry.getString("nameCn"));
            list.add(map);
            map = new HashMap<String, Object>();

        }
        for(i = 0; i < SJBContinentsFragment.size();i++){
            for(int j = 0;j<list.size();j++)
            {
                Boolean temp = false;
                if(temp == false){
                    temp = ((String)list.get(j).get("nameCn")).equals(SJBContinentsFragment.get(i).getString("nameCn"));
                }else {
                    break;
                }
            }
            AVObject SJBcountry = SJBContinentsFragment.get(i).getAVObject("country");
            map.put("nameCn",SJBContinentsFragment.get(i).getString("nameCn"));
            map.put("country",SJBcountry.getString("nameCn"));
            list.add(map);
            map = new HashMap<String, Object>();
        }
        return list;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值