Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/188.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java.lang.NullPointerException:Android Studio_Java_Android_Nullpointerexception - Fatal编程技术网

java.lang.NullPointerException:Android Studio

java.lang.NullPointerException:Android Studio,java,android,nullpointerexception,Java,Android,Nullpointerexception,java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“void android.widget.ListView.setAdapter(android.widget.ListAdapter)” 当我试图用聊天适配器设置listView时,第67行出现了一个NullPointerException。下面是课堂: 我已将**放置在获取NullPointerException的行的周围。当我将messageAdapter设置为一个名为ChatAdapter(thi

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“void android.widget.ListView.setAdapter(android.widget.ListAdapter)”

当我试图用聊天适配器设置listView时,第67行出现了一个NullPointerException。下面是课堂:

我已将**放置在获取NullPointerException的行的周围。当我将messageAdapter设置为一个名为ChatAdapter(this)的内部类的新对象时,我并不理解为什么它返回null

导入android.content.Context;
导入android.content.Intent;
导入android.database.Cursor;
导入android.os.Bundle;
导入android.support.annotation.NonNull;
导入android.support.v7.app.AppActivity;
导入android.support.v7.widget.LinearLayoutManager;
导入android.support.v7.widget.RecyclerView;
导入android.support.v7.widget.Toolbar;
导入android.support.design.widget.FloatingActionButton;
导入android.support.design.widget.Snackbar;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.ArrayAdapter;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.ListView;
导入android.widget.TextView;
导入android.widget.Toast;
导入java.util.ArrayList;
导入java.util.List;
公共类MessageListActivity扩展了AppCompatActivity{
/**
*活动是否处于双窗格模式,即在平板电脑上运行
*装置。
*/
列表视图列表视图;
按钮发送按钮;
ArrayList ArrayList=新的ArrayList();
ChatDatabaseHelper Cdb;
私有布尔值窗格;
ChatAdapter messageAdapter=null;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u消息\u列表);
Toolbar Toolbar=(Toolbar)findViewById(R.id.Toolbar);
设置支持操作栏(工具栏);
setTitle(getTitle());
listView=(listView)findViewById(R.id.chatListView);
final EditText EditText=(EditText)findViewById(R.id.messageText);
sendButton=(按钮)findViewById(R.id.sendButton);
messageAdapter=new ChatAdapter(this);//ChatAdapter是内置适配器
**setAdapter(messageAdapter)**
Cdb=新的ChatDatabaseHelper(此);
Cursor Cursor=Cdb.getMessages();//get messages方法的类型为数据库帮助器类中的Cursor
//光标将在数据库中移动以查找下一个文本(如果有)。
while(cursor.moveToNext(){arrayList.add(cursor.getString(cursor.getColumnIndex(Cdb.KEY_MESSAGE)));}
sendButton.setOnClickListener(新视图.OnClickListener(){
@凌驾
public void onClick(View v){//单击send按钮的侦听器
String chatText=editText.getText().toString();//将editText更改为字符串
add(chatText);//将EditTest中的字符串添加到arrayList
布尔值isInserted=Cdb.insertData(ChatterText);//将消息文本插入数据库
如果(isInserted=true)
{Toast.makeText(MessageListActivity.this,“Message Sent”,Toast.LENGTH_SHORT).show();}//如果将消息插入数据库,则此Toast将显示
否则{
Toast.makeText(MessageListActivity.this,“消息未发送”,Toast.LENGTH_SHORT).show();}//如果消息未进入数据库,则此Toast将显示
messageAdapter.notifyDataSetChanged();//通知适配器消息已发送,从传入更改为传出
editText.setText(“”;//将发送按钮上的文本设置为空白。
}//onClick视图的结束
});//onclick侦听器的结尾
if(findViewById(R.id.message\u detail\u container)!=null){
//详图容器视图将仅显示在
//大屏幕布局(res/values-w900dp)。
//如果存在此视图,则
//活动应处于双窗格模式。
mTwoPane=true;
}
}
类ChatAdapter扩展了ArrayAdapter{//自定义适配器类//当您使用它为您形成for循环的所有适配器时。
公共聊天适配器(MessageListActivity ctx){
super(ctx,0);
}//默认构造函数
//方法返回数组中的行数
//将显示运行for循环的次数
public int getCount(){return arrayList.size();}//将返回数组的大小
公共字符串getItem(int-position){return arrayList.get(position);}//将返回位置处的项
//getview方法
@凌驾
公共视图getView(int位置,最终视图convertView,视图组父级){//内部类
LayoutInflater充气器=MessageListActivity.this.getLayoutInflater();//充气器将xml布局充气到视图中。
查看结果=空;
如果(位置%2==0){//如果数组中的位置号为奇数,则执行此操作;如果位置号为偶数,则执行此操作。
结果=充气机。充气(R.layout.chat_row_incoming,null);//根据位置显示布局传入
}否则{
结果=充气器。充气(R.layout.chat_row_outing,null);//根据位置显示布局传出
}
TextView message=(TextView)result.findViewById(R.id.messageText);//创建连接到messageText的TextView类型的消息
最终字符串messageText=getItem(位置);
message.setText(messageText);
result.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
如果(mTwoPane){
Bundle参数=新Bundle();
arguments.putString(MessageDetailFragment.ARG_ITEM_ID,messageText);
MessageDetailFragment=新建MessageDetailFragment();
fragment.setArguments(参数);
getSupportFragmentMana
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

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


public class MessageListActivity extends AppCompatActivity {

/**
 * Whether or not the activity is in two-pane mode, i.e. running on a tablet
 * device.
 */

ListView listView;
Button sendButton;
ArrayList<String> arrayList = new ArrayList<String>(); 
ChatDatabaseHelper Cdb;
private boolean mTwoPane;
ChatAdapter messageAdapter = null;


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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setTitle(getTitle());

    listView = (ListView)findViewById(R.id.chatListView);
    final EditText editText = (EditText)findViewById(R.id.messageText);
    sendButton = (Button)findViewById(R.id.sendButton);
    messageAdapter = new ChatAdapter(this); // chatAdapter is a built in  adapater
    **listView.setAdapter(messageAdapter);**
    Cdb = new ChatDatabaseHelper(this);

    Cursor cursor = Cdb.getMessages(); // get messages method is of type Cursor from database helper class

    // cursor will move through the database to find the next text if there is any.
    while (cursor.moveToNext()) { arrayList.add(cursor.getString(cursor.getColumnIndex(Cdb.KEY_MESSAGE))); }

    sendButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) { // on click listener for the send button

            String chatText =  editText.getText().toString(); // changing editText to String
            arrayList.add(chatText); // adding the string from EditTest to arrayList
            boolean isInserted =  Cdb.insertData(chatText); // inserting the message text into the database
            if(isInserted = true)
            { Toast.makeText(MessageListActivity.this,"Message Sent",Toast.LENGTH_SHORT).show(); } // if the message inserts into the database this toast will show
            else {
                Toast.makeText(MessageListActivity.this,"Message not Sent",Toast.LENGTH_SHORT).show(); } // if message does not nter the database this toast will show
            messageAdapter.notifyDataSetChanged(); // notifying the adapter that a message has been sent, changing from incoming to outgoing
            editText.setText(" "); // set the text on the send button to blank.

        } // end of onClick view

    }); // end of onClickListener


    if (findViewById(R.id.message_detail_container) != null) {
        // The detail container view will be present only in the
        // large-screen layouts (res/values-w900dp).
        // If this view is present, then the
        // activity should be in two-pane mode.
        mTwoPane = true;
    }
}

class ChatAdapter extends ArrayAdapter<String> { // custom adapter class // when youc all the adapter it forms the for loop for you.

    public ChatAdapter(MessageListActivity ctx) {
        super(ctx, 0);
    } // default constructor

    // method to return the number of rows that will be in your array
    // will tell how many times to run a for loop
    public int getCount(){ return arrayList.size(); } // will return the size of the array
    public String getItem(int position){ return arrayList.get(position); } // will return the item at position

    // getview method
    @Override
    public View getView(int position, final View convertView, ViewGroup parent) {// inner class

        LayoutInflater Inflater = MessageListActivity.this.getLayoutInflater(); // an inflater inflates the xml layout into a view.
        View result = null;

        if(position%2 == 0){ // if position number in the array is odd do this, if number is even, do this.
            result = Inflater.inflate(R.layout.chat_row_incoming, null); // depending on the position, show layout incoming

        } else {
            result = Inflater.inflate(R.layout.chat_row_outgoing,null); // depending on the position, show layout outgoing

        }

        TextView message = (TextView)result.findViewById(R.id.messageText); // creating a message of type TextView connected to messageText
        final String messageText = getItem(position) ;
        message.setText(messageText);

        result.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mTwoPane) {
                    Bundle arguments = new Bundle();
                    arguments.putString(MessageDetailFragment.ARG_ITEM_ID,messageText );
                    MessageDetailFragment fragment = new MessageDetailFragment();
                    fragment.setArguments(arguments);
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.message_detail_container, fragment)
                            .commit();
                } else {
                    Context context = v.getContext();
                    Intent intent = new Intent(context, MessageDetailActivity.class);
                    intent.putExtra(MessageDetailFragment.ARG_ITEM_ID,messageText );

                    context.startActivity(intent);
                }

            }
        });

        return result; // return the view which is the Inflater.

    }
} // end of chat adapter class

private void setupRecyclerView(@NonNull RecyclerView recyclerView) {
    recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}

public class SimpleItemRecyclerViewAdapter
        extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {

    private final List<DummyContent.DummyItem> mValues;

    public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
        mValues = items;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.message_list_content, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.mItem = mValues.get(position);
        holder.mIdView.setText(mValues.get(position).id);
        holder.mContentView.setText(mValues.get(position).content);

        holder.mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mTwoPane) {
                    Bundle arguments = new Bundle();
                    arguments.putString(MessageDetailFragment.ARG_ITEM_ID, holder.mItem.id);
                    MessageDetailFragment fragment = new MessageDetailFragment();
                    fragment.setArguments(arguments);
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.message_detail_container, fragment)
                            .commit();
                } else {
                    Context context = v.getContext();
                    Intent intent = new Intent(context, MessageDetailActivity.class);
                    intent.putExtra(MessageDetailFragment.ARG_ITEM_ID, holder.mItem.id);

                    context.startActivity(intent);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mValues.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public final View mView;
        public final TextView mIdView;
        public final TextView mContentView;
        public DummyContent.DummyItem mItem;

        public ViewHolder(View view) {
            super(view);
            mView = view;
            mIdView = (TextView) view.findViewById(R.id.id);
            mContentView = (TextView) view.findViewById(R.id.content);
        }

        @Override
        public String toString() {
            return super.toString() + " '" + mContentView.getText() + "'";
        }
    }
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.ChatWindow">

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/chatListView"
    android:layout_alignParentStart="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentBottom="false"
    android:layout_alignWithParentIfMissing="false"
    android:layout_above="@+id/sendButton" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/sendButton"
    android:id="@+id/sendButton"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:singleLine="true" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/messageText"
    android:layout_toStartOf="@id/sendButton"
    android:layout_alignParentStart="true"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:enabled="true"
    />

 </RelativeLayout>
 messageAdapter = new ChatAdapter(MessageListActivity .this);