Creating a putExtra to another class won't work - java

So I am trying to pass data from my HomePage.class(my main activity) to my ContactHelper class but it just seems to crash.
This is the code that crashes the app:
Context context = view.getContext();
Intent i = new Intent(context, ContactHelper.class);
i.putExtra("name", displayName);
i.putExtra("phone", phone);
i.putExtra("email", contactEmail);
i.putExtra("amount", Amount);
i.putExtra("curDate", CurDate);
i.putExtra("dueDate", DueDate);
i.putExtra("curTime", TimeCur);
i.putExtra("timeDue", TimeDue);
//on below line we are starting a new activity,
context.startActivity(i);
Which is inside my getContacts function:
#SuppressLint("Range")
private void getContacts(View view) {
// this method is use to read contact from users device.
// on below line we are creating a string variables for
// our contact id and display name.
String contactId = "";
String displayName = "";
String phone = "";
String contactEmail = "";
String Amount = "0";
String CurDate = "11111111";
String DueDate = "99999999";
String TimeCur = "0";
String TimeDue = "0";
// on below line we are calling our content resolver for getting contacts
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
// on blow line we are checking the count for our cursor.
if (cursor.getCount() > 0) {
// if the count is greater than 0 then we are running a loop to move our cursor to next.
while (cursor.moveToNext()) {
// on below line we are getting the phone number.
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
// we are checking if the has phone number is > 0
// on below line we are getting our contact id and user name for that contact
contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// on below line we are calling a content resolver and making a query
Cursor phoneCursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{contactId},
null);
// on below line we are moving our cursor to next position.
if (phoneCursor.moveToNext()) {
// on below line we are getting the phone number for our users and then adding the name along with phone number in array list.
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactsModalArrayList.add(new ContactsModal(displayName, phoneNumber));
}
// on below line we are closing our phone cursor.
phoneCursor.close();
}
}
Context context = view.getContext();
Intent i = new Intent(context, ContactHelper.class);
i.putExtra("name", displayName);
i.putExtra("phone", phone);
i.putExtra("email", contactEmail);
i.putExtra("amount", Amount);
i.putExtra("curDate", CurDate);
i.putExtra("dueDate", DueDate);
i.putExtra("curTime", TimeCur);
i.putExtra("timeDue", TimeDue);
//on below line we are starting a new activity,
context.startActivity(i);
}
// on below line we are closing our cursor.
cursor.close();
// on below line we are hiding our progress bar and notifying our adapter class.
loadingPB.setVisibility(View.GONE);
contactRVAdapter.notifyDataSetChanged();
}
I am trying to pass the intent to the class below to a function named getContactInfo:
package com.example.myan;
import android.app.AlertDialog;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.ContactsContract.RawContacts;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class ContactHelper extends AppCompatActivity {
static Context context;
static String number;
static String newName;
static String newNumber;
public static Cursor getContactCursor(ContentResolver contactHelper,
String startsWith) {
String[] projection = { ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor cur = null;
try {
if (startsWith != null && !startsWith.equals("")) {
cur = contactHelper.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " like \"" + startsWith + "%\"", null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
} else {
cur = contactHelper.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, null, null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
}
cur.moveToFirst();
} catch (Exception e) {
e.printStackTrace();
}
return cur;
}
public void getContactInfo(View view) {
Intent intent = getIntent();
String getName = intent.getStringExtra("name");
String getPhone = intent.getStringExtra("phone");
String getEmail = intent.getStringExtra("email");
String getAmount = intent.getStringExtra("amount");
String getCurDate = intent.getStringExtra("curDate");
String getDueDate = intent.getStringExtra("dueDate");
String getCurTime = intent.getStringExtra("curTime");
String getTimeDue = intent.getStringExtra("timeDue");
Integer getFirstDate4thValue = Integer.valueOf(String.valueOf(intent.getStringExtra(getCurDate).charAt(3)));
Integer getFirstDate3rdValue = Integer.valueOf(String.valueOf(intent.getStringExtra(getCurDate).charAt(2)));
String getFirstDateNumber = String.valueOf(getFirstDate3rdValue) + String.valueOf(getFirstDate4thValue);
Integer getSecondDate4thValue = Integer.valueOf(String.valueOf(intent.getStringExtra(getDueDate).charAt(3)));
Integer getSecondDate3rdValue = Integer.valueOf(String.valueOf(intent.getStringExtra(getDueDate).charAt(2)));
String getSecondDateNumber = String.valueOf(getSecondDate3rdValue) + String.valueOf(getSecondDate4thValue);
if (Integer.valueOf(String.valueOf(intent.getStringExtra(getAmount))) > 0) {
view.findViewById(R.id.txtfront).setVisibility(View.VISIBLE);
}
if (Integer.valueOf(String.valueOf(intent.getStringExtra(getAmount))) == 0) {
view.findViewById(R.id.txtfront).setVisibility(View.GONE);
}
if (Integer.valueOf(getFirstDateNumber) != Integer.valueOf(getSecondDateNumber)) {
view.findViewById(R.id.txtDueToday).setVisibility(View.GONE);
}
if (Integer.valueOf(getFirstDateNumber) == Integer.valueOf(getSecondDateNumber)) {
view.findViewById(R.id.txtLate).setVisibility(View.GONE);
view.findViewById(R.id.txtDueToday).setVisibility(View.VISIBLE);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setMessage(intent.getStringExtra(getName) + " owes you $" + intent.getStringExtra(getAmount) + ".00 today at " + intent.getStringExtra(getTimeDue) + " O'Clock.");
alertDialogBuilder.setIcon(R.drawable.ic_launcher_background);
alertDialogBuilder.setTitle("MYAN");
alertDialogBuilder.setNegativeButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
if (Integer.valueOf(getFirstDateNumber) > Integer.valueOf(getSecondDateNumber)) {
view.findViewById(R.id.txtLate).setVisibility(View.VISIBLE);
view.findViewById(R.id.txtDueToday).setVisibility(View.GONE);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setMessage(intent.getStringExtra(getName) + " is late and has owed you on " + intent.getStringExtra(getDueDate) + " and owes you $" + intent.getStringExtra(getAmount) + ".00");
alertDialogBuilder.setIcon(R.drawable.myanlogo);
alertDialogBuilder.setTitle("MYAN");
alertDialogBuilder.setNegativeButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
if (Integer.valueOf(getFirstDateNumber) < Integer.valueOf(getSecondDateNumber)) {
view.findViewById(R.id.txtLate).setVisibility(View.GONE);
}
}
public static long getContactID(ContentResolver contactHelper,
String phone) {
Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phone));
String[] projection = { PhoneLookup._ID };
Cursor cursor = null;
try {
cursor = contactHelper.query(contactUri, projection, null, null,
null);
if (cursor.moveToFirst()) {
int personID = cursor.getColumnIndex(PhoneLookup._ID);
return cursor.getLong(personID);
}
return -1;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
cursor = null;
}
}
return -1;
}
public static void deleteContact(ContentResolver contactHelper,
String number) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
String[] args = new String[] { String.valueOf(getContactID(
contactHelper, number)) };
ops.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI)
.withSelection(RawContacts.CONTACT_ID + "=?", args).build());
try {
contactHelper.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
}
}
Why would it be crashing?
My ultimate goal here is to have objects in my ContactsRVAdapter to become visible and not visible, and also text change, like current date and time.
[This is the FloatingActionButton which I am trying to manipulate][1]
Which is in a RecyclerView
But I cant seem to reach the items in my FloatingActionButton(ContactsRVAdapter) in any way.
Here is my ContactsRVAdapter class:
package com.example.myan;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.net.URISyntaxException;
import java.util.ArrayList;
class ContactRVAdapter extends RecyclerView.Adapter<ContactRVAdapter.ViewHolder> {
public static final String CHANNEL_1="CHANNEL1";
// creating variables for context and array list.
private Context context;
private ArrayList<ContactsModal> contactsModalArrayList;
private ContentResolver contactHelper;
private String number;
private TextView contactLate;
private View view;
private Intent intent;
// creating a constructor
public ContactRVAdapter(Context context, ArrayList<ContactsModal> contactsModalArrayList) {
this.context = context;
this.contactsModalArrayList = contactsModalArrayList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// passing our layout file for displaying our card item
try {
return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.contacts_rv_item, parent, false));
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
// below method is use for filtering data in our array list
public void filterList(ArrayList<ContactsModal> filterlist) {
// on below line we are passing filtered
// array list in our original array list
contactsModalArrayList = filterlist;
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// getting data from array list in our modal.
ContactsModal modal = contactsModalArrayList.get(position);
// on below line we are setting data to our text view.
holder.contactTV.setText(modal.getUserName());
ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
// generate random color
int color = generator.getRandomColor();
// below text drawable is a circular.
TextDrawable drawable2 = TextDrawable.builder().beginConfig()
.width(100) // width in px
.height(100) // height in px
.endConfig()
// as we are building a circular drawable
// we are calling a build round method.
// in that method we are passing our text and color.
.buildRound(modal.getUserName().substring(0, 1), color);
// setting image to our image view on below line.
holder.contactIV.setImageDrawable(drawable2);
// on below line we are adding on click listener to our item of recycler view.
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// on below line we are opening a new activity and passing data to it.
Intent i = new Intent(context, ContactDetailActivity.class);
i.putExtra("name", modal.getUserName());
i.putExtra("contact", modal.getContactNumber());
//on below line we are starting a new activity,
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return contactsModalArrayList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView contactLate;
public ImageView txtFront;
// on below line creating a variable
// for our image view and text view.
private ImageView contactIV;
private TextView contactTV;
private ImageView btnDeleteContact;
private ImageView textDueToday;
private Intent intent;
private String getName;
private String getPhone;
private String getEmail;
private String getAmount;
private String getCurDate;
private String getDateDue;
private String getCurTime;
private String getDueTime;
public ViewHolder(#NonNull View itemView) throws URISyntaxException {
super(itemView);
// initializing our image view and text view.
contactIV = itemView.findViewById(R.id.idIVContact);
contactTV = itemView.findViewById(R.id.idTVContactName);
//contactLate = itemView.findViewById(R.id.txtLate);
//txtFront = itemView.findViewById(R.id.txtfront);
//textDueToday = itemView.findViewById(R.id.txtDueToday);
}
}
}
So all I am trying to do is make it to where I can manipulate the objects inside ContactsRVAdapter class which is a Floating action button.
And my Logcat
FATAL EXCEPTION: main
Process: com.example.myan, PID: 1719
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myan/com.example.myan.HomePage}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.view.View.getContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3645)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3782)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:101)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7872)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.view.View.getContext()' on a null object reference
at com.example.myan.HomePage.getContacts(HomePage.java:286)
at com.example.myan.HomePage.access$200(HomePage.java:39)
at com.example.myan.HomePage$4.onPermissionsChecked(HomePage.java:159)
at com.karumi.dexter.DexterInstance$1.run(Unknown Source:43)
at com.karumi.dexter.MainThread.execute(Unknown Source:6)
at com.karumi.dexter.DexterInstance.checkMultiplePermissions(Unknown Source:71)
at com.karumi.dexter.DexterInstance.checkPermissions(Unknown Source:0)
at com.karumi.dexter.Dexter.check(Unknown Source:10)
at com.example.myan.HomePage.requestPermissions(HomePage.java:187)
at com.example.myan.HomePage.onCreate(HomePage.java:69)
at android.app.Activity.performCreate(Activity.java:8305)
at android.app.Activity.performCreate(Activity.java:8284)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1417)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3626)

try this code...
Intent i = new Intent(this, ContactHelper.class);
The crash is in your view. You are passing view of an activity, which doesn't exist or has been finished.
Context context = view.getContext();
In this function, pass context of existing activity.
private void getContacts(View view) {
...
}

Check the datatypes of the data that you are parsing in Another activities. It should be parcelable or serializable.

Related

Android Studio Database Column Must be > 0 error

I'm working on an assignment for a college course. I'm really new to coding so I apologize if this is an obvious fix.
The assignment is:
Create an activity app with two forms. The main form should have a list view, an add button, an edit button, a view button, and a delete button. On the click of any button you should navigate the user to the second form that will be populated properly for the button action using data passed using an intent object. Your second form should be a layout to input a name and address. The form needs to contain First Name, Last Name, Street Address, Town, State, and Zip code. All your entry fields should be correctly labeled / Hinted so the user will know what to enter. In addition to the fields you will need an “OK”, "Cancel", and a “Clear” button. If the user clicks the “Clear” button you need to clear all the entries. If the user clicks the “OK” or “Cancel” buttons, you should return the button selection and form data to the main form using an intent object. The main activity should process the response and add, update, or delete the record. All records should be added, updated, or delete within a SQLite database that is automatically created by your application. Your program should generate an alert message that confirms the action completed.
I'm getting an error in the cursorToAddressAttributeGroup method saying that the value cursor.getColumnIndexshould be greater than 0. How do I set it to be greater than 0?
This is the class that is having the issue:
package com.example.program5;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.*;
import com.example.program5.AddressCollection.AddressCollectionDB;
public class AddressDatabaseHelper extends SQLiteOpenHelper
{
public static final String TABLE_ADDRESS = "address";
public static final String COLUMN_ID = "id";
public static final String COLUMN_FIRSTNAME = "firstName";
public static final String COLUMN_LASTNAME ="lastName";
public static final String COLUMN_STREET_ADDRESS = "streetAddress";
public static final String COLUMN_TOWN = "town";
public static final String COLUMN_STATE = "state";
public static final String COLUMN_ZIP ="zip";
private static final String DATABASE_NAME = "address.db";
private static final int DATABASE_VERSION = 1;
// Database creation SQL statement
private static final String DATABASE_CREATE_SQL = "create table "
+ TABLE_ADDRESS + "("
+ COLUMN_ID + " integer primary key autoincrement, "
+COLUMN_FIRSTNAME + " text not null, "
+COLUMN_LASTNAME + "text not null, "
+COLUMN_STREET_ADDRESS + "text not null, "
+COLUMN_TOWN + "text not null, "
+COLUMN_STATE + "text not null, "
+COLUMN_ZIP + "text not null);";
public AddressDatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//onCreate method creates table
#Override
public void onCreate(SQLiteDatabase database)
{
//directly executes SQl statement create table
database.execSQL(DATABASE_CREATE_SQL);
}
//onUpgrade method upgrades the table
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
//drops table if it exists
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ADDRESS);
//calls onCreate method and passes db as an argument
onCreate(db);
}
}
class AddressDataSource
{
private SQLiteDatabase database;
private final AddressDatabaseHelper dbHelper;
private String[] allColumns = { AddressDatabaseHelper.COLUMN_ID,
AddressDatabaseHelper.COLUMN_FIRSTNAME, AddressDatabaseHelper.COLUMN_LASTNAME,
AddressDatabaseHelper.COLUMN_STREET_ADDRESS, AddressDatabaseHelper.COLUMN_TOWN,
AddressDatabaseHelper.COLUMN_STATE, AddressDatabaseHelper.COLUMN_ZIP };
//AddressDataSource passes c as argument
public AddressDataSource(Context c)
{
super();
// dbHelper equals AddressDatabaseHelper passing c as parameter
dbHelper = new AddressDatabaseHelper(c);
}
//open method
public void open() throws SQLException {
//sets database equal to dbHelper.getWritableDatabase
database = dbHelper.getWritableDatabase();
}
//close method
public void close()
{
//closes dbHelper
dbHelper.close();
}
//createAddress method passes address as argument
public long createAddress(AddressAttributeGroup address)
{
//creates new ContentValues object called values
ContentValues values = new ContentValues();
//puts values of firstname and lastname into COLUMN_NAME
values.put(AddressDatabaseHelper.COLUMN_ID,address.id);
values.put(AddressDatabaseHelper.COLUMN_FIRSTNAME, address.firstName );
values.put(AddressDatabaseHelper.COLUMN_LASTNAME, address.lastName );
values.put(AddressDatabaseHelper.COLUMN_STREET_ADDRESS, address.streetAddress);
values.put(AddressDatabaseHelper.COLUMN_TOWN,
address.town);
values.put(AddressDatabaseHelper.COLUMN_STATE,address.state);
values.put(AddressDatabaseHelper.COLUMN_ZIP,address.zip);
/* returns insertId */
long insertId = database.insert(AddressDatabaseHelper.TABLE_ADDRESS,
null,
values);
return insertId;
// return database.insert(AddressDatabaseHelper.TABLE_ADDRESS,null,values);
}
//deleteAddress method passes address as argument
public void deleteAddress(AddressAttributeGroup address)
{ //sets id equal to address.id
long id = address.id;
//deletes the entry stored at address.id in the TABLE_ADDRESS table
database.delete(AddressDatabaseHelper.TABLE_ADDRESS,
AddressDatabaseHelper.COLUMN_ID + " = " + id, null);
}
//getAllAddresses method
public AddressCollectionDB getAllAddresses() throws Exception
{ AddressCollectionDB addresses = new AddressCollectionDB();
Cursor cursor = database.query(AddressDatabaseHelper.TABLE_ADDRESS,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast())
{
//adds address to addresses
addresses.addAddress(cursorToAddressAttributeGroup(cursor));
//and moves cursor to next entry
cursor.moveToNext();
}
//closes the cursor
cursor.close();
//returns addresses
return addresses;
}
private AddressAttributeGroup cursorToAddressAttributeGroup(Cursor cursor)
{
//error must be greater than 0. Figure out what is causing the error?
(cursor.getInt(cursor.getColumnIndex(AddressDatabaseHelper.COLUMN_ID)),
cursor.getString(cursor.getColumnIndex(AddressDatabaseHelper.COLUMN_FIRSTNAME)),
cursor.getString(cursor.getColumnIndex(AddressDatabaseHelper.COLUMN_LASTNAME)),
cursor.getString(cursor.getColumnIndex(AddressDatabaseHelper.COLUMN_STREET_ADDRESS)),
cursor.getString(cursor.getColumnIndex(AddressDatabaseHelper.COLUMN_TOWN)),
cursor.getString(cursor.getColumnIndex(AddressDatabaseHelper.COLUMN_STATE)),
cursor.getString(cursor.getColumnIndex(AddressDatabaseHelper.COLUMN_ZIP)));
}
}
Here are theother classes in the program for context:
AddressAttributeGroup Class:
package com.example.program5;
public class AddressAttributeGroup {
//declare Strings for name and address and a long for the id number
public long id;
public String firstName;
public String lastName;
public String streetAddress;
public String town;
public String state;
public String zip;
//constructor
public AddressAttributeGroup(long id, String firstName, String lastName, String streetAddress,
String town, String state, String zip) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.streetAddress = streetAddress;
this.town = town;
this.state = state;
this.zip = zip;
}
AddressCollection Class:
package com.example.program5;
import android.content.Context;
import java.util.ArrayList;
public class AddressCollection {
ArrayList<AddressAttributeGroup> addressList = new ArrayList<>();
final int MAXIMUM_ADDRESS_COUNT = 10;
//boolean that checks if amount of records in arrayList equal to or greater than limit
public boolean isAddressLimitReached()
{
return (addressList.size() >= MAXIMUM_ADDRESS_COUNT);
}
public int addAddress(AddressAttributeGroup address) throws Exception {
//if arrayList is full
if (isAddressLimitReached())
{
throw (new Exception("Maximum Address Reached."));
}
//adds new address to the arraylist addressList
addressList.add(address);
//returns the index of address
return addressList.indexOf(address);
}
public void setAddress(int addressIndex, AddressAttributeGroup address) {
addressList.set(addressIndex, address);
}
public void removeAddress(int addressIndex) {
//removes address at the index addressIndex
addressList.remove(addressIndex);
}
//
public AddressAttributeGroup getAddress(int addressIndex) {
return addressList.get(addressIndex);
}
static class AddressCollectionDB extends AddressCollection
{static public AddressDataSource addressData;
public static AddressCollectionDB AddressCollectionFactory(Context context)
{
AddressCollectionDB resultCode = new AddressCollectionDB();
addressData = new AddressDataSource(context);
try {
addressData.open();
resultCode = addressData.getAllAddresses();
addressData.close();
} catch (Exception e) {
e.printStackTrace();
}
return resultCode;
}
public int addAddress (AddressAttributeGroup address) throws Exception
{
if (isAddressLimitReached())
throw (new Exception("Maximum Address Reached."));
addressData.open();
address.id = addressData.createAddress(address);
addressData.close();
return super.addAddress(address);
}
public void setAddress ( int addressIndex, AddressAttributeGroup address)
{
addressData.open();
addressData.deleteAddress(getAddress(addressIndex));
address.id = addressData.createAddress(address);
addressData.close();
super.setAddress(addressIndex, address);
}
public void removeAddress ( int addressIndex)
{
addressData.open();
addressData.deleteAddress(getAddress(addressIndex));
addressData.close();
super.removeAddress(addressIndex);
}
}
}
AddressConsole class:
package com.example.program5;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.program5.StrongIntent.TypeOfAction;
import com.example.program5.AddressCollection.AddressCollectionDB;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class AddressConsole extends AppCompatActivity implements View.OnClickListener,
AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener {
Button cmdAdd;
Button cmdDelete;
Button cmdView;
Button cmdEdit;
TextView textAddressMessage;
EditText editRecordNumber;
ListView listOfAddresses;
final int ADDRESS_ENTRY = 1001;
AddressCollectionDB addresses;
//AddressCollection addresses = new AddressCollection();
AddressArrayAdapter addressAdapter;
int recordNumber = +1;
#Override
protected void onCreate(Bundle saveInstanceState)
{
super.onCreate(saveInstanceState);
setContentView(R.layout.address_console);
textAddressMessage = findViewById(R.id.textAddressMessage);
editRecordNumber = findViewById(R.id.editRecordNumber);
cmdAdd = findViewById(R.id.cmdAdd);
cmdAdd.setOnClickListener(this);
cmdEdit = findViewById(R.id.cmdEdit);
cmdEdit.setOnClickListener(this);
cmdDelete = findViewById(R.id.cmdDelete);
cmdDelete.setOnClickListener(this);
cmdView = findViewById(R.id.cmdView);
cmdView.setOnClickListener(this);
listOfAddresses = findViewById(R.id.listOfAddresses);
listOfAddresses.setOnItemClickListener (this);
listOfAddresses.setOnItemSelectedListener( this);
addresses = AddressCollectionDB.AddressCollectionFactory(this);
addressAdapter = new AddressArrayAdapter(this, R.layout.row_layout, addresses);
listOfAddresses.setAdapter(addressAdapter);
}
void displayError(Exception message) {
Toast.makeText(this,message.getMessage(),Toast.LENGTH_LONG).show();
}
void displayError(){
Toast.makeText(this, "Maximum Number Of Addresses Reached!",Toast.LENGTH_LONG).show();
}
void displayInfo(String message)
{
Toast.makeText(this, message,Toast.LENGTH_SHORT).show();
}
//hmm why is this never used?
void displayAddressMessage(AddressAttributeGroup address)
{//issue
textAddressMessage.setText("Address:" + address.firstName + " " + address.lastName + " " +
address.streetAddress + " "
+ address.town + "" + address.state + " " + address.zip);
}
void clearAddressMessage()
{
textAddressMessage.setText("");
}
#Override
public void onClick(View view) {
StrongIntent intent;
//if user clicks add button
if(cmdAdd.getId() == view.getId())
{
//if address limit has not been reached
if(!addresses.isAddressLimitReached())
{
//intent equals new Strong Intent
intent = new StrongIntent();
//intent action is equal to ADD
intent.action = TypeOfAction.ADD;
startActivityForResult(intent.getIntent(this, AddressEntry.class),ADDRESS_ENTRY);
}
//else
else
//calls display error message
displayError();
}
else
{
try {
{
AddressAttributeGroup address = addresses.getAddress(recordNumber);
//if user clicks edit
if(cmdEdit.getId() == view.getId())
{
//intent equals new StrongIntent passing address, typeOfAction and record number as arguments
intent = new StrongIntent(address,TypeOfAction.EDIT,recordNumber);
startActivityForResult(intent.getIntent(this,AddressEntry.class),ADDRESS_ENTRY);
}
//if user clicks delete button
if(cmdDelete.getId()==view.getId())
{
//intent equals StrongIntent passing address DELETE and record number as arguments
intent = new StrongIntent(address, TypeOfAction.DELETE,recordNumber);
startActivityForResult(intent.getIntent(this,AddressEntry.class),ADDRESS_ENTRY);
}
//if user clicks view
if(cmdView.getId() == view.getId())
{
//calls displayAddressMessage and passes address as an argument
displayAddressMessage(address);
}
}
//catch block
} catch (Exception ex) {
displayError(ex);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
StrongIntent addressIntent = new StrongIntent(data);
if (requestCode == ADDRESS_ENTRY) {
try {
//switch statement passes resultCode as argument
switch (resultCode) {
case RESULT_OK:
AddressAttributeGroup address = new AddressAttributeGroup(addressIntent.addressIndex,addressIntent.firstName, addressIntent.lastName,
addressIntent.streetAddress, addressIntent.town, addressIntent.state, addressIntent.zip);
switch (addressIntent.action) {
case ADD:
addresses.addAddress(address);
displayAddressMessage(address);
displayInfo("Added + Address:" + address.firstName + " " + address.lastName + " " + address.streetAddress + " "
+ address.town + "" + address.state + " " + address.zip);
break;
case DELETE:
addresses.removeAddress(addressIntent.addressIndex);
displayInfo("Address Deleted");
clearAddressMessage();
editRecordNumber.setText("");
recordNumber =-1;
break;
case EDIT:
addresses.setAddress(addressIntent.addressIndex,address);
displayAddressMessage(address);
displayInfo("Address Updated");
break;
}
addressAdapter.notifyDataSetChanged();
break;
case RESULT_CANCELED:
displayInfo("Cancelled");
break;
}
}
//catch block
catch(Exception ex)
{
displayError(ex);
}
}
super.onActivityResult(requestCode,resultCode,data);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
onItemSelected(parent, view, position,id);
AddressAttributeGroup address = addresses.getAddress(recordNumber);
displayAddressMessage(address);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
recordNumber = position;
editRecordNumber.setText(String.valueOf(recordNumber));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
class AddressArrayAdapter extends ArrayAdapter<AddressAttributeGroup> {
private final Context context;
private final AddressCollection addresses;
public AddressArrayAdapter(Context context, int resource, AddressCollection addresses) {
super(context, resource, addresses.addressList);
this.context = context;
this.addresses = addresses;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
AddressAttributeGroup address = addresses.getAddress(position);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView;
rowView = inflater.inflate(R.layout.row_layout, parent, false);
TextView firstNameTextView = rowView.findViewById(R.id.editFirstName);
TextView lastNameTextView = rowView.findViewById(R.id.editLastName);
TextView addressTextView = rowView.findViewById(R.id.editStreetAddress);
TextView townTextView;
townTextView = rowView.findViewById(R.id.editTown);
TextView stateTextView = rowView.findViewById(R.id.editState);
TextView zipTextView = rowView.findViewById(R.id.editZip);
firstNameTextView.setText(address.firstName);
lastNameTextView.setText(address.lastName);
addressTextView.setText(address.streetAddress);
townTextView.setText(address.town);
stateTextView.setText(address.state);
zipTextView.setText(address.zip);
return rowView;
}
}
}
Strong Intent Class:
package com.example.program5;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class StrongIntent
{
public String firstName;
public String lastName;
public String streetAddress;
public String town;
public String state;
public String zip;
public enum TypeOfAction
{
ADD,
EDIT,
DELETE
}
TypeOfAction action;
int addressIndex = +1;
Intent intent;
public StrongIntent(Intent intent)
{
Bundle bundle = intent.getExtras();
//try/catch block for retrieving key value pairs for intent bundle
try
{
firstName = bundle.getString("firstName");
lastName = bundle.getString("lastName");
streetAddress = bundle.getString("streetAddress");
town = bundle.getString("town");
state = bundle.getString("state");
zip = bundle.getString("zip");
//retrieves the action type chosen
action = TypeOfAction.values()[bundle.getInt("action",0)];
//gets address index
addressIndex = bundle.getInt("addressIndex");
}
//catch block
catch (Exception ex) {
ex.printStackTrace();
}
}
//constructor
public StrongIntent()
{ firstName = "";
lastName = "";
streetAddress = "";
town = "";
state= "";
zip = "";
}
//constructor which passes addressAttributes, action and addressIndex as arguments
public StrongIntent(AddressAttributeGroup addressAttributes, TypeOfAction action, int addressIndex)
{
firstName = addressAttributes.firstName;
lastName = addressAttributes.lastName;
streetAddress = addressAttributes.streetAddress;
town = addressAttributes.town;
state= addressAttributes.state;
zip = addressAttributes.zip;
this.action = action;
this.addressIndex = addressIndex;
}
//sets intent equal to null
public void clearIntent()
{
intent = null;
}
//adds data to intent bundle
void putExtras()
{
intent.putExtra("firstName",firstName);
intent.putExtra("lastName",lastName);
intent.putExtra("streetAddress",streetAddress);
intent.putExtra("town",town);
intent.putExtra("state",state);
intent.putExtra("zip",zip);
intent.putExtra("action",action.ordinal());
intent.putExtra("addressIndex",addressIndex);
}
public Intent getIntent()
{ //if intent is equal to null
if (intent == null)
//sets intent equal to new Intent
{ intent = new Intent();
//calls putExtras method
putExtras();
}
//returns intent
return intent;
}
public Intent getIntent(Activity addressEntry,
Class<AddressEntry> class1)
{
//if intent is equal to null
if (intent == null)
{
intent = new Intent(addressEntry,class1);
//calls putExtras method
putExtras();
}
//returns intent
return intent;
}
}
AddressEntry Class:
package com.example.program5;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AddressEntry extends Activity implements View.OnClickListener{
Button cmdSave;
Button cmdClear;
Button cmdCancel;
EditText editFirstName;
EditText editLastName;
EditText editStreetAddress;
EditText editTown;
EditText editState;
EditText editZip;
int result;
StrongIntent stIntent;
#Override
public void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.address_entry);
editFirstName = findViewById(R.id.editFirstName);
editLastName = findViewById(R.id.editLastName);
editStreetAddress = findViewById(R.id.editStreetAddress) ;
editTown = findViewById(R.id.editTown);
editState = findViewById(R.id.editState);
editZip = findViewById(R.id.editZip);
cmdSave = findViewById(R.id.cmdSave);
cmdSave.setOnClickListener(this);
cmdClear = findViewById(R.id.cmdClear);
cmdClear.setOnClickListener(this);
cmdCancel = findViewById(R.id.cmdCancel);
cmdCancel.setOnClickListener(this);
stIntent = new StrongIntent(getIntent());
editFirstName.setText(stIntent.firstName);
editLastName.setText(stIntent.lastName);
editStreetAddress.setText(stIntent.streetAddress);
editTown.setText(stIntent.town);
editState.setText(stIntent.state);
editZip.setText(stIntent.zip);
//if the type of action is equal to DELETE
if (stIntent.action ==StrongIntent.TypeOfAction.DELETE)
//if user clicks Save sets text to Delete
cmdSave.setText(R.string.deleteString);
//enables action when delete is not selected
editFirstName.setEnabled(stIntent.action!=StrongIntent.TypeOfAction.DELETE);
editLastName.setEnabled(stIntent.action!=StrongIntent.TypeOfAction.DELETE);
editStreetAddress.setEnabled(stIntent.action != StrongIntent.TypeOfAction.DELETE);
editTown.setEnabled(stIntent.action != StrongIntent.TypeOfAction.DELETE);
editState.setEnabled(stIntent.action != StrongIntent.TypeOfAction.DELETE);
editZip.setEnabled(stIntent.action != StrongIntent.TypeOfAction.DELETE);
cmdClear.setEnabled(stIntent.action!=StrongIntent.TypeOfAction.DELETE);
}
#Override
public void onClick(View view)
{
//if Save is clicked
if(cmdSave.getId() == view.getId())
{
//result equals RESULT_OK
result = RESULT_OK;
//calls the finish method
finish();
}
//if Clear is clicked
if(cmdClear.getId() == view.getId())
//clears all values entered
{ editFirstName.setText("");
editLastName.setText("");
editStreetAddress.setText("");
editTown.setText("");
editState.setText("");
editZip.setText("");
}//if Cancel is clicked
if(cmdCancel.getId() == view.getId())
{ //result is equal to RESULT_CANCELED
result = RESULT_CANCELED;
//calls finish method
finish();
}
}
#Override
public void finish()
{ //clears intent
stIntent.clearIntent();
//sets firstName equal to editFirstName
stIntent.firstName= editFirstName.getText().toString();
//sets lastName equal to editLastName
stIntent.lastName = editLastName.getText().toString();
//sets streetAddress equal to editStreetAddress
stIntent.streetAddress =editStreetAddress.getText().toString();
//sets town equal to editTown
stIntent.town = editTown.getText().toString();
//sets state equal to editState
stIntent.state = editState.getText().toString();
//sets zip equal to editZip
stIntent.zip = editZip.getText().toString();
//sets result passing result and the intent as arguments
setResult(result, stIntent.getIntent());
//calls super.finish method
super.finish();
}
}
I believe that the cause is an issue with SDK 31.
The options to circumvent this is to do one of the following:-
Change to use SDK 30 in the build gradle.
Use #SuppressLint("Range") on the line before private AddressAttributeGroup cursorToAddressAttributeGroup(Cursor cursor)
Use getColumnIndexOrThrow instead of getColumnIndex
get the index prior to the get????
e.g.
int idx = cursor.getColumnIndex(AddressDatabaseHelper.COLUMN_ID);
cursor.getInt(idx);
You should also change :
// Database creation SQL statement
private static final String DATABASE_CREATE_SQL = "create table "
+ TABLE_ADDRESS + "("
+ COLUMN_ID + " integer primary key autoincrement, "
+COLUMN_FIRSTNAME + " text not null, "
+COLUMN_LASTNAME + "text not null, "
+COLUMN_STREET_ADDRESS + "text not null, "
+COLUMN_TOWN + "text not null, "
+COLUMN_STATE + "text not null, "
+COLUMN_ZIP + "text not null);";
to :-
// Database creation SQL statement
private static final String DATABASE_CREATE_SQL = "create table "
+ TABLE_ADDRESS + "("
+ COLUMN_ID + " integer primary key autoincrement, "
+COLUMN_FIRSTNAME + " text not null, "
+COLUMN_LASTNAME + " text not null, "
+COLUMN_STREET_ADDRESS + "text not null, " //<<<<< ADDED SPACE
+COLUMN_TOWN + " text not null, " //<<<<< ADDED SPACE
+COLUMN_STATE + " text not null, " //<<<<< ADDED SPACE
+COLUMN_ZIP + " text not null);"; //<<<<< ADDED SPACE
As otherwise the column names (those commented with //<<<<< ADDED SPACE) will be the expected column name suffixed with text and would then result in -1 being returned and a resultant column index error when run. e.g. Instead of lastname the column name would be lastnametext

Update ListView in Fragment after AlertDialog dismiss

I have a Fragment containing ListView. I'm adding some values to the database with a dialog and I want to update this ListView after dialog is dismissed. Also, when I change the tab, the ListView is not updated but when the application is turned on and off, the ListView is updated.
Fragment and Dialog classes are as follows:
Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_teams, container, false);
listViewTeams = rootView.findViewById(R.id.listView_teams);
TeamDatabase teamDatabase = new TeamDatabase(getContext());
teamDatabase.open();
arrayListTeam = teamDatabase.getAllTeams();
teamDatabase.close();
int resID = R.layout.team_list_item;
teamListArrayAdapter = new TeamListArrayAdapter(getContext(), resID, arrayListTeam);
listViewTeams.setAdapter(teamListArrayAdapter);
return rootView;
}
Dialog onClick Method:
#Override
public void onClick(View view) {
int id = view.getId();
switch (id){
case R.id.button_alertDialogAddTeam_cancel:
this.dismiss();
break;
case R.id.button_alertDialogAddTeam_ok:
Team team = new Team();
team.setName(editTextTeamName.getText().toString());
team.setCode(editTextTeamCode.getText().toString());
TeamDatabase teamDatabase = new TeamDatabase(getContext());
teamDatabase.open();
if(teamDatabase.addNewTeam(team)) {
Toast.makeText(getContext(), team.getCode() + " - " +
team.getName() + " was added successfully", Toast.LENGTH_SHORT).show();
}
this.dismiss();
break;
}
}
TeamDatabase class:
public static final String TABLE_NAME = "team";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_CODE = "code";
private static final String KEY_EMBLEM = "emblem";
private Context context;
public static final String CREATE_TABLE = "CREATE TABLE "+
TABLE_NAME + " ("+
KEY_ID + " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, "+
KEY_NAME + " TEXT NOT NULL, "+
KEY_CODE + " TEXT NOT NULL, " +
KEY_EMBLEM + " TEXT);";
public TeamDatabase(Context context) {
super(context);
this.context = context;
}
public boolean addNewTeam(Team team){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_NAME, team.getName());
contentValues.put(KEY_CODE, team.getCode());
return db.insert(TABLE_NAME, null, contentValues) > 0;
}
public ArrayList<Team> getAllTeams()
{
ArrayList<Team> teams = new ArrayList<Team>();
Cursor cursor = db.query(TABLE_NAME, new String[]{KEY_ID,
KEY_NAME,
KEY_CODE}, null, null, null, null, null);
while(cursor.moveToNext()) {
Team team = new Team();
team.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)));
team.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
team.setCode(cursor.getString(cursor.getColumnIndex(KEY_CODE)));
teams.add(team);
}
return teams;
}
DatabaseHelper class:
private static final String DATABASE_NAME = "fixtureCreator.db";
private static final int DATABASE_VERSION = 1;
public SQLiteDatabase db;
public DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(TeamDatabase.CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersinon) {
Log.w("TaskDBAdapter", "Upgrading from version " +
oldVersion + " to " + newVersinon + ", which will destroy all old data");
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TeamDatabase.TABLE_NAME);
onCreate(sqLiteDatabase);
}
public DatabaseHelper open() throws SQLException {
try{
db = this.getWritableDatabase();
}catch (SQLException e){
db = this.getReadableDatabase();
}
return this;
}
public void close(){
db.close();
}
On clicking the item in your first Activity, start your second Activity with startActivityForResult()
And then in Second Activity, after dismissing the dialog,in onClick of that button call,
intent.putExtra("new data", "item text");
setResult(RESULT_OK, intent);
finish();
Now you come back to your first Activity and here you have to implement onActivityResult() callback.
You can extract data from that intent's extras and set that respective item in your array and call notifyDataSetChanged().
This is ideally how you should be doing it.
The problem can be solved using fetching the data after saving it each time you click on the Dialog and then call notifyDataSetChanged() on your adapter. However, there is more elegant way of achieving this kind of behaviour, which will solve both of your problems using content observer.
In case of having a content observer in your database table you need to declare a URI first which references your table.
public static final Uri DB_TABLE_TEAM_URI = Uri
.parse("sqlite://" + Constants.ApplicationPackage + "/" + DB_TABLE_TEAM);
// DB_TABLE_TEAM refers to the database table that you have for storing teams.
Now in your addNewTeam function you need to do the following.
public boolean addNewTeam(Team team) {
// .. Save the team in database
// Notify the observer about the change in the content
context.getContentResolver().notifyChange(DBConstants.DB_TABLE_TEAM_URI, null);
}
You need to call notifyChange() function whenever you add or update an entry in your team table.
Now in your Activity or Fragment you need to register your observer on your cursor having the team data fetched from your team table.
cursor = teamDatabase.getAllTeamsInCursor();
this.registerContentObserver(cursor, DBConstants.DB_TABLE_TEAM_URI);
Now populate your ListView using the cursor by passing it to your adapter of ListView. The list will be updated automatically once a new data has been inserted in your team table.
Update
Modify the addNewTeam function in your TeamDatabase class as follows.
public static final Uri DB_TABLE_TEAM_URI = Uri
.parse("sqlite://" + Constants.ApplicationPackage + "/" + DB_TABLE_TEAM);
public boolean addNewTeam(Team team){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_NAME, team.getName());
contentValues.put(KEY_CODE, team.getCode());
boolean success = db.insert(TABLE_NAME, null, contentValues) > 0;
context.getContentResolver().notifyChange(DBConstants.DB_TABLE_TEAM_URI, null);
return success;
}
To implement the functionalities with LoaderCallbacks you first need to implement the interface of LoaderCallbacks in your Fragment. So the declaration of your Fragment will look like.
public class TeamsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
// .... Code
}
Now you need to override the functions that comes along with the interface of LoaderCallbacks.
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new SQLiteCursorLoader(getActivity()) {
#Override
public Cursor loadInBackground() {
// Initialize your database
TeamDatabase teamDatabase = new TeamDatabase(getActivity());
Cursor cursor = teamDatabase.getAllTeams();
if (cursor != null) {
// Register the content observer here
this.registerContentObserver(cursor, DBConstants.DB_TABLE_TEAM_URI);
}
return cursor;
}
};
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Set the cursor in your adapter. Handle null values in your setCursor function in your adapter. The cursor might return null when the table is empty.
teamAdapter.setCursor(cursor);
teamAdapter.notifyDataSetChanged();
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
Now in your onCreateView function in the Fragment, you need to initiate the loader to fetch data from the table.
getLoaderManager().initLoader(0, null, this).forceLoad();
And destroy the loader and un-register the receiver in the onDestroyView function.
#Override
public void onDestroyView() {
getLoaderManager().destroyLoader(0);
super.onDestroyView();
}
I was missing the SQLiteCursorLoader class to be added here.
package com.wooz.observer.databases;
import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.Arrays;
public abstract class SQLiteCursorLoader extends AsyncTaskLoader<Cursor> {
private final ForceLoadContentObserver mObserver;
private Uri mUri;
private String[] mProjection;
private String mSelection;
private String[] mSelectionArgs;
private String mSortOrder;
private Cursor mCursor;
/* Runs on a worker thread */
#Override
public abstract Cursor loadInBackground();
/**
* Registers an observer to get notifications from the content provider
* when the cursor needs to be refreshed.
*/
public void registerContentObserver(Cursor cursor, Uri observerUri) {
cursor.registerContentObserver(mObserver);
cursor.setNotificationUri(getContext().getContentResolver(), observerUri);
}
/* Runs on the UI thread */
#Override
public void deliverResult(Cursor cursor) {
try {
if (isReset()) {
// An async query came in while the loader is stopped
if (cursor != null) {
cursor.close();
}
return;
}
Cursor oldCursor = mCursor;
mCursor = cursor;
if (isStarted()) {
super.deliverResult(cursor);
}
if (oldCursor != null && oldCursor != cursor && !oldCursor.isClosed()) {
oldCursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Creates an empty unspecified CursorLoader. You must follow this with
* calls to {#link #setUri(Uri)}, {#link #setSelection(String)}, etc
* to specify the query to perform.
*/
public SQLiteCursorLoader(Context context) {
super(context);
mObserver = new ForceLoadContentObserver();
}
/**
* Creates a fully-specified CursorLoader. See
* {#link ContentResolver#query(Uri, String[], String, String[], String)
* ContentResolver.query()} for documentation on the meaning of the
* parameters. These will be passed as-is to that call.
*/
public SQLiteCursorLoader(Context context, Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
super(context);
mObserver = new ForceLoadContentObserver();
mUri = uri;
mProjection = projection;
mSelection = selection;
mSelectionArgs = selectionArgs;
mSortOrder = sortOrder;
}
/**
* Starts an asynchronous load of the contacts list data. When the result is ready the callbacks
* will be called on the UI thread. If a previous load has been completed and is still valid
* the result may be passed to the callbacks immediately.
* <p>
* Must be called from the UI thread
*/
#Override
protected void onStartLoading() {
if (mCursor != null) {
deliverResult(mCursor);
}
if (takeContentChanged() || mCursor == null) {
forceLoad();
}
}
/**
* Must be called from the UI thread
*/
#Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
#Override
public void onCanceled(Cursor cursor) {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
#Override
protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
if (mCursor != null && !mCursor.isClosed()) {
mCursor.close();
}
mCursor = null;
}
public Uri getUri() {
return mUri;
}
public void setUri(Uri uri) {
mUri = uri;
}
public String[] getProjection() {
return mProjection;
}
public void setProjection(String[] projection) {
mProjection = projection;
}
public String getSelection() {
return mSelection;
}
public void setSelection(String selection) {
mSelection = selection;
}
public String[] getSelectionArgs() {
return mSelectionArgs;
}
public void setSelectionArgs(String[] selectionArgs) {
mSelectionArgs = selectionArgs;
}
public String getSortOrder() {
return mSortOrder;
}
public void setSortOrder(String sortOrder) {
mSortOrder = sortOrder;
}
#Override
public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
super.dump(prefix, fd, writer, args);
writer.print(prefix);
writer.print("mUri=");
writer.println(mUri);
writer.print(prefix);
writer.print("mProjection=");
writer.println(Arrays.toString(mProjection));
writer.print(prefix);
writer.print("mSelection=");
writer.println(mSelection);
writer.print(prefix);
writer.print("mSelectionArgs=");
writer.println(Arrays.toString(mSelectionArgs));
writer.print(prefix);
writer.print("mSortOrder=");
writer.println(mSortOrder);
writer.print(prefix);
writer.print("mCursor=");
writer.println(mCursor);
//writer.print(prefix); writer.print("mContentChanged="); writer.println(mContentChanged);
}
private class CursorLoaderContentObserver extends ContentObserver {
public CursorLoaderContentObserver() {
super(new Handler());
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
#Override
public void onChange(boolean selfChange) {
onContentChanged();
}
}
}
You should call notifyDataSetChanged just before dismissing the dialoge
teamListArrayAdapter.notifyDataSetChanged();
You should change you code something like this below
#Override
public void onClick(View view) {
int id = view.getId();
switch (id){
case R.id.button_alertDialogAddTeam_cancel:
this.dismiss();
break;
case R.id.button_alertDialogAddTeam_ok:
Team team = new Team();
team.setName(editTextTeamName.getText().toString());
team.setCode(editTextTeamCode.getText().toString());
TeamDatabase teamDatabase = new TeamDatabase(getContext());
teamDatabase.open();
if(teamDatabase.addNewTeam(team)) {
Toast.makeText(getContext(), team.getCode() + " - " +
team.getName() + " was added successfully", Toast.LENGTH_SHORT).show();
}
arrayListTeam = teamDatabase.getAllTeams();
teamListArrayAdapter.notifyDataSetChanged();
this.dismiss();
break;
}
}
Add this code in onCreateView:
teamListArrayAdapter.notifyDataSetChanged();

How to get selected xls file path from uri for SDK 17 or below for android?

I need the solution for sdk version 17 or below
this is my method.
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null){
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
i use this method but cursor value null return
help
use my FileSelector :
how to use :
new FileSelector(this, new String[]{FileSelector.XLS, FileSelector.XLSX}).selectFile(new FileSelector.OnSelectListener() {
#Override
public void onSelect(String path) {
G.toast(path);
}
});
new FileSelector(this, new String[]{".jpg", ".jpeg"}).selectFile(new FileSelector.OnSelectListener() {
#Override
public void onSelect(String path) {
G.toast(path);
}
});
source code : (create class 'FileSelector' and copy/paste)
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Typeface;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;
/**
* Created by Javad on 2019-11-28 at 4:43 PM.
*/
public class FileSelector {
private Activity context;
private String[] extensions;
private ArrayList<SelectedFile> itemsData = new ArrayList<>();
public static final String MP4 = ".mp4", MP3 = ".mp3", JPG = ".jpg", JPEG = ".jpeg", PNG = ".png", DOC = ".doc", DOCX = ".docx", XLS = ".xls", XLSX = ".xlsx", PDF = ".pdf";
public FileSelector(Activity context, String[] extensions) {
this.context = context;
this.extensions = extensions;
}
public interface OnSelectListener {
void onSelect(String path);
}
public void selectFile(OnSelectListener listener) {
String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
listOfFile(new File(sdCard));
dialogFileList(listener);
}
private void listOfFile(File dir) {
File[] list = dir.listFiles();
for (File file : list) {
if (file.isDirectory()) {
if (!new File(file, ".nomedia").exists() && !file.getName().startsWith(".")) {
Log.w("LOG", "IS DIR " + file);
listOfFile(file);
}
} else {
String path = file.getAbsolutePath();
for (String ext : extensions) {
if (path.endsWith(ext)) {
SelectedFile selectedFile = new SelectedFile();
selectedFile.path = path;
String[] split = path.split("/");
selectedFile.name = split[split.length - 1];
itemsData.add(selectedFile);
Log.i("LOG", "ADD " + selectedFile.path + " " + selectedFile.name);
}
}
}
}
Log.d("LOG", itemsData.size() + " DONE");
}
private void dialogFileList(OnSelectListener listener) {
LinearLayout lytMain = new LinearLayout(context);
lytMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
lytMain.setOrientation(LinearLayout.VERTICAL);
int p = convertToPixels(12);
lytMain.setPadding(p, p, p, p);
lytMain.setGravity(Gravity.CENTER);
TextView textView = new TextView(context);
textView.setLayoutParams(new LinearLayout.LayoutParams(screenWidth(), ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setText("JDM File Selecor");
RecyclerView recyclerView = new RecyclerView(context);
lytMain.addView(textView);
lytMain.addView(recyclerView);
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
// dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(lytMain);
dialog.setCancelable(true);
dialog.show();
AdapterFile adapter = new AdapterFile(dialog, listener, itemsData);
recyclerView.setAdapter(adapter);
LinearLayoutManager LayoutManager = new LinearLayoutManager(context);
LayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(LayoutManager);
}
private int convertToPixels(int dp) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
private int screenWidth() {
return context.getResources().getDisplayMetrics().widthPixels;
}
private class SelectedFile {
public String path = "";
public String name = "";
}
private class AdapterFile extends RecyclerView.Adapter<AdapterFile.ViewHolder> {
private ArrayList<SelectedFile> itemsData;
private OnSelectListener listener;
private Dialog dialog;
public AdapterFile(Dialog dialog, OnSelectListener listener, ArrayList<SelectedFile> itemsData) {
this.itemsData = itemsData;
this.listener = listener;
this.dialog = dialog;
}
// Create new views (invoked by the layout manager)
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setOrientation(LinearLayout.VERTICAL);
TextView txtName = new TextView(context);
TextView txtPath = new TextView(context);
txtPath.setTypeface(txtPath.getTypeface(), Typeface.ITALIC);
txtPath.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
linearLayout.addView(txtName);
linearLayout.addView(txtPath);
ViewHolder viewHolder = new ViewHolder(linearLayout);
return viewHolder;
}
// inner class to hold a reference to each item of RecyclerView
public class ViewHolder extends RecyclerView.ViewHolder {
public LinearLayout linearLayout;
public TextView txtName;
public TextView txtPath;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
linearLayout = (LinearLayout) itemLayoutView;
txtName = (TextView) linearLayout.getChildAt(0);
txtPath = (TextView) linearLayout.getChildAt(1);
}
}
#Override
public int getItemCount() {
return itemsData.size();
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
final SelectedFile selectedFile = itemsData.get(position);
viewHolder.txtName.setText(selectedFile.name);
viewHolder.txtPath.setText(selectedFile.path);
viewHolder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
listener.onSelect(selectedFile.path);
}
});
}
}
}
path = uri.getPath(); only this line is used for get the path of selected file.
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/vnd.ms-excel");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(getApplicationContext(), "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
// Get the path
try {
path = uri.getPath();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}

Accessing shared preferences in a non-activity class from fragment class

I have a fragment:
public class TodayVerse extends Fragment
{
TextView textView;
DailyQuranMethods dailyQuranMethods;
public TodayVerse() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_today_verse, container, false);
textView = (TextView) view.findViewById(R.id.verse);
// setChapterVerse();
textView.setText(dailyQuranMethods.getVerseToday(dailyQuranMethods.DateToday(),getActivity().getApplicationContext()) + "\nChapter:" + dailyQuranMethods.getChapterTodayName(dailyQuranMethods.DateToday(),getActivity().getApplicationContext()));
return view;
}
}
This fragment calls a non-activity class :
dailyQuranMethods which uses sharedPrefrences. For the purpose, I had to pass a Context as parameter. I passed:
getActivity().getApplicationContext()
The methods in dailyQuranMethods are like:
public String getVerseToday(String today,Context context){
...
}
On running the app, I have following logcat:
06-19 06:07:56.587 9887-9887/? E/AndroidRuntime﹕ FATAL EXCEPTION:
main
java.lang.NullPointerException
at com.example.shiza.dailyquranverses.TodayVerse.onCreateView(TodayVerse.java:35)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490)
at android.support.v4.app.FragmentTabHost.onAttachedToWindow(FragmentTabHost.java:283)
at android.view.View.dispatchAttachedToWindow(View.java:9788)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2198)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2206)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2206)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2206)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2206)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2206)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:971)
at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2467)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
The error is in the following line:
textView.setText(dailyQuranMethods.getVerseToday(dailyQuranMethods.DateToday(),getActivity().getApplicationContext())
+ "\nChapter:" + dailyQuranMethods.getChapterTodayName(dailyQuranMethods.DateToday(),getActivity().getApplicationContext()));
Looks like, I am unable to get Context in my non-activity class. I tried a lot, but nothing helped. Please help me to solve this.
Edit 1 : The non-activity class is:
package com.example.shiza.dailyquranverses;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.MatrixCursor;
import android.preference.PreferenceManager;
import android.provider.BaseColumns;
import android.widget.SimpleCursorAdapter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;
import com.example.shiza.dailyquranverses.TodayChapter;
import android.preference.Preference;
/**
* Created by Shiza on 19-06-2015.
*/
public class DailyQuranMethods {
// generate a random number.
SharedPreferences sharedPreferencesChapter;
SharedPreferences sharedPreferencesVerse;
private static String TODAY_CHAPTER = "TODAY_CHAPTER";
private static String TODAY_VERSE = "TODAY_VERSE";
Context context;
public int GetRandom(int min, int max) {
Random ran = new Random();
return ran.nextInt((max - min) + 1) + min;
}
public void setChapterVerseOfToday(Context context)
{
sharedPreferencesChapter = context.getSharedPreferences(TODAY_CHAPTER, Context.MODE_PRIVATE);
sharedPreferencesVerse = context.getApplicationContext().getSharedPreferences(TODAY_VERSE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor_chapter = sharedPreferencesChapter.edit();
SharedPreferences.Editor editor_verse = sharedPreferencesVerse.edit();
int chapter_no = GetRandom(1, 114);
String chapter_array_name = "chapter_" + chapter_no;
String verse = sharedPreferencesVerse.getString(DateToday(),null);
if ( verse == null )
{
editor_verse.putString(DateToday(), getVerse(context,chapter_array_name));
editor_verse.apply();
}
int chapter_number = sharedPreferencesChapter.getInt(DateToday(),0);
if ( chapter_number == 0 )
{
editor_chapter.putInt(DateToday(),chapter_no);
editor_chapter.apply();
}
}
public String getVerseToday(String today,Context context)
{
sharedPreferencesVerse = context.getSharedPreferences(TODAY_VERSE, Context.MODE_PRIVATE);
return sharedPreferencesVerse.getString(today,"7. The Way of those on whom You have bestowed Your Grace, not (the way) of those who earned Your Anger (such as the Jews), nor of those who went astray (such as the Christians).");
}
public String getVerse(Context context,String chapter_array_name)
{
int id = context.getResources().getIdentifier(chapter_array_name, "array", context.getPackageName());
String[] chapter = context.getResources().getStringArray(id);
int random_verse = GetRandom(1, chapter.length - 1);
return chapter[random_verse];
}
public String[] getChapterTodayContent(String today,Context context)
{
sharedPreferencesChapter = context.getSharedPreferences(TODAY_CHAPTER, Context.MODE_PRIVATE);
int chapter_no = sharedPreferencesChapter.getInt(today, 2);
String chapter_array_name = "chapter_" + chapter_no;
int id = context.getResources().getIdentifier(chapter_array_name, "array", context.getApplicationContext().getPackageName());
return context.getResources().getStringArray(id);
}
public String getChapterTodayName(String today,Context context)
{
sharedPreferencesChapter = context.getApplicationContext().getSharedPreferences(TODAY_CHAPTER,Context.MODE_PRIVATE);
int chapter_no = sharedPreferencesChapter.getInt(today, 0);
String[] chapterName = context.getResources().getStringArray(R.array.chapters);
return chapterName[chapter_no - 1];
}
public String DateToday()
{
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("ddMMyyyy");
return df.format(c.getTime());
}
// Get quran verses in android
public String[] getQuranVerses(Context context) {
String[] whole_quran = new String[7000];
String[] current_chapter;
String chapterSize = "";
String[] chapter_names;
String chapter_array_name;
int total_verse = 0, verse_in_current_chapter, chapter_number;
chapter_names = context.getResources().getStringArray(R.array.chapters);
for (chapter_number = 1; chapter_number < 114; chapter_number++) {
// Grab each chapter containing verse from Quran
chapter_array_name = "chapter_" + chapter_number;
int id = context.getResources().getIdentifier(chapter_array_name, "array", context.getPackageName());
current_chapter = context.getResources().getStringArray(id);
for (verse_in_current_chapter = 1; verse_in_current_chapter < current_chapter.length - 1; verse_in_current_chapter++) {
whole_quran[total_verse] = current_chapter[verse_in_current_chapter] + "," + chapter_names[chapter_number - 1];
total_verse++;
}
chapterSize += chapter_number + ":" + chapter_names[chapter_number - 1] + ":" + current_chapter.length + "\n";
}
return whole_quran;
}
// public void search()
// {
// // Use search view on the top of your app
//
// search = (SearchView) findViewById(R.id.mySearchView);
// search.setQueryHint("Search Qur'an");
//
//// create a suggestion adapter for dropdown
// final String[] from = new String[] {"cityName"};
// final int[] to = new int[] {android.R.id.text1};
// mAdapter = new SimpleCursorAdapter(this,
// android.R.layout.simple_list_item_2,
// null,
// from,
// to,
// CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
//
// search.setSuggestionsAdapter(mAdapter);
//
// search.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
// #Override
// public boolean onSuggestionClick(int position) {
// // Your code here
//
//
// Cursor theCursor = (Cursor) mAdapter.getCursor();
// String selectedItem = theCursor.getString(position);
//// Toast.makeText(getBaseContext(), " on suggestion click position and item is" + position + selectedItem, Toast.LENGTH_LONG).show();
//
//
// startActivity(new Intent(getBaseContext(), MainActivity.class));
//
// return true;
// }
//
// #Override
// public boolean onSuggestionSelect(int position) {
// // Your code here
//// Toast.makeText(getBaseContext(), " on suggestion select position is" + position, Toast.LENGTH_LONG).show();
//
// startActivity(new Intent(getBaseContext(), MainActivity.class));
//
// return true;
// }
// });
//
// search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//
//
// #Override
// public boolean onQueryTextSubmit(String query) {
// startActivity(new Intent(getBaseContext(), MainActivity.class));
//
// return false;
// }
//
// #Override
// public boolean onQueryTextChange(String newText) {
// //
// dailyQuranMethods.populateAdapter(newText,getApplicationContext());
//
// return false;
// }
//
//
// });
//
//
//
// }
public void populateAdapter(String query, Context context, SimpleCursorAdapter mAdapter) {
String[] SUGGESTIONS = getQuranVerses(context);
final MatrixCursor c = new MatrixCursor(new String[]{BaseColumns._ID, "cityName"});
int j = 0;
int k = 0;
if (query.length() > 3) {
k = GetRandom(0, 60);
// Toast.makeText(getApplicationContext(),"K is " + k,Toast.LENGTH_LONG).show();
for (int i = 0; i < 6144; i++) {
if (SUGGESTIONS[i].toLowerCase().contains(query.toLowerCase()) && SUGGESTIONS[i].length() > 0) {
c.addRow(new Object[]{i, SUGGESTIONS[i]});
j++;
if (j > 100) {
break;
}
}
}
if (j == 0) {
c.addRow(new Object[]{0, "No results found."});
}
} else {
c.addRow(new Object[]{0, "Please enter at least 3 characters."});
c.addRow(new Object[]{1, "Please be patient, we have to find in more than 6,000 verses"});
}
mAdapter.changeCursor(c);
}
}
Calling getActivity() is fine, it will resolve to a Context. You don't need the full getActivity().getApplicationContext(). This may cause a problem since you're telling Android to use the context of the application instead of the current Activity. Someday you'll appreciate this.
Besides that, you NEED to create instance of dailyQuranMethods. In Java, you always need to create with new unless the object is static. This is good to remember.
Code sample:
public TodayVerse() {
DailyQuranMethods dailyQuranMethods = new DailyQuranMethods();
}
Good luck with Android Java...

Total price using rawQuery in android [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've been trying to get the price value from the database and try to make a grand total. I used the rawQuery but always crashed.I think theres a problem in my rawQuery..i still cant get the total after many times i've tried..
this is the code:
DBAdapter
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
// ------------------------------------ DBAdapter.java ---------------------------------------------
// TO USE:
// Change the package (at top) to match your project.
// Search for "TODO", and make the appropriate changes.
public class DBAdapter {
/////////////////////////////////////////////////////////////////////
// Constants & Data
/////////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_QUANTITY = "studentnum";
public static final String KEY_PRICE = "favcolour";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_QUANTITY = 2;
public static final int COL_PRICE = 3;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_QUANTITY, KEY_PRICE};
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE = "mainTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a value).
// NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
+ KEY_NAME + " text not null, "
+ KEY_QUANTITY + " integer not null, "
+ KEY_PRICE + " string not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String name, String studentNum, String favColour) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_QUANTITY, studentNum);
initialValues.put(KEY_PRICE, favColour);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public Cursor getTotalPrice() {
Cursor c = db.rawQuery("SELECT SUM("+ KEY_PRICE +")from " + DATABASE_TABLE, null);
return c;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, int studentNum, String favColour) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_QUANTITY, studentNum);
newValues.put(KEY_PRICE, favColour);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading.
* Used to handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
Listprice:
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
/**
* Created by User on 6/2/2015.
*/
public class Listprice extends ActionBarActivity {
DBAdapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listprice);
openDB();
TextView textView = (TextView) findViewById(R.id.order90);
TextView textView1 = (TextView) findViewById(R.id.quan90);
TextView textView2 = (TextView) findViewById(R.id.price90);
TextView textView3 = (TextView) findViewById(R.id.totalprice);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String newText = extras.getString("firstmessage");
String newText1 = extras.getString("secondmessage");
String newText2 = extras.getString("thirdmessage");
if (newText != null) {
textView.setText(newText);
}
if (newText1 != null) {
textView1.setText(newText1);
}
if (newText2 != null) {
textView2.setText(newText2);
}
}
String num1 = textView.getText().toString().trim();
int num2 = Integer.parseInt(textView1.getText().toString());
int num3 = Integer.parseInt(textView2.getText().toString());
int num4 = num2 * num3;
registerListClickCallBack();
myDb.insertRow(num1, "Quantity = " + num2, ""+num4);
populateListViewFromDB();
Cursor sum=myDb.getTotalPrice();
textView3.setText(""+sum);
}
private void populateListViewFromDB() {
Cursor cursor = myDb.getAllRows();
//Query for the record we just added.
//Use the ID:
startManagingCursor(cursor);
String[] fromFieldNames = new String[]
{DBAdapter.KEY_NAME, DBAdapter.KEY_QUANTITY, DBAdapter.KEY_PRICE};
int[] toViewIDs = new int[]
{R.id.item_name, R.id.quantities, R.id.pricest};
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
this,
R.layout.item_layout,
cursor,
fromFieldNames,
toViewIDs
);
// Set the adapter for the list view
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setAdapter(myCursorAdapter);
}
private void openDB(){
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void closeDB() {
myDb.close();
}
private void registerListClickCallBack() {
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long idInDB) {
updateItemForId(idInDB);
}
});
}
private void updateItemForId(final long idInDB) {
final Cursor cursor = myDb.getRow(idInDB);
if (cursor.moveToFirst()) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Listprice.this);
// Setting Dialog Title
alertDialog.setTitle("Confirm Delete...");
// Setting Dialog Message
alertDialog.setMessage("Are you sure you want delete this?");
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
myDb.deleteRow(idInDB);
populateListViewFromDB();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
cursor.close();
populateListViewFromDB();
}
public void clear(View view) {
myDb.deleteAll();
populateListViewFromDB();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void addFood(View view) {
Intent gotofood = new Intent(this, food.class);
startActivity(gotofood);
}
public void addDrinks(View view) {
Intent gotodrinks = new Intent(this, drink.class);
startActivity(gotodrinks);
}
public void gotomainmaenu(View view) {
Intent gotomain = new Intent(this, MainActivity.class);
startActivity(gotomain);
}
}
It sounds like you want the sum of each item's price multiplied by that item's quantity. If so, this should work:
public double getTotalPrice() {
String sql = "select sum(" + KEY_QUANTITY + " * " + KEY_PRICE + ") from "
+ DATABASE_TABLE;
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
return cursor.getDouble(0);
}
return 0;
}

Categories

Resources