在列表视图中实现OnClickListener时出现Null指针异常错误

时间:2014-11-25 07:13:41

标签: android

我正在尝试实现一个列表视图,其中显示了一些带有呼叫和电子邮件选项的联系人列表。如果按下了呼叫按钮,则应该呼叫该人,并使用电子邮件按钮进行呼叫。

但问题是: - 我在列表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) - 错误是&#34;无法解析方法&#34;  2.完成() - 错误是:&#34;无法解决方法&#34;  3. Toast.makeset() - 错误是:&#34;无法解决方法&#34;

这是我更新的代码:

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();
        }
    }


 }

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

3 个答案:

答案 0 :(得分:0)

以下代码行:

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();

        }
    }
});

将上述代码移至getView() SpecialAdapter方法。另外,将android:descendantFocusability="blocksDescendants"添加到LinearLayout的最高mylist.xml。这将有效。

答案 1 :(得分:0)

按如下方式编写代码:

您的 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;
  }
}

答案 2 :(得分:-1)

在其他任何事情之前,您的代码无法按预期工作,因为每当您按下呼叫按钮时,按钮ID都是“电子邮件”,这始终是假的。你可以摆脱那些支票,他们是不情愿的。

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