. lang。RuntimeException:无法启动activity ComponentInfo{com.example.namecardlistview.MainActivity}: java.lang。NullPointerException(复制)

时间:2021-08-19 00:38:22

This question already has an answer here:

这个问题已经有了答案:

I am trying to create my own Android app but am having errors

我正在尝试创建我自己的Android应用程序,但是有错误

Logcat:

Logcat:

02-20 05:51:45.955: I/DB(2527): Database opened
02-20 05:51:46.555: I/DB(2527): Returned 3 rows
02-20 05:51:46.595: D/AndroidRuntime(2527): Shutting down VM
02-20 05:51:46.647: W/dalvikvm(2527): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
02-20 05:51:46.666: E/AndroidRuntime(2527): FATAL EXCEPTION: main
02-20 05:51:46.666: E/AndroidRuntime(2527): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.namecardlistview/com.example.namecardlistview.MainActivity}: java.lang.NullPointerException
02-20 05:51:46.666: E/AndroidRuntime(2527):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
02-20 05:51:46.666: E/AndroidRuntime(2527):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
02-20 05:51:46.666: E/AndroidRuntime(2527):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-20 05:51:46.666: E/AndroidRuntime(2527):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
02-20 05:51:46.666: E/AndroidRuntime(2527):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-20 05:51:46.666: E/AndroidRuntime(2527):     at android.os.Looper.loop(Looper.java:137)
02-20 05:51:46.666: E/AndroidRuntime(2527):     at android.app.ActivityThread.main(ActivityThread.java:5041)
02-20 05:51:46.666: E/AndroidRuntime(2527):     at java.lang.reflect.Method.invokeNative(Native Method)
02-20 05:51:46.666: E/AndroidRuntime(2527):     at java.lang.reflect.Method.invoke(Method.java:511)
02-20 05:51:46.666: E/AndroidRuntime(2527):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-20 05:51:46.666: E/AndroidRuntime(2527):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-20 05:51:46.666: E/AndroidRuntime(2527):     at dalvik.system.NativeStart.main(Native Method)
02-20 05:51:46.666: E/AndroidRuntime(2527): Caused by: java.lang.NullPointerException
02-20 05:51:46.666: E/AndroidRuntime(2527):     at com.example.namecardlistview.MainActivity.refreshDisplay(MainActivity.java:65)
02-20 05:51:46.666: E/AndroidRuntime(2527):     at com.example.namecardlistview.MainActivity.onCreate(MainActivity.java:46)
02-20 05:51:46.666: E/AndroidRuntime(2527):     at android.app.Activity.performCreate(Activity.java:5104)
02-20 05:51:46.666: E/AndroidRuntime(2527):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
02-20 05:51:46.666: E/AndroidRuntime(2527):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
02-20 05:51:46.666: E/AndroidRuntime(2527):     ... 11 more
02-20 05:56:46.835: I/Process(2527): Sending signal. PID: 2527 SIG: 9

MainActivity:

MainActivity:

package com.example.namecardlistview;

import java.util.List;

import com.example.namecardlistview.NewActivity;
import com.example.namecardlistview.DetailActivity;
import com.example.namecardlistview.CardDataSource;
import com.example.namecardlistview.R;
import com.example.namecardlistview.NameCard;
import android.widget.ListView;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.app.Activity;
import android.content.Intent;

public class MainActivity extends ListActivity {

     CardDataSource datasource;
     List<NameCard> cards;
     Long cardID;
     String cardName;
     ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); 


        datasource = new CardDataSource(this);
        datasource.open();
        listView = (ListView) findViewById(R.id.listview); //getListView();
        //ViewGroup header = (ViewGroup) getLayoutInflater().inflate(R.layout.header, listView, false);
        //listView.addHeaderView(header, null, false);
        refreshDisplay();
        //setListAdapter(new ArrayAdapter<String>(this, R.layout.list_fruit,FRUITS));

        listView.setTextFilterEnabled(true); 
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    private void refreshDisplay() { 
         cards = datasource.findAll();
         String[] cardArray= new String[cards.size()];
         for (int i=0; i<cards.size();i++)
         {
             cardArray[i]= cards.get(i).getName();
         }
         listView.setAdapter(new ArrayAdapter<String>(this, R.layout.list_card,cardArray));
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
        position-=1;
        cardID=cards.get(position).getId();
        cardName=cards.get(position).getName();
        Intent intent = new Intent(this,DetailActivity.class);
        intent.putExtra("name", cards.get(position).getName());
        intent.putExtra("id", cards.get(position).getId());
        startActivityForResult(intent, 2);

    }
    public void addCard (MenuItem item){

        // Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show();
        /* Fruit myFruit = new Fruit();
         myFruit.setTitle("Apple");
         myFruit.setDescription("apple is good");
         datasource.create(myFruit);*/
         Intent intent = new Intent(this,NewActivity.class);
         startActivityForResult(intent, 1);
     }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
    // Toast.makeText(this, "listenered activated", Toast.LENGTH_SHORT).show();
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK)
        {
            //String mybenefit =  data.getStringExtra("benefit");
            //fruit.setDescription(mybenefit);

            refreshDisplay();

            Toast.makeText(this, cardName + " is added", Toast.LENGTH_SHORT).show();
        }else if (resultCode==10)
        {
            datasource.removeCard(cardID);
            refreshDisplay();
            Toast.makeText(this, cardName +" is deleted", Toast.LENGTH_SHORT).show();
        }else if (resultCode==11)
        {

            refreshDisplay();
            Toast.makeText(this, cardName +" is updated", Toast.LENGTH_SHORT).show();
        }
    }

}

I just started using * so i have no idea what i am supposed to do. so just tell me whatever code you need.

我刚开始使用*,所以我不知道该怎么做。告诉我你需要什么代码。

Also, is there a easier way to create a code block other than putting 4 spaces for all the lines? EDIT: nevermind fount the shortcut -.- im an idiot

另外,除了为所有行设置4个空格之外,是否还有更简单的方法来创建代码块?编辑:别介意创建快捷方式-。——我是个白痴

EDIT:

编辑:

CardDataSource:

CardDataSource:

package com.example.namecardlistview;

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

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.example.namecardlistview.NameCard;
import com.example.namecardlistview.CardDBOpenHelper;

public class CardDataSource {

public static final String LOGTAG="DB";

    private static final String[] allColumns = {
        CardDBOpenHelper.COLUMN_ID,
        CardDBOpenHelper.COLUMN_NAME,
        CardDBOpenHelper.COLUMN_OCCUPATION,
        CardDBOpenHelper.COLUMN_COMPANY,
        CardDBOpenHelper.COLUMN_EMAIL,
        CardDBOpenHelper.COLUMN_NUMBER,
        CardDBOpenHelper.COLUMN_URL,
        CardDBOpenHelper.COLUMN_SUMMARY,
        CardDBOpenHelper.COLUMN_FAVOURITE};

    SQLiteOpenHelper dbhelper;
    SQLiteDatabase database;

    public CardDataSource(Context context) {
        dbhelper = new CardDBOpenHelper(context);
    }

    public void open() {
        Log.i(LOGTAG, "Database opened");
        database = dbhelper.getWritableDatabase();
    }

    public void close() {
        Log.i(LOGTAG, "Database closed");       
        dbhelper.close();
    }

    public NameCard create(NameCard card) {
        ContentValues values = new ContentValues();
        values.put(CardDBOpenHelper.COLUMN_NAME, card.getName());
        values.put(CardDBOpenHelper.COLUMN_COMPANY, card.getCompany());
        values.put(CardDBOpenHelper.COLUMN_EMAIL, card.getEmail());
        values.put(CardDBOpenHelper.COLUMN_FAVOURITE, card.isFavourite());
        values.put(CardDBOpenHelper.COLUMN_NUMBER, card.getPhone());
        values.put(CardDBOpenHelper.COLUMN_OCCUPATION, card.getOccupation());
        values.put(CardDBOpenHelper.COLUMN_SUMMARY, card.getSummary());
        values.put(CardDBOpenHelper.COLUMN_URL, card.getUrl());
        long insertid = database.insert(CardDBOpenHelper.TABLE_CARDS, null, values);
        card.setId(insertid);
        return card;
    }

    public NameCard update(NameCard card) {
        ContentValues values = new ContentValues();
        values.put(CardDBOpenHelper.COLUMN_NAME, card.getName());
        database.update(CardDBOpenHelper.TABLE_CARDS, values, CardDBOpenHelper.COLUMN_ID+'=' + card.getId(), null);
        return card;
    }

    public List<NameCard> findAll() {
        List<NameCard> cards = new ArrayList<NameCard>();

        Cursor cursor = database.query(CardDBOpenHelper.TABLE_CARDS, allColumns, 
                null, null, null, null, null);

        Log.i(LOGTAG, "Returned " + cursor.getCount() + " rows");
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                NameCard card = new NameCard();
                card.setId(cursor.getLong(cursor.getColumnIndex(CardDBOpenHelper.COLUMN_ID)));
                card.setName(cursor.getString(cursor.getColumnIndex(CardDBOpenHelper.COLUMN_NAME)));
                card.setCompany(cursor.getString(cursor.getColumnIndex(CardDBOpenHelper.COLUMN_COMPANY)));
                card.setEmail(cursor.getString(cursor.getColumnIndex(CardDBOpenHelper.COLUMN_EMAIL)));
                card.setFavourite(1 == cursor.getInt(cursor.getColumnIndex(CardDBOpenHelper.COLUMN_FAVOURITE)));
                card.setOccupation(cursor.getString(cursor.getColumnIndex(CardDBOpenHelper.COLUMN_OCCUPATION)));
                card.setPhone(cursor.getString(cursor.getColumnIndex(CardDBOpenHelper.COLUMN_NUMBER)));
                card.setUrl(cursor.getString(cursor.getColumnIndex(CardDBOpenHelper.COLUMN_URL)));
                card.setSummary(cursor.getString(cursor.getColumnIndex(CardDBOpenHelper.COLUMN_SUMMARY)));
                cards.add(card);
            }
        }
        Log.i(LOGTAG, "Going to return cards now");
        return cards;
    }

    public boolean removeCard(Long id) {

        String where = CardDBOpenHelper.COLUMN_ID + "=" +id ;
        int result = database.delete(CardDBOpenHelper.TABLE_CARDS, where, null);
        return (result == 1);
    }

}

list_card.xml:

list_card.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
<Listview
    android:id="@+id/listview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
</RelativeLayout>

1 个解决方案

#1


2  

You are missing setContentView() method in onCreate().

在onCreate()中缺少setContentView()方法。

#1


2  

You are missing setContentView() method in onCreate().

在onCreate()中缺少setContentView()方法。