热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

为什么我的HashMap中的空值?-WhynullvalueinmyHashMap?

WhyisphonenumberinmyHashMapgivingmeanullvalue?TheideaisthatIloopthroughallcontact

Why is phonenumber in my HashMap giving me a null value? The idea is that I loop through all contacts on my phone. In my try - catch statement, which is working fine, I see all my contacts in logcat with :

为什么我的HashMap中的phonenumber给我一个空值?我的想法是我遍历手机上的所有联系人。在我的try-catch语句中,工作正常,我在logcat中看到了所有联系人:

System.out.println("JSON: " + phonenumber);

But with my code System.out.println("contact is : " + phonenumber); later on in the Hashmap I get in logcat :

但是我的代码是System.out.println(“contact is:”+ phonenumber);后来在Hashmap中我得到了logcat:

contact is : null

I want to post all the phone numbers to a MySql database, can you tell me what I am doing wrong ?

我想将所有电话号码发布到MySql数据库,你能告诉我我做错了什么吗?

public class MainActivity extends AppCompatActivity {

    // this is the php file we are contacting with Volley
    private static final String CHECKPHONENUMBER_URL = "http://www.sitetocheckwithVolley.com/filetocheckwithVolley.php";

    //we are posting phoneNo, which in PHP is phonenumber
    public static final String KEY_PHOnENUMBER= "phonenumber";

    //alContacts is a list of all the phone numbers
    public static final ArrayList alCOntacts= new ArrayList();

    Button buttonCheck;
    TextView textView;

    String phonenumber;

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

        buttOnCheck= (Button) findViewById(R.id.buttonCheck);
        textView = (TextView) findViewById(R.id.textView);



        //get the names and phone numbers of all contacts in phone book
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);

        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {


                String id = cur.getString(
                        cur.getColumnIndex(ContactsContract.Contacts._ID));

                if (cur.getInt(cur.getColumnIndex(
                        ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                    Cursor pCur = cr.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                            new String[]{id}, null);
                    while (pCur.moveToNext()) {
                        String phOneNo= pCur.getString(pCur.getColumnIndex(
                                ContactsContract.CommonDataKinds.Phone.NUMBER));

                        alContacts.add(phoneNo);
                        // break;
                    }
                    pCur.close();

                }
            }
        }

        buttonCheck.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                CheckifUserisContact();
            }
        });

    }



    private void CheckifUserisContact() {

        StringRequest stringRequest = new StringRequest(Request.Method.POST, CHECKPHONENUMBER_URL,
                new Response.Listener() {
                    @Override
                    public void onResponse(String response) {

                        try {

                            JSONObject jsOnObjectContact= new JSONObject();
                            //put all phone contacts into jsonObjectContact
                            for (int i = 0; i  getParams() throws AuthFailureError {
                Map params = new HashMap();
             //The KEY, KEY_PHOnENUMBER= "phonenumber" . In PHP we will have $_POST["phonenumber"]
             //The VALUE, phonenumber, will be of the form "12345678"
                params.put(KEY_PHONENUMBER,phonenumber);
                System.out.println("contact is : " + phonenumber);
                return params;


        }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);


    }

2 个解决方案

#1


1  

I get in logcat :

我进入logcat:

  contact is : null

Because it's never assigned between onCreate and the getParams() methods

因为它从未在onCreate和getParams()方法之间分配

String phonenumber;  // null until onResponse

It'll also continue to be null while alContacts.isEmpty() according to the logic of the code

根据代码的逻辑,它也将继续为null,而alContacts.isEmpty()

//The VALUE, phonenumber, will be of the form "12345678"

// VALUE,phonenumber,形式为“12345678”

Okay, then set it to that instead of not setting it at all

好的,然后将其设置为,而不是根本不设置它

You seem to be using a String phoneNo... Is that what you want instead? Then don't make a secondary String variable and instead assign the field. However, then you only are posting the last string of the contacts, not the whole list

你似乎正在使用一个String phoneNo ...这是你想要的吗?然后不要创建辅助字符串变量,而是分配字段。但是,您只会发布联系人的最后一个字符串,而不是整个列表


Note, this is how to correctly iterate a Cursor

注意,这是如何正确迭代Cursor

   if (cur.moveToFirst()) {
        while (cur.moveToNext()) {

Or simply

for (cur.moveToFirst(); cur.moveToNext(); ) {

And, as pointed out, you're collecting a list, but only putting in one element into the parameters. Did you want to post a JSONArray?

并且,正如所指出的,您正在收集一个列表,但只在参数中加入一个元素。你想发布一个JSONArray吗?

#2


0  

Thanks to cricket_007 answer above, I modified my code like so :

感谢上面的cricket_007回答,我修改了我的代码:

public class MainActivity extends AppCompatActivity {

    // this is the php file we are contacting with Volley
    private static final String CHECKPHONENUMBER_URL = "http://www.thesitetocheck.com/thefiletocheck.php";

    //we are posting phoneNo, which in PHP is phonenumber
    public static final String KEY_PHOnENUMBER= "phonenumber";

    //alContacts is a list of all the phone numbers
    public static final ArrayList alCOntacts= new ArrayList();

    JSONObject jsOnObjectContact= new JSONObject();

    Button buttonCheck;
    TextView textView;
    String phoneNo;

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

        buttOnCheck= (Button) findViewById(R.id.buttonCheck);
        textView = (TextView) findViewById(R.id.textView);



        //get the names and phone numbers of all contacts in phone book
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);

        if (cur.moveToFirst()) {
            while (cur.moveToNext()) {


                String id = cur.getString(
                        cur.getColumnIndex(ContactsContract.Contacts._ID));

                if (cur.getInt(cur.getColumnIndex(
                        ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                    Cursor pCur = cr.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                            new String[]{id}, null);
                    while (pCur.moveToNext()) {
                        phOneNo= pCur.getString(pCur.getColumnIndex(
                                ContactsContract.CommonDataKinds.Phone.NUMBER));

                        alContacts.add(phoneNo);
                        // break;
                    }
                    pCur.close();

                }
            }
        }

        buttonCheck.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                try {


                    //put all phone contacts into jsonObjectContact
                    for (int i = 0; i () {
                    @Override
                    public void onResponse(String response) {

                        }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();

                    }

                }) {

         @Override
            protected Map getParams() throws AuthFailureError {
                Map params = new HashMap();
             //The KEY, KEY_PHOnENUMBER= "phonenumber" . In PHP we will have $_POST["phonenumber"]
             //The VALUE, phonenumber, will be of the form "12345678"
                params.put(KEY_PHONENUMBER,jsonObjectContact.toString());
                System.out.println("contact is : " + jsonObjectContact);
                return params;


        }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);


    }
}

推荐阅读
  • 本文分享了一个关于在C#中使用异步代码的问题,作者在控制台中运行时代码正常工作,但在Windows窗体中却无法正常工作。作者尝试搜索局域网上的主机,但在窗体中计数器没有减少。文章提供了相关的代码和解决思路。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • ASP.NET2.0数据教程之十四:使用FormView的模板
    本文介绍了在ASP.NET 2.0中使用FormView控件来实现自定义的显示外观,与GridView和DetailsView不同,FormView使用模板来呈现,可以实现不规则的外观呈现。同时还介绍了TemplateField的用法和FormView与DetailsView的区别。 ... [详细]
  • 本文介绍了Python爬虫技术基础篇面向对象高级编程(中)中的多重继承概念。通过继承,子类可以扩展父类的功能。文章以动物类层次的设计为例,讨论了按照不同分类方式设计类层次的复杂性和多重继承的优势。最后给出了哺乳动物和鸟类的设计示例,以及能跑、能飞、宠物类和非宠物类的增加对类数量的影响。 ... [详细]
  • 本文介绍了在处理不规则数据时如何使用Python自动提取文本中的时间日期,包括使用dateutil.parser模块统一日期字符串格式和使用datefinder模块提取日期。同时,还介绍了一段使用正则表达式的代码,可以支持中文日期和一些特殊的时间识别,例如'2012年12月12日'、'3小时前'、'在2012/12/13哈哈'等。 ... [详细]
  • Android工程师面试准备及设计模式使用场景
    本文介绍了Android工程师面试准备的经验,包括面试流程和重点准备内容。同时,还介绍了建造者模式的使用场景,以及在Android开发中的具体应用。 ... [详细]
  • 本文介绍了在MFC下利用C++和MFC的特性动态创建窗口的方法,包括继承现有的MFC类并加以改造、插入工具栏和状态栏对象的声明等。同时还提到了窗口销毁的处理方法。本文详细介绍了实现方法并给出了相关注意事项。 ... [详细]
  • 如何自行分析定位SAP BSP错误
    The“BSPtag”Imentionedintheblogtitlemeansforexamplethetagchtmlb:configCelleratorbelowwhichi ... [详细]
  • 本文介绍了使用kotlin实现动画效果的方法,包括上下移动、放大缩小、旋转等功能。通过代码示例演示了如何使用ObjectAnimator和AnimatorSet来实现动画效果,并提供了实现抖动效果的代码。同时还介绍了如何使用translationY和translationX来实现上下和左右移动的效果。最后还提供了一个anim_small.xml文件的代码示例,可以用来实现放大缩小的效果。 ... [详细]
  • Spring源码解密之默认标签的解析方式分析
    本文分析了Spring源码解密中默认标签的解析方式。通过对命名空间的判断,区分默认命名空间和自定义命名空间,并采用不同的解析方式。其中,bean标签的解析最为复杂和重要。 ... [详细]
  • Nginx使用(server参数配置)
    本文介绍了Nginx的使用,重点讲解了server参数配置,包括端口号、主机名、根目录等内容。同时,还介绍了Nginx的反向代理功能。 ... [详细]
  • 标题: ... [详细]
  • 本文介绍了iOS数据库Sqlite的SQL语句分类和常见约束关键字。SQL语句分为DDL、DML和DQL三种类型,其中DDL语句用于定义、删除和修改数据表,关键字包括create、drop和alter。常见约束关键字包括if not exists、if exists、primary key、autoincrement、not null和default。此外,还介绍了常见的数据库数据类型,包括integer、text和real。 ... [详细]
  • Oracle seg,V$TEMPSEG_USAGE与Oracle排序的关系及使用方法
    本文介绍了Oracle seg,V$TEMPSEG_USAGE与Oracle排序之间的关系,V$TEMPSEG_USAGE是V_$SORT_USAGE的同义词,通过查询dba_objects和dba_synonyms视图可以了解到它们的详细信息。同时,还探讨了V$TEMPSEG_USAGE的使用方法。 ... [详细]
  • 本文介绍了在iOS开发中使用UITextField实现字符限制的方法,包括利用代理方法和使用BNTextField-Limit库的实现策略。通过这些方法,开发者可以方便地限制UITextField的字符个数和输入规则。 ... [详细]
author-avatar
weizhe
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有