【问题标题】:Null pointer Exception error on implementing OnClickListener inside a list view在列表视图中实现 OnClickListener 时出现空指针异常错误
【发布时间】:2014-11-25 07:13:40
【问题描述】:

我正在尝试实现一个列表视图,该视图显示了一些带有呼叫和电子邮件选项的联系人列表。如果按下呼叫按钮,则它应该向该人拨打电话,并且与电子邮件按钮相同。

但这就是问题所在:- 我在列表 Activity 中编写了 OnClickListener,当我运行它时,它给了我一个 Null Pointer Exception 错误。

请指导。提前谢谢。

下面是我的代码。

MyActivity.java

package com.vanjasrivastava.customlistview;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MyActivity extends Activity {

   // Array of strings storing country names
   String[] countries = new String[] {"Mr.Vikas Raina", "Mrs. Jeetu Sharma", "Mr.Kuashik Ghosh", "Mr.Niranjan Lal", "Ms. Swati Garg", "Ms. Manju", "Mr. M. Kakhani", };

   // Array of integers points to images stored in /res/drawable-ldpi/
   int[] flags = new int[]{R.drawable.vikas, R.drawable.jeetu, R.drawable.ghosh, R.drawable.nlal,  R.drawable.swati, R.drawable.manju, R.drawable.manish};

  // Array of strings to store currencies
  String[] currency = new String[]{"Assistant Professor", "Assistant Professor", "Assistant Professor", "Assistant Professor", "Assistant Professor", "Assistant Professor", "Assistant Professor",       };

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_my);

  // Each row in the list stores country name, currency and flag
  List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();

  for(int i=0;i<7;i++){

    HashMap<String, String> hm = new HashMap<String,String>();
    hm.put("txt", " " + countries[i]);
    hm.put("cur"," " + currency[i]);
    hm.put("flag", Integer.toString(flags[i]) );
            aList.add(hm);
   }

  // Keys used in Hashmap
  String[] from = { "flag","txt","cur" };

  // Ids of views in listview_layout
  int[] to = { R.id.flag,R.id.txt,R.id.cur};


  SpecialAdapter adapter = new SpecialAdapter(getBaseContext(), aList, R.layout.mylist, from, to);
  // Getting a reference to listview of main.xml layout file
  ListView listView = ( ListView ) findViewById(R.id.listview);

  // Setting the adapter to the listView
  listView.setAdapter(adapter);

  ImageButton callButton = (ImageButton)findViewById(R.id.call);
  ImageButton mailButton = (ImageButton)findViewById(R.id.email);
  callButton.setOnClickListener(new View.OnClickListener() {

  @Override
  public void onClick(View v) {

  if(v.getId()==R.id.email) {

      phoneCall();
      }
     }
  });

  mailButton.setOnClickListener(new View.OnClickListener() {

  @Override
  public void onClick(View v) {

     if(v.getId()==R.id.email) {

            sendEmail();
        }
       }
      });
    }

    private void phoneCall() {

        String phoneCallUri ="tel:+91 1573 225001";
        Intent phoneCallIntent = new Intent(Intent.ACTION_CALL);
        phoneCallIntent.setData(Uri.parse(phoneCallUri));
        startActivity(phoneCallIntent);
    }

    protected void sendEmail() {

        Log.i("Send email", "");

        String[] TO = {"abc@gmail.com"};
        String[] CC = {"xyz@gmail.com"};
        Intent emailIntent = new Intent(Intent.ACTION_SEND);
        emailIntent.setData(Uri.parse("mailto:"));
        emailIntent.setType("text/plain");

        emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
        emailIntent.putExtra(Intent.EXTRA_CC, CC);
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
        emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message goes here");

        try {

            startActivity(Intent.createChooser(emailIntent, "Send mail..."));
            finish();
            Log.i("Finished sending email...", "");
        } catch (android.content.ActivityNotFoundException ex) {

            Toast.makeText(MyActivity.this, "There is no email client installed.", Toast.LENGTH_SHORT).show();
        }
    }
}

SpecialAdapter.java

package com.vanjasrivastava.customlistview;

/**
 * Created by vanjasrivastava on 11/21/14.
*/
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;

public class SpecialAdapter extends SimpleAdapter {

    private int[] colors = new int[] { 0x50888888, 0x7500aced };

    public SpecialAdapter(Context context, List<HashMap<String, String>> items, int resource,    String[] from, int[] to) {

        super(context, items, resource, from, to);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View view = super.getView(position, convertView, parent);
        int colorPos = position % colors.length;
        view.setBackgroundColor(colors[colorPos]);
        return view;
    }
}

mylist.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/flag"
        android:layout_width="110dp"
        android:layout_height="130dp"
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textSize="20dp"
            android:paddingTop="30dp"
            android:paddingRight="10dp"
            android:paddingBottom="10dp" />

        <TextView
            android:id="@+id/cur"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textSize="15dp"
            android:paddingTop="0.5dp"
            android:paddingRight="5dp"
            android:paddingBottom="5dp" />

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:weightSum="1"
            android:layout_gravity="center_horizontal">

            <ImageButton
                android:id="@+id/call"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:layout_weight="0.5"
                android:paddingTop="10dp"
                android:src="@drawable/cl" />

            <ImageButton
                android:id="@+id/email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="0.5"
                android:paddingTop="10dp"
                android:paddingLeft="10dp"
                android:src="@drawable/email" />

        </LinearLayout>
    </LinearLayout>
</LinearLayout>

更新:

我对代码进行了一些更改,但仍然显示错误: 在行 1. startActivity(Intent) - 错误是“无法解析方法” 2.finish() - 错误是:“无法解析方法” 3. Toast.makeset() - 错误是:“无法解析方法”

这是我更新的代码:

MyActivity.java

 package com.vanjasrivastava.customlistview;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import android.app.Activity;
 import android.content.Intent;
 import android.net.Uri;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.View;
 import android.widget.ImageButton;
 import android.widget.ImageView;
 import android.widget.ListView;
 import android.widget.SimpleAdapter;
 import android.widget.Toast;

 public class MyActivity extends Activity {

 // Array of strings storing country names
 String[] countries = new String[] { "Mr.Vikas Raina","Mrs. Jeetu Sharma","Mr.Kuashik    Ghosh","Mr.Niranjan Lal","Ms. Swati Garg","Ms. Manju", "Mr. M. Kakhani",};
 // Array of integers points to images stored in /res/drawable-ldpi/
 int[] flags = new int[]{R.drawable.vikas,R.drawable.jeetu,R.drawable.ghosh,R.drawable.nlal,     R.drawable.swati,R.drawable.manju,R.drawable.manish};
 // Array of strings to store currencies
 String[] currency = new String[]{"Assistant Professor","Assistant Professor","Assistant Professor",      "Assistant Professor","Assistant Professor","Assistant Professor","Assistant Professor"};

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_my);
 // Each row in the list stores country name, currency and flag
 List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
    for(int i=0;i<7;i++){
        HashMap<String, String> hm = new HashMap<String,String>();
        hm.put("txt", " " + countries[i]);
        hm.put("cur"," " + currency[i]);
        hm.put("flag", Integer.toString(flags[i]) );
        aList.add(hm);
    }

    // Keys used in Hashmap
    String[] from = { "flag","txt","cur" };

    // Ids of views in listview_layout
    int[] to = { R.id.flag,R.id.txt,R.id.cur};

    // Instantiating an adapter to store each items
    // R.layout.listview_layout defines the layout of each item
    //SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.mylist, from, to);
    SpecialAdapter adapter = new SpecialAdapter(getBaseContext(), aList, R.layout.mylist, from, to);
    // Getting a reference to listview of main.xml layout file
    ListView listView = ( ListView ) findViewById(R.id.listview);

    // Setting the adapter to the listView
    listView.setAdapter(adapter);


    }

}

SpecialAdapter.java

 package com.vanjasrivastava.customlistview;

 /**
 * Created by vanjasrivastava on 11/21/14.
 */
    import java.util.HashMap;
    import java.util.List;
    import android.view.View;
    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.net.Uri;
    import android.util.Log;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageButton;
    import android.widget.SimpleAdapter;
    import android.widget.Toast;

    public class SpecialAdapter extends SimpleAdapter {
    private int[] colors = new int[] { 0x50888888, 0x7500aced };
    ImageButton callButton;
    ImageButton mailButton;
    public SpecialAdapter(Context context, List<HashMap<String, String>> items, int resource, String[] from, int[] to) {
    super(context, items, resource, from, to);
   }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    int colorPos = position % colors.length;
    view.setBackgroundColor(colors[colorPos]);


    callButton = (ImageButton) view.findViewById(R.id.call);
    mailButton = (ImageButton) view.findViewById(R.id.email);
    callButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      if (v.getId() == R.id.call) {

                phoneCall();
            }
        }
    });
    mailButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
         if (v.getId() == R.id.email) {
                sendEmail();
            }
        }
    });
    return view;
  }
    private void phoneCall()
    {
        String phoneCallUri ="tel:+91 1573 225001";
        Intent phoneCallIntent = new Intent(Intent.ACTION_CALL);
        phoneCallIntent.setData(Uri.parse(phoneCallUri));
        startActivity(phoneCallIntent);
    }
protected void sendEmail() {
        Log.i("Send email", "");

        String[] TO = {"abc@gmail.com"};
        String[] CC = {"xyz@gmail.com"};
        Intent emailIntent = new Intent(Intent.ACTION_SEND);
        emailIntent.setData(Uri.parse("mailto:"));
        emailIntent.setType("text/plain");


        emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
        emailIntent.putExtra(Intent.EXTRA_CC, CC);
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
        emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message goes here");

        try {
            startActivity(Intent.createChooser(emailIntent, "Send mail..."));
            finish();
            Log.i("Finished sending email...", "");
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(MyActivity.this,
                            "There is no email client installed.", Toast.LENGTH_SHORT).show();
        }
    }


 }

我该如何解决这些错误。 请指导。

【问题讨论】:

  • 可以加个logcat吗?
  • 您在Adapter 中实现onClickListener 的位置?
  • 在 Getview 方法中获取电话/电子邮件按钮的 ID。在 getview 中编写 setOnClickListener 方法。
  • 你错误地实现了onclicklistener,在SpecialAdapter.class中实现onClick
  • 你看到我的回答了吗?你在哪里接触到这个?如果您回复将不胜感激:)

标签: android


【解决方案1】:

以下代码行:

callButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {


        if(v.getId()==R.id.email)
        {

            phoneCall();

        }
    }
});

mailButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.email)
        {

            sendEmail();

        }
    }
});

将上面的代码移到SpecialAdaptergetView()方法中。另外,将android:descendantFocusability="blocksDescendants" 添加到mylist.xml 的最顶部LinearLayout。这将起作用。

【讨论】:

    【解决方案2】:

    编写代码如下:

    您的 SpecialAdapter.java 应该像这样,并跳过 MyActivity.java

    中两个按钮的 clicklisterner
    public class SpecialAdapter extends SimpleAdapter {
       private int[] colors = new int[] { 0x50888888, 0x7500aced };
        ImageButton callButton ,mailButton;
    
    
       public SpecialAdapter(Context context, List<HashMap<String, String>> items, int  
                   resource,    String[] from, int[] to) {
              super(context, items, resource, from, to);
    
          }
    
     @Override
     public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        int colorPos = position % colors.length;
        view.setBackgroundColor(colors[colorPos]);
    
        callButton = (ImageButton)view .findViewById(R.id.call);
        mailButton = (ImageButton)view .findViewById(R.id.email);
    
        callButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
    
    
             // Here  you get the position of clicked item that you can retrive the value   from
             // array with the help of position
    
               // phoneCall();
    
    
        }
    });
    
       mailButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
    
            // Here  you get the position of clicked item that you can retrive the value from
             // array with the help of position
    
              //  sendEmail();
    
    
        }
      });
    
        return view;
      }
    }
    

    【讨论】:

    • 当我按照您的建议进行更改时..它在“findViewById”处显示错误。错误说::“无法解析方法”
    • 如何消除错误“无法解析方法 findViewById(int)”,请您指导一下?甚至它在我写“startActivity(Intent)”的行以及我调用 Toast.maketext() 的地方都显示错误。
    • 更多详情请参考此链接>> (wptrafficanalyzer.in/blog/…)
    【解决方案3】:

    首先,您的代码无法按预期工作,因为您在每次按下通话按钮时检查按钮 ID 是否为“电子邮件”,这始终是错误的。你可以去掉这些检查,它们是多余的。

    正如其他人所建议的,您的 onClick 方法挂钩应该在您的自定义适配器中的 getView() 方法中完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多