Created
March 4, 2019 13:54
-
-
Save pteacher/c793988b7d4330bda53e54dda0c71ff5 to your computer and use it in GitHub Desktop.
DB with adapter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package myitschool.com.databaseapp; | |
import android.database.Cursor; | |
import android.database.sqlite.SQLiteDatabase; | |
import android.database.sqlite.SQLiteOpenHelper; | |
import android.support.v7.app.AppCompatActivity; | |
import android.os.Bundle; | |
import android.util.Log; | |
import android.widget.ArrayAdapter; | |
import android.widget.Button; | |
import android.widget.EditText; | |
import android.widget.ListView; | |
import android.widget.SimpleAdapter; | |
import android.widget.Toast; | |
import java.lang.reflect.Array; | |
import java.util.ArrayList; | |
public class MainActivity extends AppCompatActivity { | |
DBHelper dbHelper; | |
ListView lvMain; | |
SQLiteDatabase db; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
lvMain = findViewById(R.id.listview); | |
db = openOrCreateDatabase("players.db", MODE_PRIVATE, null); | |
db.execSQL("CREATE TABLE IF NOT EXISTS scores (id INTEGER PRIMARY KEY AUTOINCREMENT, nickname VARCHAR(10), score INTEGER)"); | |
String nameGen[] = {"KA", "PI", "PO", "ELON", "MUSK", "RO", "MI", "LER", "ZIN", "GO"}; | |
addRecord(nameGen[(int)(Math.random() * nameGen.length)] | |
+ nameGen[(int)(Math.random() * nameGen.length)], | |
(int)(Math.random() * 100) * 5); | |
showDB(); | |
} | |
public void addRecord(String nickname, int score) { | |
db.execSQL(String.format("INSERT INTO scores (nickname, score) VALUES ('%s', %d)", nickname, score)); | |
} | |
public void showDB() { | |
Cursor c = db.rawQuery("SELECT * FROM scores", null); | |
int nicknameIndex = c.getColumnIndex("nickname"); | |
int scoreIndex = c.getColumnIndex("score"); | |
Log.d("MAIN_ACTIVITY", Integer.toString(nicknameIndex) + " - " + Integer.toString(scoreIndex)); | |
ArrayList<String> data = new ArrayList<>(); | |
if (c.moveToFirst()) { | |
do { | |
Toast.makeText(getApplicationContext(), c.getString(nicknameIndex), Toast.LENGTH_SHORT).show(); | |
Toast.makeText(getApplicationContext(), c.getInt(scoreIndex) + "", Toast.LENGTH_SHORT).show(); | |
data.add(c.getString(nicknameIndex) + " " + c.getInt(scoreIndex)); | |
} while (c.moveToNext()); | |
} | |
ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, data.toArray()); | |
lvMain.setAdapter(adapter); | |
adapter.notifyDataSetChanged(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment