Mam bazę danych i wprowadziłem do niej kilka Intów, mam jednak problem bo nim jak mogę pobrać dane z bazy danych i wprowadzić je do zmiennej ?
Baza SQlLite
package com.example.instalingv3;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
public class DatabaseHelper extends SQLiteOpenHelper {
ArrayList<String> selectedItems = new ArrayList<String>();
public static final String DATABASE_NAME = "Number.db";
public static final String TABLE_NAME = "number_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NUMBER";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NUMBER TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(int number){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,number);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result==-1)
return false;
else
return true;
}
// public int getUserDataCount() {
//
// final SQLiteDatabase db = this.getWritableDatabase();
//
// String countQuery = "SELECT * FROM " + TABLE_NAME;
// Cursor cursor = db.rawQuery(countQuery, null);
// cursor.close();
//
// // return count
// return cursor.getCount();
// }
///////////////////////////////////////////////////////////////////////////
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
// public Cursor getInformation(DatabaseOperations dop){
//
// SQLiteDatabase SQ=dop.getReadableDatabase();
// String[] coloumns={TableInfo.};
//
// };
//
// public ArrayList<Model> getAllData() {
//
// selectedItems.clear();//your arraylist
//
// SQLiteDatabase db = this.getWritableDatabase();
// Cursor cursor = db.rawQuery("select * from stars_table", null);
// if (cursor.getCount() != 0) {
// if (cursor.moveToFirst()) {
// do {
// Model item = new Model();//your object
// item.status = cursor.getString(cursor.getColumnIndex("stars")); //your variable
//
//
// cartList.add(item);
//
// } while (cursor.moveToNext());
// }
// }
// cursor.close();
// db.close();
// return cartList;
// }
}
Kod aplikacji
package com.example.instalingv3;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class Start extends AppCompatActivity {
DatabaseHelper myDb;
private int loop = 19;
private int random = 81;
private int[] miss = new int[loop];
private int m = 0;
private int i = -1;
private int j = 0;
private int rand;
private String[] word = new String[]{
"0. word_ang - word_pl\n" + "1. gap year / take a gap year - rok przerwy po ukończeniu szkoły średniej\n" +
"2. safety course - kurs zasad bezpieczeństwa\n" + "3. increase - zwiększać się (o ilości/jakości)\n" +
"4. decrease - zmniejszać się (o ilości/jakości)\n" +
"5. within walking distance - w odległości, którą można pokonać pieszo\n" +
"6. mention - wspomnieć o czymś\n" + "7. overland - drogą lądową / naziemny\n" +
"8. memorable - niezapomniany/ godny zapamiętania\n" +
"9. sign up with - zapisać się/zaangażować/związać się z \n" +
"10. deliverer - doręczyciel/dostawca\n" + "11. paragliding - paralotnia\n" + "12. placement - położenie/lokalizacja\n" +
"13. research - badania naukowe\n" + "14. expences - wydatki\n" + "15. cruise ship - statek rejsowy\n" +
"16. on board - na pokładzie\n" + "17. off the coast - z daleka od brzegu\n" + "18. available - dostępne\n" +
"19. working hours - godziny pracy\n" + "20. deal with - radzić sobie z\n" + "21. counsellor - doradca/opiekun\n" +
"22. freelance - pracować jako wolny strzelec\n" + "23. call back - oddzwonić później\n" + "24. take on - zatrudniać\n" +
"25. hold a certificate - posiadać dyplom\n" + "26. put through - połączyć przez telefon\n" + "27. flood - powódź\n" +
"28. volcanic eruption - wybuch wulkanu\n" + "29. drought - susza\n" + "30. pollution - zanieczyszczenie\n" +
"31. earthquake - trzęsienie ziemi\n" + "32. pump out - wypompowywać/emitować\n" + "33. toward - w kierunku\n" +
"34. grow - rosnąć/uprawiać\n" + "35. canoe - kajak\n" + "36. fireworks - fajerwerki\n" +
"37. light up - rozświetlić\n" + "38. sheke - trząść się\n" + "39. fall off - spadać/odpadać\n" +
"40. twister - tornado/trąba powietrzna\n" + "41. calm - spokojny/nieporuszony\n" +
"42. weatherman - prezenter pogody\n" + "43. strike - uderzyć/nadejść/dopaść\n" +
"44. pray - modlić się\n" + "45. prayer - modlitwa\n" + "46. put down - wpisywać/kłaść\n" +
"47. huge - ogromny/olbrzymi\n" + "48. directly - bezpośrednio\n" + "49. unexpected - nieoczekiwany\n" +
"50. expected - oczekiwany\n" + "51. chase - gonić/ścigać\n" +
"52. awake - obudzony/przebudzony/obudzić/przebudzić się\n" +
"53. prediction - przewidywanie\n" + "54. predict - przewidywać\n" +
"55. spontaneous decision - decyzja spontaniczna\n" + "56. global warming - globalne ocieplenie\n" +
"57. rising level - podnoszący się poziom\n" +
"58. cover - przykrywać/pokrywać/przykrywa/pokrywa (czasownik i rzeczownik)\n" + "59. glacier - lodowiec\n" +
"60. well - studnia\n" + "61. cause - powodować\n" + "62. precious - drogocanny\n" +
"63. collect donations - zbierać datki\n" + "64. fossil fuel - paliwo kopalne\n" +
"65. ice cap - pokrywa lodowa\n" + "66. blanket - koc\n" + "67. shortage - brak/niedobór\n" +
"68. leak - przeciekać/wyciek\n" + "69. dispose of - unieszkodliwić/uporać się z\n" +
"70. dump - skład/zrzut\n" + "71. breed - rasa/gatunek\n" + "72. die out - wymrzeć/wyginąć\n" +
"73. scarce - rzadki/mało spotykany\n" + "74. look for - szukać\n" + "75. look after - opiekować się\n" +
"76. cub - kocię/młode\n" + "77. cuddly - milutki\n" + "78. fierce-looking - wyglądający groźnie\n" +
"79. habitat - środowisko/miejsce występowania\n" + "80. in case of - w razie/jeśli wystąpi\n"
};
private String[] row_spliter = new String[random];
private String[] word_pl = new String[row_spliter.length];
private String[] word_ang = new String[row_spliter.length];
public static final String PREFS_NAME = "MyPrefsFile";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
/////////////////Pobieranie banych z bazy sql//////////////
myDb=new DatabaseHelper(this);
ArrayList<String> theList=new ArrayList<>();
Cursor data = myDb.getAllData();
if(data.getCount()==0){
Toast.makeText(Start.this, "Miaelem z czyms problem sorka", Toast.LENGTH_LONG).show();
}
else{
while(data.moveToNext()){
// data.getInt(1);
rand=data.getInt(1);
}
}
// public ArrayList<Model> getAllData() {
//
// theList.clear();//your arraylist
//
// SQLiteDatabase db = this.getWritableDatabase();
// Cursor cursor = db.rawQuery("select * from "+COL_1, null);
// if (cursor.getCount() != 0) {
// if (cursor.moveToFirst()) {
// do {
// Model item = new Model();//your object
// item.status = cursor.getString(cursor.getColumnIndex("NUMBER")); //your variable
//
//
// theList.add(item);
//
// } while (cursor.moveToNext());
// }
// }
// cursor.close();
// db.close();
// return cartList;
// }
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
i=sharedPreferences.getInt("i",i);
for (int i = 0; i <= random - 1; i++) {
String[] split_n = word[0].split("\n");
for (int j = 0; j <= random - 1; j++) {
row_spliter[j] = split_n[j];
}
}
for (int i = 0; i <= random - 1; i++) {
row_spliter[i] = row_spliter[i].replace(i + ". ", "");
}
String[][] wordsArray = new String[2][row_spliter.length];
for (int i = 0; i <= row_spliter.length - 1; i++) {
String[] word_split = row_spliter[i].split(" - ");
for (int j = 0; j < word_split.length; j++) {
wordsArray[j][i] = word_split[j];
}
}
for (int i = 0; i <= row_spliter.length - 1; i++) {
word_ang[i] = wordsArray[0][i];
word_pl[i] = wordsArray[1][i];
if (word_ang[i].contains("/")) {
word_ang[i] = word_ang[i].substring(0, word_ang[i].indexOf("/"));
}
while (word_ang[i].endsWith(" ") || (word_pl[i].startsWith(" "))) {
if (word_ang[i].endsWith(" ")) {
word_ang[i] = word_ang[i].substring(0, word_ang[i].length() - 1);
}
if (word_pl[i].startsWith(" ")) {
word_pl[i] = word_pl[i].replaceFirst(" ", "");
}
}
}
/////////////////////////////////////////////////////////////////////////////
// rand = (int) (Math.random() * row_spliter.length + 1);
// int rand_back = (int) (Math.random() * row_spliter.length + 1);
// if (rand == rand_back) {
// rand = (int) (Math.random() * row_spliter.length + 1);
// }
/////////////////////////////////////////////////////////////////////////////////////////////
// //Podglad zmiennych zapisanych w bazie danych
// Cursor res=myDb.getAllData();
// if(res.getCount()==0){
// //show message
// //Pokazuje komunikat o bledzie
// showMessage("Error","Nothing found");
// return;
// } else {
// StringBuffer buffer=new StringBuffer();
// while(res.moveToNext()){
// //Wyproawdzanie dannych z bayz danych po nazwie wiersza
// buffer.append("Id :"+res.getString(0)+"\n");
// for(int i=1;i<=loop;i++) {
// buffer.append("Number :" + res.getString(i) + "\n");
// }
// buffer.append("Number :" + res.getString(19) + "\n\n");
// }
// //Show all data
// //Pokazuje w okienku dialogowym wszystkie wprowadzone dane do db
// showMessage("Data",buffer.toString());
// }
i= i+1;
sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("i",i);
editor.commit();
TextView word_random = (TextView) findViewById(R.id.word_random);
// word_random.setText(word_ang[rand] + " -" + i);
word_random.setText(rand);
checkingWord();
}
private void checkingWord() {
Button check = (Button) findViewById(R.id.check);
check.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText user_word = (EditText) findViewById(R.id.user_word);
String user_word_string = user_word.getText().toString();
Intent intent2 = getIntent();
Intent intent = new Intent(Start.this, End.class);
TextView word_random = (TextView) findViewById(R.id.word_random);
// Jezeli piersza tura petli zostanie zakonczona
// if(i>loop) {
// int l=intent2.getIntExtra("l",0);
// String miss_ang=intent2.getStringExtra("miss_ang"+"_"+l);
// String miss_pl=intent2.getStringExtra("miss_pl"+"_"+l);
// int m=intent2.getIntExtra("m",0);
// if(m!=0){
// word_random.setText(miss_ang + " [" + i);
// }
// }
//
intent.putExtra("word_user", user_word_string);
intent.putExtra("word_ang", word_ang[rand]);
intent.putExtra("word_pl", word_pl[rand]);
intent.putExtra("i",i);
startActivity(intent);
}
});
}
public void showMessage(String title, String Message){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}