Please i am trying to create a login from a preloaded database. But i am having problems copying database. Below is my debug error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.babbangona.preloadedtestingagain, PID: 11863
java.lang.Error: Error copying database
at com.babbangona.preloadedtestingagain.DBHandler.createDatabase(DBHandler.java:42)
at com.babbangona.preloadedtestingagain.DBcopyActivity$1.onClick(DBcopyActivity.java:28)
at android.view.View.performClick(View.java:6199)
at android.view.View$PerformClick.run(View.java:23235)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1073)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934) I/art:
Enter while loop. I/art: Enter while loop. Disconnected from the
target VM, address: 'localhost:8600', transport: 'socket'
My DBHandler java file:
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class DBHandler extends SQLiteOpenHelper{
String DB_PATH = null;
private static String DB_NAME = "rehoboth.db";
private SQLiteDatabase myDatabase;
private final Context myContext;
public DBHandler(Context context){
super(context, DB_NAME, null, 2);
this.myContext = context;
this.DB_PATH = "/data/data" + context.getPackageName() + "/databases/";
Log.e("Path 1", DB_PATH);
}
public void createDatabase() throws IOException {
boolean dbExist = checkDatabase();
if(dbExist){
/* openDatabase();
int cVersion = myDatabase.getVersion();
if(cVersion != 2){
onUpgrade(myDatabase, myDatabase.getVersion(),2);
close();
}*/
}else{
this.getReadableDatabase();
try{
copyDatabase();
}catch (IOException e){
throw new Error("Error copying database");
}
}
}
private boolean checkDatabase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDatabase() throws IOException{
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[10];
int length;
while((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDatabase() throws SQLException{
String myPath = DB_PATH + DB_NAME;
myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
#Override
public synchronized void close(){
if(myDatabase != null)
myDatabase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db){
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
if(newVersion > oldVersion)
try{
copyDatabase();
}catch (IOException e){
e.printStackTrace();
}
}
public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy){
return myDatabase.query("rehoboth", null, null, null, null, null, null);
}
}
My main Activity:
import android.app.Activity;
import android.database.Cursor;
import android.database.SQLException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
public class DBcopyActivity extends Activity {
Cursor c = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dbcopy);
((Button) findViewById(R.id.button1)).setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
DBHandler myDbHelper = new DBHandler(DBcopyActivity.this);
try{
myDbHelper.createDatabase();
}catch(IOException ioe){
throw new Error("Unable to create database");
}try{
myDbHelper.openDatabase();
}catch(SQLException sqle){
throw sqle;
}
Toast.makeText(DBcopyActivity.this, "Successfully Imported", Toast.LENGTH_SHORT).show();
c = myDbHelper.query("rehoboth", null, null, null, null, null, null);
if(c.moveToFirst()){
do{
Toast.makeText(DBcopyActivity.this,
"_id: " + c.getString(0) + "\n" +
"NAME: " + c.getString(1) + "\n" +
"PASSWORD: " + c.getString(2),
Toast.LENGTH_LONG).show();
}while (c.moveToNext());
}
}
});
}
}
Related
I am trying to build a messenger type app. And for this, I have uploaded an image from my phone to firebase. And the image is successfully stored in firebase storage. And I am trying to show the image on my phone. And I use Picasso to retrieve the image from firebase. But my picture isn't showing. But when I add placeholder I can see the default image that is set by a placeholder. How can I solve this problem? My code is given below:
package com.example.whatsapp2;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.io.IOException;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
public class SettingsActivity extends AppCompatActivity {
private Button UpdateAccountSetting;
private EditText userName, userStatus;
private CircleImageView userProfileImage;
private String currentUserId;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;
private static final int GalleryPick = 1;
private StorageReference UserProfileImagesRef;
private ProgressDialog loadingBar;
private Toolbar SettingsToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
FirebaseApp.initializeApp(this);
mAuth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
UserProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
InitializeFields();
userName.setVisibility(View.INVISIBLE);
UpdateAccountSetting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UpdateSettings();
}
});
RetrieveUserInfo();
userProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,GalleryPick);
}
});
}
private void RetrieveUserInfo() {
RootRef.child("Users").child(currentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name")) && (dataSnapshot.hasChild("image"))){
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("status").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveStatus);
Picasso.get().load(retrieveProfileImage).into(userProfileImage);
//Picasso.get().load(retrieveProfileImage).placeholder(R.drawable.profile_image).resize(100,100).centerCrop().into(userProfileImage);
}
else if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name"))){
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("status").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveStatus);
}
else {
userName.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(),"Please set & update your profile information...",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void UpdateSettings() {
String setUserName = userName.getText().toString();
String setStatus = userStatus.getText().toString();
if (TextUtils.isEmpty(setUserName)) {
Toast.makeText(this,"Please write your user name first....",Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setStatus)) {
Toast.makeText(this,"Please write your status....",Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, Object> profileMap = new HashMap<>();
profileMap.put("uid", currentUserId);
profileMap.put("name", setUserName);
profileMap.put("status", setStatus);
RootRef.child("Users").child(currentUserId).updateChildren(profileMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(getApplicationContext(),"Profile Updated Successfully...",Toast.LENGTH_SHORT).show();
}
else {
String message = task.getException().toString();
Toast.makeText(getApplicationContext(),"Error : "+message,Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void InitializeFields() {
UpdateAccountSetting = findViewById(R.id.update_settings_button);
userName = findViewById(R.id.set_user_name);
userStatus =findViewById(R.id.set_profile_status);
userProfileImage = findViewById(R.id.set_profile_image);
loadingBar = new ProgressDialog(this);
SettingsToolbar = findViewById(R.id.settings_toolbar);
setSupportActionBar(SettingsToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setTitle("Account Settings");
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(this,MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GalleryPick && resultCode == RESULT_OK && data != null){
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
//userProfileImage.setImageURI(ImageUri);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK){
loadingBar.setTitle("Set Profile Image");
loadingBar.setMessage("Please wait, your profile image is updating...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImagesRef.child(currentUserId+".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),"Profile Image uploaded Successfully...",Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
RootRef.child("Users").child(currentUserId).child("image").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),"Image save in Database Successfully...",Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else{
String message = task.getException().toString();
Toast.makeText(getApplicationContext(),"Error:"+message,Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
else{
String message = task.getException().toString();
Toast.makeText(getApplicationContext(),"Error:"+message,Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
}
}
You can resolve this issue by simply adding 1 line of code:
//in this block
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GalleryPick && resultCode == RESULT_OK && data != null ) {
Uri ImageUri = data.getData();
userProfileImage.setImageURI(ImageUri); //add this line
i have wrriten a code and getting error in
06-30 23:55:00.702 2499-2499/com.example.parthtiwari.trace E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.parthtiwari.trace, PID: 2499
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null
my code is
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.AuthResult;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
private FirebaseAuth fb;
private DatabaseReference databaseReference;
private EditText editTextEmail;
private EditText editTextPassword;
private EditText editTextName, mobile_number,vehicle_number,editTextAddress;
private Button buttonSignup;
private TextView textViewSignin;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fb = FirebaseAuth.getInstance();
if(fb.getCurrentUser() != null){
finish();
startActivity(new Intent(getApplicationContext(),welcome.class));
}
databaseReference = FirebaseDatabase.getInstance().getReference();
editTextAddress = (EditText) findViewById(R.id.Address);
editTextName = (EditText) findViewById(R.id.name);
mobile_number = (EditText) findViewById(R.id.mobile);
vehicle_number = (EditText) findViewById(R.id.vehicle);
editTextEmail = (EditText) findViewById(R.id.Email);
editTextPassword = (EditText) findViewById(R.id.Password);
buttonSignup = (Button) findViewById(R.id.Signup);
textViewSignin = (TextView) findViewById(R.id.Signin);
progressDialog = new ProgressDialog(this);
FirebaseUser user = fb.getCurrentUser();
buttonSignup.setOnClickListener(this);
textViewSignin.setOnClickListener(this);
}
private void registerUser() {
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if (TextUtils.isEmpty(email)) {
Toast.makeText(this, "Please enter email",
Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please enter password",
Toast.LENGTH_LONG).show();
return;
}
progressDialog.setMessage("Registering Please Wait...");
progressDialog.show();
fb.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Successfully registered", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Registration Error", Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
saveUserInformation();
}
private void saveUserInformation() {
String name = editTextName.getText().toString().trim();
String mob = mobile_number.getText().toString().trim();
String vehicle = vehicle_number.getText().toString().trim();
String add = editTextAddress.getText().toString().trim();
//creating a userinformation object
userinfo userInformation = new userinfo(name, mob, vehicle, add);
//getting the current logged in user
FirebaseUser user = fb.getCurrentUser();
databaseReference.child(user.getUid()).setValue(userInformation);
//displaying a success toast
Toast.makeText(this, "Information Saved...", Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View view) {
if(view == buttonSignup){
registerUser();
}
if(view == textViewSignin){
startActivity(new Intent(this, login.class));
}
}
}
Try moving saveUserInformation() into your onCompletionListener.
Looks like saveUserInformation() is called before registration is completed.
fb.createUserWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
saveUserInformation(authResult);
Toast.makeText(MainActivity.this, "Successfully
registered",Toast.LENGTH_LONG).show();
progressDialog.dismiss(); }).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Registration Error",
Toast.LENGTH_LONG).show();
progressDialog.dismiss();
});
and change
saveUserInformation(AuthResult authResult)
authResult.getUid();
I don't know what will be the fix to the error cause I already mentioned the column names and I have a name column in my database.(I am just a beginner) please help me.
This is my DbH class
package sjdb.db;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by user on 30/09/2016.
*/
public class DbH extends SQLiteOpenHelper {
private Context mycontext;
private String DB_PATH = "/data/data/sjdb.db/databases/";
private static String DB_NAME = "red.db";
private static String DB_TABLE="form";
public static String Col_1="name";
public static String Col_2="address";
public static String Col_3="number";
public SQLiteDatabase myDataBase;
/*private String DB_PATH = "/data/data/"
+ mycontext.getApplicationContext().getPackageName()
+ "/databases/";
*/
public DbH(Context context) throws IOException {
super(context,DB_NAME,null,1);
this.mycontext=context;
}
public void createdatabase() throws IOException{
boolean dbexist = checkdatabase();
if(dbexist)
{
System.out.println(" Database exists.");
}
else{
this.getReadableDatabase();
try{
copydatabase();
}
catch(IOException e){
throw new Error("Error copying database");
}
}
}
private boolean checkdatabase() {
//SQLiteDatabase checkdb = null;
boolean checkdb = false;
try{
String myPath = DB_PATH + DB_NAME;
File dbfile = new File(myPath);
checkdb = SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE) != null;
checkdb = dbfile.exists();
}
catch(SQLiteException e){
System.out.println("Database doesn't exist");
}
return checkdb;
}
private void copydatabase() throws IOException {
//Open your local db as the input stream
InputStream myinput = mycontext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outfilename = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myoutput = new FileOutputStream(outfilename);
// transfer byte to inputfile to outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myinput.read(buffer))>0)
{
myoutput.write(buffer,0,length);
}
//Close the streams
myoutput.flush();
myoutput.close();
myinput.close();
}
public void opendatabase() throws SQLException
{
//Open the database
String mypath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READONLY);
}
public synchronized void close(){
if(myDataBase != null){
myDataBase.close();
}
super.close();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// This will return a cursor containing database records
public Cursor data(){
Cursor c;
String[] from = new String[] {Col_1, Col_2, Col_3};
c=myDataBase.query(DB_TABLE,from,null, null,null,null,null);
return c;
}
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
}
And this is my MyActivity class
package sjdb.db;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
public class MyActivity extends Activity implements View.OnClickListener {
/** Called when the activity is first createdl. */
Cursor cur;
TextView tv, tv1, tv2;
DbH db;
Button next,back;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
tv=(TextView)findViewById(R.id.text);
tv1=(TextView)findViewById(R.id.text1);
tv2=(TextView)findViewById(R.id.text2);
next=(Button)findViewById(R.id.next);
back=(Button)findViewById(R.id.back);
next.setOnClickListener(this);
back.setOnClickListener(this);
try {
db=new DbH(this);
} catch (IOException e2) {
e2.printStackTrace();
}
try {
db.createdatabase();
} catch (IOException e) {
e.printStackTrace();
}
db.opendatabase();
cur=db.data();
cur.moveToFirst();
tv.setText(cur.getString(1));
tv1.setText(cur.getString(2));
tv2.setText(cur.getString(3));
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.next :
if(cur.isLast())
{
cur.moveToFirst();
tv.setText(""+cur.getString(1));
tv1.setText(""+cur.getString(2));
tv2.setText(""+cur.getString(3));
}
else
{
cur.moveToNext();
tv.setText(""+cur.getString(1));
tv1.setText(""+cur.getString(2));
tv2.setText(""+cur.getString(3));
}
break;
case R.id.back:
{
if(cur.isFirst())
{
cur.moveToLast();
tv.setText(""+cur.getString(1));
tv1.setText(""+cur.getString(2));
tv2.setText(""+cur.getString(3));
}
else {cur.moveToPrevious();
tv.setText(""+cur.getString(1));
tv1.setText(""+cur.getString(2));
tv2.setText(""+cur.getString(3));
}
break;
}
}
}
}
This is the error:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{sjdb.db/sjdb.db.MyActivity}: android.database.sqlite.SQLiteException: no such column: name: , while compiling: SELECT name, address, number FROM form
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
at android.app.ActivityThread.access$600(ActivityThread.java:128)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4517)
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:993)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: no such column: name: , while compiling: SELECT name, address, number FROM form
at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:143)
at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:127)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:94)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:53)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1686)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1571)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1527)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1607)
at sjdb.db.DbH.data(DbH.java:122)
at sjdb.db.MyActivity.onCreate(MyActivity.java:47)
at android.app.Activity.performCreate(Activity.java:4470)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
at android.app.ActivityThread.access$600(ActivityThread.java:128)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4517)
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:993)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
at dalvik.system.NativeStart.main(Native Method)
I/Process: Sending signal. PID: 11719 SIG: 9
column: name: , while compiling: SELECT name, address, number FROM form
Try looking these part. Are these correct?
Try to fit this code if it doesnt go to your TextView.
When i press "Lägg till(Add)" i put textin my three edittext boxes, then i'll press OK and it should save it in database and display it in my listview with the first editbox text as tite. When i press on a item in my listview i want to be abel to show inputed text and if i press "RADERA(delete)" i want to be able to delete it from databas and listview.
my database adapter
package com.projekt;
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 DBAdapter {
static final String KEY_ROWID = "id";
static final String KEY_PASS = "pass";
static final String KEY_USERNAME = "user";
static final String KEY_TITLE = "title";
static final String TAG = "DBAdapter";
static final String DATABASE_NAME = "DBPASS";
static final String DATABASE_TABLE = "information";
static final int DATABASE_VERSION = 1;
static final String DATABASE_CREATE = "create table information (id integer primary key autoincrement, "
+ "user text not null, pass text not null, title text not null);";
final Context context;
DatabaseHelper DBHelper;
SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
// ---opens the database---
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
public void close() {
DBHelper.close();
}
public long insertInfo(String title, String user, String pass) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_USERNAME, user);
initialValues.put(KEY_PASS, pass);
return db.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteInfo(long rowId) {
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public void delete_byID(int id){
db.delete(DATABASE_TABLE, KEY_ROWID+"="+id, null);
}
public Cursor getAllInfo() {
return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_USERNAME,
KEY_PASS, KEY_TITLE }, null, null, null, null, null);
}
public Cursor getInfo(String title) throws SQLException {
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID, KEY_USERNAME, KEY_PASS, KEY_TITLE }, KEY_PASS + "= '" + title + "'",
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateInfo(long rowId, String title, String user, String pass) {
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_USERNAME, user);
args.put(KEY_PASS, pass);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
my program
package com.projekt;
import java.util.ArrayList;
//import java.util.Arrays;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
//import android.text.Editable;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
public class layout2 extends Activity implements OnClickListener, OnItemClickListener {
Button btn3;
ListView lv;
private ArrayAdapter<String> listAdapter;
String titleInfo;
ArrayList<String> nameList;
EditText anvNamn;
EditText pass;
EditText title;
DBAdapter db = new DBAdapter(this);
String passInfo = "";
String anv = "";
String titleInfo2 = "";
String visa;
int del;
Cursor c;
Button btn5;
public void onCreate(Bundle savedInstanceState) {
//Start
super.onCreate(savedInstanceState);
setContentView(R.layout.program_layout);
btn3 = (Button) findViewById(R.id.button3);
btn3.setOnClickListener(this);
btn5 = (Button) findViewById(R.id.button5);
btn5.setOnClickListener(this);
lv = (ListView) findViewById(R.id.listView1);
nameList = new ArrayList<String>();
listAdapter = new ArrayAdapter<String>(this, R.layout.row, nameList);
lv.setAdapter(listAdapter);
lv.setOnItemClickListener(this);
getAllData();
//Stop
}
private ArrayList<String> getAllData() {
// ---get all contacts---
db.open();
c = db.getAllInfo();
if (c.moveToFirst()) {
do {
anv = c.getString(1);
passInfo = c.getString(2);
titleInfo2 = c.getString(3);
//in = new String (anv, passInfo, titleInfo2);
//nameList.add(in);
listAdapter.add(titleInfo2);
//updateList();
} while (c.moveToNext());
//listAdapter.add(titleInfo2);
//del = c.getInt(c.getColumnIndex(db.KEY_ROWID));
}
db.close();
//listAdapter.add(titleInfo2);
return nameList;
}
public void inputDialog() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
LinearLayout lila1 = new LinearLayout(this);
lila1.setOrientation(1);
anvNamn = new EditText(this);
pass = new EditText(this);
title = new EditText(this);
lila1.addView(title);
lila1.addView(anvNamn);
lila1.addView(pass);
title.setText("Titel");
anvNamn.setText("Användarnamn");
pass.setText("Lösenord");
alert.setView(lila1);
title.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
title.setText("");
}
});
anvNamn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
anvNamn.setText("");
}
});
pass.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
pass.setText("");
}
});
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String titleDB = title.getText().toString();
String userDB = anvNamn.getText().toString();
String passDB = pass.getText().toString();
listAdapter.add(titleDB);
db.open();
db.insertInfo(titleDB, userDB, passDB);
db.close();
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button3:
inputDialog();
break;
case R.id.button5:
Intent nextActivity = new Intent(this, MainActivity.class);
startActivity(nextActivity);
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
// TODO Auto-generated method stub
String text = nameList.get(arg2);
//final int ar = arg2;
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(titleInfo2);
alert.setMessage("Användarnamn: " + anv + "\nLösenord: "+ passInfo);
final String radera = listAdapter.getItem(arg2).toString();
final long raderaPos = listAdapter.getItemId(arg2);
alert.setNegativeButton("RADERA",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//String s = (String) arg0.getItemAtPosition(arg2);
db.open();
//db.updateInfo(arg2, anv, passInfo, titleInfo);
db.deleteInfo(arg2);
db.updateInfo(arg2, anv, passInfo, titleInfo);
db.close();
listAdapter.remove(radera);
}
});
alert.show();
}
}
im from sweden my string names may be confusing.
Never ever use parameter names like arg0,1,...
It is impossible to understand code that uses such names.
Apparently, in some places, the code uses arg2 (the position of the view in the adapter) where it should use arg3 (the item's row id).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
I really need a sqlite database file for studies.
I'm creating an application in C# and I need a database with many tables, field, views, indexes, constraints and so on. And I don't want to create it myself using sqlite command line tool.
So I suppose may be someone can say where I can find such file, may be different applications or examples, or even can send me their own database file. I will appreciate any help.
There is a nice sample database called Chinook. It's trying to be the modern example to replace NorthWind. They have versions for different database servers including SQLite.
Homepage, DB diagram, etc.. http://chinookdatabase.codeplex.com/
Github (seems more updated than CodePlex) https://github.com/lerocha/chinook-database
Latest SQLite download to date of post: https://chinookdatabase.codeplex.com/releases/view/55681#fileDownload6
Download SQLite Sample Database to get the Chinook database file directly http://www.sqlitetutorial.net/sqlite-sample-database/
More SQLite related projects and samples on CodePlex http://www.codeplex.com/site/search?query=sqlite&ac=8
Also, check this sample in the SQLite .NET client forums (attached to first post)
Getting the Microsoft EFQuerySamples project to work with SQLite
Maybe a GUI tool to create database stuff will make starting easier, check this one, free for personal use
http://www.sqliteexpert.com/
Personally, I create SQLite databases for testing NHibernate mappings. Usually I create my classes and mappings then use the mappings to generate schema to a new SQLite file (or in memory database, more often) and use that. Most NHibernate introduction articles do that as well.
SQLite is whidely used by many applications so I am pretty sure very lot examples can be found on your computer. For example, on my Win10 PC if I search in "c:\Users\Konstantin" (my profile) for files with:
file name mask: *.sqlite;*.db
text inside: SQLite format 3
I am currently getting 785 results. Most of them, which have that text in the beginning - it is 99% SQLite database files. Particularly I see that it is used by skype, viber, dropbox, office and firefox.
I used sqlightCrud operation
First creat database class.
package com.db;
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;
import android.widget.Toast;
public class DataBaseSampleActivity {
/** for database */
static final String DataBaseName = "EmployeDB";
/** for employee table */
static final String EmployeTable = "Employees";
static final String ColEmpID = "EmpId";
static final String ColEmpName = "EmpName";
static final String ColEmpAge = "EmpAge";
static final String ColDept = "Dept";
/** for department table */
static final String DeptTable = "Department";
static final String ColDeptID = "DeptId";
static final String ColDeptName = "DeptName";
public static final int DATABASE_VERSION = 2;
//private static final String KEY_ROWID = "_id";
private static final String EMPLOYEE_TABLE_CREATE ="Create table " + EmployeTable +
//"(_id INTEGER UNIQUE," + [old code]
"("+ColEmpID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
ColEmpName + " VARCHAR(15) ," +
ColEmpAge + " INT(15) ," +
ColDept + " VARCHAR(15)) ";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DataBaseSampleActivity(Context ctx){
Log.i("test****", "**test***");
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper{
public DatabaseHelper(Context context){
super(context, DataBaseName , null, DATABASE_VERSION);
Log.i("context","context");
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(EMPLOYEE_TABLE_CREATE);
Log.i("************", "table created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w("tag", "Upgrading database from version " + oldVersion + " to "+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + EmployeTable);
onCreate(db);
}
};
public DataBaseSampleActivity open() throws SQLException{
db = DBHelper.getWritableDatabase();
Log.i("open", "message");
return this;
}
public void close(){
DBHelper.close();
}
//public long insert(Integer empid, String empname, Integer empage, String empdept) {
public long insert(String empname, Integer empage, String empdept) {
Log.i("**** suruchitest **** ","*** test ***");
ContentValues initialValues = new ContentValues();
//initialValues.put(ColEmpID, empid);
initialValues.put(ColEmpName, empname);
initialValues.put(ColEmpAge, empage);
initialValues.put(ColDept, empdept);
return db.insert(EmployeTable, null, initialValues);
}
public Cursor getEmpValues(){
Cursor mCursor = db.query(EmployeTable, null, null, null, null, null, null);
return mCursor;
}
public boolean deleteEmpList(long rowId){
Toast.makeText(context, "deleted", 2000).show();
return db.delete(EmployeTable, ColEmpID +" = " + rowId, null) > 0;
}
public boolean updateEmplist(String empname, Integer empage, String empdept, Integer rowid){
ContentValues initialValues = new ContentValues();
Log.i("##### "+rowid,""+empname+" "+empage+" "+empdept);
//initialValues.put(ColEmpID, rowid);
initialValues.put(ColEmpName,empname);
initialValues.put(ColEmpAge,empage);
initialValues.put(ColDept,empdept);
try{
int b = db.update(EmployeTable, initialValues, ColEmpID+ " = " + rowid, null);
Log.i("update", "up "+rowid+" ddd "+b);
return true;
}catch (Exception e){
Log.d("asdfasdfsadfasdf", "_--___--__--_=-_");
return false;
}
}
}
2. create Main Activity
package com.db;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
Button buttonsubmit;
EditText empid,empname,empage,empdept;
String emp_name, emp_dept;
//Integer emp_id,emp_age;
Integer emp_age;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonsubmit = (Button) findViewById(R.id.btnSubmit);
buttonsubmit.setOnClickListener(this);
// empid =(EditText) findViewById(R.id.empid);
empname =(EditText) findViewById(R.id.empname);
empage =(EditText) findViewById(R.id.empage);
empdept =(EditText) findViewById(R.id.empdpt);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DataBaseSampleActivity dbObj = new DataBaseSampleActivity(getApplicationContext());
// String Emp_ids = empid.getText().toString();
// emp_id = Integer.parseInt(Emp_ids);
//emp_id = empid.getText().toString();
String Emp_ages = empage.getText().toString();
emp_age = Integer.parseInt(Emp_ages);
//emp_age = empage.getText().toString();
emp_name = empname.getText().toString();
emp_dept = empdept.getText().toString();
try {
Log.i("try", "message");
dbObj.open();
//long temp = dbObj.insert(emp_id, emp_name, emp_age, emp_dept);
long temp = dbObj.insert(emp_name, emp_age, emp_dept);
//Toast.makeText(getApplicationContext(), "temp"+temp, 3000).show();
dbObj.close();
Intent intent = new Intent(this,ShowListView.class);
startActivity(intent);
} catch (Exception e) {
// TODO: handle exception
Log.i("catch", "message");
}
}
}
2. Create listclass to show tha data
package com.db;
import java.lang.reflect.Array;
import java.util.ArrayList;
import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ShowListView extends Activity {
ArrayList<String> arrname = new ArrayList<String>();
ArrayList<String> arrage = new ArrayList<String>();
ArrayList<String> arrdept = new ArrayList<String>();
ArrayList<Integer> arrRowId = new ArrayList<Integer>();
ArrayList<Integer> arrDelId = new ArrayList<Integer>();
Array[] arr;
Button deleteBtn;
Button btnadd;
int index = 0;
public int pos;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.emplist);
//Toast.makeText(getApplicationContext(), "LIST VIEW", 5000).show();
ToGetCursorValues();
}
public void ToGetCursorValues(){
DataBaseSampleActivity db = new DataBaseSampleActivity(getApplicationContext());
db.open();
try {
Cursor cur = db.getEmpValues();
cur.moveToFirst();
arrRowId.clear();
arrname.clear();
arrage.clear();
arrdept.clear();
while (!cur.isAfterLast()) {
arrRowId.add(cur.getInt(cur.getColumnIndex(db.ColEmpID)));
arrname.add(cur.getString(cur.getColumnIndex(db.ColEmpName)));
arrage.add(cur.getString(cur.getColumnIndex(db.ColEmpAge)));
arrdept.add(cur.getString(cur.getColumnIndex(db.ColDept)));
cur.moveToNext();
}
//Log.i("#####","col "+arrlist.size());
//Toast.makeText(getApplicationContext(), "* "+arrname.size()+","+arrage.size()+","+arrdept.size(), 5000).show();
//Toast.makeText(getApplicationContext(), "***** "+arrRowId.get(0), 2000).show();
} catch (Exception e) {
// TODO: handle exception
}
ListView lst = (ListView) findViewById(R.id.mylist);
lst.setAdapter(new ListAdapter(getApplicationContext()));
db.close();
}
public class ListAdapter extends BaseAdapter implements OnCheckedChangeListener,OnClickListener{
private LayoutInflater inflater = null;
public ListAdapter(Context c){
Log.i("Context","Context");
inflater = LayoutInflater.from(c);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
//return 0;
return arrname.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
class ViewHolder{
TextView empnameview;
TextView empageview;
TextView empdeptview;
CheckBox empchkbox;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(final int position, View convertView, ViewGroup parent) {
Log.i("*view","view*");
ViewHolder vh;
//ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
Log.i("*null1*","*null1*");
vh = new ViewHolder();
convertView = inflater.inflate(R.layout.customlist, null);
Log.i("*null2*","*null2*");
pos = position;
vh.empnameview = (TextView) convertView.findViewById(R.id.ename);
vh.empageview = (TextView) convertView.findViewById(R.id.eage);
vh.empdeptview = (TextView) convertView.findViewById(R.id.edept);
vh.empchkbox = (CheckBox) convertView.findViewById(R.id.ckekDelete);
Log.i("*null3*","*null3*");
vh.empnameview.setText(arrname.get(position));
vh.empnameview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(ShowListView.this,UpdateDB.class);
String name = arrname.get(position);
int age = Integer.parseInt(arrage.get(position));
String dept = arrdept.get(position);
int rowid = arrRowId.get(position);
intent.putExtra("KeyName" , name);
intent.putExtra("Keyage" , age);
intent.putExtra("Keydept" , dept);
intent.putExtra("Rowid", rowid);
startActivity(intent);
}
});
vh.empageview.setText(arrage.get(position));
vh.empdeptview.setText(arrdept.get(position));
vh.empchkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), "OnChecked"+position, 2000).show();
if(buttonView.isChecked()){
arrDelId.add(arrRowId.get(position));
//Toast.makeText(getApplicationContext(), "OnChecked"+position, 2000).show();
// DataBaseSampleActivity db = new DataBaseSampleActivity(getApplicationContext());
// db.open();
// db.deleteEmpList(arrRowId.get(position));
// Toast.makeText(getApplicationContext(), "delet", 3000).show();
// db.close();
//
}
else{
for(int i=0;i<arrDelId.size();i++){
if(arrRowId.get(position) == arrDelId.get(i)){
arrDelId.remove(i);
}
}
}
}
});
Log.i("******", "complete");
} else {
Log.i("*not*","*not*");
vh = (ViewHolder) convertView.getTag();
}
deleteBtn = (Button) findViewById(R.id.delBtn);
deleteBtn.setOnClickListener(this);
btnadd = (Button) findViewById(R.id.addBtn);
btnadd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent inte = new Intent(ShowListView.this, MainActivity.class);
startActivity(inte);
}
});
// imageView.setImageResource(thumbarr[position]);
return convertView;
}
public View getView1(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for(int i=0;i<arrDelId.size();i++){
//Toast.makeText(getApplicationContext(), "OnDeleteClick "+i, 2000).show();
DataBaseSampleActivity db = new DataBaseSampleActivity(getApplicationContext());
db.open();
db.deleteEmpList(arrDelId.get(i));
//Toast.makeText(getApplicationContext(), "delet", 3000).show();
db.close();
}
ToGetCursorValues();
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
}
}
}
3. for update
package com.db;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class UpdateDB extends Activity implements OnClickListener{
Intent intnt;
EditText editname,editage,editdept;
Button updateBtn;
int row_id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editname = (EditText) findViewById(R.id.empname);
editage = (EditText) findViewById(R.id.empage);
editdept = (EditText) findViewById(R.id.empdpt);
updateBtn = (Button) findViewById(R.id.btnSubmit);
updateBtn.setText("Update");
intnt = getIntent();
editname.setText(intnt.getStringExtra("KeyName"));
editage.setText(""+intnt.getIntExtra("Keyage",0));
editdept.setText(intnt.getStringExtra("Keydept"));
row_id = intnt.getIntExtra("Rowid", 0);
updateBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "update", 3000).show();
DataBaseSampleActivity db = new DataBaseSampleActivity(getApplicationContext());
db.open();
String empname = editname.getText().toString();
int empage = Integer.parseInt(editage.getText().toString());
String empdept = editdept.getText().toString();
//db.deleteEmpList(row_id);
db.updateEmplist(empname, empage, empdept,row_id);
//Toast.makeText(getApplicationContext(), "delet", 3000).show();
db.close();
Intent list = new Intent(UpdateDB.this,ShowListView.class);
startActivity(list);
}
});
// Toast.makeText(getApplicationContext(), "update "+intnt.getIntExtra("Keyage",0), 3000).show();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}