Android Studio:尝试单击列表中的对象并启动新活动时出现NullPointerException

时间:2018-06-13 20:16:02

标签: java android nullpointerexception

我有一个Room数据库,其中包含一个成员列表。列表中有不同的成员。我想点击一个特定的成员,然后它应该开始一个新的活动,我可以看到有关该成员的其他信息。但是当我点击某个成员时,该应用程序崩溃了。

我的适配器代码:

public class MemberListAdapter extends RecyclerView.Adapter<MemberListAdapter.MemberViewHolder> {

    private List<Member> mMember;
    private MemberClickListener listener;


    public interface MemberClickListener {
        void onMemberClick(int position);
    }

    public MemberListAdapter(final MemberClickListener listener) {
        this.listener = listener;
    }


    @Override
    public MemberViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_member, parent, false);
        return new MemberViewHolder(itemView, listener);
    }


    void setMember(List<Member> members) {
        mMember = members;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        if (mMember != null)
            return mMember.size();
        else return 0;
    }


    @Override
    public void onBindViewHolder(MemberViewHolder holder, int position) {
        holder.bind(mMember.get(position), listener);
    }

    class MemberViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private final MemberClickListener listener;
        private final TextView firstname;
        private final TextView surname;
        private final TextView balance;

        MemberViewHolder(View itemView, MemberClickListener listener) {
            super(itemView);
            firstname = itemView.findViewById(R.id.layout_firstname);
            surname = itemView.findViewById(R.id.layout_surname);
            balance = itemView.findViewById(R.id.layout_balance);
            this.listener = listener;

            itemView.setOnClickListener(this);
        }


        public void bind(final Member member, final MemberClickListener listener) {
            firstname.setText(member.getFirstname());
            surname.setText(member.getSurname());
            //balance.setText(toString(member.getBalance()));

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.i("test1", "beforelistenercheck");
                    if (listener != null) {
                        Log.i("test2", "duringlistenercheck");
                        listener.onMemberClick(getAdapterPosition());
                        Log.i("test3", "aftergettingposition");
                    }
                }
            });
        }

        public void onClick(View v) {
            if (listener != null) {
                ********listener.onMemberClick(getAdapterPosition());********
            }
        }
    }
}

我的主要活动代码:

public class MemberMainActivity extends AppCompatActivity implements MemberListAdapter.MemberClickListener{

    private MemberViewModel mMemberViewModel;
    private List<Member> mMember;

    void setMember(List<Member> members) {
        mMember = members;
    }

    public static final int NEW_MEMBER_ACTIVITY_REQUEST_CODE = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_member);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MemberMainActivity.this, NewMemberActivity.class);
                startActivityForResult(intent, NEW_MEMBER_ACTIVITY_REQUEST_CODE);
            }
        });

        RecyclerView recyclerView = findViewById(R.id.recyclerviewcard_member);
        final MemberListAdapter adapter = new MemberListAdapter(this);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        mMemberViewModel = ViewModelProviders.of(this).get(MemberViewModel.class);

        mMemberViewModel.getAllMember().observe(this, new Observer<List<Member>>() {
            @Override
            public void onChanged(@Nullable final List<Member> members) {
                // Update the cached copy of the words in the adapter.
                adapter.setMember(members);
            }
        });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == NEW_MEMBER_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
            Member member = new Member(data.getStringExtra(NewMemberActivity.EXTRA_REPLY), data.getStringExtra(NewMemberActivity.EXTRA_REPLY2));
            mMemberViewModel.insert(member);
        } else {
            Toast.makeText(
                    getApplicationContext(),
                    R.string.empty_not_saved,
                    Toast.LENGTH_LONG).show();
        }
    }


    public void onMemberClick(int position) {
        **********Member member = mMember.get(position);**********
        MemberInfo.open(this, member.getId());
    }
}

点击成员后应启动的活动代码:

public class MemberInfo extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_memberinfo);

        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("MemberID")) {
            long memberid = intent.getLongExtra("MemberID", -1);
            // TODO: get customer details based on customer id
            Bundle bundle = new Bundle();
            bundle.putLong("MemberID", memberid);
            intent.putExtras(bundle);
            startActivity(intent);
        }
        else {
            Toast.makeText(
                    getApplicationContext(),
                    R.string.empty_not_saved,
                    Toast.LENGTH_LONG).show();
        }
    }

    public static void open(Activity activity, long memberid) {
        Intent intent = new Intent(activity, MemberInfo.class);
        intent.putExtra("MemberID", memberid);
        activity.startActivity(intent);
    }
}

错误:

logcat: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
        at com.example.ahash.mainbuchhaltung.Member.MemberMainActivity.onMemberClick(MemberMainActivity.java:81)
        at com.example.ahash.mainbuchhaltung.Member.MemberListAdapter$MemberViewHolder$1.onClick(MemberListAdapter.java:86)
        at android.view.View.performClick(View.java:6256)
        at android.view.View$PerformClick.run(View.java:24701)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

我用星星标记了错误所在的行。 我也尝试用这个问题的答案来解决我的问题:What is a NullPointerException, and how do I fix it?

我的适配器代码中有三个不同的日志,名为“test1”,“test2”和“test3”。我模仿了我的应用程序,我的logcat中显示了“test1”和“test2”,但没有显示“test3”。

我已经为此工作了三个星期,而且我仍然面临着和以前一样的问题。任何人都可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:1)

你的SELECT __DisplayName, EventDate, RIGHT(CONVERT(varchar(20),DATEADD(HOUR, -5 , EventDate), 100),7) + ' to ' + RIGHT(CONVERT(varchar(20), DATEADD(HOUR, -5 , EndDate), 100),7), location, __EventType FROM (SELECT *, ROW_NUMBER() OVER ( PARTITION BY Id ORDER BY eventdate asc ) AS ROWNUM FROM TABLE ) x WHERE ROWNUM = 1 AND __ApprovalStatus = 'Approved' AND __EventType not in ('1','-1'); 在onMemberClick方法中为空。

答案 1 :(得分:1)

我使用您的代码创建了一个新项目,您忘记初始化名为“mMember”的成员列表。

我创建了一个加载假成员的方法,一切都正常运行。

示例:

private void loadFakeData(){
        mMember = new ArrayList<>();
        Member newMember;
        for (int i = 0; i < 10; i++) {
            newMember = new Member();
            newMember.setFirstName("Firstname " + i);
            newMember.setSurName("Surname " + i);

            mMember.add(newMember);
        }
        mAdapter.setMember(mMember);
    }

答案 2 :(得分:0)

当您访问主活动时,private List<Member> mMember未初始化(很可能是在听众中)。

您可以改为private List<Member> mMember = new ArrayList<Member();,并且至少有一个空列表。

作为替代方案,您可以在mMember = new ArrayList<Member>(); mMemberViewModel.getAllMember().observe(this, new Observer<List<Member>>()之前的onCreate()之前的某处插入using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Windows; public partial class MainWindow : Window { private Websocket_listen _listener; public MainWindow() { _listener = new Websocket_listen("127.0.0.1", 13000); _listener.StringReceived += _listener_StringReceived; _listener.Start(); } private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) { _running = false; _listener.Stop(); } private void _listener_StringReceived(string received) { } } public class Websocket_listen { public readonly int port = 13000; public readonly IPAddress localAddr; private TcpListener server = null; private TcpClient client = null; private NetworkStream stream = null; private bool connected = false; private byte[] bytes = new byte[2048]; private byte[] _last_key = new byte[4]; private int _last_message_length; private bool read_more_message; private Thread _current_thread; private bool _running = true; private int _received = 0; private StringBuilder _results = new StringBuilder(); public event Action<string> StringReceived = null; public Websocket_listen(string ipaddress, int port) { this.port = port; localAddr = IPAddress.Parse(ipaddress); server = new TcpListener(localAddr, port); } public void _running_loop() { while (_running) { try { server.Server.ReceiveTimeout = 5000; server.Server.SendTimeout = 5000; client = server.AcceptTcpClient(); // Get a stream object for reading and writing stream = client.GetStream(); } catch (Exception ex) { continue; } while (_running) { try { try { l.AcquireWriterLock(-1); if (messsages.Count > 0) { byte[] msg = System.Text.Encoding.ASCII.GetBytes(messsages[0]); //byte[] msg = System.Text.Encoding.ASCII.GetBytes("Connected to " + Environment.MachineName); Array.Copy(msg, 0, bytes, 2, msg.Length); bytes[0] = 0x81; bytes[1] = (byte)msg.Length; // Send back a response. stream.Write(bytes, 0, msg.Length + 2); messsages.RemoveAt(0); } } finally { l.ReleaseWriterLock(); } } catch { } try { _received = stream.Read(bytes, 0, bytes.Length); } catch { continue; } if (_received == 0) continue; if (!connected) { _is_connection(); continue; } if (!_parse_message()) break; } } try { stream.Close(); client.Close(); } catch (Exception ex) { } } private bool _parse_message() { int offset = 0; int message_length = 0; if (read_more_message) { _last_message_length -= bytes.Length; message_length = _last_message_length; if (message_length < bytes.Length) message_length += 8; } else { _results.Clear(); var trigger = bytes[0]; var magic_byte = bytes[1]; bool is_text = (0x1 & trigger) != 0; bool is_fin = (0x80 & trigger) != 0; if (trigger == 0x88) { connected = false; return false; } /* text = 0x81 binary = 0x82 close 0x88 ping 0x89 pong -0x8A */ if (!is_fin) { return true; } if (!is_text) { return true; } //If the second byte minus 128 is between 0 and 125, this is the length of message. //If it is 126, the following 2 bytes (16-bit unsigned integer), if 127, the following 8 bytes (64-bit unsigned integer) are the length. var r = magic_byte - 128; var key_starts_at = 0; if (r <= 125) { key_starts_at = 2; message_length = r; } else if (r == 126) { key_starts_at = 4; message_length = BitConverter.ToUInt16(new byte[] { bytes[3], bytes[2] }, 0); } else if (r == 127) { key_starts_at = 10; for (var m = 7; m >= 0; --m) { message_length += bytes[m] << (8 * (7 - m)); } } else { // not documented } //// because its encoded _last_message_length = message_length; Array.Copy(bytes, key_starts_at, _last_key, 0, 4); offset = key_starts_at + 4; } for (var mx = 0; mx < message_length && offset + mx < bytes.Length; ++mx) { bytes[offset + mx] = (byte)(bytes[offset + mx] ^ _last_key[mx % 4]); } var new_result = System.Text.Encoding.ASCII.GetString(bytes, offset, Math.Min(message_length, bytes.Length - offset)); _results.Append(new_result); read_more_message = message_length > bytes.Length; if (!read_more_message) { try { StringReceived?.Invoke(_results.ToString()); } catch (Exception ex) { } } return true; } private void _is_connection() { try { string data = System.Text.Encoding.ASCII.GetString(bytes, 0, _received); if (!new Regex("^GET").IsMatch(data)) return; Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine + "Connection: Upgrade" + Environment.NewLine + "Upgrade: websocket" + Environment.NewLine + "Sec-WebSocket-Accept: " + Convert.ToBase64String( SHA1.Create().ComputeHash( Encoding.UTF8.GetBytes( new Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" ) ) ) + Environment.NewLine + Environment.NewLine); stream.Write(response, 0, response.Length); connected = true; } catch (Exception ex) { } } public void Stop() { _running = false; } public void Start() { // Start listening for client requests. server.Start(); _current_thread = new Thread(new ThreadStart(_running_loop)); _current_thread.Start(); } ReaderWriterLock l = new ReaderWriterLock(); List<string> messsages = new List<string>(); internal void Send(string msg) { try { l.AcquireWriterLock(-1); messsages.Add(msg); } catch { } finally { l.ReleaseWriterLock(); } } }