Форум программистов, компьютерный форум, киберфорум
Программирование Android
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 5.00/4: Рейтинг темы: голосов - 4, средняя оценка - 5.00
0 / 0 / 0
Регистрация: 23.07.2013
Сообщений: 62

База данных

25.10.2019, 14:35. Показов 828. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Подскажите, в чем может быть ошибка при запуске приложения с использование готовой базы данных SQLite, где может быть ошибка, испробовал все варианты, не могу понять где ошибка и как исправить, вот коды по формам JAVA и XML

active_bandit.xml

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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=".BanditActivity">
 
    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">
 
        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/MyColor"
            app:navigationIcon="?attr/actionModeCloseDrawable"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:title="Уголовные авторитеты" />
 
    </com.google.android.material.appbar.AppBarLayout>
 
    <include layout="@layout/content_bandit" />
 
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:backgroundTint="#D32F2F"
        app:srcCompat="@android:drawable/ic_menu_add" />
 
</androidx.coordinatorlayout.widget.CoordinatorLayout>
content_bandit.xml

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    android:background="?attr/colorButtonNormal"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".BanditActivity"
    tools:showIn="@layout/activity_bandit">
 
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
 
        <ImageView
            android:id="@+id/imgPhoto"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            tools:srcCompat="@tools:sample/avatars" />
 
        <TextView
            android:id="@+id/txtName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="clip_vertical|center_vertical"
            android:text="@string/TextAvtor" />
 
        <TextView
            android:id="@+id/txtOpis"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="clip_vertical|center_vertical"
            android:text="@string/TextOpis" />
    </LinearLayout>
 
 
</androidx.constraintlayout.widget.ConstraintLayout>
Манифест

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bandit">
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <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=".BanditActivity"
            android:label="@string/title_activity_bandit"
            android:theme="@style/AppTheme.NoActionBar"></activity>
    </application>
 
</manifest>
DatabaseHelper.java

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package com.example.bandit;
 
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
class DatabaseHelper extends SQLiteOpenHelper {
    private static String DB_PATH; // полный путь к базе данных
    private static String DB_NAME = "band.db";
    private static final int SCHEMA = 1; // версия базы данных
    static final String TABLE = "bandit"; // название таблицы в бд
    // названия столбцов
    static final String COLUMN_ID = "_id";
    static final String COLUMN_NAME = "Name";
    static final String COLUMN_INFO = "Info";
    static final String COLUMN_PICTURE = "Imageinf";
 
    public SQLiteDatabase database;
    private final Context myContext;
    private boolean mNeedUpdate = false;
 
    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, SCHEMA);
        if (android.os.Build.VERSION.SDK_INT >= 17)
            DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
        else
            DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
        this.myContext = context;
 
        copyDataBase();
 
        this.getReadableDatabase();
    }
 
    public void updateDataBase() throws IOException {
        if (mNeedUpdate) {
            File dbFile = new File(DB_PATH + DB_NAME);
            if (dbFile.exists())
                dbFile.delete();
 
            copyDataBase();
 
            mNeedUpdate = false;
        }
    }
 
    private boolean checkDataBase() {
        File dbFile = new File(DB_PATH + DB_NAME);
        return dbFile.exists();
    }
 
    private void copyDataBase() {
        if (!checkDataBase()) {
            this.getReadableDatabase();
            this.close();
            try {
                copyDBFile();
            } catch (IOException mIOException) {
                throw new Error("ErrorCopyingDataBase");
            }
        }
    }
 
    private void copyDBFile() throws IOException {
        //InputStream mInput = myContext.getAssets().open(DB_NAME);
        InputStream mInput = myContext.getResources().openRawResource(R.raw.band);
        OutputStream mOutput = new FileOutputStream(DB_PATH + DB_NAME);
        byte[] mBuffer = new byte[1024];
        int mLength;
        while ((mLength = mInput.read(mBuffer)) > 0)
            mOutput.write(mBuffer, 0, mLength);
        mOutput.flush();
        mOutput.close();
        mInput.close();
    }
 
    public boolean openDataBase() throws SQLException {
        database = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.CREATE_IF_NECESSARY);
        return database != null;
    }
 
    @Override
    public synchronized void close() {
        if (database != null)
            database.close();
        super.close();
    }
 
    @Override
    public void onCreate(SQLiteDatabase db) {
 
    }
 
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (newVersion > oldVersion)
            mNeedUpdate = true;
    }
}
BanditActivity.java

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package com.example.bandit;
 
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
 
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
 
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
 
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
 
 
import java.io.IOException;
 
 
public class BanditActivity extends AppCompatActivity {
 
    private ImageView imgPhoto;
    private TextView txtName;
    private TextView txtOpis;
    private LinearLayout chemaT;
 
    ListView userList;
    DatabaseHelper databaseHelper;
    SQLiteDatabase db;
    Cursor userCursor;
    SimpleCursorAdapter userAdapter;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bandit);
 
        databaseHelper = new DatabaseHelper(this);
        // создаем базу данных
        try {
            databaseHelper.updateDataBase();
        } catch (IOException ioe) {
            throw new Error("Не возможно инициализировать базу данных");
        }
 
        try {
            db = databaseHelper.getWritableDatabase();
        } catch (SQLException sqle) {
            throw sqle;
        }
 
 
        imgPhoto = (ImageView) findViewById(R.id.imgPhoto);
        txtName = (TextView) findViewById(R.id.txtName);
        txtOpis = (TextView) findViewById(R.id.txtOpis);
 
 
 
 
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
 
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }
 
    @Override
    public void onResume() {
        super.onResume();
        // открываем подключение
        db = databaseHelper.getWritableDatabase();
        //получаем данные из бд в виде курсора
        userCursor =  db.rawQuery("select * from "+ DatabaseHelper.TABLE, null);
        // определяем, какие столбцы из курсора будут выводиться в ListView
        String[] headers = new String[] {DatabaseHelper.COLUMN_NAME, DatabaseHelper.COLUMN_INFO, DatabaseHelper.COLUMN_PICTURE};
        // создаем адаптер, передаем в него курсор
        userAdapter = new SimpleCursorAdapter(this, R.layout.content_bandit,
                userCursor, headers, new int[]{R.id.txtName, R.id.txtOpis, R.id.imgPhoto}, 0);
        txtName.setText(String.valueOf(userCursor.getCount()));
        txtOpis.setText(String.valueOf(userCursor.getCount()));
        userAdapter.setViewBinder(new YourViewBinder());
        userList.setAdapter(userAdapter);
    }
 
    public class YourViewBinder  implements SimpleCursorAdapter.ViewBinder {
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
 
            if (view.getId() == R.id.imgPhoto) {
                ImageView iv = (ImageView) view;
                //iv.setImageResource(R.drawable.kazakov);
                try {
                    Bitmap bm = BitmapFactory.decodeStream(getAssets().open(cursor.getString(columnIndex)));
                    iv.setImageBitmap(bm);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return true;
            }
 
            return false;
        }
    }
 
 
    @Override
    public void onDestroy(){
        super.onDestroy();
        // Закрываем подключение и курсор
        db.close();
        userCursor.close();
    }
 
}
После запуска приложения вылетает ошибка вот ее лог

Кликните здесь для просмотра всего текста
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bandit, PID: 17477
java.lang.RuntimeException: Unable to resume activity {com.example.bandit/com.example.bandit.BanditActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(andro id.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performResume Activity(ActivityThread.java:3502)
at android.app.ActivityThread.handleResumeA ctivity(ActivityThread.java:3542)
at android.app.ActivityThread.handleLaunchA ctivity(ActivityThread.java:2790)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessa ge(ActivityThread.java:1523)
at android.os.Handler.dispatchMessage(Handl er.java:102)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(Activity Thread.java:6238)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$Metho dAndArgsCaller.run(ZygoteInit.java:933)
at com.android.internal.os.ZygoteInit.main( ZygoteInit.java:823)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(andro id.widget.ListAdapter)' on a null object reference
at com.example.bandit.BanditActivity.onResu me(BanditActivity.java:96)
at android.app.Instrumentation.callActivity OnResume(Instrumentation.java:1270)
at android.app.Activity.performResume(Activ ity.java:6981)
at android.app.ActivityThread.performResume Activity(ActivityThread.java:3479)
at android.app.ActivityThread.handleResumeA ctivity(ActivityThread.java:3542)*
at android.app.ActivityThread.handleLaunchA ctivity(ActivityThread.java:2790)*
at android.app.ActivityThread.-wrap12(ActivityThread.java)*
at android.app.ActivityThread$H.handleMessa ge(ActivityThread.java:1523)*
at android.os.Handler.dispatchMessage(Handl er.java:102)*
at android.os.Looper.loop(Looper.java:163)*
at android.app.ActivityThread.main(Activity Thread.java:6238)*
at java.lang.reflect.Method.invoke(Native Method)*
at com.android.internal.os.ZygoteInit$Metho dAndArgsCaller.run(ZygoteInit.java:933)*
at com.android.internal.os.ZygoteInit.main( ZygoteInit.java:823)*
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
25.10.2019, 14:35
Ответы с готовыми решениями:

ListView, База данных и SimpleCursorAdapter - onItemClick срабатывает только после добавления данных
Здравствуйте! Подскажите, плиз, решение проблемы новичку... есть БД... подключаюсь через SimpleCursorAdapter ... Нажатие на строке...

База данных!
У меня база данных забита в xml файле, как этот файл подключить к андройд приложению!

база данных
здравствуйте, возник вопрос. приложение создает базу данных, потом пользователь удаляет программу, что происходит с базой данных?

2
1570 / 1168 / 426
Регистрация: 08.05.2012
Сообщений: 5,219
25.10.2019, 15:14
Причём тут база данных, userList нигде не инициализируется, о чём и говорится в ошибке.
0
0 / 0 / 0
Регистрация: 23.07.2013
Сообщений: 62
25.10.2019, 18:42  [ТС]
Хорошо, как инициализировать listview, на форме linearlout, adapter к нему не подключается, не такой функции

Добавлено через 1 час 15 минут
Заработало, вот только данные из таблицы SQLITE не выводятся, показывает только количество строк в базе

Добавлено через 57 минут
Ошибка исправлена, проблема заключалась в создании дополнительного adaptera.xml, на который перекинул два textview и imageview, в строке BanditActivity.java

Java
1
2
       userAdapter = new SimpleCursorAdapter(this, R.layout.content_bandit,
                userCursor, headers, new int[]{R.id.txtName, R.id.txtOpis, R.id.imgPhoto}, 0);
заменил на

Java
1
2
userAdapter = new SimpleCursorAdapter(this, R.layout.adapter_item,
                userCursor, headers, new int[]{R.id.txtName, R.id.txtOpis, R.id.imgPhoto}, 0);
Заработало, осталось только немного скелет поправить - внешний вид, а так пока работает

Спасибо можно тему закрывать

Если кому нужно вот все рабочие части

activity_bandit.xml

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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=".BanditActivity">
 
    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">
 
        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/MyColor"
            app:navigationIcon="?attr/actionModeCloseDrawable"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:title="Уголовные авторитеты" />
 
    </com.google.android.material.appbar.AppBarLayout>
 
    <include layout="@layout/content_bandit" />
 
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:backgroundTint="#D32F2F"
        app:srcCompat="@android:drawable/ic_menu_add" />
 
</androidx.coordinatorlayout.widget.CoordinatorLayout>
adapter_item.xml

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical">
 
    <ImageView
        android:id="@+id/imgPhoto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        tools:srcCompat="@tools:sample/avatars" />
 
    <TextView
        android:id="@+id/txtName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="clip_vertical|center_vertical"
        android:text="@string/TextAvtor" />
 
    <TextView
        android:id="@+id/txtOpis"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="clip_vertical|center_vertical"
        android:text="@string/TextOpis" />
</LinearLayout>
content_bandit.xml

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    android:background="?attr/colorButtonNormal"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".BanditActivity"
    tools:showIn="@layout/activity_bandit">
 
    <TextView
        android:id="@+id/header"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:text="@string/HEADER_KOL"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout"
        app:layout_constraintEnd_toStartOf="@+id/linearLayout"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
 
        <TextView
            android:id="@+id/txtShow"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/Show_text" />
 
        <ListView
            android:id="@+id/userList"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
 
 
</androidx.constraintlayout.widget.ConstraintLayout>
DatabaseHelper.java

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package com.example.bandit;
 
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
class DatabaseHelper extends SQLiteOpenHelper {
    private static String DB_PATH; // полный путь к базе данных
    private static String DB_NAME = "band.db";
    private static final int SCHEMA = 2; // версия базы данных
    static final String TABLE = "bandit"; // название таблицы в бд
    // названия столбцов
    static final String COLUMN_ID = "_id";
    static final String COLUMN_NAME = "Name";
    static final String COLUMN_INFO = "Info";
    static final String COLUMN_PICTURE = "Imageinf";
 
    public SQLiteDatabase database;
    private final Context myContext;
    private boolean mNeedUpdate = false;
 
    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, SCHEMA);
        if (android.os.Build.VERSION.SDK_INT >= 17)
            DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
        else
            DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
        this.myContext = context;
 
        copyDataBase();
 
        this.getReadableDatabase();
    }
 
    public void updateDataBase() throws IOException {
        if (mNeedUpdate) {
            File dbFile = new File(DB_PATH + DB_NAME);
            if (dbFile.exists())
                dbFile.delete();
 
            copyDataBase();
 
            mNeedUpdate = false;
        }
    }
 
    private boolean checkDataBase() {
        File dbFile = new File(DB_PATH + DB_NAME);
        return dbFile.exists();
    }
 
    private void copyDataBase() {
        if (!checkDataBase()) {
            this.getReadableDatabase();
            this.close();
            try {
                copyDBFile();
            } catch (IOException mIOException) {
                throw new Error("ErrorCopyingDataBase");
            }
        }
    }
 
    private void copyDBFile() throws IOException {
        //InputStream mInput = myContext.getAssets().open(DB_NAME);
        InputStream mInput = myContext.getResources().openRawResource(R.raw.band);
        OutputStream mOutput = new FileOutputStream(DB_PATH + DB_NAME);
        byte[] mBuffer = new byte[1024];
        int mLength;
        while ((mLength = mInput.read(mBuffer)) > 0)
            mOutput.write(mBuffer, 0, mLength);
        mOutput.flush();
        mOutput.close();
        mInput.close();
    }
 
    public boolean openDataBase() throws SQLException {
        database = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.CREATE_IF_NECESSARY);
        return database != null;
    }
 
    @Override
    public synchronized void close() {
        if (database != null)
            database.close();
        super.close();
    }
 
    @Override
    public void onCreate(SQLiteDatabase db) {
 
    }
 
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (newVersion > oldVersion)
            mNeedUpdate = true;
    }
}
BanditActivity.java

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package com.example.bandit;
 
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
 
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
 
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
 
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
 
 
import java.io.IOException;
 
 
public class BanditActivity extends AppCompatActivity {
 
    private ImageView imgPhoto;
    private TextView txtName;
    private TextView txtOpis;
    private TextView header;
    private TextView txtShow;
    private LinearLayout chemaT;
 
    ListView userList;
    DatabaseHelper databaseHelper;
    SQLiteDatabase db;
    Cursor userCursor;
    SimpleCursorAdapter userAdapter;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bandit);
 
        databaseHelper = new DatabaseHelper(this);
        // создаем базу данных
        try {
            databaseHelper.updateDataBase();
        } catch (IOException ioe) {
            throw new Error("Не возможно инициализировать базу данных");
        }
 
        try {
            db = databaseHelper.getWritableDatabase();
        } catch (SQLException sqle) {
            throw sqle;
        }
 
 
        imgPhoto = (ImageView) findViewById(R.id.imgPhoto);
        txtName = (TextView) findViewById(R.id.txtName);
        txtOpis = (TextView) findViewById(R.id.txtOpis);
        userList = (ListView) findViewById(R.id.userList);
        header = (TextView) findViewById(R.id.header);
        txtShow = (TextView) findViewById(R.id.txtShow);
 
 
 
 
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
 
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }
 
    @Override
    public void onResume() {
        super.onResume();
        // открываем подключение
        db = databaseHelper.getWritableDatabase();
        //получаем данные из бд в виде курсора
        userCursor =  db.rawQuery("select * from "+ DatabaseHelper.TABLE, null);
        // определяем, какие столбцы из курсора будут выводиться в ListView
        String[] headers = new String[] {DatabaseHelper.COLUMN_NAME, DatabaseHelper.COLUMN_INFO, DatabaseHelper.COLUMN_PICTURE};
        // создаем адаптер, передаем в него курсор
        userAdapter = new SimpleCursorAdapter(this, R.layout.adapter_item,
                userCursor, headers, new int[]{R.id.txtName, R.id.txtOpis, R.id.imgPhoto}, 0);
        header.setText("Количество элементов в базе: " + String.valueOf(userCursor.getCount()));
        userAdapter.setViewBinder(new YourViewBinder());
        userList.setAdapter(userAdapter);
    }
 
    public class YourViewBinder  implements SimpleCursorAdapter.ViewBinder {
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
 
            if (view.getId() == R.id.imgPhoto) {
                ImageView iv = (ImageView) view;
                //iv.setImageResource(R.drawable.kazakov);
                try {
                    Bitmap bm = BitmapFactory.decodeStream(getAssets().open(cursor.getString(columnIndex)));
                    iv.setImageBitmap(bm);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return true;
            }
 
            return false;
        }
    }
 
 
    @Override
    public void onDestroy(){
        super.onDestroy();
        // Закрываем подключение и курсор
        db.close();
        userCursor.close();
    }
 
}
МАНИФЕСТ

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bandit">
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <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=".BanditActivity"
            android:label="@string/title_activity_bandit"
            android:theme="@style/AppTheme.NoActionBar"></activity>
    </application>
 
</manifest>
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
25.10.2019, 18:42
Помогаю со студенческими работами здесь

База данных
Знаю, достал уже с вопросами о базе данных! Так в общем проблема в следующем: я создавал базу данных по примеру...

База данных
На компьютере имеется база данных. Сервер называется localhost( 1-ый слайд). Имеется файл mysql.class.php (расположен в той же папке где и...

База данных!
Бегал по книгам и по сайтам не как не могу разобраться с базами данных в андройд приложениях! package com.example.proba_one; ...

База данных SQLite
Добрый день. Может я повторюсь с вопросом, но вы уж меня простите, не могу найти... Подскажите, пожалуйста, где можно прочитать как создать...

Не создается база данных
Здравствуйте. не получается создать базу данных((((( есть класс: package com.page; import android.content.Context; import...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
Установка Qt Creator для C и C++: ставим среду, CMake и MinGW без фреймворка Qt
8Observer8 05.04.2026
Среду разработки Qt Creator можно установить без фреймворка Qt. Есть отдельный репозиторий для этой среды: https:/ / github. com/ qt-creator/ qt-creator, где можно скачать установщик, на вкладке Releases:. . .
AkelPad-скрипты, структуры, и немного лирики..
testuser2 05.04.2026
Такая программа, как AkelPad существует уже давно, и также давно существуют скрипты под нее. Тем не менее, прога живет, периодически что-то не спеша дополняется, улучшается. Что меня в первую очередь. . .
Отображение реквизитов в документе по условию и контроль их заполнения
Maks 04.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "ПланированиеСпецтехники", разработанного в конфигурации КА2. Данный документ берёт данные из другого нетипового документа. . .
Фото всей Земли с борта корабля Orion миссии Artemis II
kumehtar 04.04.2026
Это первое подобное фото сделанное человеком за 50 лет. Снимок называют новым вариантом легендарной фотографии «The Blue Marble» 1972 года, сделанной с борта корабля «Аполлон-17». Новое фото. . .
Вывод диалогового окна перед закрытием, если документ не проведён
Maks 04.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "СписаниеМатериалов", разработанного в конфигурации КА2. Задача: реализовать программный контроль на предмет проведения документа. . .
Программный контроль заполнения реквизитов табличной части документа
Maks 02.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "СписаниеМатериалов", разработанного в конфигурации КА2. Задача: 1. Реализовать контроль заполнения реквизита. . .
wmic не является внутренней или внешней командой
Maks 02.04.2026
Решение: DISM / Online / Add-Capability / CapabilityName:WMIC~~~~ Отсюда: https:/ / winitpro. ru/ index. php/ 2025/ 02/ 14/ komanda-wmic-ne-naydena/
Программная установка даты и запрет ее изменения
Maks 02.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "СписаниеМатериалов", разработанного в конфигурации КА2. Задача: при создании документов установить период списания автоматически. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru