SQLite table returning Null Date - java

I am working on an Android Activity that reads Date of Birth entered by the user and instantiates an object with the value. The date is then stored in an SQLite table. The problem is that I get a NULL date value when I query the table later for the Date.
The date is being received correctly by the constructor of the object. However, it returns NULL when queried for it later.
It will be great if you could point out the error.
Method that reads the Date, instantiates the object and stores in SQLite. The value is being read from EditText dob
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final EditText name = (EditText) findViewById(R.id.nameinput);
final EditText dob = (EditText) findViewById(R.id.dobinput);
final EditText mobile_no = (EditText) findViewById(R.id.mnuminput);
final EditText alt_no = (EditText) findViewById(R.id.altnuminput);
final EditText email_id = (EditText) findViewById(R.id.emailinput);
final EditText home_adr = (EditText) findViewById(R.id.homeadrinput);
final EditText off_adr = (EditText) findViewById(R.id.offadrinput);
final EditText notes = (EditText) findViewById(R.id.notesinput);
final TextView flag = (TextView) findViewById(R.id.insertflaglabel);
String name_converted = name.getText().toString();
String mobile_no_converted = mobile_no.getText().toString();
String alt_no_converted = alt_no.getText().toString();
String email_id_converted = email_id.getText().toString();
String home_adr_converted = home_adr.getText().toString();
String off_adr_converted = off_adr.getText().toString();
String notes_converted = notes.getText().toString();
DateFormat df = DateFormat.getDateInstance();
Date dob_converted = new Date(DateFormat.MEDIUM);
try {
dob_converted = df.parse(dob.getText().toString());
} catch (ParseException e) {
e.printStackTrace();
}
Log.d("add_client", "Date read is " +dob_converted);
client client_new = new client(name_converted, dob_converted, mobile_no_converted, alt_no_converted, home_adr_converted, off_adr_converted, email_id_converted, notes_converted);
Context context = getBaseContext();
database_handler insert_client = new database_handler(context);
Log.d("add_client", "Date instantiated is " +client_new.getDOB());
insert_client.addClient(client_new);
flag.setText("Client Details Saved!");
}
});
}
Method that queries SQLite for Date of Birth using .getDOB()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_clientdetails);
Bundle extras = getIntent().getExtras();
Integer tab_id = 0;
if (extras != null) {
tab_id = (int) extras.getInt("client_id");
}
TextView namev = (TextView) findViewById(R.id.namevalue);
TextView mobnum = (TextView) findViewById(R.id.mnumvalue);
TextView date_ob = (TextView) findViewById(R.id.dobvalue);
TextView altnum = (TextView) findViewById(R.id.altnumvalue);
TextView off_addr = (TextView) findViewById(R.id.offadrvalue);
TextView home_addr = (TextView) findViewById(R.id.homeadrvalue);
TextView email_addr = (TextView) findViewById(R.id.emailvalue);
TextView notes_client = (TextView) findViewById(R.id.notesvalue);
Context c_displayclient = getBaseContext();
database_handler dhandle = new database_handler(c_displayclient);
String TAG = "display_clientdetails";
Log.d(TAG, "Value of ID is " +tab_id);
final client c_details = dhandle.getClient(tab_id);
namev.setText(c_details.getName());
mobnum.setText(c_details.getMobile_number());
altnum.setText(c_details.getAlt_num());
DateFormat datef = DateFormat.getDateInstance(DateFormat.MEDIUM);
Log.d("display_clientdetails", "Date of Birth is " +c_details.getDOB());
String text_date = datef.format(c_details.getDOB());
date_ob.setText(text_date);
Instantiation Code
// constructor
public client(String name,Date dob,String mobile_number,String alternate_number,String office_address, String home_address,String email_id,String notes)
{
this.name = name;
this.dob=dob;
Log.d("client", "dob received in client constructor is " +this.dob);
this.mobile_number = mobile_number;
this.alternate_number=alternate_number;
this.office_address=office_address;
this.home_address=home_address;
this.email_id=email_id;
this.notes=notes;
}
Method that returns the Date of Birth
// getting Date of Birth
public Date getDOB(){
Log.d("client", "Date returned is " +this.dob);
return this.dob;
}
Method that Adds a new entry to the Database Table
public void addClient(client client_instance) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, client_instance.getName()); // Client Name
values.put(KEY_MO_NO, client_instance.getMobile_number()); // Client Phone
values.put(KEY_DOB, client_instance.getDOB().toString());
values.put(KEY_ALT_NO, client_instance.getAlt_num());
values.put(KEY_OFF_ADR, client_instance.getOff_adr());
values.put(KEY_HOM_ADR, client_instance.getHome_adr());
values.put(KEY_EMAIL, client_instance.getEmail());
values.put(KEY_NOTES, client_instance.getNotes());
db.insert(TABLE_CLIENTS, null, values);
db.close(); // Closing database connection
}
Method for Getting Data from the Database
// Getting single contact
client getClient(int id) {
SQLiteDatabase db = this.getReadableDatabase();
client client_instance = new client();
String TAG ="database_handler";
Cursor cursor = db.query(TABLE_CLIENTS, new String[] {
KEY_NAME, KEY_MO_NO, KEY_DOB, KEY_ALT_NO, KEY_OFF_ADR, KEY_HOM_ADR, KEY_EMAIL, KEY_NOTES}, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if(cursor != null) Log.d(TAG, "cursor is not null");
// if(cursor.moveToFirst()) Log.d(TAG, "move to first is true");
if (cursor != null && cursor.moveToFirst()) {
client_instance.setName(cursor.getString(0));
client_instance.setMobileNumber(cursor.getString(1));
//Convert Datefield from String to Date so that the setDOB method can accept it as argument
DateFormat dateform = DateFormat.getDateInstance(DateFormat.FULL);
Date d_of_b = new Date(DateFormat.FULL);
try {
d_of_b = dateform.parse(cursor.getString(2));
} catch (ParseException e) {
e.printStackTrace();
}
//Set Date of Birth
client_instance.setDOB(d_of_b);
client_instance.setAlt_num(cursor.getString(3));
client_instance.setOff_adr(cursor.getString(4));
client_instance.setHome_adr(cursor.getString(5));
client_instance.setEmail(cursor.getString(6));
client_instance.setNotes(cursor.getString(7));
Log.d(TAG, "Email is " +cursor.getString(3));
cursor.close();
}
return client_instance;
}
Method for Setting the Date of Birth into a new Client Instance
public void setDOB(Date dob){
this.dob = dob;
}

Your issue is you have to use the same Date format when you format & parse date.
You should use Specific date format such as "MM/dd/yyyy"
Your solution is
When you format Date ( When inserting client into SQLite)
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
String dobAsString = format.format ( dob_Date_object);
// Store dobAsString in SQLite
When you parse Date (When reading client from SQLite)
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
String dobAsString = // ... Read from SQLite
Date dob = format.parse(dobAsString);
You should not use String for store DATE data. You should use Long datatype (Convert Date to timestamp - long data type). See below reason:
If you use String: "06/12/2014" Greater than "03/12/2015": WRONG!!!
If you use Long: Long_timestamp("06/12/2014") Less than Long_timestamp("03/12/2015"): Correct

Related

Retrieving Info from an Intent, then Setting it to a textview inside a Fragment - Android

I have the following code in which i am trying to retrieve the data that i have sent from my main activity using intents and on my next activity i am extending a fragment class (which is essential as i am using a third party library to encorporate animated charts). The problem that i am having is that my app is running without any errors, however the information is not displaying in the textboxes. Is there different syntax to "SetText" when extending a fragment class?
The code that i have on my creating a line activity(Snippet as does not allow full code:
dateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dateButton.setText(date.toString());
// Creates an instance of current DateTime which represents the
// current date time.
DateTime dateTime = new DateTime();
DateTimeFormatter fmt = DateTimeFormat.forPattern("E d MMM yyyy" + "\n" + " h:mm a ");
String formattedtime = fmt.print(dateTime);
dateButton.setText(formattedtime);
// Plus some hours, minutes, and seconds to the original DateTime.
DateTimeFormatter fmt2 = DateTimeFormat.forPattern("E d MMM yyyy" + "\n" + " h:mm a ");
DateTime dateTime1 = dateTime.plusHours(timeadded);
String endtimecalc = fmt2.print(dateTime1);
TextView endtime = findViewById(endtimetextView);
endtime.setText(endtimecalc);
String spinnerSelection = String.valueOf(spinner.getSelectedItem());
String spinnerSelection2 = String.valueOf(spinner2.getSelectedItem());
String q = quantity.getText().toString();
String d = duration.getText().toString();
//INSERT DATA TO DATABASE
boolean isInserted = myDb.insertData(
spinnerSelection,
spinnerSelection2,
q,
d,
formattedtime,
endtimecalc);
if (isInserted == true)
Toast.makeText(CreateLine.this, "Data Inserted Successfully", Toast.LENGTH_LONG).show();
else
Toast.makeText(CreateLine.this, "Data not Inserted", Toast.LENGTH_LONG).show();
}
});
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cursor res = myDb.getAllData();
StringBuffer buffer0 = new StringBuffer();
StringBuffer buffer1 = new StringBuffer();
StringBuffer buffer2 = new StringBuffer();
StringBuffer buffer3 = new StringBuffer();
StringBuffer buffer4 = new StringBuffer();
StringBuffer buffer5 = new StringBuffer();
StringBuffer buffer6 = new StringBuffer();
if ( res != null && res.moveToFirst()) {
do {
buffer0.setLength(0);
buffer1.setLength(0);
buffer2.setLength(0);
buffer3.setLength(0);
buffer4.setLength(0);
buffer5.setLength(0);
buffer6.setLength(0);
String getid = res.getString(0);
String getlt = res.getString(1);
String getpt = res.getString(2);
String getqty = res.getString(3);
String getdur = res.getString(4);
String getst = res.getString(5);
String getet = res.getString(6);
buffer0.append(getid);
buffer1.append(getlt);
buffer2.append(getpt);
buffer3.append(getqty);
buffer4.append(getdur);
buffer5.append(getst);
buffer6.append(getet);
} while (res.moveToNext());
}
Intent TransferData = new Intent(CreateLine.this, LineDetails.class);
Bundle extras = new Bundle();
extras.putString("ID", buffer0.toString());
extras.putString("LineType", buffer1.toString());
extras.putString("PackageType", buffer2.toString());
extras.putString("Quantity", buffer3.toString());
extras.putString("Duration", buffer4.toString());
extras.putString("Starttime",buffer5.toString());
extras.putString("endtime", buffer6.toString());
TransferData.putExtras(extras);
setContentView(R.layout.line_details);
SamplerAdapter samplesAdapter = new SamplerAdapter(getSupportFragmentManager());
ViewPager samplesPager = (ViewPager) findViewById(R.id.samplesPager);
samplesPager.setAdapter(samplesAdapter);
}
});
}
}
Code that i have on my receiving line details:
public class LineDetails extends SampleFragment {
final private float[] mTrackBackWidth = {30f, 60f, 30f, 40f, 30f};
final private float[] mTrackWidth = {30f, 30f, 30f, 30f, 30f};
final private boolean[] mClockwise = {true, true, true, false, true};
final private boolean[] mRounded = {true, true, true, true, true};
final private boolean[] mPie = {false, false, false, false, true};
final private int[] mTotalAngle = {360, 360, 320, 260, 360};
final private int[] mRotateAngle = {0, 180, 180, 0, 270};
private int mBackIndex;
private int mSeries1Index;
private int mSeries2Index;
private int mStyleIndex;
SQLiteDatabase db;
DatabaseHelper databaseHelper;
Cursor cursor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myInflatedView = inflater.inflate(R.layout.line_details, container, false);
Intent ReceiveData = getActivity().getIntent();
Bundle extras = ReceiveData.getExtras();
String id = extras.getString("ID");
String linetype = extras.getString("LineType");
String packagetype = extras.getString("PackageType");
String Quantity = extras.getString("Quantity");
String Duration = extras.getString("Duration");
String Starttime = extras.getString("Starttime");
String endtime = extras.getString("endtime");
TextView LT = (TextView) myInflatedView.findViewById(R.id.textViewLT);
TextView PT = (TextView) myInflatedView.findViewById(R.id.textViewPT);
TextView QTY = (TextView) myInflatedView.findViewById(R.id.textViewQTY);
TextView DUR = (TextView) myInflatedView.findViewById(R.id.textViewDUR);
TextView ST = (TextView) myInflatedView.findViewById(R.id.textViewST);
TextView ET = (TextView) myInflatedView.findViewById(R.id.textViewET);
LT.setText(linetype);
PT.setText(packagetype);
QTY.setText(Quantity);
DUR.setText(Duration);
ST.setText(Starttime);
ET.setText(endtime);
return myInflatedView;
}
If you have multiple values then try this technique using Bundles:
Sending Intent :
Intent intent = new Intent(MainActivity.this, Report_Fragment.class);
Bundle extras = new Bundle();
extras.putFloat("bmi",mybmi);
extras.putFloat("fats",myfat);
extras.putString("weight",myfinalweight);
extras.putString("coments",coments);
intent.putExtras(extras);
startActivity(intent);
Getting Intent in fragment :
Intent intent = getActivity().getIntent();
Bundle extras = intent.getExtras();
Float bmi = extras.getFloat("bmi");
Float fats = extras.getFloat("fats");
String weight=extras.getString("weight");
String coments=extras.getString("coments");
Replace my variables with yours!
try it
for sending
Fragment fragment=new LineDetails();
Bundle extras = new Bundle();
extras.putFloat("bmi",mybmi);
extras.putFloat("fats",myfat);
extras.putString("weight",myfinalweight);
extras.putString("coments",coments);
fragment.setArguments(extras);
getSupportFragmentManager().beginTransaction().add(R.id.frame_container,fragment).commit();
for getting,
Float bmi = getArguments().getFloat("bmi");
Float fats = getArguments().getFloat("fats");
String weight=getArguments().getString("weight");
String coments=getArguments().getString("coments");

Android update user after login by using volley

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!

Cursor query returning 0

I am building an application with database but a problem arises when I am retrieving the values from the database it returns empty (i.e. returned cursor has 0 tuples) and I am sure that database contains some information into it.
I am providing my code please help if you noticed any error.
Fragment where user inputs data to database:
public class FCar extends Fragment implements AdapterView.OnItemSelectedListener {
public FCar() {
}
CarDataBaseAdapter carDataBaseAdapter;
SessionManagement session;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// inflating the view
final View rootView = inflater.inflate(R.layout.fragment_car, container, false);
// declaring stuff, not sure why it has to be final
final Spinner carSpinner;
final EditText editTextDistance, editTextMin;
Button btnSubmitCar;
// create new car database
carDataBaseAdapter = new CarDataBaseAdapter(getActivity());
carDataBaseAdapter = carDataBaseAdapter.open();
SQLiteDatabase x = carDataBaseAdapter.getDatabaseInstance();
session = new SessionManagement(getActivity().getApplicationContext());
// display existing tables
/*
Cursor hi = x.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
hi.moveToFirst();
int f = hi.getCount();
String g = Integer.toString(f);
Toast.makeText(getActivity().getApplicationContext(), g, Toast.LENGTH_LONG).show();
while ( !hi.isAfterLast() ) {
String h = (hi.getString( hi.getColumnIndex("name")) );
hi.moveToNext();
Toast.makeText(getActivity().getApplicationContext(), h, Toast.LENGTH_LONG).show();
}
*/
// Get References of Views
carSpinner = (Spinner) rootView.findViewById(R.id.spinner_car_type);
editTextDistance = (EditText) rootView.findViewById(R.id.editTextcarDistance);
editTextMin = (EditText) rootView.findViewById(R.id.editTextcarMin);
// Spinner click listener
carSpinner.setOnItemSelectedListener(this);
// set default spinner selection
carSpinner.setSelection(0);
// Spinner Drop down elements
List<String> categories = new ArrayList<>();
categories.add("Standard");
categories.add("Truck");
categories.add("Electric/Hybrid");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
carSpinner.setAdapter(dataAdapter);
// identifying the button
btnSubmitCar = (Button) rootView.findViewById(R.id.button_car_submit);
btnSubmitCar.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// take username entry from login / sign up form via method in FProfile
// String currentUser = getSingleEntry();
String username = session.getUsername();
SimpleDateFormat formata = new SimpleDateFormat("MM/dd/yyyy", Locale.CANADA);
String date = formata.format(new Date());
String type = carSpinner.getSelectedItem().toString();
// convert distance to integer
int distance = 0;
try {
distance = Integer.parseInt(editTextDistance.getText().toString());
} catch (NumberFormatException nfe) {
System.out.println("Could not parse distance " + nfe);
}
// convert minutes to integer
int time = 0;
try {
time = Integer.parseInt(editTextMin.getText().toString());
} catch (NumberFormatException nfe) {
System.out.println("Could not parse minutes" + nfe);
}
// Save the Data in Database
carDataBaseAdapter.insertEntry(username, date, type, distance, time);
// link back to input menu
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.putExtra("caller", "Input");
startActivity(intent);
}
}
);
return rootView;
}
This is my query:
public Cursor getCarEntry(String username, String Day, String Type) {
Cursor carCursor = db.query(true, "CAR", new String[]{"distance, time"}, "USERNAME=? AND DATE=? AND TYPE=?", new String[]{username, Day, Type}, null, null, null, "50");
if (carCursor.getCount() < 1) {
carCursor.close();
}
carCursor.moveToFirst();
for (int i = 0; i < carCursor.getCount(); i++) {
int distance = carCursor.getInt(carCursor.getColumnIndex("DISTANCE"));
int time = carCursor.getInt(carCursor.getColumnIndex("TIME"));
}
return carCursor;
Then I retrieve it in a fragment
carStandardCursors[i] = carDataBaseAdapter.getCarEntry(currentUsername, searchDate, "Standard");
Then I made a loop to perform math on the cursors
for (int i = 0; i < 7; i++) {
Cursor ccursor = carStandardCursors[i];
carStandardTotal = CalculateCarStandard(ccursor);
carStandard[dex] = carStandardTotal;
And I found that the values in carStandardCursors[i] were all zero.
Use Facebook Stetho Library to check whether the database contains Values or not.Then only you can get an idea.
stetho library
the problem is here,
public Cursor getCarEntry(String username, String Day, String Type) {
Cursor carCursor = db.query(true, "CAR", **new String[]{"distance, time"}**, "USERNAME=? AND DATE=? AND TYPE=?", new String[]{username, Day, Type}, null, null, null, "50");
if (carCursor.getCount() < 1) {
carCursor.close();
}
carCursor.moveToFirst();
for (int i = 0; i < carCursor.getCount(); i++) {
int distance = carCursor.getInt(carCursor.getColumnIndex("DISTANCE"));
int time = carCursor.getInt(carCursor.getColumnIndex("TIME"));
}
return carCursor;
change it to
public Cursor getCarEntry(String username, String Day, String Type) {
Cursor carCursor = db.query(true, "CAR", new String[]{"DISTANCE", "TIME"}, "USERNAME=? AND DATE=? AND TYPE=?", new String[]{username, Day, Type}, null, null, null, "50");
if (carCursor.getCount() < 1) {
return carCursor;
}else{
if (carCursor!= null) {
carCursor.moveToNext();
}
return carCursor;
}
and then get this cursor at your method call and then at their
Cursor call = classObject.getCarEntry(username, Day, Type);
int distance = call .getInt(carCursor.getColumnIndex("DISTANCE"));
int time = call .getInt(carCursor.getColumnIndex("TIME"));
if more than one data then use while loop and ArrayAdapter

Unable to write date from string to TextView

No matter what variation of code to display the date is used it won't set the text of the TextView.
public void setDate (View view){
TextView dateView;
Date dNow = new Date();
String str = String.format("Current Date : %tc", dNow);
dateView = (TextView)findViewById(R.id.date_Text_View);
dateView.setText("The date is" + str);
}
Cheers,
Harris
After creating TextView onCreate(), you should call setDate() method.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_game);
TextView dateView = (TextView)findViewById(R.id.date_Text_View);
setDate(dateView);
}
public void setDate (TextView view){
String str = String.format("%tc", new Date());
view.setText("The date is " + str);
}

How to display a specific row in my database through another activity?

I wanted to display a specific row in my table. I have two Activities the first activity is to input the ID passed to the 2nd Activity which is going to display the row in my table based on the ID that I inputed.
Hope you can help with my problem. I don't know what is wrong in my code.
//MainActivity:
public class MainActivity extends Activity {
EditText et_id;
public void doView(View v){
String id = et_id.getText().toString();
if(!id.isEmpty()){
Intent i = new Intent(this.getApplicationContext(), ActivityView.class);
i.putExtra("id", id);
startActivity(i);
} else {
Dialog d = new Dialog(this);
d.setTitle("Message");
TextView tv = new TextView(this);
tv.setText("ID must be provided");
d.setContentView(tv);
d.show();
}
}
}
//ActivityView.class
public class ActivityView extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_view);
TextView tv_id = (TextView) findViewById(R.id.tvId);
TextView tv_name = (TextView) findViewById(R.id.tvName);
TextView tv_course = (TextView) findViewById(R.id.tvCourse);
Bundle extra = getIntent().getExtras();
String id = extra.getString("id");
DBase db = new DBase(this);
db.open();
String[] rec = db.getRecord(Integer.parseInt(id));
db.close();
if(rec[0]!=null){
tv_name.setText(rec[0]);
tv_course.setText(rec[1]);
} else {
Dialog d = new Dialog(this);
d.setTitle("Message");
TextView tv = new TextView(this);
tv.setText("There is no record");
d.setContentView(tv);
d.show();
}
}
}
//DBase.java
public String[] getRecord(int rid) throws SQLException{
String selectQuery = "SELECT * FROM "+DB_TABLE+"WHERE"+K_RID+"="+rid;
Cursor c = null;
c = dBase.rawQuery(selectQuery, null);
String[] data = new String[2];
if(c.moveToFirst()){
int indexName = c.getColumnIndex(K_NAME);
int indexCourse = c.getColumnIndex(K_COURSE);
data[0] = c.getString(indexName);
data[1] = c.getString(indexCourse);
}
return data;
}
I suspect the reason your code won't work is because your query is wrong:
String selectQuery = "SELECT * FROM "+DB_TABLE+"WHERE"+K_RID+"="+rid;
You don't have any white space, so your table name, where column, and id are all getting smashed together. Make sure there is a space between each item:
String selectQuery = "SELECT * FROM " + DB_TABLE + " WHERE " + K_RID + " = " + rid;

Categories