Я отредактировал вопрос, чтобы отразить ответ. Я создавал new Artists()
каждый раз, когда вызывался метод DatabaseHelper getArtists()
. Поэтому я удалил artists = new Artists();
в getArtists()
в классе DatabaseHelper
. Вместо того, чтобы сразу создавать экземпляр его снова и снова, я научился просто использовать контекст его в конструкторе. Поэтому я получаю ссылку Artists()
в конструкторе DatabaseHelper
, как это.ContextWrapper.getResources nullpointer при добавлении строк в TableLayout
public DatabaseController(Context c){
myContext = c;
artists = (Artists) myContext;
}
// ОРИГИНАЛЬНЫЙ ВОПРОС/КОД
Я получаю NPE в android.content.ContextWrapper.getResources(ContextWrapper.java:89)
, и я не могу понять, что происходит. Многие поиски указали, что проблема заключается в том, что getResources вызывается где-то, что не является onCreate, но я не называю getResources нигде.
Я пытаюсь извлечь данные из базы данных и программно заполнить TableLayout из него.
Активность исполнителя.
public class Artists extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private DatabaseController dbcon;
public TableLayout table;
public static int artistPopulateCatcher = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_artists);
table = (TableLayout)findViewById(R.id.table_artists);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_artists);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if(artistPopulateCatcher == 0) {
dbcon = new DatabaseController(this);
dbcon.open();
dbcon.getArtists();
dbcon.close();
}
}
public void AddNewArtistDialog(View view) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
final View layout = LayoutInflater.from(this).inflate(R.layout.addartistdialog, null);
builder.setView(layout)
.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final EditText name = (EditText) layout.findViewById(R.id.edittext_artist_name);
final EditText email = (EditText) layout.findViewById(R.id.edittext_artist_email);
final CheckBox is21 = (CheckBox) layout.findViewById(R.id.checkBox_is21);
String artistIs21;
String artistName;
String artistEmail;
if (is21.isChecked()){
artistIs21 = "Yes";
artistName = name.getText().toString();
artistEmail = email.getText().toString();
dbcon.open();
dbcon.AddArtist(artistName, artistIs21, artistEmail);
dbcon.close();
} else{
artistIs21 = "No";
artistName = name.getText().toString();
artistEmail = email.getText().toString();
dbcon.open();
dbcon.AddArtist(artistName, artistIs21, artistEmail);
dbcon.close();
}
dialog.cancel();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
public void PopulateArtist(String artist, int draw, String is21, String email){
Log.d("TAG", artist+", "+draw+", "+is21);
TableRow tr = new TableRow(this);
tr.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
TextView artistName = new TextView(this);
TextView artistDraw = new TextView(this);
TextView artistIs21 = new TextView(this);
TextView artistEmail = new TextView(this);
artistName.setText(artist);
artistDraw.setText(String.valueOf(draw));
artistIs21.setText(is21);
artistEmail.setText(email);
tr.addView(artistName);
tr.addView(artistDraw);
tr.addView(artistIs21);
tr.addView(artistEmail);
table.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT));
}
Моя база данных Контроллер:
public class DatabaseController{
private DatabaseHelper dbHelper;
public Context myContext;
private SQLiteDatabase db;
public Artists artists;
public DatabaseController(Context c){
myContext = c;
}
public DatabaseController open() throws SQLException{
dbHelper = new DatabaseHelper(myContext);
db = dbHelper.getWritableDatabase();
return this;
}
public void close(){
dbHelper.close();
}
public void AddArtist(String name, String is21, String email){
ContentValues values = new ContentValues();
values.put(DatabaseHelper.KEY_NAME, name);
values.put(DatabaseHelper.KEY_IS21, is21);
values.put(DatabaseHelper.KEY_EMAIL, email);
values.put(DatabaseHelper.KEY_DRAW, 0);
db.insert(DatabaseHelper.TABLE_ARTISTS, null, values);
}
public Cursor getArtists() {
artists.artistPopulateCatcher = 1;
artists = new Artists();
Cursor cursor = db.rawQuery("SELECT * FROM Artists", null);
cursor.moveToFirst();
while (cursor.isAfterLast() == false){
String name = cursor.getString(cursor.getColumnIndex("Name"));
int draw = cursor.getInt(cursor.getColumnIndex("Draw"));
String is21 = cursor.getString(cursor.getColumnIndex("Is21"));
String email = cursor.getString(cursor.getColumnIndex("Email"));
artists.PopulateArtist(name, draw, is21, email);
cursor.moveToNext();
}
return cursor;
}
public int updateArtist(int _id, String artistName, int draw, String is21, String email){
ContentValues cv = new ContentValues();
cv.put(dbHelper.KEY_ID, _id);
cv.put(dbHelper.KEY_NAME, artistName);
cv.put(dbHelper.KEY_DRAW, draw);
cv.put(dbHelper.KEY_IS21, is21);
cv.put(dbHelper.KEY_EMAIL, email);
int i = db.update(dbHelper.TABLE_ARTISTS, cv, dbHelper.KEY_ID + " = "+_id, null);
return i;
}
}
И вот StackTrace:
java.lang.RuntimeException: Unable to start activity ComponentInfo{scarycat.promotertools/scarycat.promotertools.Artists}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2237)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5137)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:718)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getResources(ContextWrapper.java:89)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:78)
at android.support.v7.app.AppCompatActivity.getResources(AppCompatActivity.java:542)
at android.view.View.<init>(View.java:3569)
at android.view.ViewGroup.<init>(ViewGroup.java:459)
at android.widget.LinearLayout.<init>(LinearLayout.java:168)
at android.widget.TableRow.<init>(TableRow.java:61)
at scarycat.promotertools.Artists.PopulateArtist(Artists.java:112)
at scarycat.promotertools.DatabaseController.getArtists(DatabaseController.java:53)
at scarycat.promotertools.Artists.onCreate(Artists.java:55)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5137)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:718)
at dalvik.system.NativeStart.main(Native Method)
Что такое линия Художники.java:117 – USKMobility
TableRow tr = new TableRow (this); –
Метод PopulateArtist находится в деятельности художника? – USKMobility