我正在尝试保存并在listView上显示条目,当我点击saveBtn时,会出现以下错误。
尝试在空对象引用上调用虚方法'void android.widget.ListView.setAdapter(android.widget.ListAdapter)'“
任何人都可以帮助我吗?
MainActivity.java
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.Image;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity_Write {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button newBtn = (Button) findViewById(R.id.btnNewEntry);
newBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Activity_Write.class));
}
});
}
Activity_Write.java
import android.content.EntityIterator;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by Koh on 11/11/2015.
*/
public class Activity_Write extends AppCompatActivity {
EditText TitleTxt;
EditText WriteTxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write);
TitleTxt = (EditText) findViewById(R.id.txtTitle);
WriteTxt = (EditText) findViewById(R.id.txtWrite);
entryListView = (ListView) findViewById(R.id.listView);
final Button SaveBtn = (Button) findViewById(R.id.btnSave);
SaveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addEntry(TitleTxt.getText().toString(), WriteTxt.getText().toString());
populateList();
finish();
Toast.makeText(getApplicationContext(), "The post has been saved", Toast.LENGTH_SHORT).show();
}
});
TitleTxt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
SaveBtn.setEnabled(!TitleTxt.getText().toString().trim().isEmpty());
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
private void populateList() {
ArrayAdapter<Entry> adapter = new EntryListAdaptor();
entryListView.setAdapter(adapter);
}
private void addEntry(String title, String passage) {
Entries.add(new Entry(title, passage));
}
public class EntryListAdaptor extends ArrayAdapter<Entry> {
public EntryListAdaptor() {
super (Activity_Write.this, R.layout.listview_item, Entries);
}
@Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);
Entry currentEntry = Entries.get(position);
TextView title = (TextView) view.findViewById(R.id.entryTitle);
title.setText(currentEntry.getTitle());
TextView passage = (TextView) view.findViewById(R.id.entryPassage);
passage.setText(currentEntry.getPassage());
return view;
}
}
Entry.java
import android.net.Uri;
/**
* Created by Koh on 12/11/2015.
*/
public class Entry {
public String _title, _passage;
public Entry (String title, String passage) {
_title = title;
_passage = passage;
}
public String getTitle() {
return _title;
}
public String getPassage() {
return _passage;
}
的AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="unipersonalinc.mypersonalediary" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:windowSoftInputMode="stateAlwaysHidden">
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Activity_Write"></activity>
</application>
</manifest>
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:weightSum="1">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="71dp"
android:layout_weight="0.35">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1"
android:focusableInTouchMode="true">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtSearch"
android:layout_weight="0.98"
android:hint="Search..." />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:id="@+id/btnSearch" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sort By Date"
android:id="@+id/btnSortDate"
android:layout_gravity="left"
android:layout_weight="0.90" />
<Button
android:layout_width="174dp"
android:layout_height="wrap_content"
android:text="Sorty By Title"
android:id="@+id/btnSortytitle"
android:layout_gravity="right" />
</LinearLayout>
</LinearLayout>
<ListView
android:layout_width="wrap_content"
android:layout_height="252dp"
android:id="@+id/listView"
android:layout_weight="0.56" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Entry"
android:id="@+id/btnNewEntry"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp" />
</LinearLayout>
</RelativeLayout>
activity_Write.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="vertical"
android:id="@+id/Passagetxt">
<ImageView
android:layout_width="300dp"
android:layout_height="200dp"
android:id="@+id/imEntryImage"
android:layout_gravity="center"
android:src="@drawable/download"
android:layout_marginTop="10dp"
android:layout_marginBottom="0dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/txtTitle"
android:hint="Title..."
android:layout_marginBottom="2dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="@+id/txtWrite"
android:hint="Write Here..."
android:background="#00000000"
android:layout_marginBottom="10dp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/btnSave"
android:layout_gravity="right"
android:enabled="false" />
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Cancel"
android:id="@+id/btnCancel"
android:layout_gravity="right" />
</LinearLayout>
</LinearLayout>
listView_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="100dp"
android:layout_height="80dp"
android:id="@+id/ivEntryImage" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="@+id/entryTitle"
android:layout_marginTop="10dp"
android:text="Title" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/entryPassage"
android:layout_marginTop="10dp"
android:text="Passage" />
</LinearLayout>
DatabaseHandler.Java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Koh on 13/11/2015.
*/
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "entriesManager",
TABLE_ENTRIES = "entries",
KEY_ID = "id",
KEY_TITLE = "title",
KEY_PASSAGE = "passage",
KEY_IMAGEURI = "imageUri";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_ENTRIES + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TITLE + " TEXT," + KEY_PASSAGE + " TEXT," + KEY_IMAGEURI + " TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ENTRIES);
onCreate(db);
}
public void createEntry(Entry entry) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID,entry.getId());
values.put(KEY_TITLE, entry.getTitle());
values.put(KEY_PASSAGE, entry.getPassage());
values.put(KEY_IMAGEURI, entry.getImageUri().toString());
db.insert(TABLE_ENTRIES, null, values);
db.close();
}
public Entry getEntry(int id) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_ENTRIES, new String[] {KEY_ID, KEY_TITLE, KEY_PASSAGE, KEY_IMAGEURI}, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Entry entry = new Entry(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), Uri.parse(cursor.getString(3)));
db.close();
cursor.close();
return entry;
}
public void deleteEntry(Entry entry) {
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_ENTRIES, KEY_ID + "=?", new String[]{String.valueOf(entry.getId())});
db.close();
}
public int getEntriesCount() {
SQLiteDatabase db;
db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_ENTRIES, null);
int count = cursor.getCount();
db.close();
cursor.close();
return count;
}
public int updataEntry(Entry entry) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, entry.getTitle());
values.put(KEY_PASSAGE, entry.getPassage());
values.put(KEY_IMAGEURI, entry.getImageUri().toString());
return db.update(TABLE_ENTRIES, values, KEY_ID + "=?", new String[]{String.valueOf(entry.getId())});
}
public List<Entry> getAllEntries() {
List<Entry> entries = new ArrayList<Entry>();
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_ENTRIES, null);
if (cursor.moveToFirst()) {
do {
Entry entry = new Entry(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), Uri.parse(cursor.getString(3)));
entries.add(entry);
}
while (cursor.moveToNext());
}
return entries;
}
}
答案 0 :(得分:0)
修改MainActivity
和Activity_Write
的代码,如下所示
<强> MainActivity.java 强>
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE = 100;
private List<Entry> entryList;
private ListView lsvtEntries;
private EntryListAdaptor adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button newBtn = (Button) findViewById(R.id.btnNewEntry);
lsvtEntries = (ListView) findViewById(R.id.listView);
entryList = new ArrayList<>();
adapter = new EntryListAdaptor();
lsvtEntries.setAdapter(adapter);
newBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(new Intent(MainActivity.this, Activity_Write.class), REQUEST_CODE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case REQUEST_CODE:
if (data != null) {
String title = data.getStringExtra("Title");
String passage = data.getStringExtra("Passage");
Entry newEntry = new Entry(title, passage);
entryList.add(newEntry);
adapter.notifyDataSetChanged();
}
break;
}
}
}
private class EntryListAdaptor extends ArrayAdapter<Entry> {
private TextView tvTitle, tvMessage;
public EntryListAdaptor() {
super(MainActivity.this, R.layout.layout_item, entryList);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_item, null);
tvTitle = (TextView) convertView.findViewById(R.id.entryTitle);
tvMessage = (TextView) convertView.findViewById(R.id.entryPassage);
tvTitle.setText(entryList.get(position).getTitle());
tvMessage.setText(entryList.get(position).getPassage());
return convertView;
}
}
}
<强> Activity_Write.java 强>
public class Activity_Write extends AppCompatActivity {
EditText TitleTxt;
EditText WriteTxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write);
TitleTxt = (EditText) findViewById(R.id.txtTitle);
WriteTxt = (EditText) findViewById(R.id.txtWrite);
final Button SaveBtn = (Button) findViewById(R.id.btnSave);
SaveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent data = new Intent();
data.putExtra("Title", TitleTxt.getText().toString());
data.putExtra("Passage", WriteTxt.getText().toString());
setResult(RESULT_OK, data);
finish();
Toast.makeText(getApplicationContext(), "The post has been saved", Toast.LENGTH_SHORT).show();
}
});
TitleTxt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
SaveBtn.setEnabled(!TitleTxt.getText().toString().trim().isEmpty());
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
}