I have two SQLiteDatabases in my application. One retrieves the user's input from the class DataEntryHome. The other retrieves the user's input from the class GarmentEntry. I also have two activities which display the user's inputs in the form of a ListView. These are shown in the activities RecapPage and RecapOrderDetails.
To make things simpler for myself as a new java programmer, I have used separate dbHelper, DataProvider and ListDataAdapter classes for the separate databases.
My issue is that in the RecapOrderDetails class, the ListView is populated with the contents from DataEntryHome rather than from GarmentEntry. The ListView in RecapPage works as it should.
Here is all of the code that I think is relevant:
DataEntryHome:
public class DataEntryHome extends AppCompatActivity implements TextWatcher{
private static Button DataEntryButtonN, SaveDataButton, PreviewButton;
Context context = this;
UserDbHelper userDbHelper;
SQLiteDatabase sqLiteDatabase;
EditText ContactName,ContactSurname,ContactEmail,ContactPhone,ContactAddInfo;
Button saveDetails;
public static ArrayList<String> CUSTOMERS = new ArrayList<String>();
String customers[];
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
final EditText surnameArray = (EditText) findViewById(R.id.customerSurnameEntry);
saveDetails = (Button) findViewById(R.id.saveDetailsButton);
saveDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String erm=surnameArray.getText().toString().trim();
if(erm.length() != 0){
CUSTOMERS.add(erm);
surnameArray.setText("");
}
Intent arrayItems = new Intent(DataEntryHome.this, RecapPage.class);
Bundle arrayItemsBundle = new Bundle();
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_entry_home);
ContactName = (EditText) findViewById(R.id.customerFirstNameEntry);
ContactName.addTextChangedListener(this);
ContactSurname = (EditText) findViewById(R.id.customerSurnameEntry);
ContactSurname.addTextChangedListener(this);
ContactEmail = (EditText) findViewById(R.id.customerEmail);
ContactEmail.addTextChangedListener(this);
ContactPhone = (EditText) findViewById(R.id.customerNumber);
ContactPhone.addTextChangedListener(this);
ContactAddInfo = (EditText) findViewById(R.id.addInfo1);
setupSaveDataButton();
}
public void addContact(View view) {
String name = ContactName.getText().toString();
String surname = ContactSurname.getText().toString();
String email = ContactEmail.getText().toString();
String phone = ContactPhone.getText().toString();
String add_info = ContactAddInfo.getText().toString();
userDbHelper = new UserDbHelper(context);
sqLiteDatabase = userDbHelper.getWritableDatabase();
userDbHelper.addInformation(name,surname,email,phone,add_info,sqLiteDatabase);
Toast.makeText(getBaseContext(), "Data saved", Toast.LENGTH_SHORT).show();
userDbHelper.close();
}
RecapPage:
public class RecapPage extends AppCompatActivity{
ListView listView;
SQLiteDatabase sqLiteDatabase;
UserDbHelper userDbHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
Button goButtonAction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recap_page);
goButtonAction = (Button) findViewById(R.id.goButton);
listView = (ListView) findViewById(R.id.list_view);
listView.setClickable(true);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(listDataAdapter);
userDbHelper = new UserDbHelper(getApplicationContext());
sqLiteDatabase = userDbHelper.getReadableDatabase();
cursor = userDbHelper.getInformation(sqLiteDatabase);
if(cursor.moveToFirst()) {
do {
String first_name, surname, email, phone, add_info;
first_name = cursor.getString(0);
surname = cursor.getString(1);
email = cursor.getString(2);
phone = cursor.getString(3);
add_info = cursor.getString(4);
DataProvider dataProvider = new DataProvider(first_name,surname,email,phone,add_info);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
Intent arrayItems = getIntent();
Bundle arrayItemsBundle = arrayItems.getExtras();
}
GarmentEntry:
public class GarmentEntry extends AppCompatActivity {
Spinner tcshenspinner, backprintoptionsspinner, tcbackhenspinner, cosspinner, ppspinner;
ArrayAdapter<CharSequence> tcshenspinneradapter, backprintoptionsspinneradapter, tcbackhenspinneradapter,
cosspinneradapter, ppspinneradapter;
Button nextButton1;
public static ImageView imagePreview;
public static final String IMAGE_RES_ID_1 = "image_res_id_1";
Context contextOrder = this;
OrderDbHelper userDbHelperOrder;
SQLiteDatabase sqLiteDatabaseOrder;
EditText OrderNoOfShirts, OrderFrontText,OrderShirt1;
Spinner OrderColourOfShirts, OrderPrintPosition, OrderColourOfText, OrderBackPrint, OrderBackColour;
Button saveOrderDetails;
public static ArrayList<String> ORDERINFO = new ArrayList<>();
String orderinfo[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.garment_entry);
final EditText shirtArray = (EditText)findViewById(R.id.noofshirts);
saveOrderDetails = (Button)findViewById(R.id.saveOrderDetails);
saveOrderDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String erm=shirtArray.getText().toString().trim();
if (erm.length() != 0){
ORDERINFO.add(erm);
shirtArray.setText("");
}
Intent arrayItemsOrder = new Intent(GarmentEntry.this, RecapOrderDetails.class);
Bundle arrayItemsOrderBundle = new Bundle();
}
});
OrderNoOfShirts = (EditText)findViewById(R.id.noofshirts);
OrderColourOfShirts = (Spinner)findViewById(R.id.cosspinner);
OrderFrontText = (EditText)findViewById(R.id.fronttexthint);
OrderPrintPosition = (Spinner)findViewById(R.id.ppspinner);
OrderColourOfText = (Spinner)findViewById(R.id.tcshenspinner);
OrderBackPrint = (Spinner)findViewById(R.id.backprintoptionsspinner);
OrderBackColour = (Spinner)findViewById(R.id.tcbackhenspinner);
OrderShirt1 = (EditText)findViewById(R.id.nnsshirt1);
}
public void addOrder(View view){
String no_of_shirts = OrderNoOfShirts.getText().toString();
String colour_of_shirts = OrderColourOfShirts.getSelectedItem().toString();
String front_text = OrderFrontText.getText().toString();
String print_position = OrderPrintPosition.getSelectedItem().toString();
String colour_of_text = OrderColourOfText.getSelectedItem().toString();
String back_print = OrderBackPrint.getSelectedItem().toString();
String back_colour = OrderBackColour.getSelectedItem().toString();
String shirt_1 = OrderShirt1.getText().toString();
userDbHelperOrder = new OrderDbHelper(contextOrder);
sqLiteDatabaseOrder = userDbHelperOrder.getWritableDatabase();
userDbHelperOrder.addInformationOrder(no_of_shirts,colour_of_shirts,front_text,print_position,colour_of_text,back_print,
back_colour,shirt_1, null,null,null,null,null,null,null,null,null,null,sqLiteDatabaseOrder);
Toast.makeText(getBaseContext(), "Data saved", Toast.LENGTH_SHORT).show();
userDbHelperOrder.close();
}
RecapOrderDetails:
public class RecapOrderDetails extends AppCompatActivity {
ListView listViewOrder;
SQLiteDatabase sqLiteDatabaseOrder;
UserDbHelper userDbHelperOrder;
Cursor cursorOrder;
ListDataAdapterOrder listDataAdapterOrder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recap_order_details);
listViewOrder = (ListView)findViewById(R.id.list_view_order);
listViewOrder.setClickable(true);
listDataAdapterOrder = new ListDataAdapterOrder(getApplicationContext(),R.layout.order_layout);
listViewOrder.setAdapter(listDataAdapterOrder);
userDbHelperOrder = new UserDbHelper(getApplicationContext());
sqLiteDatabaseOrder = userDbHelperOrder.getReadableDatabase();
cursorOrder = userDbHelperOrder.getInformation(sqLiteDatabaseOrder);
if (cursorOrder.moveToFirst()){
do {
String no_of_shirts, colour_of_shirts, front_text, print_position, text_colour, back_print, back_colour, shirt1;
no_of_shirts = cursorOrder.getString(0);
colour_of_shirts = cursorOrder.getString(1);
front_text = cursorOrder.getString(2);
print_position = cursorOrder.getString(3);
text_colour = cursorOrder.getString(4);
/*back_print = cursorOrder.getString(5);
back_colour = cursorOrder.getString(6);
shirt1 = cursorOrder.getString(7);*/
DataProviderOrder dataProviderOrder = new DataProviderOrder(no_of_shirts,colour_of_shirts,front_text,print_position,
text_colour,null,null,null);
listDataAdapterOrder.add(dataProviderOrder);
}while (cursorOrder.moveToNext());
}
Intent arrayItems = getIntent();
Bundle arrayItemsBundle = arrayItems.getExtras();
}
I THINK the reason why the wrong data is being passed into the second database is because of this:
if (cursorOrder.moveToFirst()){
do {
String no_of_shirts, colour_of_shirts, front_text, print_position, text_colour, back_print, back_colour, shirt1;
no_of_shirts = cursorOrder.getString(0);
colour_of_shirts = cursorOrder.getString(1);
front_text = cursorOrder.getString(2);
print_position = cursorOrder.getString(3);
text_colour = cursorOrder.getString(4);
/*back_print = cursorOrder.getString(5);
back_colour = cursorOrder.getString(6);
shirt1 = cursorOrder.getString(7);*/
DataProviderOrder dataProviderOrder = new DataProviderOrder(no_of_shirts,colour_of_shirts,front_text,print_position,
text_colour,null,null,null);
listDataAdapterOrder.add(dataProviderOrder);
Are the values 0-4 reserved for the first database (for DataEntryHome)?
I also think that this:
userDbHelperOrder = new UserDbHelper(getApplicationContext());
sqLiteDatabaseOrder = userDbHelperOrder.getReadableDatabase();
cursorOrder = userDbHelperOrder.getInformation(sqLiteDatabaseOrder);
has something to do with the matter.
I have figured it out.
On activity RecapOrderDetails, This:
userDbHelperOrder = new UserDbHelper(getApplicationContext());
was this issue.
To resolve it, I had to do the following:
OrderDbHelper = orderDbHelperOrder
in the main method.
And then replace
userDbHelperOrder = new UserDbHelper(getApplicationContext());
with
orderDbHelperOrder = new OrderDbHelper(getApplicationContext());
Related
I have 3 java classes (MainActivity, DatabaseOpenHelper and DatabaseAccess)
My add and show buttons work perfectly, but not my delete button. Add adds name and nickname into the database, show shows the list of names in the same layout under the buttons.
Here is my code in MainActivity.class
public class MainActivity extends AppCompatActivity {
public EditText name123, dogName, dogNickname;
public Button query_button, add_button, show_button, delete_button;
public TextView result_address;
public ListView listView;
ArrayList<String> naziv = new ArrayList<>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name123 = findViewById(R.id.name);
query_button = findViewById(R.id.query_button);
result_address = findViewById(R.id.result);
dogName = findViewById(R.id.et_dogName);
dogNickname = findViewById(R.id.et_dogNickname);
add_button = findViewById(R.id.add_button);
show_button = findViewById(R.id.show_button);
delete_button = findViewById(R.id.delete_button);
listView = findViewById(R.id.doglistview);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_selectable_list_item, naziv);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getApplicationContext());
databaseAccess.open();
long result = databaseAccess.add(dogName.getText().toString(), dogNickname.getText().toString());
if(result > 0){
dogName.setText("");
dogNickname.setText("");
} else {
Toast.makeText(getApplicationContext(), "Dodaj ime i nadimak", Toast.LENGTH_SHORT).show();
}
databaseAccess.close();
}
});
show_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
naziv.clear();
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getApplicationContext());
databaseAccess.open();
Cursor cnn = databaseAccess.getAllNames();
while (cnn.moveToNext()){
String name = cnn.getString(0);
naziv.add(name);
}
listView.setAdapter(adapter);
databaseAccess.close();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), naziv.get(position), Toast.LENGTH_SHORT).show();
}
});
//setting onclicklistener to query button
query_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//create the instance of database access class and open database connection
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getApplicationContext());
databaseAccess.open();
//getting sting value of edittext
String n = name123.getText().toString();
String address = databaseAccess.getAddress(n);//getAddress method to get address
//setting text to result field
result_address.setText(address);
databaseAccess.close();
}
});
delete_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getApplicationContext());
databaseAccess.open();
Integer deletedRows = databaseAccess.deleteData("id_dogName");
if (deletedRows > 0){
Toast.makeText(MainActivity.this, "Deleted data", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "Data not deleted", Toast.LENGTH_SHORT).show();
}
databaseAccess.close();
}
});
}
}
And here is the code from DatabaseAccess.class:
public class DatabaseAccess {
static final String NAME = "name_dogName";
static final String NICKNAME = "nickname_dogName";
static final String TBNAME = "dogName";
static final String ROWID = "id_dogName";
private SQLiteOpenHelper openHelper;
private SQLiteDatabase db;
private static DatabaseAccess instance;
Cursor c = null;
//private constructor so that object creation from outside the class is avoided
private DatabaseAccess(Context context)
{
openHelper = new DatabaseOpenHelper(context);
}
//to return the single instance of database
public static DatabaseAccess getInstance(Context context)
{
if(instance == null)
{
instance = new DatabaseAccess(context);
}
return instance;
}
//to open the database
public void open()
{
db = openHelper.getWritableDatabase();
}
//closing the database connection
public void close()
{
if(db!=null)
{
db.close();
}
}
//method to query and return the results from database
//query for address by passing name
public String getAddress(String name)
{
c = db.rawQuery("select nickname_dogName from dogName where name_dogName = ?", new String[]{name});
String nickname = "";
while (c.moveToNext())
{
String address = c.getString(0);
nickname += address;
}
return nickname;
}
//add
public long add(String name, String nickname){
try {
ContentValues contentValues = new ContentValues();
contentValues.put(NAME, name);
contentValues.put(NICKNAME, nickname);
return db.insert(TBNAME, ROWID, contentValues);
} catch (SQLException e){
e.printStackTrace();
}
return 0;
}
public Cursor getAllNames (){
String[] columns = {NAME, ROWID, NICKNAME};
return db.query(TBNAME, columns, null, null, null, null, null);
}
public Integer deleteData (String id){
return db.delete(TBNAME, "id_dogName", new String[]{id});
}
}
When I click on my phone on the delete button it throws me out of the app. How to correct my code and make the delete button delete a selected item from the list?
something wrong in the second argument, your where clause should include "=?"
public Integer deleteData (String id){
return db.delete(TBNAME, "id_dogName=?", new String[]{id});
}
I have a problem with database in android.
I'd like to collect data from an activity then transfer them to another activity that should show them into a ListView and save them into the DB.
The problem is that the app shows only the first item in the listview and I don't know if all data are saved into the DB. When I try to insert a new item, the app probably overrides the first item and shows the newest one.
Thanks a lot!
public class HomeActivity extends AppCompatActivity {
Button addPets;
private ListView mainListView;
private ArrayList<User> listUser;
private ArrayAdapter adapter;
private DBAdapter dbAdapter;
DBOpenHelper myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
addPets = (Button)findViewById(R.id.add_friends);
addPets.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent apriRegistraPet = new Intent(HomeActivity.this, RegisterActivity.class);
startActivity(apriRegistraPet);
}
});
dbAdapter = DBAdapter.getInstance(this);
mainListView = (ListView)findViewById(R.id.elenco_pets);
listUser = new ArrayList<User>();
adapter = new ArrayAdapter<User>(this, android.R.layout.simple_list_item_1, listUser);
mainListView.setAdapter(adapter);
mainListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
onLongClick(position, mainListView);
return true;
}
});
}
private void addNewItem(User user) {
long idx = dbAdapter.insertUser(user);
user.setId(idx);
listUser.add(0, user);
adapter.notifyDataSetChanged();
}
private void onLongClick(final int position, final ListView listView){
User user = (User)listView.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), "Deleted Item", Toast.LENGTH_LONG).show();
if(!dbAdapter.deleteUser(user)){
return;
}
listUser.remove(user);
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
super.onResume();
dbAdapter.open();
fillData();
Bundle extras = getIntent().getExtras();
if(extras != null){
String nome = extras.getString("Nome");
String razza = extras.getString("Razza");
String sesso = extras.getString("Sesso");
User user = new User(0, nome, razza, sesso, 10, 2000);
addNewItem(user);
}
}
public void fillData(){
Cursor cursor = dbAdapter.getAllEntries();
this.listUser.clear();
cursor.moveToFirst();
while(!cursor.isAfterLast()){
long idx = cursor.getLong(cursor.getColumnIndex(DBContract.AttributiRegistrazione._ID));
String nome = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.NOME));
String razza = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.RAZZA));
String sesso = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.SESSO));
this.listUser.add(0, new User(idx, nome, razza, sesso, 10, 2000));
cursor.moveToNext();
}
cursor.close();
adapter.notifyDataSetChanged();
}
And this is Register Activity
public class RegisterActivity extends AppCompatActivity {
ImageButton settaImmagine;
String imgDecodableString;
Spinner sprazza;
Spinner spsesso;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//Clicco V e mette nella listview
ImageButton salva = (ImageButton)findViewById(R.id.button_salva);
salva.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText editText = (EditText)findViewById(R.id.name);
sprazza = (Spinner)findViewById(R.id.spinner_razza);
String razza = sprazza.getSelectedItem().toString();
spsesso = (Spinner)findViewById(R.id.spinner_sesso);
String sesso = spsesso.getSelectedItem().toString();
Intent resultIntent = new Intent(RegisterActivity.this, HomeActivity.class);
resultIntent.putExtra("Nome", editText.getText().toString());
resultIntent.putExtra("Razza", razza);
resultIntent.putExtra("Sesso", sesso);
startActivity(resultIntent);
}
});
DBAdapter class;
public class DBAdapter {
private static final String TAG = "DBAdapter";
private static DBAdapter dbAdapter;
private static DBOpenHelper dbOpenHelper;
private SQLiteDatabase db;
public synchronized static DBAdapter getInstance(Context context){
if(dbAdapter==null) {
dbAdapter = new DBAdapter(context.getApplicationContext());
}
return dbAdapter;
}
private DBAdapter(Context context) {dbOpenHelper = DBOpenHelper.getInstance(context);}
public DBAdapter open() throws SQLException{
try{
db = dbOpenHelper.getWritableDatabase();
}
catch (SQLException e){
Log.e(TAG, e.toString());
throw e;
}
return this;
}
public void close() {
db.close();
}
public long insertUser (User user){
Log.v(TAG, "Inserisci un User to DB: " +user.getNome());
long idx = db.insert(DBContract.AttributiRegistrazione.NOME_TABELLA, null, user.getAsContentValue());
user.setId(idx);
Log.v(TAG, "Added user with ID: "+idx);
return idx;
}
public boolean deleteUser (User user){
Log.v(TAG, "Removing User: " + user.getClass());
return db.delete(DBContract.AttributiRegistrazione.NOME_TABELLA,
DBContract.AttributiRegistrazione.NOME + "=" + user.getNome(), null) == 1;
}
public boolean deleteUser(String name){
Log.v(TAG, "Removing user: " + name);
return db.delete(DBContract.AttributiRegistrazione.NOME_TABELLA,
DBContract.AttributiRegistrazione.NOME + "=" + name, null) == 1;
}
public Cursor getAllEntries(){
return db.query(DBContract.AttributiRegistrazione.NOME_TABELLA,
null, null, null, null, null, null);
}
ERROR LOG
E/SQLiteLog: (1) table Registrazione has no column named Anno_nascita 04-10 13:57:21.142 10175-10175/com.b.uzzo.snappaw E/SQLiteDatabase: Error inserting Anno_nascita=2000 Peso=10.0 Nome=simone Sesso=Maschio Razza=Akita Inu
android.database.sqlite.SQLiteException: table Registrazione has no column named Anno_nascita (code 1): , while compiling: INSERT INTO Registrazione(Anno_nascita,Peso,Nome,Sesso,Razza) VALUES (?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:898)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:509)
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:1500)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1373)
at com.b.uzzo.snappaw.DBAdapter.insertUser(DBAdapter.java:49)
at com.b.uzzo.snappaw.HomeActivity.addNewItem(HomeActivity.java:105)
at com.b.uzzo.snappaw.HomeActivity.onResume(HomeActivity.java:140)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1269)
at android.app.Activity.performResume(Activity.java:6770)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3522)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3591)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2825)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1542)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6319)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1085)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:946)
But it's created in DBContract class
public class DBContract {
static final String DB_NAME = "RegistrazioneCuccioli";
static final int DB_VERSION = 1;
static abstract class AttributiRegistrazione implements BaseColumns{
static final String NOME_TABELLA = "Registrazione";
static final String NOME = "Nome";
static final String RAZZA = "Razza";
static final String SESSO = "Sesso";
static final String PESO = "Peso";
static final String ANNO_NASCITA = "Anno_nascita";
}
}
In fillData method of HomeActivity class, You are adding data into Arraylist using list.add(0,new User()),which add your data into 0 index, that is cause of your problem. You should have to call list.add(user)
Try this updated Code:
public void fillData(){
Cursor cursor = dbAdapter.getAllEntries();
this.listUser.clear();
if (cursor.moveToFirst()){
do {
long idx = cursor.getLong(cursor.getColumnIndex(DBContract.AttributiRegistrazione._ID));
String nome = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.NOME));
String razza = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.RAZZA));
String sesso = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.SESSO));
User user = new User(idx, nome, razza, sesso, 10, 2000);
this.listUser.add(user);
}while(cursor.moveToNext());
}
cursor.close();
adapter.notifyDataSetChanged();}
I'm currently having trouble of updating a user profile after they have login. The table i have is different but is linked together, which mean i get the Username from another table and update the profile details on another table. Here is my php and java file. Additionally, i'm not really good at android and php coding, any guidance will be much appreciated!
UpdateProfile.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if( !empty( $_POST ) )
{
$connect = mysqli_connect("localhost", "root", "", "users");
$Username = $_POST['Username'];
$Dri_IC = $_POST["Dri_IC"];
$Dri_Name = $_POST["Dri_Name"];
$Date_of_Birth = $_POST["Date_of_Birth"];
$Carplate = $_POST["Carplate"];
$Dri_Street_Add = $_POST["Dri_Street_Add"];
$Dri_Postal_Code = $_POST["Dri_Postal_Code"];
$Dri_City = $_POST["Dri_City"];
$Dri_State = $_POST["Dri_State"];
$Dri_Country = $_POST["Dri_Country"];
$statement = mysqli_prepare($connect, "UPDATE dri_details SET Dri_IC='$Dri_IC', Dri_Name='$Dri_Name', Date_of_Birth='$Date_of_Birth',
Carplate='$Carplate', Dri_Street_Add='$Dri_Street_Add', Dri_Postal_Code='$Dri_Postal_Code', Dri_City='$Dri_City', Dri_State='$Dri_State', Dri_Country='$Dri_Country'
INNER JOIN account_details ON account_details.Acc_ID = dri_details.Dri_ID WHERE account_details.Username='$Username'");
mysqli_stmt_bind_param($statement, "sissssssss", $Username, $Dri_IC, $Dri_Name, $Date_of_Birth, $Carplate, $Dri_Street_Add, $Dri_Postal_Code, $Dri_City, $Dri_State, $Dri_Country);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
}
?>
ProfileUpdate.java
public class ProfileUpdate extends AppCompatActivity {
private EditText editTextDriIC, editTextDriName;
private Button buttonUpPro;
private TextView tvDisplay;
SessionManager session;
public static String global_Usernames;
public static String global_AccPass;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_profile);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if(getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Session class instance
session = new SessionManager(getApplicationContext());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// get name
String Username = user.get(SessionManager.KEY_USERNAME);
global_Usernames = Username;
// get password
String Acc_Pass = user.get(SessionManager.KEY_PASSWORD);
global_AccPass = Acc_Pass;
final EditText etIdentitycard = (EditText) findViewById(R.id.etIdentitycard);
final EditText etName = (EditText) findViewById(R.id.etName);
final EditText etDOB = (EditText) findViewById(R.id.etDOB);
final EditText etCarplate = (EditText) findViewById(R.id.etCarplate);
final EditText etAddress = (EditText) findViewById(R.id.etAddress);
final EditText etPostal = (EditText) findViewById(R.id.etPostal);
// Get a reference to the AutoCompleteTextView in the layout
final AutoCompleteTextView etCity = (AutoCompleteTextView) findViewById(R.id.etCity);
// Get the string array
String[] cities = getResources().getStringArray(R.array.city_array);
// Create the adapter and set it to the AutoCompleteTextView
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, cities);
etCity.setAdapter(adapter);
// Get a reference to the AutoCompleteTextView in the layout
final AutoCompleteTextView etState = (AutoCompleteTextView) findViewById(R.id.etState);
// Get the string array
String[] states = getResources().getStringArray(R.array.state_array);
// Create the adapter and set it to the AutoCompleteTextView
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, states);
etState.setAdapter(adapter);
// Get a reference to the AutoCompleteTextView in the layout
final AutoCompleteTextView etCountry = (AutoCompleteTextView) findViewById(R.id.etCountry);
// Get the string array
String[] country = getResources().getStringArray(R.array.countries_array);
// Create the adapter and set it to the AutoCompleteTextView
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, country);
etCountry.setAdapter(adapter);
final Button buttonUpPro = (Button) findViewById(R.id.bUpdate);
final Calendar myCalendar = Calendar.getInstance();
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
private void updateLabel() {
//String myFormat = "YYYY/MM/DD"; //In which you need put here
//DateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
String myFormat = "yyyy/MM/dd"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
//DateFormat sdf = DateFormat.getDateInstance(DateFormat.LONG, Locale.UK);
etDOB.setText(sdf.format(myCalendar.getTime()));
}
};
etDOB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(ProfileUpdate.this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
buttonUpPro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String Dri_IC = etIdentitycard.getText().toString().trim();
final String Dri_Name = etName.getText().toString().trim();
final String Date_of_Birth = etDOB.getText().toString();
final String Carplate = etCarplate.getText().toString().trim();
final String Dri_Street_Add = etAddress.getText().toString().trim();
final String Dri_Postal_Code = etPostal.getText().toString().trim();
final String Dri_City = etCity.getText().toString().trim();
final String Dri_State = etState.getText().toString().trim();
final String Dri_Country = etCountry.getText().toString().trim();
if (etIdentitycard.getText().toString().matches("") || etName.getText().toString().matches("") || etDOB.getText().toString().matches("") || etAddress.getText().toString().matches("")
|| etPostal.getText().toString().matches("") || etCity.getText().toString().matches("") || etState.getText().toString().matches("") || etCountry.getText().toString().matches("")) {
if (TextUtils.isEmpty(Dri_IC)) {
etIdentitycard.setError("You are required to enter your Identification Card Number");
}
if (TextUtils.isEmpty(Dri_Name)) {
etName.setError("You are required to enter your Full Name");
}
if (TextUtils.isEmpty(Date_of_Birth)) {
etDOB.setError("You are required to enter your Date of Birth");
}
if (TextUtils.isEmpty(Dri_Street_Add)) {
etAddress.setError("You are required to enter your House Address");
}
if (TextUtils.isEmpty(Dri_Postal_Code)) {
etPostal.setError("You are required to enter your Postal Code");
}
if (TextUtils.isEmpty(Dri_City)) {
etCity.setError("You are required to enter City name");
}
if (TextUtils.isEmpty(Dri_State)) {
etState.setError("You are required to enter State name");
}
if (TextUtils.isEmpty(Dri_Country)) {
etCountry.setError("You are required to enter Country name");
}
} else {
Response.Listener<String> responeListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonRespone = new JSONObject(response);
boolean success = jsonRespone.getBoolean("success");
/*if (success){
Intent intent = new Intent(RegisterActivity2.this, LoginActivity.class);
RegisterActivity2.this.startActivity(intent);
}*/
if (!success){
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileUpdate.this);
builder.setMessage("Retry")
.setNegativeButton("Retry", null)
.create()
.show();
} else {
Toast.makeText(ProfileUpdate.this, getString(R.string.profile_update_success), Toast.LENGTH_LONG).show();
//Intent intent = new Intent(RegisterActivity2.this, LoginActivity.class);
//RegisterActivity2.this.startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
ProfileUpdateRequest profileUpdateRequest = new ProfileUpdateRequest(Dri_IC, Dri_Name, Date_of_Birth, Carplate, Dri_Street_Add, Dri_Postal_Code, Dri_City, Dri_State, Dri_Country, responeListener);
RequestQueue queue = Volley.newRequestQueue(ProfileUpdate.this);
queue.add(profileUpdateRequest);
}
}
});
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
ProfileUpdateRequest.java
public class ProfileUpdateRequest extends StringRequest {
private static final String PROFILEUPDATE_REQUEST = "http://192.168.1.5/UpdateProfile.php";
private Map<String, String> params;
public ProfileUpdateRequest(String Dri_IC, String Dri_Name, String Date_of_Birth, String Carplate, String Dri_Street_Add, String Dri_Postal_Code, String Dri_City, String Dri_State, String Dri_Country, Response.Listener<String> listener){
super (Method.POST, PROFILEUPDATE_REQUEST, listener, null);
Log.i("Getting url info",""+PROFILEUPDATE_REQUEST + " " + Dri_IC + " " + Dri_Name + " " + Date_of_Birth);
params = new HashMap<>();
params.put("Dri_IC", Dri_IC + "");
params.put("Dri_Name", Dri_Name);
params.put("Date_of_Birth", Date_of_Birth);
params.put("Carplate", Carplate);
params.put("Dri_Street_Add", Dri_Street_Add);
params.put("Dri_Postal_Code", Dri_Postal_Code);
params.put("Dri_City", Dri_City);
params.put("Dri_State", Dri_State);
params.put("Dri_Country", Dri_Country);
params.put("Username", MainActivity.global_Username);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
I'm not sure what went wrong, after i click update on my android, it did not show success or error, and the database did not update as well. Any help will be much appreciated!
I have a second activity that handles all the user input and another activity that handles all the data from the second activity. What I want to do is call a class "SubmitName" from the activity to the second activity so that I dont need to pass the values from second activity to the main activity anymore. Here are the codes..
MainActivity (Where the class "SubmitName" are located and values are passed.)
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
TextView Name;
String lastname;
String licensenumber;
String mviolation;
String maplace;
String maddress;
String phonenumber;
String officername;
String contactnumber;
String datetime;
RecyclerView.LayoutManager layoutManager;
RecyclerAdapter adapter;
ArrayList<Violator> arrayList = new ArrayList<>();
BroadcastReceiver broadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addBtn = (Button)findViewById(R.id.btnAdd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, FragActivity.class);
startActivity(intent);
}
});
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
Name = (TextView) findViewById(R.id.tvName);
Intent intent = getIntent();
String str = intent.getStringExtra("firstname");
lastname = intent.getStringExtra("lastname");
licensenumber = intent.getStringExtra("licensenumber");
mviolation = intent.getStringExtra("violation");
maplace = intent.getStringExtra("arrestplace");
maddress = intent.getStringExtra("address");
phonenumber = intent.getStringExtra("phonenumber");
contactnumber = intent.getStringExtra("contactnumber");
officername = intent.getStringExtra("officername");
datetime = intent.getStringExtra("datetime");
Name.setText(str);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
readFromLocalStorage();
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
readFromLocalStorage();
}
};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.nav_bar, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.TrafficAd:
Intent i = new Intent(this, TrafficAdvisory.class);
this.startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
public void submitName(View view)
{
String name = Name.getText().toString();
String lname = lastname;
String lnumber = licensenumber;
String violation = mviolation;
String aplace = maplace;
String address = maddress;
String pnumber = phonenumber;
String cnumber = contactnumber;
String oname = officername;
String dtime = datetime;
saveToAppServer(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime);
Name.setText("");
}
public void readFromLocalStorage()
{
arrayList.clear();
DbHelper dbHelper = new DbHelper(this);
SQLiteDatabase database = dbHelper.getReadableDatabase();
Cursor cursor = dbHelper.readFromLocalDatabase(database);
while (cursor.moveToNext())
{
String name = cursor.getString(cursor.getColumnIndex(DBContract.NAME));
String lname = cursor.getString(cursor.getColumnIndex(DBContract.LNAME));
String lnumber = cursor.getString(cursor.getColumnIndex(DBContract.LNUMBER));
String violation = cursor.getString(cursor.getColumnIndex(DBContract.VIOLATION));
String aplace = cursor.getString(cursor.getColumnIndex(DBContract.ARRESTPLACE));
String address = cursor.getString(cursor.getColumnIndex(DBContract.ADDRESS));
String pnumber = cursor.getString(cursor.getColumnIndex(DBContract.PNUMBER));
String cnumber = cursor.getString(cursor.getColumnIndex(DBContract.CNUMBER));
String oname = cursor.getString(cursor.getColumnIndex(DBContract.ONAME));
String dtime = cursor.getString(cursor.getColumnIndex(DBContract.DTIME));
int sync_status = cursor.getInt(cursor.getColumnIndex(DBContract.SYNC_STATUS));
arrayList.add(new Violator(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,sync_status));
}
adapter.notifyDataSetChanged();
cursor.close();
}
public void saveToAppServer(final String name,final String lname, final String lnumber,final String violation, final String aplace,final String address, final String pnumber, final String cnumber, final String oname, final String dtime)
{
if (checkNetworkConnection())
{
StringRequest stringRequest = new StringRequest(Request.Method.POST,DBContract.SERVER_URL,
new Response.Listener<String>(){
#Override
public void onResponse(String response){
try {
JSONObject jsonObject = new JSONObject(response);
String Response = jsonObject.getString("response");
if(Response.equals("OK"))
{
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_OK);
}
else
{
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
}
} catch (JSONException e){
e.printStackTrace();
}
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("name",name);
params.put("lname",lname);
params.put("lnumber",lnumber);
params.put("violation", violation);
params.put("aplace", aplace);
params.put("address",address);
params.put("pnumber",pnumber);
params.put("cnumber",cnumber);
params.put("oname",oname);
params.put("dtime",dtime);
return params;
}
}
;
MySingleton.getInstance(MainActivity.this).addToRequestQue(stringRequest);
}
else
{
saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
}
}
SecondActivity (Where inputs are handled and data passing to the mainactivity)
public class ViolatorDetail extends AppCompatActivity implements View.OnClickListener{
EditText Name;
Button btnClose;
TextView DTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_violator_detail);
DTime = (TextView)findViewById(R.id.tvDTime);
final String currentDT = DateFormat.getDateTimeInstance().format(new Date());
DTime.setText(currentDT);
btnClose = (Button) findViewById(R.id.btnClose);
btnClose.setOnClickListener(this);
Button btnSubmit = (Button)findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText Name = (EditText)findViewById(R.id.etfName);
EditText LName = (EditText)findViewById(R.id.etlName);
EditText LNumber = (EditText)findViewById(R.id.etlNumber);
EditText Violation = (EditText)findViewById(R.id.etViolation);
EditText Arrestplace = (EditText)findViewById(R.id.etaPlace);
EditText Address = (EditText)findViewById(R.id.etAddress);
EditText PNumber = (EditText)findViewById(R.id.etpNumber);
EditText CNumber = (EditText)findViewById(R.id.etcNumber);
EditText OName = (EditText)findViewById(R.id.etoName);
String DT = DTime.getText().toString();
Intent intent = new Intent(ViolatorDetail.this, MainActivity.class);
intent.putExtra("firstname", Name.getText().toString());
intent.putExtra("lastname", LName.getText().toString());
intent.putExtra("licensenumber", LNumber.getText().toString());
intent.putExtra("violation", Violation.getText().toString());
intent.putExtra("arrestplace", Arrestplace.getText().toString());
intent.putExtra("address", Address.getText().toString());
intent.putExtra("phonenumber", PNumber.getText().toString());
intent.putExtra("contactnumber", CNumber.getText().toString());
intent.putExtra("officername", OName.getText().toString());
intent.putExtra("datetime", DT);
startActivity(intent);
}
});
}
}
What I want to do is call the "SUBMITNAME" class to the second activity so that no data passing will be done anymore.
As other friends mentioned Intent is a correct and good way to transfer data between activities. But if you want to avoid writing so much code to transfer data I suggest to create a pure java class (or java bean) and define all needed fields in that class (note: this class should implement java.io.Serializable interface). Now you could transfer instances of this class between activities.
I don’t think there is a better way of passing data between activities than Intents.
What you probably need is encapsulation of passing of extra. You can achieve this by making a static method in the ViolatorDetail class, which accepts as arguments as values you would like to pass, and returns Intent.
public static Intent newIntent(Context packageContext, String ... args){
Intent intent = new Intent(packageContext, ViolatorDetail.this);
intent.putExtra(EXTRA_STRING_ARGS, args);
return intent;
}
Then in the caller class you make an intent by makeing a static call on that function, and pass values as arguments
Intent intent = ViolatorDetail.newIntent(getActivity(), strings)
startActivity(intent);
However, in your case, you should probably make a more sensible way of passing data than as array of strings.
If you don't want to pass data between Activities with Intent, you can do it by writing certain data in a file and when you need it just read from it... I did it like this and I'm still happy i did it that way, it's simple and relatively quick, you just have to care a little about IOExceptions.
I have a TimePicker which I'd like to use to determine a length of time a user can stay connected. Lets say the time now is 10:00 if the user selects 11:00 - I'd like the source code below to determine that there are 60 minutes between the current time - and the time selected and set that to a string/long (minutes) which I then have displayed as a textview.
I've coded everything as I thought it should be - however the textview never seems to update with minutes value. Everytime I attempt to view the data - I get a value of 0 not matter what the timepicker is set to.
Anyone have any suggestions? I'm stumped at the moment and I'm not sure what else to try.
ADDEDITDEVICE.JAVA (where the timepicker and minutes determination takes place)
public class AddEditDevice extends Activity {
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private TimePicker timeEt;
private TextView ssidTextView;
Date date = new Date();
TimePicker tp;
// #Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_country);
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
String ssidString = info.getSSID();
if (ssidString.startsWith("\"") && ssidString.endsWith("\"")){
ssidString = ssidString.substring(1, ssidString.length()-1);
//TextView ssidTextView = (TextView) findViewById(R.id.wifiSSID);
ssidTextView = (TextView) findViewById(R.id.wifiSSID);
ssidTextView.setText(ssidString);
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
timeEt = (TimePicker) findViewById(R.id.timeEdit);
Bundle extras = getIntent().getExtras();
if (extras != null)
{
rowID = extras.getLong("row_id");
nameEt.setText(extras.getString("name"));
capEt.setText(extras.getString("cap"));
codeEt.setText(extras.getString("code"));
String time = extras.getString("time");
String[] parts = time.split(":");
timeEt.setCurrentHour(Integer.valueOf(parts[0]));
timeEt.setCurrentMinute(Integer.valueOf(parts[1]));
timeEt.setIs24HourView(false);
date.setMinutes(tp.getCurrentMinute());
date.setHours(tp.getCurrentHour());
Long.toString(minutes);
}
Button saveButton =(Button) findViewById(R.id.saveBtn);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
if (nameEt.getText().length() != 0)
{
AsyncTask<Object, Object, Object> saveContactTask =
new AsyncTask<Object, Object, Object>()
{
#Override
protected Object doInBackground(Object... params)
{
saveContact();
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
saveContactTask.execute((Object[]) null);
}
else
{
AlertDialog.Builder alert = new AlertDialog.Builder(AddEditDevice.this);
alert.setTitle(R.string.errorTitle);
alert.setMessage(R.string.errorMessage);
alert.setPositiveButton(R.string.errorButton, null);
alert.show();
}
}
});}
}
long minutes = ((new Date()).getTime() - date.getTime()) / (1000 * 60);
private void saveContact()
{
DatabaseConnector dbConnector = new DatabaseConnector(this);
if (getIntent().getExtras() == null)
{
// Log.i("Test for Null", ""+dbConnector+" "+nameEt+" "+capEt+" "+timeEt+" "+codeEt+" "+ssidTextView);
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
Long.toString(minutes),
ssidTextView.getText().toString());
}
else
{
dbConnector.updateContact(rowID,
nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
Long.toString(minutes),
ssidTextView.getText().toString());
}
}
}
VIEW COUNTRY.JAVA (where the minutes data set by the timepicker should be visible)
public class ViewCountry extends NfcBeamWriterActivity {
private static final String TAG = ViewCountry.class.getName();
protected Message message;
NfcAdapter mNfcAdapter;
private static final int MESSAGE_SENT = 1;
private long rowID;
private TextView nameTv;
private TextView capTv;
private TextView codeTv;
private TextView timeTv;
private TextView ssidTv;
private TextView combined;
private TextView minutes;
//String timetest = "300";
// String a="\"";
// String b="\"";
// String message1 = a + ssidTv.getText().toString() +"," +
// capTv.getText().toString()+b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_country);
SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("name", true);
editor.putBoolean("cap", true);
editor.putBoolean("code", true);
editor.putBoolean("time", true);
editor.putBoolean("ssid",true);
editor.putBoolean("minutes",true);
editor.putBoolean("timetest",true);
editor.commit();
setDetecting(true);
startPushing();
setUpViews();
Bundle extras = getIntent().getExtras();
rowID = extras.getLong(CountryList.ROW_ID);
}
private void setUpViews() {
nameTv = (TextView) findViewById(R.id.nameText);
capTv = (TextView) findViewById(R.id.capText);
timeTv = (TextView) findViewById(R.id.timeEdit);
codeTv = (TextView) findViewById(R.id.codeText);
ssidTv = (TextView) findViewById(R.id.wifiSSID);
minutes = (TextView) findViewById(R.id.Minutes);
}
#Override
protected void onResume() {
super.onResume();
new LoadContacts().execute(rowID);
}
private class LoadContacts extends AsyncTask<Long, Object, Cursor> {
DatabaseConnector dbConnector = new DatabaseConnector(ViewCountry.this);
#Override
protected Cursor doInBackground(Long... params) {
dbConnector.open();
return dbConnector.getOneContact(params[0]);
}
#Override
protected void onPostExecute(Cursor result) {
super.onPostExecute(result);
result.moveToFirst();
int nameIndex = result.getColumnIndex("name");
int capIndex = result.getColumnIndex("cap");
int codeIndex = result.getColumnIndex("code");
int timeIndex = result.getColumnIndex("time");
int ssidIndex = result.getColumnIndex("ssid");
nameTv.setText(result.getString(nameIndex));
capTv.setText(result.getString(capIndex));
timeTv.setText(result.getString(timeIndex));
codeTv.setText(result.getString(codeIndex));
ssidTv.setText(result.getString(ssidIndex));
result.close();
dbConnector.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view_country_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.editItem:
Intent addEditContact = new Intent(this, AddEditDevice.class);
// addEditContact.putExtra(CountryList.ROW_ID, rowID);
// addEditContact.putExtra("name", nameTv.getText());
// addEditContact.putExtra("cap", capTv.getText());
// addEditContact.putExtra("code", codeTv.getText());
startActivity(addEditContact);
return true;
case R.id.user1SettingsSave:
Intent Tap = new Intent(this, Tap.class);
startActivity(Tap);
return true;
case R.id.deleteItem:
deleteContact();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void deleteContact() {
AlertDialog.Builder alert = new AlertDialog.Builder(ViewCountry.this);
alert.setTitle(R.string.confirmTitle);
alert.setMessage(R.string.confirmMessage);
alert.setPositiveButton(R.string.delete_btn,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int button) {
final DatabaseConnector dbConnector = new DatabaseConnector(
ViewCountry.this);
AsyncTask<Long, Object, Object> deleteTask = new AsyncTask<Long, Object, Object>() {
#Override
protected Object doInBackground(Long... params) {
dbConnector.deleteContact(params[0]);
return null;
}
#Override
protected void onPostExecute(Object result) {
finish();
}
};
deleteTask.execute(new Long[] { rowID });
}
});
alert.setNegativeButton(R.string.cancel_btn, null).show();
}
}
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":" + timeEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
minutes,
Long.toString(minutes),
ssidTextView.getText().toString());
You have that code to add a contact, BUT in your database conector you have:
public void insertContact(String name,
String cap,
String code,
String time,
long minutes,
String ssid,
String string){
I think that don't match, so this is why don't insert correctly.
BTW i can't comment at the moment because i need 50 reputation.
Regards
USE CREATE TABLE IF NOT EXISTS T/N then your problem wil be solved.
otherwise it will override the current table at the same time all the data will be lost.