Error when start activity and upload Database - java

When I click a Button I starting a new activity, called Profilo.java. My code is:
package com.example.prenotazione_esame;
import android.app.Activity; import android.app.AlertDialog; import
android.content.DialogInterface; import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import android.os.*;
import android.view.Menu; import android.view.MenuItem; import
android.widget.Button; import android.widget.EditText; import
android.view.View; import android.view.View.OnClickListener; import
android.widget.Toast;
public class Profilo extends Activity {
private LoginDataBase dbLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int id = getIntent().getExtras().getInt("id");
setContentView(R.layout.profilo);
SQLiteDatabase db = dbLogin.getWritableDatabase();
}
}
this LoginDataBase.java
public class LoginDataBase extends SQLiteOpenHelper {
private static final String DB_NAME="Login_DB";
private static final int DB_VERSION=1;
public LoginDataBase(Context context){
super(context,DB_NAME,null,DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql="";
sql+= "CREATE TABLE T_LOGIN (";
sql+= " _id_LOGIN INTEGER PRIMARY KEY AUTOINCREMENT,";
sql+= " USERNAME TEXT NOT NULL,";
sql+= " PASSWORD TEXT NOT NULL";
sql+=")";
db.execSQL(sql);
String sql2="";
sql2+= "CREATE TABLE T_PROFILO (";
sql2+= " _id_PROFILO INTEGER PRIMARY KEY AUTOINCREMENT,";
sql2+= " NOME TEXT NOT NULL,";
sql2+= " COGNOME TEXT NOT NULL,";
sql2+= " ETA TEXT NOT NULL,";
sql2+= " SESSO TEXT(1) NOT NULL,";
sql2+= " CODICE_FISCALE TEXT NOT NULL,";
sql2+= " CITTA TEXT NOT NULL,";
sql2+= " INDIRIZZO TEXT NOT NULL,";
sql2+= " TELEFONO TEXT NOT NULL,";
sql2+= " _id_L INTEGER NOT NULL,";
sql2+= " FOREIGN KEY(_id_L) REFERENCES T_LOGIN(_id_LOGIN)";
sql2+= ")";
db.execSQL(sql2);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Aggiornamento delle tabelle
}
}
the problem is when I try to take my database db. My app crash.
Where is the problem?

You need to inicializate dbLogin.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int id = getIntent().getExtras().getInt("id");
setContentView(R.layout.profilo);
///NEW
LoginDataBase dbLogin = new LoginDataBase (this, "NAMEOFDATABASE", null, 1);
///END OF NEW
SQLiteDatabase db = dbLogin.getWritableDatabase();
}
}
You class LoginDataBase must have a constructor similar than this:
public class LoginDataBase extends SQLiteOpenHelper {
private static final String DB_NAME="Login_DB";
private static final int DB_VERSION=1;
public LoginDataBase (Context contexto, String name,
CursorFactory factory, int version) {
super(contexto, name, factory, version);
}
Or you can also change this and continue with your constructor:
///NEW
LoginDataBase dbLogin = new LoginDataBase (this);
///END OF NEW

Related

Data doesn't get saved in database, which it did before, but after I updated the database version it doesn't

Thanks for helping me fix my problem!
Issue
The issue is that the data never gets saved into the database, which it did before, but then i updated the database version and now it does not.
Is there an error thrown? Yes there is and its right down below.
E/SQLiteLog: (1) near "0": syntax error
E/SQLiteDatabase: Error inserting 0=20 id=csdfergeg userid=csdfergeg email=erregegergr
android.database.sqlite.SQLiteException: near "0": syntax error (code 1): , while compiling: INSERT INTO Info(0,id,userid,email) VALUES (?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:890)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:501)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1546)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1417)
at com.vikkivuk.mxelevator.Database.addUserInfo(Database.java:50)
at com.vikkivuk.mxelevator.finishScene$1.onClick(finishScene.java:61)
at android.view.View.performClick(View.java:6294)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
My code:
Database Class:
package com.vikkivuk.mxelevator;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class Database extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "UserInfo";
private static final String TABLE_NAME = "Info";
private static final String KEY_ID = "id";
private static final String KEY_USERID = "userid";
private static final String KEY_EMAIL = "email";
private static final String KEY_CODE = "code";
public Database(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_USERID + " TEXT," + KEY_EMAIL + " TEXT," + Integer.parseInt(KEY_CODE) + " TEXT" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void addUserInfo(UserInfo info){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_ID, info.UserId);
contentValues.put(KEY_EMAIL, info.Email);
contentValues.put(KEY_USERID, info.UserId);
contentValues.put(KEY_CODE, info.CODE);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public List<UserInfo> getUserInfo(){
List<UserInfo> results = new ArrayList<UserInfo>();
String GET_ALL = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(GET_ALL, null);
if (cursor.moveToFirst()) {
do {
UserInfo userInfo = new UserInfo(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
results.add(userInfo);
} while (cursor.moveToNext());
}
db.close();
return results;
}
public void deleteUserInfo(UserInfo info){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ? ", new String[] {String.valueOf(info.ID)});
db.close();
}
}
UserInfo:
package com.vikkivuk.mxelevator;
public class UserInfo {
public String ID;
public String UserId;
public String Email;
public String CODE;
public UserInfo(String uid, String mail, String el_code){
UserId = uid;
Email = mail;
CODE = el_code;
}
public UserInfo(String userId, String uid, String mail, String el_code){
UserId = uid;
Email = mail;
ID = userId;
CODE = el_code;
}
}
UserInfoAdapter:
package com.vikkivuk.mxelevator;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.List;
public class UserInfoAdapter extends ArrayAdapter<UserInfo> {
public UserInfoAdapter(Context context, List<UserInfo> info) {
super(context, 0, info);
}
public View getView(int position, View convertView, ViewGroup parent){
UserInfo info = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.user_info_item_row, parent, false);
}
TextView uid = convertView.findViewById(R.id.textview_userid);
TextView email = convertView.findViewById(R.id.textview_email);
TextView textcode = convertView.findViewById(R.id.codetext);
uid.setText(info.UserId);
email.setText(info.Email);
textcode.setText(info.CODE);
return convertView;
}
}
Finish scene:
package com.vikkivuk.mxelevator;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;
import java.util.Random;
public class finishScene extends AppCompatActivity {
EditText userId, email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_finish_scene);
userId = findViewById(R.id.userid);
email = findViewById(R.id.email);
CheckBox agreeCheck = findViewById(R.id.agreeCheck1);
Boolean checked = agreeCheck.isChecked();
Button submit = findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (userId.length() < 5) {
Toast.makeText(getApplicationContext(), "Your UID is too short!", Toast.LENGTH_SHORT).show();
return;
} else if (email.length() < 6) {
Toast.makeText(getApplicationContext(), "Your EMAIL is too short!", Toast.LENGTH_SHORT).show();
return;
} else if (!agreeCheck.isChecked()) {
Toast.makeText(getApplicationContext(), "Please check the agree box!", Toast.LENGTH_SHORT).show();
return;
} else {
Random rand = new Random();
int int_random1 = rand.nextInt(10000);
int int_random2 = rand.nextInt(10);
int int_random3 = rand.nextInt(10);
int int_random4 = rand.nextInt(15);
int int_random5 = rand.nextInt(25);
int random_code = int_random1 + int_random2 + int_random3 + int_random4 + int_random5;
Database db = new Database(finishScene.this);
UserInfo info = new UserInfo(userId.getText().toString(), email.getText().toString(), String.valueOf(random_code));
db.addUserInfo(info);
db.close();
userId.setText("");
email.setText("");
Toast.makeText(getApplicationContext(), "Data saved! Pending approval...", Toast.LENGTH_LONG).show();
Intent intent = new Intent(userId.getContext(), Success.class);
startActivity(intent);
}
}
});
}
}
ShowData:
package com.vikkivuk.mxelevator;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.List;
public class ShowData extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_data);
List<UserInfo> info = new Database(this).getUserInfo();
UserInfoAdapter adapter = new UserInfoAdapter(this, info);
ListView listView = findViewById(R.id.userInfoList);
listView.setAdapter(adapter);
Button goback = findViewById(R.id.goback1);
goback.setOnClickListener(v -> {
Intent intent = new Intent(goback.getContext(), MainActivity.class);
startActivity(intent);
});
}
}
That's all of my classes. Also, I would like to specify that I don't actually know what database versions are since I started with the android studio 3 days ago.
please try this I implemented some change on the UserInfo class
the Id must be an integer and you add a String
database.java
public class MyBase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "UserInfo";
private static final String TABLE_NAME = "Info";
private static final String KEY_ID = "id";
private static final String KEY_USERID = "userid";
private static final String KEY_EMAIL = "email";
private static final String KEY_CODE = "code";
public MyBase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_USERID + " INTEGER," + KEY_EMAIL + " TEXT," + KEY_CODE + " TEXT" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void addUserInfo(UserInfo info) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
// contentValues.put(KEY_ID, info.UserId); i removed this
contentValues.put(KEY_EMAIL, info.Email);
contentValues.put(KEY_USERID, info.UserId);
contentValues.put(KEY_CODE, info.CODE);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public List<UserInfo> getUserInfo() {
List<UserInfo> results = new ArrayList<>();
String GET_ALL = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(GET_ALL, null);
if (cursor.moveToFirst()) {
do {
UserInfo userInfo = new UserInfo(cursor.getInt(0), cursor.getInt(1), cursor.getString(2), cursor.getInt(3));
results.add(userInfo);
} while (cursor.moveToNext());
}
db.close();
return results;
}
public void deleteUserInfo(UserInfo info) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ? ", new String[]{String.valueOf(info.ID)});
db.close();
}
}
and UserInfo :
public class UserInfo {
public int ID;
public int UserId;
public String Email;
public int CODE;
public UserInfo(int uid, String mail, int el_code) {
UserId = uid;
Email = mail;
CODE = el_code;
}
public UserInfo(int userId, int uid, String mail, int el_code) {
UserId = uid;
Email = mail;
ID = userId;
CODE = el_code;
}
}
i hope that's help you

no such table: reward (code 1): , while compiling: INSERT INTO reward(Reward2,Reward1,Reward3) VALUES (?,?,?)

Hello I'm a student and doing my final year project using sql and android studio. I want to create multiple table and I've trying to follow the example but it doesn't work. the error was no table created. Here my coding
DatabaseHelper.java
package com.example.multipletable;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import androidx.annotation.Nullable;
import static android.content.ContentValues.TAG;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "MultipleTable";
private static final int DATABASE_VERSION = 3;
private static final String TABLE_1 = "register";
private static final String TABLE_2 = "activity";
private static final String TABLE_3 = "reward";
String table_1 = "CREATE TABLE "+TABLE_1+" (matricno TEXT PRIMARY KEY, password TEXT, email TEXT)";
String table_2 = "CREATE TABLE "+TABLE_2+" (id INTEGER PRIMARY KEY AUTOINCREMENT, t_question TEXT, date DEFAULT CURRENT_DATE)";
String table_3 = "CREATE TABLE "+TABLE_3+" (_id INTEGER PRIMARY KEY AUTOINCREMENT, badge_green TEXT, badge_purple TEXT, badge_maroon TEXT)";
public DatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(table_1);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "Current version"+db.getVersion());
for (int version=oldVersion+1; version<=newVersion; version++) {
switch (version) {
case 2:
db.execSQL(table_2);
case 3:
db.execSQL(table_3);
}
}
// Log.e("DATABASE VERSION", db.getVersion()+" ");
//
// db.execSQL("DROP TABLE IF EXISTS "+TABLE_1);
// db.execSQL("DROP TABLE IF EXISTS "+TABLE_2);
// db.execSQL("DROP TABLE IF EXISTS "+TABLE_3);
//
// onCreate(db);
}
public boolean insert(String matNo, String pswd, String email) {
SQLiteDatabase db_1 = this.getWritableDatabase();
ContentValues contentValues1 = new ContentValues();
contentValues1.put("MatricNo", matNo);
contentValues1.put("Password", pswd);
contentValues1.put("Email", email);
db_1.insert(TABLE_1, null, contentValues1);
return true;
}
public boolean insert2(String question) {
SQLiteDatabase db_2 = this.getWritableDatabase();
ContentValues contentValues2 = new ContentValues();
contentValues2.put("Question", question);
contentValues2.put("Date", getDate());
db_2.insert(TABLE_2, null, contentValues2);
return true;
}
public boolean insert3(String green, String purple, String maroon) {
SQLiteDatabase db_3 = this.getWritableDatabase();
ContentValues contentValues3 = new ContentValues();
contentValues3.put("Reward1", green);
contentValues3.put("Reward2", purple);
contentValues3.put("Reward3", maroon);
db_3.insert(TABLE_3, null, contentValues3);
return true;
}
private String getDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
}
MainActiviti.java
package com.example.multipletable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText name, pswd, email;
Button btn_1;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.txt_name);
pswd = findViewById(R.id.txt_password);
email = findViewById(R.id.txt_email);
btn_1 = findViewById(R.id.btn_next_1);
db = new DatabaseHelper(this);
btn_1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String person = name.getText().toString();
String pass = pswd.getText().toString();
String mail = email.getText().toString();
Boolean insert = db.insert(person, pass, mail);
if (insert==true) {
Toast.makeText(getApplicationContext(), "Data 1 saved", Toast.LENGTH_SHORT).show();
Intent intent1 = new Intent(MainActivity.this, Activity2.class);
startActivity(intent1);
}
else {
Toast.makeText(getApplicationContext(), "Data 1 error", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Activity2.java
package com.example.multipletable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Activity2 extends AppCompatActivity {
EditText question;
Button btn2;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
question = findViewById(R.id.txt_question);
btn2 = findViewById(R.id.btn_next_2);
db = new DatabaseHelper(this);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String ques = question.getText().toString();
Boolean insert2 = db.insert2(ques);
if (insert2==true) {
Toast.makeText(getApplicationContext(), "Data 2 saved", Toast.LENGTH_SHORT).show();
Intent intent2 = new Intent(Activity2.this, Activity3.class);
startActivity(intent2);
}
else {
Toast.makeText(getApplicationContext(), "Data 2 error", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Activity3.java
package com.example.multipletable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Activity3 extends AppCompatActivity {
EditText green, purple, maroon;
Button btn3;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_3);
green = findViewById(R.id.txt_green);
purple = findViewById(R.id.txt_purple);
maroon = findViewById(R.id.txt_maroon);
btn3 = findViewById(R.id.btn_next_3);
db = new DatabaseHelper(this);
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String grn = green.getText().toString();
String ppl = purple.getText().toString();
String mrn = maroon.getText().toString();
Boolean insert3 = db.insert3(grn, ppl, mrn);
if (insert3==true) {
Toast.makeText(getApplicationContext(), "Data 3 saved", Toast.LENGTH_SHORT).show();
Intent intent3 = new Intent(Activity3.this, FINISH.class);
startActivity(intent3);
}
else {
Toast.makeText(getApplicationContext(), "Data 3 error", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Can you please help me find the solution and tell me what is wrong :(
I am not sure where your error comes from but, I am assuming its on launch or when you insert the data.
I create my SQL table like below.
However, I did encounter a really annoying issue of if I change my table my app would crash as it would not find it. The fix was I needed to uninstall the app on my phone before uploading the application from android studio to my phone. Hope it helps
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME ="TESTING.db";
// Database Version
private static final int DATABASE_VERSION = 1;
public static final String TABLE_1 = "T1";
public static final String TABLE_2 = "T2";
public static final String TABLE_3 = "T3";
public static final String COL1 = "ID";
public static final String COL2 = "D1";
public static final String COL3 = "D2";
public static final String COL4 = "D3";
public static final String COL5 = "D4";
public static final String COL6 = "D5";
public static final String COL7 = "D6";
public static final String COL8 = "time";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating required tables
String Created_TABLE_1= "CREATE TABLE " + TABLE_1 + " (ID INTEGER PRIMARY KEY, " +
"D1 TEXT, D2 TEXT, D3, TEXT, D4 TEXT, D5 TEXT, D6 TEXT, TIME TEXT)";
String Created_TABLE_2= "CREATE TABLE " + TABLE_2 + " (ID INTEGER PRIMARY KEY, " +
"D1 TEXT, D2 TEXT, D3, TEXT, D4 TEXT, D5 TEXT, D6 TEXT, TIME TEXT)";
String Created_TABLE_3= "CREATE TABLE " + TABLE_3 + " (ID INTEGER PRIMARY KEY, " +
"D1 TEXT, D2 TEXT, D3, TEXT, D4 TEXT, D5 TEXT, D6 TEXT, TIME TEXT)";
db.execSQL(Created_TABLE_1);
db.execSQL(Created_TABLE_2);
db.execSQL(Created_TABLE_3);
}
Ps Stay safe all
Thank you Eugene Troyanskii, forpas and Thomas Morris. I've solved the problem. Supposed to be assign with correct name for column according to create table statement at inserting data code, but I write it different.
Again thanks guys!

Data type mismatch when inserting data into android app database

I'm not entirely sure what could be happening, I know that there is a mismatch when I try to insert, but when I double check my code I can't see why it would spit that error out. I am simply trying to insert a username and password (both are Strings).
CONTEXT:
In my RegisterLoginActivity.java I made it when the user taps the TextView "Create account" it will grab the username and password and turn them into strings.
Then in my DatabaseOperations.java I use the function putInformation() to insert the data.
My TableData.java simply contains my table information.
RegisterLoginActivity.java;
package com.example.envy.energyvue;
import android.content.Context;
import android.database.Cursor;
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.TextView;
import android.widget.Toast;
public class RegisterLoginActivity extends AppCompatActivity {
EditText USER_NAME, USER_PASS;
TextView REG;
String user_name, user_pass;
Context ctx = this;
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
//getActionBar().hide();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_login);
USER_NAME = (EditText) findViewById(R.id.userText);
USER_PASS = (EditText) findViewById(R.id.passText);
REG = (TextView) findViewById(R.id.createAccount);
REG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
user_name = USER_NAME.getText().toString();
user_pass = USER_PASS.getText().toString();
DatabaseOperations DB = new DatabaseOperations(ctx);
DB.putInformation(DB,user_name, user_pass);
}
});
// IGNORE THIS PORTION, IT IS FOR LOGGING IN AFTER I REGISTER
//********************************************
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
user_name = USER_NAME.getText().toString();
user_pass = USER_NAME.getText().toString();
DatabaseOperations DB = new DatabaseOperations(ctx);
Cursor CR = DB.getInformation(DB);
CR.moveToFirst();
boolean loginstatus = false;
String NAME = "";
do{
if(user_name.equals(CR.getString(0)) && user_pass.equals(CR.getString(1))){
loginstatus = true;
}
}while(CR.moveToFirst());
if(loginstatus){
Toast.makeText(getBaseContext(), "Login Success", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getBaseContext(), "Login Failed", Toast.LENGTH_LONG).show();
}
}
});
}
}
DatabaseOperations.java;
package com.example.envy.energyvue;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Envy on 7/13/2016.
*
* private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" + TableData.TableInfo._ID +
" INTEGER PRIMARY KEY," + TableData.TableInfo.COLUMN_NAME_USER_ID + TEXT_TYPE + COMMA_SEP + TableData.TableInfo.COLUMN_NAME_PASSWORD + TEXT_TYPE + " );";
*/
public class DatabaseOperations extends SQLiteOpenHelper{
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "UserData.db";
private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" + TableData.TableInfo._ID +
" INTEGER PRIMARY KEY," + TableData.TableInfo.COLUMN_NAME_USER_ID + TEXT_TYPE + COMMA_SEP + TableData.TableInfo.COLUMN_NAME_PASSWORD + TEXT_TYPE + " );";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + TableData.TableInfo.TABLE_NAME;
public DatabaseOperations(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
public void putInformation(DatabaseOperations dop, String user_id, String password){
SQLiteDatabase SQ = dop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.COLUMN_NAME_USER_ID, user_id);
cv.put(TableData.TableInfo.COLUMN_NAME_PASSWORD, password);
System.out.print("LOLOLSDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD");
long newRowId;
newRowId = SQ.insert(
TableData.TableInfo.TABLE_NAME,
null,
cv);
}
public Cursor getInformation(DatabaseOperations dop){
SQLiteDatabase SQ = dop.getReadableDatabase();
String[] projection = {
TableData.TableInfo._ID,
TableData.TableInfo.COLUMN_NAME_USER_ID,
TableData.TableInfo.COLUMN_NAME_PASSWORD
};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, projection, null, null, null, null, null);
return CR;
}
}
TableData.java;
package com.example.envy.energyvue;
import android.provider.BaseColumns;
/**
* Created by Envy on 7/13/2016.
*/
public class TableData {
public TableData(){}
public static abstract class TableInfo implements BaseColumns {
public static final String TABLE_NAME = "login_information";
public static final String COLUMN_NAME_USER_ID = "user_id";
public static final String COLUMN_NAME_PASSWORD = "password";
}
}
Error:
07-15 21:18:47.996 24361-24361/com.example.envy.energyvue E/SQLiteLog: (20) statement aborts at 5: [INSERT INTO login_information(password,user_id) VALUES (?,?)] datatype mismatch
07-15 21:18:47.996 24361-24361/com.example.envy.energyvue E/SQLiteDatabase: Error inserting password= bbb user_id=bbb
android.database.sqlite.SQLiteDatatypeMismatchException: datatype mismatch (code 20)
#################################################################
Error Code : 20 (SQLITE_MISMATCH)
Caused By : Data type mismatch.
(datatype mismatch (code 20))
#################################################################
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:915)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1609)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1479)
at com.example.envy.energyvue.DatabaseOperations.putInformation(DatabaseOperations.java:59)
at com.example.envy.energyvue.RegisterLoginActivity$1.onClick(RegisterLoginActivity.java:37)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10814)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Alright guys.. after many hours, I figured it out ....I put my database name with a ".db" extension which was messing things up.

I can't get the data

I can't get the data from a database.
Can you help me, please?
Error Log :
1-10091/com.example.dogruprint.dogruprint2 E/AndroidRuntime﹕ FATAL EXCEPTION: main android.database.sqlite.SQLiteException: no such table: users (code 1): , while compiling: SELECT _id, u_name, u_pass FROM
users
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200)
at com.example.dogruprint.dogruprint2.Database.getThat(Database.java:123)
at com.example.dogruprint.dogruprint2.siparisekle$2.onClick(siparisekle.java:113)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
DATABASE.java
package com.example.dogruprint.dogruprint2;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import java.sql.SQLException;
public class Database {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "u_name";
public static final String KEY_PASS = "u_pass";
private static final String DB_NAME = "app";
private static final String DB_TABLE = "users";
private static final int version = 1;
private SQLiteDatabase ourDatabase;
private DBHelper ourHelper;
private Context ourContext;
private SQLiteDatabase writableDatabase;
public Database(Context context) {
ourContext = context;
}
public SQLiteDatabase getWritableDatabase() {
return writableDatabase;
}
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context)
{
super(context, DB_NAME, null, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
/*
final String CREATE_TABLE = " CREATE TABLE " + DB_TABLE + " ( " + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT , "
+ KEY_NAME + " VARCHAR(255) , "
+ KEY_PASS + " VARCHAR(255) ,"
;
*/
String CREATE_USERS_TABLE = "CREATE TABLE " + DB_TABLE + "(" + KEY_ROWID +
" INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_PASS + " TEXT"
+ ");";
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST " + DB_TABLE);
}
}
public Database open() throws SQLException {
ourHelper = new DBHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public Database close() {
ourHelper.close();
return this;
}
public void addThat(String name, String pass) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_PASS, pass);
ourDatabase.insert(DB_TABLE, null, cv);
}
public String getThat()
{
String[] colomns = new String[]{KEY_ROWID,KEY_NAME,KEY_PASS};
Cursor c = ourDatabase.query(DB_TABLE,colomns,null,null,null,null,null);
int İROW = c.getColumnIndex(KEY_ROWID);
int İNAME= c.getColumnIndex(KEY_NAME);
int İPASS = c.getColumnIndex(KEY_PASS);
String result = "";
for(c.moveToFirst();!c.isAfterLast();c.moveToNext())
{
result = result + "name" + c.getString(İNAME) + "pass" + c.getString(İPASS)+"\n";
}
return result;
}
}
siparisekle.java
package com.example.dogruprint.dogruprint2;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.sql.SQLException;
import static android.R.*;
public class siparisekle extends Activity {
private AutoCompleteTextView act1, act2, act3;
private EditText edittxt1;
EditText etName,etPass;
TextView tvResult;
Button bSave;
Button bShow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_siparisekle);
final Database db = new Database(this);
install_elements();
bSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean ok = true;
String name = etName.getText().toString();
String pass = etPass.getText().toString();
try {
db.open();
db.addThat(name, pass);
tvResult.setText(name + "Eklendi");
db.close();
} catch (Exception e) {
ok = false;
e.printStackTrace();
tvResult.setText("Sorun var");
} finally {
if (ok) {
Dialog d = new Dialog(siparisekle.this);
TextView tv = new TextView(siparisekle.this);
tv.setText("BASARILI");
d.setTitle("Sonuç");
d.setContentView(tv);
d.show();
}
}
}
});
bShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
try {
db.open();
String data = db.getThat();
tvResult.setText(data);
db.close();
} catch (SQLException e)
{
Toast.makeText(getApplicationContext(),"Çağırmada Bir Sorun Oluştu",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
protected void install_elements()
{
etName = (EditText) findViewById(R.id.etName);
etPass= (EditText) findViewById(R.id.etPass);
tvResult= (TextView) findViewById(R.id.tvResult);
bSave= (Button) findViewById(R.id.bSave);
bShow= (Button) findViewById(R.id.bShow);
}
}
The exception message says this:
no such table: users (code 1) while compiling "SELECT _id, u_name, u_pass FROM users"
It is looking for a table called "users" in the database, but it can't find one!
Either you haven't set up your database correctly (e.g. you haven't created the tables) or the schema (e.g. table names) for your database doesn't match what the application requires.
In fact, look at your onCreate method. All it is doing is creating and throwing away a string containing some SQL. You need to execute it ....
You really need to execute your table creation:
String CREATE_USERS_TABLE = "CREATE TABLE " + DB_TABLE + "(" + KEY_ROWID +
" INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_PASS + " TEXT" + ")";
db.execSQL(CREATE_USERS_TABLE);
You also need to call your onCreate() method inside your onUpgrade() method
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXIST " + DB_TABLE);
onCreate(db);
}

How to get the list item name from a listview to a textview in another activity?

Im creating an app where users can enter the movies they own, to show in a listview, and for random picking a movie from that list.
Now what my problem is, that when clicking on an item in the listview a new activity opens op where the item clicked is the title in a textview. So far i can get the movie from the list who is number 1 to show, but that shows it's title no matter which list item I click, how can i get the specific name depending on what item is clicked?? Thanks in advance.
My Database class:
package com.example;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MovieDatabaseHelper {
private static final String TAG = MovieDatabaseHelper.class.getSimpleName();
// database configuration
// if you want the onUpgrade to run then change the database_version
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "mymoviedatabase.db";
// table configuration
private static final String TABLE_NAME = "movie_table"; // Table name
private static final String MOVIE_TABLE_COLUMN_ID = "_id"; // a column named "_id" is required for cursor
private static final String MOVIE_TABLE_COLUMN_TITLE = "movie_title";
private static final String MOVIE_TABLE_COLUMN_YEAR = "production_year";
private DatabaseOpenHelper openHelper;
private SQLiteDatabase database;
// this is a wrapper class. that means, from outside world, anyone will communicate with MovieDatabaseHelper,
// but under the hood actually DatabaseOpenHelper class will perform database CRUD operations
public MovieDatabaseHelper(Context aContext) {
openHelper = new DatabaseOpenHelper(aContext);
database = openHelper.getWritableDatabase();
}
public void insertData (String aMovieTitle, String aMovieYear) {
// we are using ContentValues to avoid sql format errors
ContentValues contentValues = new ContentValues();
contentValues.put(MOVIE_TABLE_COLUMN_TITLE, aMovieTitle);
contentValues.put(MOVIE_TABLE_COLUMN_YEAR, aMovieYear);
database.insert(TABLE_NAME, null, contentValues);
}
//Retrieves all the records
public Cursor getAllData () {
String buildSQL = "SELECT * FROM " + TABLE_NAME + " ORDER BY " + MOVIE_TABLE_COLUMN_TITLE + " COLLATE NOCASE";
Log.d(TAG, "getAllData SQL: " + buildSQL);
return database.rawQuery(buildSQL, null);
}
// Retrieves specific record
public String getMovieTitle()
{
Cursor c =
database.query(TABLE_NAME,
new String[] { MOVIE_TABLE_COLUMN_TITLE }, null, null, null, null, null);
if (c.moveToFirst())
return c.getString(c.getColumnIndex(MOVIE_TABLE_COLUMN_TITLE ));
else
return "Nothing";
}
// Retrieves a random entry from the Database
public String getRandomMovie()
{
Cursor c = database.query(TABLE_NAME + " ORDER BY RANDOM() LIMIT 1",
new String[] { MOVIE_TABLE_COLUMN_TITLE }, null, null, null, null, null);
if(c.moveToFirst())
return c.getString(c.getColumnIndex(MOVIE_TABLE_COLUMN_TITLE ));
else
return "nothing";
}
//Check if record exist
//---deletes a particular record---
public void delete(int _id)
{
database.delete(TABLE_NAME, MOVIE_TABLE_COLUMN_ID+"="+_id, null);
}
//---updates a record---
public boolean updateRecord(long _id, String movie_title)
{
ContentValues args = new ContentValues();
args.put(MOVIE_TABLE_COLUMN_TITLE, movie_title);
return database.update(TABLE_NAME, args, MOVIE_TABLE_COLUMN_ID + "=" + _id, null) > 0;
}
// this DatabaseOpenHelper class will actually be used to perform database related operation
private class DatabaseOpenHelper extends SQLiteOpenHelper {
public DatabaseOpenHelper(Context aContext) {
super(aContext, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// Create your tables here
String buildSQL = "CREATE TABLE " + TABLE_NAME + "( " + MOVIE_TABLE_COLUMN_ID + " INTEGER PRIMARY KEY, " +
MOVIE_TABLE_COLUMN_TITLE + " TEXT, " + MOVIE_TABLE_COLUMN_YEAR + " TEXT )";
Log.d(TAG, "onCreate SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
// Database schema upgrade code goes here
String buildSQL = "DROP TABLE IF EXISTS " + TABLE_NAME;
Log.d(TAG, "onUpgrade SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL); // drop previous table
onCreate(sqLiteDatabase); // create the table from the beginning
}
}
}
My listview class:
package com.example;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
//import android.widget.Button;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
public class MyActivity extends Activity {
private CustomCursorAdapter customAdapter;
private MovieDatabaseHelper databaseHelper;
private static final int ENTER_DATA_REQUEST_CODE = 1;
private ListView listView;
MediaPlayer mp;
private static final String TAG = MyActivity.class.getSimpleName();
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dblist);
databaseHelper = new MovieDatabaseHelper(this);
final MediaPlayer mp = MediaPlayer.create(MyActivity.this, R.raw.cartoon015);
listView = (ListView) findViewById(R.id.list_data);
ImageButton okay = (ImageButton) findViewById(R.id.okay);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id ) {
Intent i = new Intent(MyActivity.this,IMDb.class);
startActivity(i);
Log.d(TAG, "clicked on item: " + position);
}
}
);
okay.setOnClickListener
(new View.OnClickListener()
{
public void onClick(View v)
{
mp.start();
mp.setVolume((float) 0.3, (float) 0.3);
Intent intent = new Intent(MyActivity.this,MovieActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
);
// Database query can be a time consuming task ..
// so its safe to call database query in another thread
// Handler, will handle this stuff for you <img src="http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif?m=1129645325g" alt=":)" class="wp-smiley">
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new CustomCursorAdapter(MyActivity.this, databaseHelper.getAllData());
listView.setAdapter(customAdapter);
}
});
}
public void onClickEnterData(View btnAdd) {
final MediaPlayer mp = MediaPlayer.create(MyActivity.this, R.raw.cartoon015);
mp.start();
mp.setVolume((float) 0.1, (float) 0.1);
startActivityForResult(new Intent(this, EnterDataActivity.class), ENTER_DATA_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ENTER_DATA_REQUEST_CODE && resultCode == RESULT_OK) {
databaseHelper.insertData(data.getExtras().getString("tag_movie_title"), data.getExtras().getString("tag_movie_year"));
customAdapter.changeCursor(databaseHelper.getAllData());
}
}
}
My movie detail class:
package com.example;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class IMDb extends Activity {
TextView Movietitle;
private MovieDatabaseHelper databaseHelper;
MediaPlayer mp;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.imdb);
Movietitle = (TextView) findViewById(R.id.movietitle);
databaseHelper = new MovieDatabaseHelper(this);
Button delete = (Button) findViewById(R.id.delete);
Movietitle.setText( databaseHelper.getMovieTitle());
}
}
Well, there is lot of code you are asking for. But I can tell you the steps
Create a Model Class for your movie,, where you can hold the db records
Create list of Model Class and then when you click the item, you get the position of record in list.
Your movie Model class must have getter and setter functions to retrieve record details.

Categories