How to show SQL data by ID in editTextView? - java

Hello I just wanna ask about this code, the problem is I just want to show the getData in an EditTextview. But it only shows in a toast what do you think will be thre revisions needed for my code to call the data in getData into a EditText thank you so much for the help.
package com.example.serviceapplication;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
public class Timeinsms extends AppCompatActivity {
DatabaseHelper myDb;
EditText editTextId,editTextsmsi;
Button btngetData,btnView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeinsms);
myDb = new DatabaseHelper(this);
editTextId = (EditText) findViewById(R.id.editText_idin);
btngetData = (Button) findViewById(R.id.button_view);
btnView = (Button) findViewById(R.id.button_viewALL);
getData();
viewAll();
}
public void getData() {
btngetData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String id = editTextId.getText().toString();
if (id.equals(String.valueOf(""))) {
editTextId.setError("Enter id to get data");
return;
}
Cursor res = myDb.getData(id);
String data = null;
if (res.moveToFirst()) {
data =
"Id:" + res.getString(0) + "\n\n" +
"Time In :" + res.getString(1) + "\n\n" +
"Customer :" + res.getString(2) + "\n\n"+
"Branch :" + res.getString(3) + "\n\n"+
"Machine :" + res.getString(4) + "\n\n";
}
showMessage("TIME OUT FORM"+"\n\n", data);
}
});
}
public void viewAll(){
btnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res=myDb.getAllData();
if(res.getCount() == 0) {
showMessage("Error","Nothing found");
return;
}
StringBuffer buffer=new StringBuffer();
while(res.moveToNext()){
buffer.append("Id:"+res.getString(0)+"\n\n");
buffer.append("Time :"+ res.getString(1)+"\n\n");
buffer.append("Customer :"+ res.getString(2)+"\n\n");
buffer.append("Branch :"+ res.getString(3)+"\n\n");
buffer.append("Machine :"+ res.getString(4)+"\n\n\n");
}
showMessage("Time In History",buffer.toString());
}
});
}
private void showMessage(String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.create();
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}

You are not showing it in a Toast, you are using an Alertdialog to Show your Message.
This would be a Toast
Toast.makeText(this,"MESSAGE TO SHOW",Toast.LENGTH_LONG).show();
At this Position
data = "Id:" + res.getString(0) + "\n\n" +
"Time In :" + res.getString(1) + "\n\n" +
"Customer :" + res.getString(2) + "\n\n"+
"Branch :" + res.getString(3) + "\n\n"+
"Machine :" + res.getString(4) + "\n\n";
you are already creating a String which contains all your data, you only have to set your Edittext with this String.
editTextId.setText("TIME OUT FORM"+"\n\n"+data);
This must be placed inside the OnClick method, as data is a local variable at this method.

Related

Why is my loop only outputting the last result?

I'm building an Android Studio app in which data can be added to a SQLite database. When I want to output the data to a page it only shows the last result in the database (it overrides). How can i prevent this from happening and output all the data?
Here's my code:
public void viewAll() {
Cursor res = myDb.getAllData();
if (res.getCount() == 0) {
// show error
System.out.println("No Data Found");
return;
}
while (res.moveToNext()) {
System.out.println("Id: " + res.getString(0) + "\n");
System.out.println("Title: " + res.getString(1) + "\n");
System.out.println("Description: " + res.getString(2) + "\n");
System.out.println("Location: " + res.getString(4) + "\n\n");
TextView textViewID = (TextView) findViewById(R.id.textViewID);
textViewID.setText("Id: " + res.getString(0) + "\n");
TextView textViewName = (TextView) findViewById(R.id.textViewName);
textViewName.setText("Name: " + res.getString(1) + "\n");
TextView textViewDescription = (TextView) findViewById(R.id.textViewDescription);
textViewDescription.setText("Description: " + res.getString(2) + "\n");
TextView textViewLocation = (TextView) findViewById(R.id.textViewLocation);
textViewLocation.setText("Location: " + res.getString(4) + "\n");
}
// show all the data
}
The expected results were all the data from the database but it only output the last entry.
EDIT
MyActivity.java
package com.example.triptracker;
import android.content.Intent;
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class MomentsActivity extends AppCompatActivity {
private TextView mTextMessage;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_moments:
Intent intent = new Intent(MomentsActivity.this, MomentsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
break;
case R.id.navigation_addmoment:
Intent intent2 = new Intent(MomentsActivity.this, AddMomentActivity.class);
intent2.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent2);
break;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDb = new DatabaseHelper(this);
setContentView(R.layout.activity_moments);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
mList = this.findViewById(R.id.my_listview);
manageListView();
}
DatabaseHelper myDb;
EditText editTitle, editDescription, editLocation;
Button btnAddData;
Button btnViewAll;
SimpleCursorAdapter mSCA; //Adapts/Handles the data for the listview
ListView mList;
Cursor mCsr;
int[] item_layout_ids_for_list = new int[]{
R.id.textview_id,
R.id.textview_name,
R.id.textview_description,
R.id.textview_location
};
String[] columns_to_list = new String[]{
DatabaseHelper.COL_1,
DatabaseHelper.COL_2,
DatabaseHelper.COL_3,
DatabaseHelper.COL_4
};
private void manageListView() {
mCsr = myDb.getAllData();
if (mSCA == null) {
// Builds the Adapter for the List
mSCA = new SimpleCursorAdapter(
this,
R.layout.mylistview_item, mCsr,
columns_to_list,
item_layout_ids_for_list,
0
);
mList.setAdapter(mSCA); // Ties the Adapter to the ListView
} else {
mSCA.swapCursor(mCsr); // Refresh the List
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mCsr.close();
}
#Override
protected void onResume() {
super.onResume();
manageListView();
}
}
DatabaseHelper.java
package com.example.triptracker;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "triptracker.db";
public static final String TABLE_NAME = "trip_table";
public static final String COL_1 = "trip_id";
public static final String COL_2 = "trip_title";
public static final String COL_3 = "trip_description";
public static final String COL_4 = "trip_image";
public static final String COL_5 = "trip_location";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (" + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_2 + " TEXT, " + COL_3 + " TEXT, " + COL_4 + " TEXT, " + COL_5 + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE_NAME);
onCreate(db);
}
// TODO: Add image functionality.
public boolean insertData(String title, String description, String location) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, title);
contentValues.put(COL_3, description);
// contentValues.put(COL_4, image);
contentValues.put(COL_5, location);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
}
It's outputting these errors:
2019-05-09 14:23:47.959 21253-21253/com.example.triptracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.triptracker, PID: 21253
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.triptracker/com.example.triptracker.MomentsActivity}: java.lang.IllegalArgumentException: column '_id' does not exist. Available columns: [trip_id, trip_title, trip_description, trip_image, trip_location]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.IllegalArgumentException: column '_id' does not exist. Available columns: [trip_id, trip_title, trip_description, trip_image, trip_location]
at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:340)
at android.widget.CursorAdapter.init(CursorAdapter.java:180)
at android.widget.CursorAdapter.<init>(CursorAdapter.java:157)
at android.widget.ResourceCursorAdapter.<init>(ResourceCursorAdapter.java:96)
at android.widget.SimpleCursorAdapter.<init>(SimpleCursorAdapter.java:104)
at com.example.triptracker.MomentsActivity.manageListView(MomentsActivity.java:81)
at com.example.triptracker.MomentsActivity.onCreate(MomentsActivity.java:52)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6669) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
2019-05-09 14:23:47.983 21253-21253/com.example.triptracker I/Process: Sending signal. PID: 21253 SIG: 9
The reason is that for each iteration of the loop you set the values of the TextViews to the values for that iteration, as such you will only likely see the last row.
You could use :-
public void viewAll() {
Cursor res = myDb.getAllData();
if (res.getCount() == 0) {
// show error
System.out.println("No Data Found");
return;
}
TextView textViewID = (TextView) findViewById(R.id.textViewID);
textViewID.setText("");
TextView textViewName = (TextView) findViewById(R.id.textViewName);
textViewName.setText("");
TextView textViewDescription = (TextView) findViewById(R.id.textViewDescription);
textViewDescription.setText("");
TextView textViewLocation = (TextView) findViewById(R.id.textViewLocation);
textViewLocation.setText("");
while (res.moveToNext()) {
System.out.println("Id: " + res.getString(0) + "\n");
System.out.println("Title: " + res.getString(1) + "\n");
System.out.println("Description: " + res.getString(2) + "\n");
System.out.println("Location: " + res.getString(4) + "\n\n");
textViewId.setText(textViewID.getText().toString()+res.getString(0) + "\n");
textViewName.setText(textViewName.getText().toString()+"Name: " + res.getString(1) + "\n");
textViewDescription.setText(textViewDescription.getText().toString() + "Description: " + res.getString(2) + "\n");
textViewLocation.setText(textViewLocation.getText().toString() + "Location: " + res.getString(4) + "\n");
}
}
Or even better as
- String concatenation in a loop is inefficient
- This also only appends a new line character after the first.
:-
public void viewAll() {
Cursor res = myDb.getAllData();
if (res.getCount() == 0) {
// show error
System.out.println("No Data Found");
return;
}
StringBuilder idsb = new StringBuilder();
StringBuilder namesb = new StringBuilder();
StringBuilder descsb = new StringBuilder();
StringBuilder locsb = new StringBuilder();
String endofline = "";
TextView textViewID = (TextView) findViewById(R.id.textViewID);
TextView textViewName = (TextView) findViewById(R.id.textViewName);
TextView textViewDescription = (TextView) findViewById(R.id.textViewDescription);
TextView textViewLocation = (TextView) findViewById(R.id.textViewLocation);
while (res.moveToNext()) {
System.out.println("Id: " + res.getString(0) + "\n");
System.out.println("Title: " + res.getString(1) + "\n");
System.out.println("Description: " + res.getString(2) + "\n");
System.out.println("Location: " + res.getString(4) + "\n\n");
idsb.append("Id: ").append(res.getString(0)).append(endofline);
namesb.append("Name: ").append(res.getString(1)).append(endofline);
descsb.append("Description: ").append(res.getString(2)).append(endofline);
locsb.append("Location: ").append(res.getString(4)).append(endofline);
if (endofline.length() == 0) {
endofline = "\n";
}
}
textViewId.setText(idsb.toString());
textViewName.setText(namesb.toString());
textViewDescription.setText(descsb.toString());
textViewLocation.setText(locsb.toString());
}
However, you probably want to use a ListView or a RecyclerView.
Additional - Use a ListView
Important Note
This example uses a CursorAdapter which make life very easy BUT they require that a column named specifically _id exists (id will not do). You may have to change you table so that the column is named _id (you can use the constant BaseColumns._ID as is used in the DBHelper below). There are other ways such as createing an _id column in the SELECT (query) e.g. SELECT rowid AS _id,* FROM the_table.
1 In the activity's layout add (replace the textviews for id/name/description/location) a ListView making sure you give it an id e.g. :-
<ListView
android:id="#+id/my_listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
2 Create a new layout mylistview_item.xml, this will have 4 textviews e.g.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textview_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textview_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textview_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textview_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
This will be the layout used for each row (item) in the listview
3 Add the following class variables :-
SimpleCursorAdapter mSCA; //Adapts/Handles the data for the listview
ListView mList;
Cursor mCsr;
4 Add the following int array as a class variable :-
int[] item_layout_ids_for_list = new int[]{
R.id.textview_id,
R.id.textview_name,
R.id.textview_description,
R.id.textview_location
};
note that these are the id's of the TextView in the layout mylistview_item.xml and will be used by the adapter to map the data from the columns to the TextViews.
5 Similarily add a String array for the column names from which the data is to be retrieved; BUT NOTE you will/may have to change the column names (the following uses CONSTANTS defined in the Database Helper (it is suggested to define such constants and always use the constants rather then hard code the names)) e.g. :-
String[] columns_to_list = new String[]{
DBHelper.COL_MYTABLE_ID,
DBHelper.COl_MYTABLE_NAME,
DBHelper.COL_MYTABLE_DESCRIPTION,
DBHelper.COl_MYTABLE_LOCATION
};
6 Add the following method to the activity :-
private void manageListView() {
mCsr = myDb.getAllData();
if (mSCA == null) {
// Builds the Adapter for the List
mSCA = new SimpleCursorAdapter(
this,
R.layout.mylistview_item, mCsr,
columns_to_list,
item_layout_ids_for_list,
0
);
mList.setAdapter(mSCA); // Ties the Adapter to the ListView
} else {
mSCA.swapCursor(mCsr); // Refresh the List
}
}
This as the method says manages the ListView. It gets the data from the db into a Cursor, constructs (instantiates) the SimpleCursorAdapter, if it hasn't been instantiated and then it ties the adapter to the ListView. If the adapter has been instantiated it tells the adapter that there is a new (changed) cursor (so the list is refreshed).
7
Add the following lines to the activity's onCreate method :-
mList = this.findViewById(R.id.my_listview);
myDb = new DBHelper(this); //<<<<<<<<<< SHOULD ALREADY HAVE SOMETHING LIKE THIS LEAVE AS IT IS
manageListView();
8 Override the onResume and onDestroy methods of your activity using :-
#Override
protected void onDestroy() {
super.onDestroy();
mCsr.close();
}
#Override
protected void onResume() {
super.onResume();
manageListView();
}
This isn't essential as yet but good practice.
onDestroy closes the when the activity is destroyed Cursor (Cursors should be closed when finished with)
less important for the main activity
onResume is overidden to call the manageListView() method (yet to be added) and will result in the listview showing the latest data upon return from another activity.
The activity I used to test this is :-
public class MainActivity extends AppCompatActivity {
DBHelper myDb;
SimpleCursorAdapter mSCA; //Adapts/Handles the data for the listview
ListView mList;
Cursor mCsr;
String[] columns_to_list = new String[]{
DBHelper.COL_MYTABLE_ID,
DBHelper.COl_MYTABLE_NAME,
DBHelper.COL_MYTABLE_DESCRIPTION,
DBHelper.COl_MYTABLE_LOCATION
};
int[] item_layout_ids_for_list = new int[]{
R.id.textview_id,
R.id.textview_name,
R.id.textview_description,
R.id.textview_location
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = this.findViewById(R.id.my_listview);
myDb = new DBHelper(this);
forTestingAddSomeData();
manageListView();
}
private void manageListView() {
mCsr = myDb.getAllData();
if (mSCA == null) {
// Builds the Adapter for the List
mSCA = new SimpleCursorAdapter(
this,
R.layout.mylistview_item, mCsr,
columns_to_list,
item_layout_ids_for_list,
0
);
mList.setAdapter(mSCA); // Ties the Adapter to the ListView
} else {
mSCA.swapCursor(mCsr); // Refresh the List
}
}
private void forTestingAddSomeData() {
if(DatabaseUtils.queryNumEntries(myDb.getWritableDatabase(),DBHelper.TABLE_MYTABLE) < 1) {
myDb.add("Test001","This is a test","Home");
myDb.add("Test002","For Testing","Garage");
myDb.add("Test003","Test using this","Loft");
myDb.add("Test004","Yet again for testing","Cupboard");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mCsr.close();
}
#Override
protected void onResume() {
super.onResume();
manageListView();
}
}
Note forTestingAddSomeData and the call to the method are just to add some testing data. Adding and using this method (so I could display some data) was omitted from the step by step guide.
In case you have problems or want to use the full code then the DBHelper class is :-
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;
public static final String TABLE_MYTABLE = "mytable";
public static final String COL_MYTABLE_ID = BaseColumns._ID;
public static final String COl_MYTABLE_NAME = "name";
public static final String COL_MYTABLE_DESCRIPTION = "description";
public static final String COl_MYTABLE_LOCATION = "location";
SQLiteDatabase mDB;
public DBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_MYTABLE +
"(" +
COL_MYTABLE_ID + " INTEGER PRIMARY KEY," +
COl_MYTABLE_NAME + " TEXT, " +
COL_MYTABLE_DESCRIPTION + " TEXT, " +
COl_MYTABLE_LOCATION + " TEXT" +
")"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long add(String name, String description, String location) {
ContentValues cv = new ContentValues();
cv.put(COl_MYTABLE_NAME,name);
cv.put(COL_MYTABLE_DESCRIPTION,description);
cv.put(COl_MYTABLE_LOCATION,location);
return mDB.insert(TABLE_MYTABLE,null,cv);
}
public Cursor getAllData() {
return mDB.query(TABLE_MYTABLE,null,null,null,null,null,null);
}
}
Result
The result of running the above is :-

Android: SQLite error in adding data

I'm working on a PiggyBank-like application wherein users can make wishlists of their wanted item and helps them save for that item. My app is still in prototype because i'm still learning android.
The problem i'm experiencing right now is every time i add a new data, it always returns false. Here's my code:
DatabaseHelper.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "people_table";
private static final String COL1 = "ID";
private static final String COL2 = "name";
private static final String COL3 = "price";
private static final String COL4 = "totalsavings";
private static final String COL5 = "duedate";
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL2 +" TEXT, " + COL3 + "TEXT, " + COL4 +"INTEGER)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
contentValues.put(COL3, item);
contentValues.put(COL4, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
/**
* Returns all the data from database
* #return
*/
public Cursor getData(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
/**
* Returns only the ID that matches the name passed in
* #param name
* #return
*/
public Cursor getItemID(String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COL1 + " FROM " + TABLE_NAME +
" WHERE " + COL2 + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
/**
* Updates the name field
* #param newName
* #param id
* #param oldName
*/
public void updateName(String newName, int id, String oldName){
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TABLE_NAME + " SET " + COL2 +
" = '" + newName + "' WHERE " + COL1 + " = '" + id + "'" +
" AND " + COL2 + " = '" + oldName + "'";
Log.d(TAG, "updateName: query: " + query);
Log.d(TAG, "updateName: Setting name to " + newName);
db.execSQL(query);
}
/**
* Delete from database
* #param id
* #param name
*/
public void deleteName(int id, String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_NAME + " WHERE "
+ COL1 + " = '" + id + "'" +
" AND " + COL2 + " = '" + name + "'";
Log.d(TAG, "deleteName: query: " + query);
Log.d(TAG, "deleteName: Deleting " + name + " from database.");
db.execSQL(query);
}
}
MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
DatabaseHelper mDatabaseHelper;
private Button btnAdd, btnViewData;
private EditText editText, editText2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//for inputs
editText = (EditText) findViewById(R.id.editText);
editText2 =(EditText) findViewById(R.id.editText2);
//buttons
btnAdd = (Button) findViewById(R.id.btnAdd);
btnViewData = (Button) findViewById(R.id.btnView);
//call database
mDatabaseHelper = new DatabaseHelper(this);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
if (editText.length() != 0) {
AddData(newEntry);
editText.setText("");
} else {
toastMessage("You must put something in the text field!");
}
String newPriceEntry = editText2.getText().toString();
if (editText2.length() != 0) {
AddData(newPriceEntry);
editText2.setText("");
} else {
toastMessage("You must put something in the text field!");
}
}
});
btnViewData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Data Successfully Inserted!");
} else {
toastMessage("Something went wrong");
}
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
ListDataActivity.java
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by User on 2/28/2017.
*/
public class ListDataActivity extends AppCompatActivity {
private static final String TAG = "ListDataActivity";
DatabaseHelper mDatabaseHelper;
private ListView mListView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
mListView = (ListView) findViewById(R.id.listView);
mDatabaseHelper = new DatabaseHelper(this);
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
//get the data and append to a list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()){
//get the value from the database in column 1
//then add it to the ArrayList
listData.add(data.getString(1));
}
//create the list adapter and set the adapter
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
//set an onItemClickListener to the ListView
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editScreenIntent = new Intent(ListDataActivity.this, EditDataActivity.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
}
else{
toastMessage("No ID associated with that name");
}
}
});
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
EditDataActivity.java
In this activity, the data will be displayed in an EditText (name), the savings goal (price). (I'm still working on the totalsavings).
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
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;
public class EditDataActivity extends AppCompatActivity {
private static final String TAG = "EditDataActivity";
private TextView myGoal, mySavings;
private Button btnSave,btnDelete, btnDeposit;
private EditText editable_item, depositInput;
DatabaseHelper mDatabaseHelper;
private String selectedName, selectedPrice;
private int selectedID, selectedTotalSavings;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_data_layout);
myGoal = (TextView) findViewById(R.id.displayGoal);
mySavings = (TextView) findViewById(R.id.displayTotalSavings);
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
btnDeposit = (Button) findViewById(R.id.btnDeposit);
editable_item = (EditText) findViewById(R.id.editable_item);
mDatabaseHelper = new DatabaseHelper(this);
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
selectedName = receivedIntent.getStringExtra("name");
//now get the price we passed as an extra
selectedPrice = receivedIntent.getStringExtra("price");
//now we get the totalsavings we passed as an extra
selectedTotalSavings = receivedIntent.getIntExtra("totalsavings", -1);
//set the text to show the current selected name
editable_item.setText(selectedName);
//set the text to show the user's saving goal
myGoal.setText(selectedPrice);
//set text to show the user's total savings so far
mySavings.setText(selectedTotalSavings);
//-----------------------------------DIALOG BOX-----------------------------------------
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter Deposit");
builder.setMessage("Enter your deposit!");
depositInput= new EditText(this);
builder.setView(depositInput);
//SET POSITIVE BUTTON
builder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String depositTxt=depositInput.getText().toString();
selectedTotalSavings = Integer.parseInt(selectedTotalSavings + depositTxt);
mySavings.setText(selectedTotalSavings);
Toast.makeText(getApplicationContext(),depositTxt, Toast.LENGTH_LONG).show();
}
});
//SET NEGATIVE BUTTON
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
//CREATE THE DIALOG
final AlertDialog depositPrompt=builder.create();
//--------------------------------------------------------------------------------------
//buttons
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String item = editable_item.getText().toString();
if(!item.equals("")){
mDatabaseHelper.updateName(item,selectedID,selectedName);
}else{
toastMessage("You must enter a name");
}
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabaseHelper.deleteName(selectedID,selectedName);
editable_item.setText("");
toastMessage("removed from database");
}
});
btnDeposit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0){
depositPrompt.show();
}
});
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
Here's the Sample Syntax
User enters details for name and price
User clicks add data
User can View Data and the data will be displayed on a ListView
User can edit and view data in the EditDataActivity
I'm not sure what the problem is.
UPDATE
so i found this code on the MainActivity Class. I'm trying to add the data from editText2 but i don't know how.
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
if (editText.length() != 0) {
AddData(newEntry);
editText.setText("");
} else {
toastMessage("You must put something in the text field!");
}
String newPriceEntry = editText2.getText().toString();
if (editText2.length() != 0) {
AddData(newPriceEntry);
editText2.setText("");
} else {
toastMessage("You must put something in the text field!");
}
}
});
btnViewData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Data Successfully Inserted!");
} else {
toastMessage("Something went wrong");
}
}
Do i have to make a new AddData?
You need to insert the right type of values as mentioned below :
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
contentValues.put(COL3, item);
contentValues.put(COL4, item); // pass an integer instead of a String as you have mentioned its datatype as INTEGER or parse it using Integer.parseInt()
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
The problem I think is in the CREATE TABLE query.
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 +" TEXT, " + COL3 + "TEXT, " + COL4 +"INTEGER)";
There is no space between COL3 and "TEXT" (same for COL4 and "INTEGER"). So just add a space like so.
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 +" TEXT, " + COL3 + " TEXT, " + COL4 +" INTEGER)";
Problem is in your addData() method. COL4 holds INTEGER value.
Try this:
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
contentValues.put(COL3, item);
contentValues.put(COL4, Integer.parseInt(item));
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
The return of db.insert() is a long and you're comparing it to an int. Change
if (result == -1) {
return false;
} else {
return true;
}
To
return (int)result == -1;

aplying onPostExecute to onClickListener

i have made program which works with AsyncTask it prints a list of the JSON data when program is executed, but the problem is that i want it to execute when i press the button. How do i get the results of AsyncTask into my onClickButtonListener ? How do i call AsyncTask from onClick?
Code:
public class Instillinger extends MainActivity {
DatabaseHelper myDb;
String navn;
String adresse;
String bilmere;
TextView visNavn;
TextView visAdresse;
TextView visBil;
EditText navnFelt;
EditText adrFelt;
EditText bilFelt;
Button lagreButton;
Button tilbakeButton;
Button visDataButton;
List<Bruker> brukere;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.instillinger);
myDb = new DatabaseHelper(this);
// visNavn = (TextView) findViewById(R.id.visNavn);
visAdresse = (TextView) findViewById(R.id.visAdresse);
//visBil = (TextView) findViewById(R.id.visBil);
navnFelt = (EditText) findViewById(R.id.navnFelt);
adrFelt = (EditText) findViewById(R.id.adrFelt);
bilFelt = (EditText) findViewById(R.id.bilFelt);
lagreButton = (Button) findViewById(R.id.lagreButton);
tilbakeButton = (Button) findViewById(R.id.tilbakeButton);
//visDataButton = (Button) findViewById(R.id.visData);
brukere = myDb.getBrukere();
for(Bruker b: brukere){
String log = "Du er registrert som: "+ b.getNavn() + "\n" +
"Adresse: " + b.getAdresse() + "\n" +
"Bilmerke: " + b.getBilmerke() + "\n" +
"For å oppdatere informasjon fyll Alle feltene nede";
visAdresse.setText(log);
}
settInnData();
}
public void settInnData() {
lagreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myDb.addContact(new Bruker("Giedrius","mldc","123","1"));
brukere = myDb.getBrukere();
for(Bruker b: brukere){
String log = "Du er registrert som: "+ b.getNavn() + "\n" +
"Adresse: " + b.getAdresse() + "\n" +
"Bilmerke: " + b.getBilmerke() + "\n" +
"Bilmerke: " + b.getState() + "\n" +
"For å oppdatere informasjon fyll Alle feltene nede";
visAdresse.setText(log);
}
//myDb.getContact(myDb.getCount()).toString();
}
});
}
}}
You can call your AsyncTask class inside your button listener by simply invoking new YourAsyncTaskName().execute(). Good Luck.

How i insert intent method to this code for when click button it will show second activity

Here is the java activity that provide to add data for record in SQLite. My question is how i insert some code for when clicking button and it will show second activity. i don't know where i should insert. And don't know what the code should be. please help me.
import java.sql.PreparedStatement;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class AddStudent extends Activity {
DatabaseStudent mHelper;
SQLiteDatabase mDb;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
mHelper = new DatabaseStudent(this);
mDb = mHelper.getWritableDatabase();
final EditText editName = (EditText)findViewById(R.id.editName);
final EditText editLastName = (EditText)findViewById(R.id.editLastName);
ImageView buttonAdd = (ImageView)findViewById(R.id.imageAdd);
buttonAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String name = editName.getText().toString();
String lastname = editLastName.getText().toString();
String condition = getIntent().getStringExtra("Condition");
double school = getIntent().getDoubleExtra("Intent", 0);
//Date&Time
java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(dt);
if(name.length() != 0 && lastname.length() != 0
) {//&& school.length() != 0
Cursor mCursor = mDb.rawQuery("SELECT * FROM "
+ DatabaseStudent.TABLE_NAME + " WHERE "
+ DatabaseStudent.COL_NAME + "='" + name + "'"
+ " AND " + DatabaseStudent.COL_LASTNAME + "='"
+ lastname + "'" + " AND "
+ DatabaseStudent.COL_SCHOOL + "='" + school //add COL_SCHOOL = currentTime
+ "'"+ " AND " + DatabaseStudent.COL_TIME + "='" + currentTime
+ "'"+ " AND " + DatabaseStudent.COL_CON + "='" + condition
+ "'", null);
if(mCursor.getCount() == 0) {
mDb.execSQL("INSERT INTO " + DatabaseStudent.TABLE_NAME
+ " (" + DatabaseStudent.COL_NAME
+ ", " + DatabaseStudent.COL_LASTNAME
+ ", " + DatabaseStudent.COL_SCHOOL
+ ", " + DatabaseStudent.COL_TIME
+ ", " + DatabaseStudent.COL_CON
+ ") VALUES ('" + name + "', '" + lastname
+ "', '" + school + "', '" + currentTime + "', '" + condition + "');");
editName.setText("");
editLastName.setText("");
Toast.makeText(getApplicationContext()
, "Already added"
, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext()
, "This data is exist"
, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext()
, "Please fill in the blank"
, Toast.LENGTH_SHORT).show();
}
}
});
}
public void onStop() {
super.onStop();
mHelper.close();
mDb.close();
}
}
You'd want to insert any code you want executed when you hit a button in the onClick method, which you have as seen here:
buttonAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// do stuff when buttonAdd is clicked
}
});
Now you can use intents inside the onClick method to begin a second activity, like so:
buttonAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(current_activity.this, second_activity.class);
startActivity(intent);
}
});
You can consult the following for more details: http://developer.android.com/training/basics/firstapp/starting-activity.html

android sqlite read all rows at once

Is there a way to read all the rows in an sqlite table and display them at once in a textview?
This is how I read them and it reads line by line ....
//---retrieves all the titles---
public Cursor getAllTitles()
{
return db.query(DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_ISBN,
KEY_TITLE,
KEY_PUBLISHER},
null,
null,
null,
null,
null);
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.Toast;
public class DatabaseActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DBAdapter db = new DBAdapter(this);
//---get all titles---
db.open();
Cursor c = db.getAllTitles();
if (c.moveToFirst())
{
do {
DisplayTitle(c);
} while (c.moveToNext());
}
db.close();
}
}
public void DisplayTitle(Cursor c)
{
Toast.makeText(this,
"id: " + c.getString(0) + "\n" +
"ISBN: " + c.getString(1) + "\n" +
"TITLE: " + c.getString(2) + "\n" +
"PUBLISHER: " + c.getString(3),
Toast.LENGTH_LONG).show();
}
First of all, you might want to look into listviews to easily display a list of data like this.
If your goal really is to display all information in one textview (or toast as you're making now), you could try making one large string, with which you create the toast:
//---get all titles---
db.open();
Cursor c = db.getAllTitles();
String text = "";
if (c.moveToFirst())
{
do {
DisplayTitle(c, text);
} while (c.moveToNext());
}
db.close();
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
}
public void DisplayTitle(Cursor c, String text)
{
text +=
"id: " + c.getString(0) + "\n" +
"ISBN: " + c.getString(1) + "\n" +
"TITLE: " + c.getString(2) + "\n" +
"PUBLISHER: " + c.getString(3);
}
db.getReadableDatabase();
StringBuffer sb=new StringBuffer();
Cursor c=db.rawQuery(SELECT * FROM TABLE_NAME);
while(c.moveToNext){
sb.append(c.getString(0);//c.getString(Column Index)
sb.append(c.getString(1);
//getString( till n number of Columns you have )
}
textView.setText(sb);

Categories