空对象引用上的'void android.widget.ListView.setAdapter(android.widget.ListAdapter)'

时间:2019-08-18 09:04:18

标签: java android

我是android的新手,我有一个应用程序,当我启动该应用程序时崩溃了。 错误是::

  

试图在空对象引用上调用虚拟方法'void android.widget.ListView.setAdapter(android.widget.ListAdapter)'

我的MainActivity代码是::

public class MainActivity extends AppCompatActivity {

// define channel
    private static final String ChANNEL_ID = "simplified_coding";
    private static final String CHANNEL_NAME = "Simplified Coding";
    private static final String ChANNEL_DESC = "Simplified Coding Notification";

    FloatingActionButton fab;
    Button sendBtn;
    Button sendBtn2;
    EditText phoneEditText;
    EditText plainEditText;


    ListView mListView ;
    ArrayList<Contacts> arrayList;
    ListAdapter listAdapter;


    ArrayAdapter adapter;
    ArrayList<String> listItem;

    MyDatabase MyDb;




    //    static TextView cipherTextView;
    static TextView receivedTextview;

    static String pubKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJoBRPFYZb19vXqpiHzo2gPTq0" +
            "D1Ey++4PohVNboTBfsscUYA8SMPX4/Jz0NmhDbtk1PL3rqOVKubcEyJumxA+l46B" +
            "gNoQsnOBqXfE5Voo0GTbgP4AeN6MnkJ8mhawj3vu2TGmQqtlFYRyYbp6MZ6Q7ops" +
            "kZBKULJJJSwC9qSpewIDAQAB";
    static String privKey="MIICXAIBAAKBgQCJoBRPFYZb19vXqpiHzo2gPTq0D1Ey++4PohVNboTBfsscUYA8" +
            "SMPX4/Jz0NmhDbtk1PL3rqOVKubcEyJumxA+l46BgNoQsnOBqXfE5Voo0GTbgP4A" +
            "eN6MnkJ8mhawj3vu2TGmQqtlFYRyYbp6MZ6Q7opskZBKULJJJSwC9qSpewIDAQAB" +
            "AoGATMqdimMgTS7s5DG0WlLOg5KmpsHFNQWNl/uAl2wLd0wgWPTA8OJJJLV0G1t1" +
            "k3/uCB0qVTmE3T7LAhFLLRwou2wZbw3w48jF4uTXQJex6cf1xHVkXy6jBUVLlddW" +
            "74MQv3pfBRs/s0NsYML4J713r55JNmTU26WDwLA2xPNiosECQQDxAQQb7i1ZmSnr" +
            "9h0J6Ss3SGqpqDr/RRvUjSmCaCZtP/YFyNEd1aseQ8Wc31PpouwFgJbFYPEOAw+n" +
            "h2UECEiHAkEAkjBUvSFOFNnQIeiq1TUN/piEehSa8inLdU1psroVr09GprpS6nGZ" +
            "df66Nv0DhMCw6N1VjywnLNi8ru5zpg34bQJBAIXZWJzihRFT/XJtd+c/Np83evXK" +
            "1ylbCn/b/ofMrDrU4SCJTYrSVn0yipf7eLEzqP3NUu9ATeDIVnNmwPWiXBUCQGCL" +
            "PJs+8IMCqdqK/q8Zf6mA7hR1oTKGeZB5VHGtRP7m+wDHElU0OqXbWP1RsM4uN2dC" +
            "LOwFu8V5SXq5jXS/yy0CQCpkkZ6YEHxcKJGptVyAtC5iYNCun0pYNjrJHflu6ia8" +
            "pvX7FcJBo2l2Kmld6gXDlYnlJpyOSTapMDjSEs/DNr8=";





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().getDecorView().setBackgroundColor(Color.rgb(249, 247, 209));
//      mDatabase = openOrCreateDatabase(SendActivity.DATABASE_NAME, MODE_PRIVATE, null);
        MyDb = new MyDatabase(this);


//        loadContact_FromDatabase();

        arrayList = new ArrayList<>();
        loadDataInListView();



        listItem = new ArrayList<>();
        mListView = (ListView) findViewById(R.id.list_view);



        // floating action button onclick
        fab = (FloatingActionButton) findViewById(R.id.floatingActionButton);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, SendActivity.class);
                startActivity(intent);
            }
        });

        // Database Code
 //       mDatabase = openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null);
//
//        CREATE_TABLE();


        // handel android8 for channel

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(ChANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            channel.setDescription(ChANNEL_DESC);
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }




        Typeface face = Typeface.createFromAsset(getAssets(),
                "fonts/BRoya.ttf");

       }

    private void loadDataInListView() {


        arrayList = MyDb.loadPHone_FromDb();
        listAdapter = new ListAdapter(this, arrayList);
        mListView.setAdapter(listAdapter);
        listAdapter.notifyDataSetChanged();

    }

    private void loadContact_FromDatabase() {
        try {


            Cursor cursor = MyDb.loadContact_FromDatabase();

            if (cursor.getCount() == 0) {
                Toast.makeText(this, "No Data To Show", Toast.LENGTH_SHORT).show();
            } else {
                while (cursor.moveToNext()) {
                    listItem.add(cursor.getString(1));
                }

                adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItem);
                mListView.setAdapter(adapter);
            }

        } catch (Exception ex) {
            Toast.makeText(this, "load data",
                    Toast.LENGTH_LONG).show();

        }
    }

    public String encryptBeforeSend(String inputString) {
        // encrypt
        byte[] userData = inputString.getBytes();
        try {
            byte[] encodeData = myRSA.encryptByPublicKey(userData, pubKey);
//            String encodeStr = new BigInteger(1, encodeData).toString(16);
            String encodeStr = Base64.encodeToString(encodeData, Base64.DEFAULT);
            return encodeStr;
        }
        catch (Exception ex){
            ex.printStackTrace();
            return ex.toString();
        }

    }


    public static String decryptAfterReceive(String receivedMsg) {
        byte[] userData = Base64.decode(receivedMsg, Base64.DEFAULT);
        try {
            byte[] decodeData = myRSA.decryptByPrivateKey(userData,privKey);
            String decodeStr = new String(decodeData);
            return decodeStr;
        }catch (Exception e){
            e.printStackTrace();
            return e.toString();
        }
    }



    public  void receiverHandler(Context context, String sender, String receivedMsg) {

        if(sender == null)
        {
            receivedTextview.setText("sender is null ");
            return;
        }

        if(receivedMsg == null)
        {
            receivedTextview.setText("msg is null ");
            return;
        }

        try {
            String decodedText = decryptAfterReceive(receivedMsg);
            if (decodedText == null) {
                decodedText = receivedMsg;
            }
            String presentableText =  "فرستنده:  " + sender + " \n\n " + decodedText;
            if(receivedTextview == null)
            {

                Intent resultIntent = new Intent(context, MessageActivity.class);
                PendingIntent resultPendingIntent = PendingIntent.getActivity(context,1, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);


                NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(context.getApplicationContext(), ChANNEL_ID)
                                .setSmallIcon(R.drawable.tic_tac_toe)
                                .setContentTitle("دوز")
                                .setContentText(presentableText)
                                .setAutoCancel(true)
                                .setContentIntent(resultPendingIntent)
                                .setPriority(NotificationCompat.PRIORITY_DEFAULT);


                NotificationManagerCompat mNotificationMgr = NotificationManagerCompat.from(context.getApplicationContext());
                mNotificationMgr.notify(1, mBuilder.build());
            }
            else{
                receivedTextview.setText(presentableText);
            }

            MyDb.addContacts(sender, decodedText, context);

        }
        catch (Exception ex)

        {
            Toast.makeText(context, ex.toString(),
                    Toast.LENGTH_LONG).show();

        }


    }

}

我的ListAdapter代码是::

public class ListAdapter extends BaseAdapter {



    Context context;
    ArrayList<Contacts> arrayList;


    public ListAdapter(Context context, ArrayList<Contacts> arrayList){

        this.context = context;
        this.arrayList = arrayList;
    }


    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public Object getItem(int position) {
        return arrayList.get(position);
    }

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


            LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertview = inflater.inflate(R.layout.list_item, null);

            TextView phoneNumber = (TextView)convertview.findViewById(R.id.list_item_textview);

            Contacts contacts = arrayList.get(position);

            phoneNumber.setText(contacts.getPhoneNumber());

        return convertview;
    }

    @Override
    public int getCount() {
        return this.arrayList.size();
    }
}

我的MainActivity.xml代码是::

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="maa.tic_tac_to.MainActivity"
    tools:layout_editor_absoluteY="81dp"
    tools:layout_editor_absoluteX="0dp">


    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/floatingActionButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/add_new_contact"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_margin="16dp"
        android:background="@color/colorAccent"/>



    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true">

    </ListView>


</RelativeLayout>

,list_item.xml是::

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

    <TextView
        android:id="@+id/list_item_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

现在,当我想进入MainActivity时,程序崩溃了! 谁能帮我!! ?????

1 个答案:

答案 0 :(得分:1)

您正在呼叫

loadDataInListView();

之前

mListView = (ListView) findViewById(R.id.list_view);

通过这种方式,当您将适配器设置为mListView时,mListView.setAdapter(listAdapter);为空