Using listviews with a database - android

and good day. My project is having 2 activities, first one to insert data into the database which works well, but then I want to show a list view of the data within the database in another activity.
I've tried local data eg fred, george in an array and the list view works great however, when I try to use the database. The activity crashes. It seems that I am unable to use "database.open"
public class MyListActivity extends Activity{
DatabaseAdapter database;
//Creates item_details based on the ListItemDetails class
ListItemDetails item_details;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
//Uses the arraylist and set the result
ArrayList<ListItemDetails> result = GetSearchResults();
ListView lv = (ListView)findViewById(R.id.listView1);
lv.setAdapter(new CustomListAdapter(getApplicationContext(),result));
}
private ArrayList<ListItemDetails> GetSearchResults() {
ArrayList<ListItemDetails> results = new ArrayList<ListItemDetails>();
item_details = new ListItemDetails();
/*
database.open();
Cursor c = database.getAllContacts();
if (c.moveToFirst())
{
do {
item_details.setFirstName(c.getString(1));
results.add(item_details);
} while (c.moveToNext());
}
*/
return results;
}
}
Here is the main activity. The database opens fine when I use the buttonShow, so I tried buttonTest and storing them into the list but it got a bit confusing for me.
public class FamousPersonActivity extends Activity {
EditText editFirstName, editLastName;
Button buttonAdd, buttonShow, buttonTest;
ListView lv;
ListItemDetails item_details;
DatabaseAdapter database;
int request_Code = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_famous_person);
database = new DatabaseAdapter(this);
lv = (ListView)findViewById(R.id.listView1);
//ArrayList<ListItemDetails> result = GetSearchResults();
//lv.setAdapter(new CustomListAdapter(getApplicationContext(),result));
editFirstName = (EditText)findViewById(R.id.editFirstName);
editLastName = (EditText)findViewById(R.id.editLastName);
buttonAdd = (Button)findViewById(R.id.buttonAdd);
buttonShow = (Button)findViewById(R.id.buttonShow);
buttonTest = (Button)findViewById(R.id.buttonTest);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), "added to database", Toast.LENGTH_SHORT).show();
database.open();
long id = database.insertContact("Test Contact", "Test Email") ;
database.close();
}
});
buttonTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent("com.id11020260.exercise6part2.MyListActivity");
startActivityForResult(i, request_Code);
}
});
buttonShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
String destPath = "/data/data/" + getPackageName() +
"/databases";
File f = new File(destPath);
if (!f.exists()) {
f.mkdirs();
f.createNewFile();
//---copy the db from the assets folder into
// the databases folder---
CopyDB(getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath + "/MyDB"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//---get all contacts---
database.open();
Cursor c = database.getAllContacts();
if (c.moveToFirst())
{
do {
DisplayContact(c);
} while (c.moveToNext());
}
database.close();
}
});
}
private ArrayList<ListItemDetails> GetSearchResults() {
ArrayList<ListItemDetails> results = new ArrayList<ListItemDetails>();
item_details = new ListItemDetails();
database.open();
Cursor c = database.getAllContacts();
if (c.moveToFirst())
{
do {
item_details.setFirstName(c.getString(1));
results.add(item_details);
} while (c.moveToNext());
database.close();
}
return results;
}
public void CopyDB(InputStream inputStream,
OutputStream outputStream) throws IOException {
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.famous_person, menu);
return true;
}
public void DisplayContact(Cursor c)
{
Toast.makeText(this,
"id: " + c.getString(0) + "\n" +
"Name: " + c.getString(1) + "\n" +
"Email: " + c.getString(2),
Toast.LENGTH_LONG).show();
}
}
This is the stack trace, I'm not sure if this is entirely correct

Try this:-
lv.setListAdapter(new ArrayAdapter(MyListActivity.this,
android.R.layout.simple_list_item_1,result));

Related

Doesn't wait Timer for user to click on answers in Android Quiz Game, and quickly run

I have navigation drawer with menu nav items. Now I define for one item, for when clicking on it, open a new activity.Inside this activity, I design layout for start flag game quiz.When clicking on play game Button, the game started so fast without waiting for click user, and finish. Inside "PlayGame" layout, I define one imageView for flags and 4 buttons for answers. Flags name and answers come from the External database. When I debug the app, countDownTimer realise null amount, Everything is correct, Just Timer doesn't wait for use, and playing Quiz is so quickly.
this is my database.
WorldCountryDatabase
public class WorldCountryDatabase extends SQLiteOpenHelper {
private static final String TAG = "databaseHelper";
private static final String DB_NAME = "worldCountries.db";
private static final int DB_VERSION = 1;
private static final String TABLE_NAME = "country";
private static String DB_PATH = "";
private Context mContext;
private SQLiteDatabase database;
public WorldCountryDatabase(Context context) {
super(context, DB_NAME, null, DB_VERSION);
DB_PATH = context.getDatabasePath(DB_NAME).getPath();
File file = new File(DB_PATH + "worldCountries.db");
if (file.exists())
openDataBase();
this.mContext = context;
}
public void createDatabase() {
boolean dbExist = checkDatabase();
if (dbExist) {
Log.d("MIN1", "Database already Exist");
} else {
this.getReadableDatabase();
}
try {
copyDataBase();
} catch (IOException e) {
e.printStackTrace();
Log.i("MIN2", e.getMessage());
}
}
private boolean checkDatabase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
} catch (SQLiteException e) {
e.printStackTrace();
Log.d("MIN3", e.getMessage());
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null;
}
public synchronized void close() {
if (database != null) {
database.close();
SQLiteDatabase.releaseMemory();
}
super.close();
}
private void copyDataBase() throws IOException {
try {
InputStream in = mContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream out = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
out.flush();
out.close();
in.close();
Log.d("MIN4", "Database copy");
} catch (SQLiteException e) {
Log.d("MIN5", e.getMessage());
}
}
public Cursor QueryData(String query) {
return database.rawQuery(query, null);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d("MIN6", "onCreate");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
Log.v("LOG_TAG", "Upgrading Database from version" + oldVersion + "To" + newVersion +
"Which will destroy all oldest data");
if (newVersion > oldVersion) {
try {
copyDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void openDataBase() {
String myPath = DB_PATH + DB_NAME;
database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
Log.d("MIN7", "Opened database");
}
// CRUD Table
public List<Questions> getAllQuestions() {
List<Questions> questionsList = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c;
try {
c = db.rawQuery("SELECT * FROM country ORDER BY Random()", null);
if (c == null) return null;
c.moveToFirst();
do {
int Id = c.getInt(c.getColumnIndex("id"));
String Image = c.getString(c.getColumnIndex("Image"));
String AnswerA = c.getString(c.getColumnIndex("AnswerA"));
String AnswerB = c.getString(c.getColumnIndex("AnswerB"));
String AnswerC = c.getString(c.getColumnIndex("AnswerC"));
String AnswerD = c.getString(c.getColumnIndex("AnswerD"));
String CorrectAnswer = c.getString(c.getColumnIndex("CorrectAnswer"));
Questions question = new Questions(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer);
questionsList.add(question);
} while (c.moveToNext());
c.close();
} catch (Exception e) {
e.printStackTrace();
}
database.close();
return questionsList;
}
// Insert Score to Ranking table.
public void insertScore(double score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues content = new ContentValues();
content.put("Score", score);
db.insert("Ranking", null, content);
}
// Get score and sort Ranking.
public List<Ranking> getRanking() {
List<Ranking> rankingList = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c;
try {
c = db.rawQuery("SELECT * FROM country ORDER BY Score DESC;", null);
if (c == null) return null;
c.moveToFirst();
do {
int ID = c.getInt(c.getColumnIndex("id"));
int Score = c.getInt(c.getColumnIndex("Score"));
Ranking ranking = new Ranking(ID, Score);
rankingList.add(ranking);
} while (c.moveToNext());
c.close();
} catch (Exception e) {
e.printStackTrace();
}
db.close();
return rankingList;
}
public int getPlayCount(int level)
{
int result = 0;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c;
try{
c = db.rawQuery("SELECT PlayCount FROM UserPlayCount WHERE Level="+level+";",null);
if(c == null) return 0;
c.moveToNext();
do{
result = c.getInt(c.getColumnIndex("PlayCount"));
}while(c.moveToNext());
c.close();
}catch (Exception ex)
{
ex.printStackTrace();
}
return result;
}
public void updatePlayCount(int level,int playCount)
{
String query = String.format("UPDATE UserPlayCount Set PlayCount = %d WHERE Level = %d",playCount,level);
database.execSQL(query);
}
this is my ChoicGame class.
ChoiceGame
public class ChoiceGame extends AppCompatActivity {
TextView modeText;
SeekBar seekBarMode;
Button playGame, scoreGame;
WorldCountryDatabase worldCountryDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_flag);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
modeText = (TextView) findViewById(R.id.modeText);
seekBarMode = (SeekBar) findViewById(R.id.seekBarMode);
playGame = (Button) findViewById(R.id.playGame);
scoreGame = (Button) findViewById(R.id.scoreGame);
worldCountryDatabase = new WorldCountryDatabase(this);
try {
worldCountryDatabase.createDatabase();
} catch (Exception e) {
e.printStackTrace();
}
//Event
seekBarMode.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (progress == 0)
modeText.setText(Common.MODE.EASY.toString());
else if (progress == 1)
modeText.setText(Common.MODE.MEDIUM.toString());
else if (progress == 2)
modeText.setText(Common.MODE.HARD.toString());
else if (progress == 3)
modeText.setText(Common.MODE.HARDEST.toString());
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
playGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), PlayGameCountry.class);
intent.putExtra("Mode", getPlayMode()); // Send Mode to Playing page
startActivity(intent);
finish();
}
});
scoreGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ScoreGame.class);
startActivity(intent);
finish();
}
});
}
private String getPlayMode() {
if (seekBarMode.getProgress() == 0)
return Common.MODE.EASY.toString();
else if (seekBarMode.getProgress() == 1)
return Common.MODE.MEDIUM.toString();
else if (seekBarMode.getProgress() == 2)
return Common.MODE.HARD.toString();
else
return Common.MODE.HARDEST.toString();
}
}
and at last this is my PlayingGame class.
PlayingGmae
public class PlayGameCountry extends AppCompatActivity implements View.OnClickListener {
final static long INTERVAL = 1; // 1 second
final static long TIMEOUT = 7; // 1 second
CountDownTimer countDownTimer;
int progressValue = 0;
int score = 0, index = 0, thisQuestion = 0, correctAnswer, totalQuestions;
List<Questions> questionsList = new ArrayList<>();
String mode;
ProgressBar progressBar;
ImageView flagCountry;
TextView scoreText, numberQuestion;
Button answerA, answerB, answerC, answerD;
WorldCountryDatabase worldCountryDatabase;
ChoiceGame choiceGame;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_game_country);
// Get data from ChoiceGame
Bundle bundle = getIntent().getExtras();
if (bundle != null)
mode = bundle.getString("Mode");
worldCountryDatabase = new WorldCountryDatabase(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
flagCountry = (ImageView) findViewById(R.id.flagQuiz);
scoreText = (TextView) findViewById(R.id.scoreText);
numberQuestion = (TextView) findViewById(R.id.trueAnswer);
answerA = (Button) findViewById(R.id.firstAnswer);
answerB = (Button) findViewById(R.id.secondAnswer);
answerC = (Button) findViewById(R.id.thirthAnswer);
answerD = (Button) findViewById(R.id.forthAnswer);
progressBar = (ProgressBar) findViewById(R.id.progressUser);
answerA.setOnClickListener(this);
answerB.setOnClickListener(this);
answerC.setOnClickListener(this);
answerD.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
questionsList = this.getQuestionMode(mode);
assert questionsList != null;
totalQuestions = questionsList.size();
countDownTimer = new CountDownTimer(INTERVAL, TIMEOUT) {
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
countDownTimer.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
private void showQuestion(int index) {
if (index < totalQuestions) {
thisQuestion++;
numberQuestion.setText(String.format("%d/%d", thisQuestion, totalQuestions));
progressBar.setProgress(0);
progressValue = 0;
int ImageId = this.getResources().getIdentifier(questionsList.get(index).getImage().toLowerCase(), "drawable", getPackageName());
flagCountry.setBackgroundResource(ImageId);
answerA.setText(questionsList.get(index).getAnswerA());
answerB.setText(questionsList.get(index).getAnswerB());
answerC.setText(questionsList.get(index).getAnswerC());
answerD.setText(questionsList.get(index).getAnswerD());
countDownTimer.start();
} else {
Intent scoreIntent = new Intent(getApplicationContext(), Done.class);
Bundle bundle = new Bundle();
bundle.putInt("SCORE", score);
bundle.putInt("TOTAL", totalQuestions);
bundle.putInt("CORRECT", correctAnswer);
scoreIntent.putExtras(bundle);
startActivity(scoreIntent);
finish();
}
}
#Override
public void onClick(View v) {
countDownTimer.cancel();
if (index < totalQuestions) {
Button clickedButton = (Button) v;
if (clickedButton.getText().equals(questionsList.get(index).getCorrectAnswer()))
{
score += 10; // increase score
correctAnswer++; //increase correct answer
showQuestion(++index);
} else
showQuestion(++index); // If choose right , just go to next question
scoreText.setText(String.format("%d", score));
}
}
private List<Questions> getQuestionMode(String mode) {
List<Questions> questionList = new ArrayList<>();
worldCountryDatabase = new WorldCountryDatabase(this);
try {
worldCountryDatabase.createDatabase();
worldCountryDatabase.openDataBase();
} catch (Exception e) {
e.printStackTrace();
}
int limit = 0;
if (mode.equals(Common.MODE.EASY.toString()))
limit = 30;
else if (mode.equals(Common.MODE.MEDIUM.toString()))
limit = 50;
else if (mode.equals(Common.MODE.HARD.toString()))
limit = 100;
else if (mode.equals(Common.MODE.HARDEST.toString()))
limit = 200;
try {
Cursor cursor = worldCountryDatabase.QueryData(String.format("SELECT * FROM country ORDER BY Random() LIMIT %d", limit));
if (cursor == null) return null;
if (cursor.moveToNext()) {
do {
int Id = cursor.getInt(cursor.getColumnIndex("id"));
String Image = cursor.getString(cursor.getColumnIndex("Image"));
String AnswerA = cursor.getString(cursor.getColumnIndex("AnswerA"));
String AnswerB = cursor.getString(cursor.getColumnIndex("AnswerB"));
String AnswerC = cursor.getString(cursor.getColumnIndex("AnswerC"));
String AnswerD = cursor.getString(cursor.getColumnIndex("AnswerD"));
String CorrectAnswer = cursor.getString(cursor.getColumnIndex("CorrectAnswer"));
Questions question = new Questions(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer);
questionList.add(question);
} while (cursor.moveToNext());
worldCountryDatabase.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return questionList;
}
}
At the first, I defining "getQuestionMode" method inside WorldCountryDatabase, but the app doesn't go to the PlayingCountryGame layout and open ScoreGame class. After I define "getQuestionMode" method inside PlayingCountryGame class. I hope to tell clear my problem.
Please help me, good friends. Thanks to all of you.
I think that you problem is the constructor and values.
https://developer.android.com/reference/android/os/CountDownTimer.html#CountDownTimer(long, long)
The constructor need the time on milliseconds and not seconds. Y ou need convert 1 second to 1000 ms.
final static long INTERVAL = 1000; // 1 second -> 1000 milliseconds
final static long TIMEOUT = 7000; // 7 seconds -> 7000 milliseconds
And the order of the params.
If you want wait 7 second the constructor is:
countDownTimer = new CountDownTimer(TIMEOUT, INTERVAL){ ... }

Listview gets popuplated from the database everytime I start the activity

I am fetching some json data into an EventApp and I am trying to store in SQLite database some of the events. I am showing the events in another activity, not the main one and whenever I go back from that activity to the main one and the I go back to the activity with the listview, the data gets duplicated every time. SO if I click to go to that activity 10 time, my data gets 10 times in the listview and in the database as well. How can I fix this?
SQLiteDatabase db = getWritableDatabase();
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
//Add new row to the database
public void addEvent(Event ev){
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.TITLE, ev.getTitle());
contentValues.put(DatabaseHelper.START_DATE, ev.getStartTime());
contentValues.put(DatabaseHelper.END_DATE, ev.getEndTime());
contentValues.put(DatabaseHelper.IMAGE_URL, ev.getImageURL());
contentValues.put(DatabaseHelper.URL, ev.getUrl());
contentValues.put(DatabaseHelper.SUBTITLE, ev.getSubtitle());
contentValues.put(DatabaseHelper.DESCRIPTION, ev.getDescription());
db.insert(TABLE_NAME, null, contentValues);
//db.close();
}
//Delete event from database
public void deleteEvent(String eventTitle){
db.execSQL("DELETE FROM " + TABLE_NAME + "WHERE " + TITLE + "=\"" + eventTitle + "\";" );
}
public int deleteEvents() {
return db.delete(DatabaseHelper.TABLE_NAME, null, null);
}
//Print the database as string
public String databaseToString(){
String dbString="";
//points to a location in results
Cursor c = getEvents();
while (c.moveToNext()){
if(c.getString(c.getColumnIndex("Title")) != null){
dbString += c.getString(c.getColumnIndex("Title"));
dbString += "\n";
}
}
//db.close();
return dbString;
}
public Cursor getEvents(){
return db.query(TABLE_NAME, ALL_COLUMNS, null, null, null, null, null, null);
}
}
This is the activity where I show the data from the database
public class StoredEventsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stored_events);
ListView listView = (ListView) findViewById(R.id.lv_stored_events);
Intent intent = getIntent();
ArrayList<Event> events = new ArrayList<Event>();
events = (ArrayList<Event>) intent.getSerializableExtra("storedEvents");
EventAdapter adapter = new EventAdapter(this, R.layout.list_view_row, R.id.stored, events );
listView.setAdapter(adapter);
}
}
Here is the method that returns the stored events
public static ArrayList<Event> returnStoredEvents(){
long id = -1;
//getStoredEvents();
Cursor c = eventsDB.getEvents();
while (c.moveToNext()){
id = c.getInt(c.getColumnIndex(eventsDB.ID));
String title = c.getString(c.getColumnIndex(eventsDB.TITLE));
String start = c.getString(c.getColumnIndex(eventsDB.START_DATE));
String end = c.getString(c.getColumnIndex(eventsDB.END_DATE));
organizeEvents.add(new Event(title, start, end, true));
}
c.close();
Log.d("DATABASE", organizeEvents.toString());
return organizeEvents;
}
Here is where I actually add some of the events:
private void readEvents(String str){
Event ev = null;
try {
JSONObject geoJSON = new JSONObject(str);
JSONArray jsonEvents = geoJSON.getJSONArray("events");
for (int i = 0; i < jsonEvents.length(); i++) {
JSONObject event = jsonEvents.getJSONObject(i);
JSONArray timeJsonEvent = event.getJSONArray("datelist");
JSONObject time = timeJsonEvent.getJSONObject(0);
title = event.getString("title_english");
Date date = new Date(time.getLong("start"));
startDate = dateFormat.format(date);
date = new Date(time.getLong("end"));
endDate = dateFormat.format(date);
imageURL = event.getString("picture_name");
url = event.getString("url");
subtitle = event.getString("subtitle_english");
description = event.getString("description_english");
if (title.charAt(0) == 'T') {
ev = new Event(title, startDate, endDate, true);
eventsDB.addEvent(ev);
}else {
ev = new Event(title, startDate, endDate, false);
}
// Process a newly found event
final Event finalEv = ev;
handler.post(new Runnable() {
public void run() {
addNewEvent(finalEv);
}
});
}
}catch (Exception e) {
Log.d(null, e.getMessage());
}
}
And here is my main:
public class MainActivity extends AppCompatActivity{
DatabaseHelper eventsDB;
ListFragment listFragment;
SimpleCursorAdapter adapter;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eventsDB = new DatabaseHelper(this);
//storedEvents.addAll(EventsListFragment.returnStoredEvents());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getTitle().equals("Sort by name")){
Toast.makeText(this, "ITEM 2 CLICKED", Toast.LENGTH_LONG).show();
EventsListFragment.sort(-1);
}else if (item.getTitle().equals("Sort by date")) {
EventsListFragment.sort(1);
}else if (item.getTitle().equals("Stored events")){
showSavedEvents();
Toast.makeText(this, "ITEM 3 CLICKED", Toast.LENGTH_LONG).show();
}
return true;
}
public void showSavedEvents(){
intent = new Intent(this, StoredEventsActivity.class);
intent.putExtra("storedEvents", EventsListFragment.returnStoredEvents());
startActivity(intent);
}
}

Adding database enteries to list view

I am creating a database within my android application that allows users to enter assignment information. At the moment the information is stored but not listed as I would like. I am looking to add function to the View Assignments button so that it returns to the AssignmentsManager page and lists the entered assignments.
I believe I will have to use something like;
listView=(ListView)findViewById(R.id.listView1); //initialise the listview
listAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0); //initialise an ArrayAdapter
listView.setAdapter(listAdapter); //set the adapter to the listview
And to add assignments to list;
listAdapter.add(c.getString(0)+c.getString(1)+c.getString(2)+c.getString(3)+c.getString(4));
I am unsure how to implement this though. Below is my class to add the assignments;
public class addassignment extends Activity {
DBAdapter db = new DBAdapter(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
}
public void addAssignment(View v) {
Log.d("test", "adding");
// get data from form
EditText nameTxt = (EditText) findViewById(R.id.editTitle);
EditText dateTxt = (EditText) findViewById(R.id.editDuedate);
EditText courseTxt = (EditText) findViewById(R.id.editCourse);
EditText notesTxt = (EditText) findViewById(R.id.editNotes);
db.open();
long id = db.insertRecord(nameTxt.getText().toString(), dateTxt
.getText().toString(), courseTxt.getText().toString(), notesTxt
.getText().toString());
db.close();
nameTxt.setText("");
dateTxt.setText("");
courseTxt.setText("");
notesTxt.setText("");
Toast.makeText(addassignment.this, "Assignment Added",
Toast.LENGTH_LONG).show();
}
public void viewAssignments(View v) {
Intent i = new Intent(this, AssignmentManager.class);
startActivity(i);
}
}
Here is the Assignments Class where the list should be displayed;
public class AssignmentManager extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.assignmentmanager);
Button addBtn = (Button) findViewById(R.id.add);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(AssignmentManager.this,
addassignment.class);
startActivity(i);
}
});
try {
String destPath = "/data/data/" + getPackageName()
+ "/databases/AssignmentDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB(getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
DBAdapter db = new DBAdapter(this);
// ---add an assignment---
db.open();
long id = db.insertRecord("Android App", "14/02/2015", "Networks",
"First Android Project");
id = db.insertRecord("Java Development", "5/02/2015", "Java",
"Complete Assignment");
db.close();
// ---get all Records---
db.open();
Cursor c = db.getAllRecords();
if (c.moveToFirst()) {
do {
DisplayRecord(c);
} while (c.moveToNext());
}
db.close();
/*
* //---get a Record--- db.open(); Cursor c = db.getRecord(2); if
* (c.moveToFirst()) DisplayRecord(c); else Toast.makeText(this,
* "No Assignments found", Toast.LENGTH_LONG).show(); db.close();
*/
// ---update Record---
/*
* db.open(); if (db.updateRecord(1, "Android App", "29/02/2015",
* "Networks", "First Android Project")) Toast.makeText(this,
* "Update successful.", Toast.LENGTH_LONG).show(); else
* Toast.makeText(this, "Update failed.", Toast.LENGTH_LONG).show();
* db.close();
*/
/*
* //---delete a Record--- db.open(); if (db.deleteRecord(1))
* Toast.makeText(this, "Delete successful.", Toast.LENGTH_LONG).show();
* else Toast.makeText(this, "Delete failed.",
* Toast.LENGTH_LONG).show(); db.close();
*/
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
// ---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
public void DisplayRecord(Cursor c) {
Toast.makeText(
this,
"id: " + c.getString(0) + "\n" + "Title: " + c.getString(1)
+ "\n" + "Due Date: " + c.getString(2),
Toast.LENGTH_SHORT).show();
}
public void addAssignment(View view) {
Intent i = new Intent("addassignment");
startActivity(i);
Log.d("TAG", "Clicked");
}
}
Can anyone show me where I should implement the lists to add the functionality?
You're on the right track. I'd simplify the process if I were you, instead of initially adding assignments individually, add an ArrayList of assignments when you're creating your adapter:
listAdapter= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, assignmentArrayList);
// now set the adapter to the ListView
listView.setAdapter(listAdapter); //set the adapter to the listview
Once your adapter is set and you make any changes to it (add, remove, etc) make sure you call .notifyDataSetChanged() so it knows to refresh the list.
listAdapter.notifyDataSetChanged(); // notify the list adapter

Display Results in ListView from Database

I am trying to display result from Database in a listView which is clickable On long click ,items can be deleted and on click it go to another activity. So I create an activity called editdeletedoctor
public class editdeletedoctor extends Activity {
private ArrayList<String> results = new ArrayList<String>();
private String tableName = TableData.TableInfo.TABLE_DOCTOR;
private SQLiteDatabase newDB;
private ArrayList<doctorClass> doctor_List = new ArrayList<doctorClass>();
public static String MODEL_TO_EDIT = "MODEL_TO_EDIT";
public ListView list;
public ArrayAdapter<String> adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
init();
openAndQueryDatabase();
displayResultList();
}
private void init() {
list = (ListView) findViewById(R.id.list);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(editdeletedoctor.this,
registerdoctor.class);
intent.putExtra("theText", doctor_List.get(position).getUsername());
intent.putExtra(editdeletedoctor.MODEL_TO_EDIT,doctor_List.get(position));
editdeletedoctor.this.finish();
startActivity(intent);
}
});
list.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
final int position, long id) {
Builder dialog = new AlertDialog.Builder(editdeletedoctor.this);
dialog.setTitle("Are you sure you want to delete This doctor?");
dialog.setPositiveButton("Yes", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
doctorClass doctor = doctor_List.get(position);
doctor_List.remove(position);
DatabaseOperations db = new DatabaseOperations(getApplicationContext());
try {
db.open();
HashMap<String, String> conditionKV = new HashMap<String, String>();
conditionKV.put(TableData.TableInfo.DOCTOR_ID, doctor.getId() + "");
db.deleteDoctor(conditionKV);
results.remove(position);
adapter.notifyDataSetChanged();
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(),
"Could not create or Open the database");
} finally {
if (db != null)
db.close();
}
dialog.dismiss();
}
});
dialog.setNegativeButton("No", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
return false;
}
});
}
private void displayResultList() {
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
DatabaseOperations db = new DatabaseOperations(getApplicationContext());
try {
db.open();
doctor_List = db.getDoctor(null);
for (doctorClass inc : doctor_List) {
if(inc.getId()==TableData.TableInfo.userID)
results.add("Name: " + inc.getUsername() + " Phone:"
+ inc.getPhone() + ",Address: "
+ inc.getAddress());
}
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(),
"Could not create or Open the database");
} finally {
if (db != null)
db.close();
}
}
}
And in the DatabaseOperations.java class :
public DatabaseOperations open() throws SQLException {
ourHelper = new DatabaseOperations(context);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public ArrayList<doctorClass> getDoctor(HashMap<String, String> conditionKV) {
Cursor m_cursor = get(TableData.TableInfo.TABLE_DOCTOR, conditionKV);
ArrayList<doctorClass> list = new ArrayList<doctorClass>();
if (m_cursor.moveToFirst()) {
do {
doctorClass model = new doctorClass();
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_ID)) != null)
model.setId(m_cursor.getInt(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_ID)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_NAME)) != null)
model.setUsername(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_NAME)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_PASS)) != null)
model.setPassword(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_PASS)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_MAIL)) != null)
model.setEmail(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_MAIL)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_PHONE)) != null)
model.setPhone(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_PHONE)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_ADDRESS)) != null)
model.setAddress(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_ADDRESS)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_GENDER)) != null)
model.setGender(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_GENDER)));
list.add(model);
} while (m_cursor.moveToNext());
}// end if
return list;
}
public Cursor get(String tableName, HashMap<String, String> conditionKV) {
String whereClause = null;
if (conditionKV != null)
whereClause = formatWherecondition(conditionKV);
String completeQuery = "SELECT * FROM " + tableName + " ";
if (whereClause != null) {
completeQuery += " WHERE " + whereClause;
}
return ourDatabase.rawQuery(completeQuery, null);
}
public String formatWherecondition(HashMap<String, String> conditionKV) {
try {
String result = "";
if (conditionKV.size() < 1) {
throw new Exception("Hahsmap condition Empty");
}
Iterator l_iterator = conditionKV.keySet().iterator();
boolean isOneField = false;
while (l_iterator.hasNext()) {
String l_key = (String) l_iterator.next();
String l_value = conditionKV.get(l_key);
if (isOneField)
result = result + " AND ";
result = result + l_key + "='" + l_value + "' ";
isOneField = true;
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public void deleteDoctor(HashMap<String, String> conditionKV) {
delete(TableData.TableInfo.TABLE_DOCTOR, conditionKV);
}
private void delete(String tableName, HashMap<String, String> conditionKV) {
String whereClause = null;
if (conditionKV == null)
return;
whereClause = formatWherecondition(conditionKV);
String completeQuery = "DELETE FROM " + tableName + " ";
if (whereClause != null) {
completeQuery += " WHERE " + whereClause;
ourDatabase.execSQL(completeQuery);
}
}
When running, an error occured, Here is the logcat
Please help me .
Thank you
Are you sure the "context" you are using here is not null ?
How about rewriting the open() function this way and calling it via open(getApplicationContext()); ?
public DatabaseOperations open(Context context) throws SQLException {
ourHelper = new DatabaseOperations(context);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}

Android convert sqlite single record to csv

I want to convert a single row to a .csv file. How am I going to do that? All I've seen in the Internet are most of them the whole sqlite db is being converted/exported to a .csv file. But my requirement is only a single record? Do you have ideas as to how am I gonna achieve this? Help is much appreciated. Thanks!
Update:
public class CSVCreationActivity extends Activity {
TextView empidtxt,empnametxt,empsaltxt;
EditText empidet,empnameet,empsalet;
Button insetbt,viewbt;
SQLiteDatabase myDatabase=null;
String DataBase_Name="employeedata";
String Table_Name="employeedetails";
Cursor c1,c2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
empidtxt=(TextView)findViewById(R.id.tv1);
empnametxt=(TextView)findViewById(R.id.tv2);
empsaltxt=(TextView)findViewById(R.id.tv3);
empidet=(EditText)findViewById(R.id.et1);
empnameet=(EditText)findViewById(R.id.et2);
empsalet=(EditText)findViewById(R.id.et3);
insetbt=(Button)findViewById(R.id.bt1);
viewbt=(Button)findViewById(R.id.bt2);
try {
myDatabase=this.openOrCreateDatabase(DataBase_Name, MODE_PRIVATE, null);
System.out.println("databse has been created.....");
myDatabase.execSQL("create table if not exists " + Table_Name + "(empid integer(10),empname varchar(50),empsal integer(10))");
System.out.println("table has been created.....");
c1 = myDatabase.rawQuery("select * from " + Table_Name, null);
c1.moveToFirst();
int count1 = c1.getCount();
System.out.println("columns --->" + count1);
if (count1 == 0) {
myDatabase.execSQL("insert into "+Table_Name+ "(empid,empname,empsal)" +"values(101,'asha',20000)");
System.out.println("data base has been inserted.....");
}
c2 = myDatabase.rawQuery("select * from " + Table_Name, null);
c2.moveToFirst();
int count2 = c2.getCount();
System.out.println("columns --->" + count2);
final int column1 = c2.getColumnIndex("empid");
final int column2 = c2.getColumnIndex("empname");
final int column3 = c2.getColumnIndex("empsal");
insetbt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (c2 != null) {
do {
int id = c2.getInt(column1);
String name = c2.getString(column2);
int salary = c2.getInt(column3);
System.out.println("empID --> "+id);
System.out.println("empNAME --> "+name);
System.out.println("empsalalry --> "+salary);
} while(c2.moveToNext());
}
}
});
viewbt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
new ExportDatabaseCSVTask().execute("");
} catch(Exception ex) {
Log.e("Error in MainActivity",ex.toString());
}
}
});
}
catch(SQLException ex) { ex.printStackTrace(); }
/*finally {
if (myDB != null) { myDB.close(); }
}*/
}
public class ExportDatabaseCSVTask extends AsyncTask<String, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(CSVCreationActivity.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Exporting database...");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
File dbFile = getDatabasePath("myDatabase.db");
System.out.println(dbFile); // displays the data base path in your logcat
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists()) { exportDir.mkdirs(); }
File file = new File(exportDir, "myfile.csv");
try {
file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
Cursor curCSV = myDatabase.rawQuery("select * from " + Table_Name,null);
csvWrite.writeNext(curCSV.getColumnNames());
while(curCSV.moveToNext()) {
String arrStr[] ={curCSV.getString(0),curCSV.getString(1),curCSV.getString(2)};
// curCSV.getString(3),curCSV.getString(4)};
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
return true;
} catch(SQLException sqlEx) {
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
return false;
} catch (IOException e) {
Log.e("MainActivity", e.getMessage(), e);
return false;
}
}
protected void onPostExecute(final Boolean success) {
if (this.dialog.isShowing()) { this.dialog.dismiss(); }
if (success) {
Toast.makeText(CSVCreationActivity.this, "Export successful!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(CSVCreationActivity.this, "Export failed", Toast.LENGTH_SHORT).show();
}
}
}
CSVWriter and CSVReader can be downloaded here
Better way to get specific record from database and then convert it to csv file ...
you just need to modify your query to achieve this
Replace this line
Cursor curCSV = myDatabase.rawQuery("select * from " + Table_Name,null);
with ur conditional query means using where operator or anything else...

Categories

Resources