android循环出现问题-无法将值放入hashmap

2023-11-30

这个问题困扰了我很长时间。我使用了一个叫bmob的云数据库,我发现我可以成功获取我想要的数据。但是,循环中可能会出现一些错误,我只能获取最后选择的项目的信息。

附注我使用一个名为 Playlist 的数组列表来存储计算数据,我将使用该数据在下一个活动中显示列表视图。

这是我的代码:

public class DestinationActivity extends Activity implements OnClickListener, NumberPicker.OnValueChangeListener {

private TextView from_place, date, days, start_time, end_time, number, money_view;
private Button addButton, subButton;
private ImageView backButton, telephone;
private ListView listView;
private Button destinationOk_btn;
private ShapeLoadingDialog shapeLoadingDialog;

private Tip startTip;

private Calendar calendar;
private DatePickerDialog dialog;
private TimePickerDialog dialog2;

private List<Destination> destinationList = new ArrayList<Destination>();


private DestinationAdapter adapter;

private int number_value = 1; 

private String time_start;
private String time_end;
private int travel_days;
double travelTime;//total playing time
double travel_time;
private int money;
private int num = 1;


private ArrayList<Integer> select_placeID = new ArrayList<Integer>(); 
public Map<Integer,Double> weightMap;
public List<Plan> planList = new ArrayList<Plan>();
int[] selectedID = new int[10];


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.destination_layout);

    //initialize the cloud database
    Bmob.initialize(this, BmobConfig.APP_ID);

    listView = (ListView) findViewById(R.id.list_destination);

    destinationOk_btn = (Button) findViewById(R.id.okButton);


    initDestinations(); // initialize the data


    adapter = new DestinationAdapter(destinationList, DestinationActivity.this);
    //adapter = new DestinationAdapter(this, destinationList, DestinationAdapter.getIsSelected());
    listView.setAdapter(adapter);

    //....listeners and textviews.......

    //submit button
    destinationOk_btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            select_placeID.clear();

            for (int i = 0; i < destinationList.size(); i++) {
                if (DestinationAdapter.getIsSelected().get(i)) {
                    select_placeID.add((i + 1));
                }

            }

            //change to int array
            selectedID = new int[select_placeID.size()];
            for(int i = 0;i<select_placeID.size();i++){
                selectedID[i] = select_placeID.get(i);
            }

            if (select_placeID.size() == 0) {
                AlertDialog.Builder builder1 = new AlertDialog.Builder(DestinationActivity.this);
                builder1.setMessage("no records");
                builder1.show();
            }
            else {
                AlertDialog.Builder builder = new AlertDialog.Builder(DestinationActivity.this);

                builder.setMessage("waiting for magic...");
                builder.show();

                /**
                 * calculate the route
                 */
                if (validate()) {
                    new calRoute().execute();
                }


            }
        }

    });
}



//initialize the data
private void initDestinations() {
    //........
}


@Override
public void onClick(View v) {
    //.......
}


/**
 * asynctask
 */
private class calRoute extends AsyncTask<Void, Void, List<Plan>>{


    public calRoute(){
        // TODO Auto-generated constructor stub
    }


    @Override
    protected List<Plan> doInBackground(Void... params) {

        List<Plan> result = calculate(time_start, time_end, travel_days);

        return result;
    }


    @Override
    protected void onPostExecute(List<Plan> result) {
        super.onPostExecute(result);
        if (result != null) {
            Toast.makeText(DestinationActivity.this, "success", Toast.LENGTH_SHORT).show();

            if(planList.size() > 0) {


                Intent intent = new Intent();
                intent.setClass(DestinationActivity.this, ActivityPlan.class);

                intent.putParcelableArrayListExtra("planInfo", (ArrayList<? extends Parcelable>) planList);

                startActivity(intent);
            }

            else{
                Toast.makeText(DestinationActivity.this, "no plan", Toast.LENGTH_SHORT).show();
            }
        }

    }
}


/**
 *plan
 **/
public List<Plan> calculate(String time_start, String time_end, int travel_days) {


    SimpleDateFormat df = new SimpleDateFormat(("HH:mm"));

    Date starttime = new Date();
    Date endtime = new Date();
    try {
        starttime = df.parse(time_start);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    try {
        endtime = df.parse(time_end);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    double l = endtime.getTime() - starttime.getTime();
    double hour = (l / (60 * 60 * 1000));
    double min = ((l / (60 * 1000)) - hour * 60);

    if(min == 0){
        min = 60;
    }
    else {
        travel_time = ((1.0 * travel_days * hour) * (min / 60)); 
        DecimalFormat decimalFormat = new DecimalFormat("#.0");
        travelTime = Double.parseDouble(decimalFormat.format(travel_time));
    }


    weightMap = new LinkedHashMap<Integer, Double>(); //store weight
    int totalPriority = 0;//total priority

    final Destination start = new Destination(116.32133, 39.92269);


    final HashMap<Integer, Integer> pMap = new HashMap<Integer, Integer>();
    final HashMap<Integer, String> nameMap = new HashMap<Integer, String>();
    final HashMap<Integer, Destination> objectMap = new LinkedHashMap<Integer, Destination>();
    /**
     * get the data from cloud database
     */
            BmobQuery<Destination> query = new BmobQuery<Destination>();
            for (int sid: selectedID) {

                query.addWhereEqualTo("id", sid);


                query.findObjects(new FindListener<Destination>() {

                    @Override
                    public void done(List<Destination> list, BmobException e) {
                        if (e == null) {
                            System.out.println("success:total" + list.size() + "items。");
                            for (Destination destination : list) {


                                int p = destination.getPriority();

                                int id = destination.getId();

                                String name = destination.getName();

                                double longitude = destination.getLongitude();
                                double latitude = destination.getLatitude();

                                objectMap.put(id, new Destination(longitude, latitude));

                                System.out.println(id);


                                double dis = DistanceUtil.distance(start.getLongitude(), start.getLatitude(),
                                        longitude, latitude);

                                pMap.put(id, p);
                                weightMap.put(id, new Double(dis));
                                nameMap.put(id, name);

                            }
                        } else {
                            Log.i("bmob", "error:" + e.getMessage() + "," + e.getErrorCode());
                        }
                    }
                });
            }


    for (Integer key : pMap.keySet()) {
        int p = pMap.get(key).intValue();
        totalPriority = totalPriority + p;
    }


    double weight = 0.0;
    for (Map.Entry<Integer, Double> hm : weightMap.entrySet()) {
        double hm2Value = pMap.get(hm.getKey());
        weight = totalPriority / hm.getValue() * hm2Value;

        weightMap.put(hm.getKey(), weight);
    }


    /**
     * 按照weight值来排序
     * 判断是否传递数据给plan_activity
     */
    MapUtil.sortByValue(weightMap);

    //排好序后计算距离
    Iterator it = weightMap.entrySet().iterator();
    int order = 0;
    while (it.hasNext()) {
        order++;
        Map.Entry entry = (Map.Entry) it.next();
        objectMap.put(new Integer(order), objectMap.get(entry.getKey()));
    }


    PlanTask planTask = new PlanTask();//封装了每个plan计算的方法


    for (Map.Entry<Integer, Double> entry : weightMap.entrySet()) {
        System.out.println("id= " + entry.getKey());


        double play_time = planTask.calPlay_time(weightMap.size(),
                weightMap.get(entry.getKey()), travelTime);

        double driving_time = planTask.calDrive_time(DistanceUtil.distance(
                objectMap.get(entry.getKey()).getLatitude(),
                objectMap.get(entry.getKey()).getLongitude(),
                objectMap.get(entry.getKey() + 1).getLatitude(),
                objectMap.get(entry.getKey() + 1).getLongitude()
        ));

        String arrive_time = "hello world";//未完待续

        String place_name = nameMap.get(entry.getKey());

        Plan plan = new Plan(place_name, arrive_time, driving_time, play_time);

        //传递plan对象list
        planList.add(entry.getKey(), plan);
    }

    return planList;

}

}

当我调试它时,我发现在calculate()函数中,输出

  BmobQuery<Destination> query = new BmobQuery<Destination>();
            for (int sid: selectedID) {

                query.addWhereEqualTo("id", sid);


query.findObjects(new FindListener<Destination>() {

                    @Override
                    public void done(List<Destination> list, BmobException e) {
                        if (e == null) {
                            System.out.println("success:total" + list.size() + "items。");
                            for (Destination destination : list) {

                                int p = destination.getPriority();

                                int id = destination.getId();

                                String name = destination.getName();


                                double longitude = destination.getLongitude();
                                double latitude = destination.getLatitude();

                                objectMap.put(id, new Destination(longitude, latitude));

                                System.out.println(id);

                                //calculate the distance
                                double dis = DistanceUtil.distance(start.getLongitude(), start.getLatitude(),
                                        longitude, latitude);

                                pMap.put(id, p);
                                weightMap.put(id, new Double(dis));
                                nameMap.put(id, name);

                            }
                        } else {
                            Log.i("bmob", "error:" + e.getMessage() + "," + e.getErrorCode());
                        }
                    }
                });

是“成功:共 1 项”。循环结束后,如果我选择了 3 项,则会显示“成功:共 1 项”。 3次,只捕获到最后一项的信息。 AND 三个哈希映射的大小:pMap、nameMap 和 objectMap 均为零。为什么???真是太奇怪了……

LogCAT 中没有错误,但是,有序列表视图无法在第二个活动中显示。请帮助我,这困扰了我很长时间。 谢谢你!!!


不幸的是,我无法弄清楚太多,因为我对反应式编程不太满意,因为该平台通常使用大量 rxjava,但这里有一些可以增强代码的东西

final HashMap<Integer, Integer> pMap = new HashMap<Integer, Integer>();
final HashMap<Integer, String> nameMap = new HashMap<Integer, String>();
final HashMap<Integer, Destination> objectMap = new LinkedHashMap<Integer, Destination>();

/**
 * get the data from cloud database
 */
BmobQuery<Destination> query = new BmobQuery<Destination>();

// this time only one list of three elements is added instead of three lists of one element each
query.addWhereContainedIn("id", Arrays.asList(selectedID));

query.findObjects(new FindListener<Destination>() {
                @Override
                public void done(List<Destination> list, BmobException e) {
                    if (e == null) {
                        System.out.println("success:total" + list.size() + "items。");
                        for (Destination destination : list) {

                            int p = destination.getPriority();

                            int id = destination.getId();

                            String name = destination.getName();


                            double longitude = destination.getLongitude();
                            double latitude = destination.getLatitude();

                            objectMap.put(id, new Destination(longitude, latitude));

                            System.out.println(id);

                            //calculate the distance
                            double dis = DistanceUtil.distance(start.getLongitude(), start.getLatitude(),
                                    longitude, latitude);

                            pMap.put(id, p);
                            weightMap.put(id, new Double(dis));
                            nameMap.put(id, name);

                        }
                        // continue execution here though you won't be able to return a list of plans here
                    } else {
                        Log.i("bmob", "error:" + e.getMessage() + "," + e.getErrorCode());
                    }
                }
});

希望这可以帮助 :)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

android循环出现问题-无法将值放入hashmap 的相关文章

  • JavaFX 多线程 - 连接线程不会更新 UI

    我正在尝试创建一个加载程序对话框 用户可以在其中知道程序正在加载所请求的内容并且程序正在按预期运行 但正因为如此 我需要join 解析器线程和之前继续主线程 这使得对话框空白 解析器任务 java public class ParserTa
  • 如何在 Spring Security 中创建自定义身份验证过滤器?

    我正在尝试创建一个自定义 Spring Security 身份验证过滤器以实现自定义身份验证方案 我花了几个小时阅读 Spring Security 但我找到的所有指南都解释了如何配置基本设置 我正在尝试编写自定义设置 但无法找到有关如何执
  • 删除 android ListView 的底部分隔线

    我有固定的高度ListView 它在列表项之间有分隔线 但它还在最后一个列表项之后显示分隔线 有没有办法在最后一项之后不显示分隔线ListView 只需添加android footerDividersEnabled false 到您的 Li
  • HttpURLConnection.getResponseCode() 冻结执行/不会超时

    我正在编写一个 Android 应用程序 它连接到受密码保护的 cPanel 服务器 Apache 2 2 22 页面 当身份验证凭据正确时 我的连接没有问题 但是 当凭据不正确时 我的 Android 应用程序似乎会冻结在HttpURLC
  • 如何统计List中某个元素出现的次数

    我有一个ArrayList Java的Collection类 如下 ArrayList
  • new Date() 和日历日期之间的区别

    在实践中 下面两个日期有什么区别 Date date new Date Date date Calendar getInstance getTime 我的理解是 new Date 是基于 UTC GMT 的日期 而日历的 getTime 基
  • 更改 Java 字符串中的日期格式

    I ve a String代表一个日期 String date s 2011 01 18 00 00 00 0 我想将其转换为Date并将其输出到YYYY MM DD format 2011 01 18 我怎样才能实现这个目标 好的 根据我
  • Android sqlite 缺少列

    我的 SQLite 数据库缺少一个我知道存在的列 我将无法从 Android 模拟器中提取数据库 因为如果不重写大量代码 就无法使用模拟器填充数据库 logcat 返回sqlite returned error code 1 msg tab
  • Android:直接从浏览器下载文件

    我试图让 Android 浏览器下载特定类型 xxx 的文件 这样我就可以设置一个应用程序与其关联 我已经成功完成了关联部分 因为我已经做到了 以便在资源管理器应用程序中单击正确类型的文件会加载适当的应用程序 我希望这会转移到浏览器 这样如
  • Java KeyListener:按下两个键时如何执行操作?

    请看下面的代码 import java awt event import javax swing import java awt public class KeyCheck extends JFrame private JButton ch
  • 使用 Spring Java 配置自动装配 bean

    是否可以使用Spring的 Autowired用 Java 编写的 Spring 配置中的注释 例如 Configuration public class SpringConfiguration Autowired DataSource d
  • 本机查询 (JPA) 未重置并返回相同的旧结果

    我有一个本机 sql 查询如下 for init i 0 i lt 2 i String sql Select from accounts where id Query query em createNativeQuery sql Acco
  • org.apache.http 软件包在 API 级别 23 中被删除。替代方案是什么?

    在更新到最新的 android API 级别 23 Marshmallow 后 通过 build gradle 添加以下更改后 所有 org apache http 类都不起作用 android compileSdkVersion 23 b
  • 具有 jsonObject 的 android 列表视图

    我正在开展一项活动 该活动请求服务器上的一个 php 文件 此 php 文件将返回给我一个JSONArray having JSONObjects作为它的元素 我明白了jArray并提取其内容 例如所有jsonObjects 每个 json
  • 有人让动物嗅探器插件工作吗?

    maven animal sniffer 插件承诺告诉我我的代码是否有任何对 Java 1 6 或更高版本 API 的引用 这对于我们这些在 MacOSX Snow Leopard 只有官方 1 6 上开发但需要交付到 1 5 环境的人来说
  • 使用可变参数绘制星形

    我的任务是编写程序 允许用户绘制星星 星星的大小和手臂数量可能不同 当我处理基本星时 我使用 GeneralPath 和点表进行处理 int xPoints 55 67 109 73 83 55 27 37 1 43 int yPoints
  • 手写签名对比

    有谁知道java中一种将手写文本样本 例如签名 亲笔签名等 与一个或多个样本进行比较的方法 最好是开源的 你可以看看这个OCR小程序 http www heatonresearch com articles 42 page1 html
  • FirebaseAuth.getInstance().signOut() 不注销

    我尝试从 firebase 注销用户 但在关闭应用程序并再次打开后 用户仍然处于连接状态 我尝试从 firebase 定期注销用户 但没有解决问题 我想知道是什么导致了这个问题 logout setOnClickListener new V
  • 重叠堆叠图像视图

    我正在尝试将图像视图堆叠在一起 70 重叠 我使用了一个frameLayout 并给每个elemnet填充了10 它有效 但是当涉及到处理事件时 这个填充让我很痛苦 有没有更好的重叠视图的方法 使用不同的布局 等 我正在为 Android
  • okHttp3 java.lang.NoSuchMethodError:没有虚拟方法 setCallWebSocket

    我已从 okhttp Retrofit 更新到 okhttp3 Retrofit2 但我的应用程序因此异常而无法启动 FATAL EXCEPTION EventThread Process appli speaky com PID 1470

随机推荐

  • 从 64 位代码访问 32 位 DLL

    我需要迁移 32 位 dll 以便在 64 位 C 以及 C 应用程序中使用它 该dll是用非托管delphi代码编写的 我无法重新编译 dll 唯一的方法是使用进程间通信 IPC 我搜索了很长时间 但没有找到太多相关信息 我找到的最好的指
  • OCaml“else”语法错误

    我是第一次学习 OCaml 我遇到了一个非常模糊的 语法错误 的麻烦 定义函数时generateboxes像这样 let rec generateboxes a b if a add1 b then force newline print
  • 两条弧线之间的交点? (弧 = 一对角之间的距离)

    我正在尝试找到一种方法来计算两条弧之间的交点 我需要用它来确定圆弧在视觉上有多少在右半边 有多少在左半边 我考虑创建右半部分的弧 并将其与实际弧相交 但我花了很多时间来解决这个问题 所以我想在这里问 以前肯定有人做过 编辑 很抱歉 当我在处
  • 如何在 C++ 中从二进制文件中删除部分

    我想使用 C 从二进制文件中删除部分 二进制文件大约有 5 10 MB 左右 我想做的事 搜索 ANSI 字符串 something 一旦找到这个字符串 我想删除接下来的n个字节 例如下面的1MB数据 我想删除这些字符 而不是用 NULL
  • Linq to XML(Base64 编码)

    我必须将 PDF 转换为 Base64 编码并将其写入 XML 文件中的元素 我已经得到了 Base64 编码的字符串 很长 很大 但我工作的规范如下 选择此选项是为了确保 XML 文件可以在没有任何潜在风险的情况下显示和验证 由于处理原始
  • 在 Gnome 或 KDE 中以编程方式在桌面上移动应用程序窗口

    我想使用 C 程序在桌面上重新定位应用程序窗口 我应该如何去做 我需要针对这两种情况的解决方案 当我拥有想要移动的应用程序的源时 通过编写外部程序来移动其他应用程序的窗口 外部 Bash 脚本 xdotool search onlyvisi
  • 如何使用c#使用Youtube api登录程序?

    有this文档 可用的 所以我用了 YouTubeRequestSettings settings new YouTubeRequestSettings Appname devkey textBox1 Text textBox2 Text
  • 使用 mkmap 加载地图时显示标题

    我可以在 iphone 应用程序项目中显示地图 并将图钉放置在我想要的位置 但我希望在视图加载时显示标题和副标题 这是我正在使用的代码 我以为放入 mapView selectAnnotation 注释动画 是 会起作用 但事实并非如此 有
  • 在调试时使用反汇编语言在什么情况下有用

    我有以下基本问题 何时我们应该在调试中涉及反汇编 如何解释反汇编 例如下面每个段代表什么 00637CE3 8B 55 08 mov edx dword ptr arItem 00637CE6 52 push edx 00637CE7 6A
  • 在 PHP 中如何清除 WSDL 缓存?

    在通过php info 保存 WSDL 缓存的位置 tmp 但我不一定知道删除所有以 WSDL 开头的文件是否安全 Yes I should能够删除所有内容 tmp 但我不知道如果我删除所有 WSDL 文件还会产生什么影响 您可以安全地删除
  • C# 根据变量的内容调用方法

    如何根据变量的内容调用方法 ex String S Hello World String Format ToUpper String sFormat s Format resulting in HELLO WORLD 这样我就可以在其他时间
  • 使用 Plink 执行 (sudo) 子命令

    我正在尝试从 Window PowerShell 命令 Linux 机器 这些命令取决于之前命令的失败 通过 因此 我必须将所有命令放在一起 我尝试了多种将命令组合在一起的方法 但最后我只收到第一个命令的输出 PS C Users sams
  • iOS 更新至 10.3.1 破坏了 HTML 输入元素

    我们有一个主要由 iPad 在现场使用的网站 不是一个应用程序 大小适合在 iPad 上使用 显然刚刚发布的更新导致了输入问题 我们有一个 HTML 输入 用于允许他们从保存的图片中进行选择
  • React VR 组件和本机模块代码之间的持久桥梁

    我试图让浏览器将一些 DOM 事件发送到 React VR 组件中 我得到的最接近的是使用 本机模块 的代码 客户端 js const windowEventsModule new WindowEventsModule function i
  • 为什么我的 GUI 看起来总是不正确?

    在 Mac 上使用 Java 中的 Netbeans GUI 构建器构建 Netbeans 中的 GUI 如下所示 当我点击预览时 看起来还不错 但有一些小变化 最后 当我运行它时 它看起来像这样 糟糕 我认为这与 Java 的 外观和感觉
  • Highcharts - 如何在日期时间 x 轴上居中标签?

    我很难弄清楚如何在 Highcharts 中的日期时间 x 轴上居中标签而不使用类别和 tickPlacement 因为 tickPlacement 仅适用于类别 我的轴是动态创建的 因此我不能简单地设置 x 偏移或填充 因为这会导致不同间
  • bv-enable-int2bv-传播选项

    set option bv enable int2bv propagation true 在线工作 但是 我的本地版本对此有所抱怨 说 错误 第 1 行第 43 列 未知参数 bv enable int2bv propagation 这是一
  • Firebase 身份验证自定义声明不会传播到客户端

    我有一个 UID 1 的用户 其中自定义声明设置为 frompos true 我通过以下方式从 ADMIN SDK for java 向该用户设置新的自定义声明 Map
  • Neo4j如何避免超级节点

    在我的 Neo4j 项目中我有Role and Permission代表用户角色和权限的实体 每个User系统中的内容与适当的角色和权限集有关系 I think Role and Permission是某种超级节点 从性能的角度来看 它们将
  • android循环出现问题-无法将值放入hashmap

    这个问题困扰了我很长时间 我使用了一个叫bmob的云数据库 我发现我可以成功获取我想要的数据 但是 循环中可能会出现一些错误 我只能获取最后选择的项目的信息 附注我使用一个名为 Playlist 的数组列表来存储计算数据 我将使用该数据在下