I'm trying to use the textview to display the contact that was selected from the listview. The listview contains contacts that was selected by the user from the android phonebook which are loaded into the listview. The textview will only show the last item in the listview, even though the user has selected another contact which wasn't the last contact in the listview.
Even though in my log prints, I can see which contact I have selected but it still defaulting to the last contact when I try to print it out onto a textview in another window.
addModem.java
display_contacts1.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id)
{
// TODO Auto-generated method stub
Object o = adapter.getItemAtPosition(position);
String str_text = o.toString();
String name = AddModem.name;
String phoneNumber = AddModem.phoneNo;
Log.e("Contacts selected", str_text);
// Display string here showing which contact was selected
Toast.makeText(getApplicationContext(), str_text + " Selected for Communication", Toast.LENGTH_LONG).show();
// Update Modem View Contact
modemView.setText(str_text);
//modemView.setText(name);
arrayAdapter.notifyDataSetChanged();
// Go back to the main screen after the contact has been selected
Intent main_menu = new Intent(AddModem.this, MainActivity.class);
main_menu.putExtra("StrValue", str_text);
startActivity(main_menu);
}
});
MainActivity.java
// This checks to see if the current contact is selected
if ( display_contacts.isEmpty())
{
number = null;
// No contacts selected from the Add Modem listview
modemView.setText("No contact selected");
}
else
{
runOnUiThread(new Runnable()
{
// This is not updating to the one selected
#Override
public void run()
{
modemView.setText(name);
Log.e("DisplayName", name);
}
});
}
In the main activity code we needed
name = getIntent().getStringExtra("StrValue");
before we printed it out on the textView
modemVide.setText(name);
Related
first time using Firebase and pretty new to android studio, i'm trying to make a schedule app where a user can create many schedules and it would be associated to their account.
At the moment a user can create an account, create a schedule (i just have 2 fields for this, will add the rest once i get the issue sorted) and also have multiple schedules.
I would like to be able to update/delete a schedule of a user but i'm struggling to get the ID of the specific schedule node in which I need to delete.
This is what i have in Firebase with a single user and 2 schedules
I added a toast when i long click a list item which displays the corresponding scheduleId of that schedule. keep in mind this is to help so i can just long click and show if the item displays the proper scheduleId.
Part of ScheduleActivity.java
What the problem is
I have a listView with all the schedules that has a listener
In the listener I have this line which gets the ID, but the issue is since its on the listener, i wont get the ID of the schedule until i click the list item and view the details, then Im only able to view the scheduleId, otherwise i get a NULL value.
scheduleId = scheduleList.get(position).getScheduleId();
public class ScheduleActivity extends AppCompatActivity implements View.OnClickListener {
private List<Schedule> scheduleList;
private List<String> scheduleIdList;
private DatabaseReference scheduleReference;
private String userId;
public static final String SCHEDULE_TITLE = "title";
public static final String SCHEDULE_DESCRIPTION = "description";
private String scheduleId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
getSupportActionBar().hide();
scheduleList = new ArrayList<>();
scheduleIdList = new ArrayList<>();
userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
scheduleReference = FirebaseDatabase.getInstance().getReference(DBStrings.DB_SCHEDULES);
registerForContextMenu(scheduleListView);
// when a user clicks any of list items
scheduleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Schedule schedule = scheduleList.get(position);
// this gets the id but the issue is i need to first click the list item then ill get the correct id, otherwise i get a NPE because i haven't accessed the list item yet
// need to figure out how to implement this in the onStart() method so i can get the scheduleId beforehand
scheduleId = scheduleList.get(position).getScheduleId();
// intent that takes me to the activity to view the schdule details
Intent viewSchedule = new Intent(ScheduleActivity.this, ViewSchedule.class);
viewSchedule.putExtra(SCHEDULE_TITLE, schedule.getTitle());
viewSchedule.putExtra(SCHEDULE_DESCRIPTION, schedule.getDescription());
startActivity(viewSchedule);
}
}
});
}
// when a user long clicks a list item, brings up menu with option to edit/delete
// Also display a toast with scheduleID so i can see if the proper id is being retrieved
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
Toast.makeText(ScheduleActivity.this, "id: " + scheduleId, Toast.LENGTH_SHORT).show();
getMenuInflater().inflate(R.menu.schedule_menu, menu);
}
// switch statement for delete/ redirect to edit activity that i left out
// load schedule data into list view
#Override
protected void onStart() {
super.onStart();
scheduleReference.child(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
scheduleList.clear();
scheduleIdList.clear();
for(DataSnapshot dataSnapshot : snapshot.getChildren()) {
Schedule schedule = dataSnapshot.getValue(Schedule.class);
// add schedules to list to show in list view
scheduleList.add(schedule);
// Add all the ids of schedules in a list, i used this in my scheduleListView.setOnItemListener to grab the scheduleId.
scheduleIdList.add(schedule.getScheduleId());
}
System.out.println("id list: " + scheduleIdList);
ScheduleListAdapter adapter = new ScheduleListAdapter(ScheduleActivity.this, scheduleList);
scheduleListView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
System.out.println("ERROR: " + error.toException());
}
});
}
private void deleteSchedule(String scheduleId) {
// At the moment i can only delete a item if i first view it by clicking, then i need to go back and it allows me to delete it, this is obviously because my listview listener issue (It does not let me delete without first clicking the item to view/access it) scheduleReference.child(userId).child(scheduleId).removeValue();
Toast.makeText(ScheduleActivity.this, "Schedule " + scheduleId + " was deleted!", Toast.LENGTH_LONG).show();
}
}
List view of schedules
The issue is in the scheduleListView.setOnItemClickListener , i need to find a way to grab the id maybe in onStart method or somewhere eother than the listener, but since I do not have access to the position like i did here, i am struggling to implement this.
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Schedule schedule = scheduleList.get(position);
// Talking about this <position>
scheduleId = scheduleList.get(position).getScheduleId();
}
Images to explain it better
I hope it makes sense, i would need to access each list item then go back to be able to delete a specific one.
I am facing a Firebase RecyclerView problem where I cannot remove unwanted CardViews from my RecyclerViews. In my code I check the city's name and the guide's chosen city to match them. It populates guide's details only if the guide's city matches the picked city, but it also shows empty cardview with default layout.
guideDataRef = FirebaseDatabase.getInstance().getReference().child("Guides");
public void recycler() {
super.onStart();
try {
//Guide RecyclerView
Query guideQuery = guideDataRef.orderByKey();
guideQuery.keepSynced(true);
FirebaseRecyclerOptions guideOptions =
new FirebaseRecyclerOptions.Builder<UserModelClass>().setQuery(guideQuery, UserModelClass.class).build();
guideAdapter = new FirebaseRecyclerAdapter<UserModelClass, guideViewHolder>(guideOptions) {
#Override
protected void onBindViewHolder(#NonNull guideViewHolder holder, final int position, #NonNull final UserModelClass model) {
String pickedcity = model.getPickedCity();
String postname = (String) cityName.getText();
if(pickedcity.equals(postname)) {
final String guide_key= getRef(position).getKey();
holder.setGuideName(model.getName());
holder.setGuideSurname(model.getSurName());
holder.setGuideImage(getApplicationContext(), model.getPhotoURL());
// holder.mView.setVisibility(View.VISIBLE);
//Guide Click listener
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent guideHireIntent = new Intent(getApplication(), GuideHireActivity.class);
guideHireIntent.putExtra("guide_id", guide_key);
finish();
startActivity(guideHireIntent);
}
});
}
}
#NonNull
#Override
public guideViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout_guides, parent, false);
return new guideViewHolder(view);
}
#Override
public void onError(DatabaseError e){
Toast.makeText(getApplicationContext(), "Error by stopping ", Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
return super.getItemCount();
}
#Override
public void onDataChanged() {
super.onDataChanged();
notifyDataSetChanged();
}
};
guideAdapter.notifyDataSetChanged();
guideRecyclerView.setAdapter(guideAdapter);
guideAdapter.startListening();
} catch (DatabaseException e) {
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
}
}
enter image description here
enter image description here
I can change the adapter visibility to gone if it does not match with the requirements but the problem is that after making it's visibility gone it is still there holding the place (but invisible - there's still an empty space). How can I avoid populating an item from the recycler view completely, instead of making it invisible if the requirements do not match?
You're not showing what guideDataRef is in your code, so I'm assuming that it's just aDatabaseReference object for everything beneath a \Guides node.
If you're doing that, you're going to get a call for onBindViewHolder for every child at that particular location. This means that you're going to be asked to make a view for every child. You cannot choose whether or not a view will appear for that item.
It looks like you're assuming that your if statement in onBindViewHolder method will skip over those items. But what's actually happening is that you're simply allowing an empty view to occupy that spot in the list.
Instead, you should come up with a query that generates only the items of interest to your list. This means you'll have to tell Firebase to filter for children that meet your criteria.
You can also read the entire contents of the location, manually filter out the items you don't want, and build a list of items you do want. You can then build an custom adapter with that list, and it can then become the input to a ListView or even better to a RecyclerView.
Description: I want to use share button. With share button user sending a list as a message. In the list each item has Title + Description
The problem: System get all items from a list and put it in the line one after another by using a comma.
I have: TitleItemOne,DescriptionItemOne,TitleItemTwo,DescriptionItemTwo
I need:
TitleItemOne - DescriptionItemOne
TitleItemTwo - DescriptionItemTwo
Or:
Maybe it is easier to replace all ODD comma "," with "-" so it will that style which i am looking for.
That's the code (needed code in Sharebutton method)
/**
* Displays list of list that were entered and stored in the app.
*/
public class CatalogActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = "myLogs";
/** Identifier for the pet data loader */
private static final int LIST_LOADER = 0;
/** Adapter for the ListView */
ListCursorAdapter mCursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog);
Log.v(TAG, "Зашли в catalog activity oncreate");
// Setup FAB to open EditorActivity
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
startActivity(intent);
}
});
// Find the ListView which will be populated with the list data
ListView listListView = (ListView) findViewById(R.id.list);
// Find and set empty view on the ListView, so that it only shows when the list has 0 items.
View emptyView = findViewById(R.id.empty_view);
listListView.setEmptyView(emptyView);
// Setup an Adapter to create a list item for each row of list data in the Cursor.
// There is no items data yet (until the loader finishes) so pass in null for the Cursor.
mCursorAdapter = new ListCursorAdapter(this, null);
listListView.setAdapter(mCursorAdapter);
// Setup the item click listener
listListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
ShoppingListBdHelper helper = new ShoppingListBdHelper(view.getContext());
if (helper.setCompleted(id)) {
mCursorAdapter.setCompleted(view);
}
}
});
// Kick off the loader
getSupportLoaderManager().initLoader(LIST_LOADER, null, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu options from the res/menu/menu_catalog.xml file.
// This adds menu items to the app bar.
getMenuInflater().inflate(R.menu.menu_catalog, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// User clicked on a menu option in the app bar overflow menu
switch (item.getItemId()) {
// Respond to a click on the "Insert dummy data" menu option
case R.id.action_share_button:
shareButton(mCursorAdapter.getCursor());
return true;
// Respond to a click on the "Delete all entries" menu option
case R.id.action_delete_all_entries:
deleteAllItems();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Share button
*/
private void shareButton(Cursor cursor) {
Log.v(TAG, "--- WE ARE IN SHARE BUTTON METHOD ---");
List<String> test;
test = new ArrayList<String>();
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
Log.d(TAG, "field: " + cursor.getString(cursor.getColumnIndex(ListContract.ListEntry.COLUMN_ITEM_NAME)));
test.add(cursor.getString(cursor.getColumnIndex(ListContract.ListEntry.COLUMN_ITEM_NAME))); //add the item
test.add(cursor.getString(cursor.getColumnIndex(ListContract.ListEntry.COLUMN_ITEM_DESCRIPTION))); //add the item
cursor.moveToNext();
}
cursor.moveToFirst();
Log.v(TAG, "--- OUR LIST INCLUDES: " + test.toString());
Intent myIntent = new Intent();
myIntent.setAction(Intent.ACTION_SEND);
myIntent.putStringArrayListExtra("test", (ArrayList<String>) test);
myIntent.putExtra(android.content.Intent.EXTRA_TEXT, test.toString());
Log.v(TAG, "--- INTENT EXTRAS ARE: " + myIntent.getExtras());
myIntent.setType("text/plain");
startActivity(Intent.createChooser(myIntent, "Share using"));
}
/**
* Helper method to delete all list in the database.
*/
private void deleteAllItems() {
Log.v(TAG, "Сработал метод удаления всех данных");
long rowsDeleted = getContentResolver().delete(ListContract.ListEntry.CONTENT_URI, null, null);
Log.v("CatalogActivity", rowsDeleted + " rows deleted from list database");
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
Log.v(TAG, "Начал работать loader cursor");
// Define a projection that specifies the columns from the table we care about.
String[] projection = {
ListContract.ListEntry._ID,
ListContract.ListEntry.COLUMN_ITEM_NAME,
ListContract.ListEntry.COLUMN_ITEM_DESCRIPTION,
ListContract.ListEntry.COLUMN_ITEM_COMPLETED
};
// This loader will execute the ContentProvider's query method on a background thread
return new CursorLoader(this, // Parent activity context
ListContract.ListEntry.CONTENT_URI, // Provider content URI to query
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Update {#link ListCursorAdapter} with this new cursor containing updated pet data
mCursorAdapter.swapCursor(data);
Log.v(TAG, "Cursor adapter загрузился");
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// Callback called when the data needs to be deleted
mCursorAdapter.swapCursor(null);
}
}
you can format your strings to html or using "\n"
string to html :
you can use Html.fromHtml() to use HTML tag in your string :
Html.fromHtml("<h2>Title</h2><br><p>Description here</p>"));
for using "\n" you can use System.getProperty("line.separator") wich is OS dependent line separator
Change
test.add(cursor.getString(cursor.getColumnIndex(ListContract.ListEntry.COLUMN_ITEM_NAME))); //add the item test.add(cursor.getString(cursor.getColumnIndex(ListContract.ListEntry.COLUMN_ITEM_DESCRIPTION)));
To
test.add(cursor.getString(cursor.getColumnIndex(ListContract.ListEntry.COLUMN_ITEM_NAME)) + "-" + (cursor.getString(cursor.getColumnIndex(ListContract.ListEntry.COLUMN_ITEM_DESCRIPTION)));
Note:
I may not have all the parenthesis correctly closed, but you get the idea
I have a list view from SQLite with checkboxes ..
It is all working fine , but when I click on one or more checkboxes and change their status then scroll down .. the checkbox status changes back to the original value (when the listview first created)
here is my code .. hope you can tell me how to solve it :
public void showSQL(){
/*
* Open the same SQLite database
* and read all it's content.
*/
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();
Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);
from = new String[]{SQLiteAdapter.NUMBER_CONTENT};
to = new int[]{R.id.text};
SimpleCursorAdapter cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from , to);
cursorAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder(){
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
String number ;
String is_star ;
if (columnIndex == cursor.getColumnIndex("numbers")) {
// If the column is IS_STAR then we use custom view.
number = cursor.getString(1);
is_star = cursor.getString(cursor.getColumnIndex("status"));
if (is_star.equals("true")) {
// set the visibility of the view to GONE
((CheckBox) view).setText(" " + number);
((CheckBox) view).setChecked(true);
return true;
}else{
((CheckBox) view).setText(" " + number);
((CheckBox) view).setChecked(false);
return true;
}
//return true;
}
return false;
}
});
stopManagingCursor(cursor);
listContent.setAdapter(cursorAdapter);
listContent.setOnItemClickListener(listContentOnItemClickListener);
mySQLiteAdapter.getAllNumbers();
mySQLiteAdapter.close();
}
private ListView.OnItemClickListener listContentOnItemClickListener
= new ListView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Cursor cursor = (Cursor) parent.getItemAtPosition(position);
int item_id = cursor.getInt(cursor.getColumnIndex(SQLiteAdapter.NUMBER_ID));
String item_content1 = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.NUMBER_CONTENT));
mySQLiteAdapter = new SQLiteAdapter(getBaseContext());
item = (CheckBox) view;
mySQLiteAdapter.openToRead();
String check = null;
Cursor c = mySQLiteAdapter.getNumberStatus(item_id);
if (c.moveToFirst()){
check = c.getString(c.getColumnIndex(SQLiteAdapter.NUMBER_STATUS));
}
mySQLiteAdapter.close();
//The change color logic is here!
if(item.isChecked()) {
mySQLiteAdapter.openToWrite();
mySQLiteAdapter.updateNumberStatus(item_id,"false");
mySQLiteAdapter.close();
// Toast.makeText(MainActivity.this, "deleted" +" "+ check, Toast.LENGTH_LONG).show();
item.setChecked(false);
}
else {
mySQLiteAdapter.openToWrite();
mySQLiteAdapter.updateNumberStatus(item_id,"true");
mySQLiteAdapter.close();
// Toast.makeText(MainActivity.this, item_content1 +" "+ check , Toast.LENGTH_LONG).show();
item.setChecked(true);
}
}};
The issue with CheckBox inside ListView is that the view gets recycled due to recycling of view.
To, maintain the state to CheckBox there has to be something that can store the state of Checkbox.
Refer this link,it is very nice example explained here.
Link 1
You have to make a class to get and set state of checkbox . that will be used as arraylist to save state of checkbox. and use it to show checked item.
Here's a head scratcher...(at least for me)
I have a contact list that displays a list of contacts from my Db. When a user clicks on one of the contacts an edit activity comes up. It all works perfectly as laid out currently, but I need to have the edit activity display the last name entry before the first name. Thinking that all the fields should have a one to one relationship, I went ahead and moved the editText(XML) for the last name above the first name in the edit activity thinking that this should be referenced by the id of the EditText. After doing so, the program is now displaying the first name in the last name field and vise-versa. I have tried wiping the user data on the emulator with no difference. I already realize this is probably one of those UH-DUH! type questions, but if anyone can point out the obvious for me, it would be appreciated. All the code shown is in the now-working state:
I've removed some chunks that would have nothing to do with my issue.
Thanks to anyone having a look at this for me!
Ken
XML:
<EditText
android:id="#+id/contact_edit_first_name"
android:inputType="textPersonName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="#string/contact_edit_first_name"
android:imeOptions="actionNext"
android:background="#color/warn" >
</EditText>
<EditText
android:id="#+id/contact_edit_last_name"
android:inputType="textPersonName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="top"
android:hint="#string/contact_edit_last_name"
android:imeOptions="actionNext"
android:background="#color/warn" >
</EditText>
This is the contact activity that displays the listView rows, and calls
createContact which sends an intent to add, edit or delete rows.
public class ContactsActivity extends ListActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private SimpleCursorAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate //DO THE ON CREATE STUFF -removed
fillData();
registerForContextMenu(getListView());
Button add_contact = (Button) findViewById(R.id.add_contact_button);
add_contact.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
createContact();
}
});
}
// Create the options menu to INSERT from the XML file
// removed - not relevant
// return true for the menu to be displayed
}
// When the insert menu item is selected, call CreateContact
//Removed
createContact();
return true;
}
return super.onOptionsItemSelected(item);
}
private void createContact() {
Intent i = new Intent(this, ContactEditActivity.class);
startActivity(i);
}
//The onListItemClick sends a URI which flags the contactEditActivity
//that this is an edit rather than a new insert.
#Override
protected void onResume() {
super.onResume();
//Starts a new or restarts an existing Loader in this manager
getLoaderManager().restartLoader(0, null, this);
}
//The fillData method binds the simpleCursorAadapter to the listView.
private void fillData() {
//The desired columns to be bound:
String[] from = new String[] { ContactsDB.COLUMN_LAST_NAME, ContactsDB.COLUMN_FIRST_NAME };
//The XML views that the data will be bound to:
int[] to = new int[] {R.id.label2, R.id.label};
// The creation of a loader using the initLoader method call.
getLoaderManager().initLoader(0, null, this);
adapter = new SimpleCursorAdapter(this, R.layout.contact_row, null, from,
to, 0);
setListAdapter(adapter);
}
// Sort the names by last name, then by first name
String orderBy = ContactsDB.COLUMN_LAST_NAME + " COLLATE NOCASE ASC"
+ "," + ContactsDB.COLUMN_FIRST_NAME + " COLLATE NOCASE ASC" ;
// Creates a new loader after the initLoader () call
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
//ETC
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data); //Call requires Min API 11
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// swap the cursor adapter
}
And Finally, this is the contact edit code that is likely the source of my grief...maybe not. Could be the save state doesn't map to the id's?
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_contact_edit);
Log.i(TAG, "INSIDE ONCREATE");
mCategory = (Spinner) findViewById(R.id.category);
mLastName = (EditText) findViewById(R.id.contact_edit_last_name);
mFirstName = (EditText) findViewById(R.id.contact_edit_first_name);
mHomePhone = (EditText) findViewById(R.id.contact_edit_home_phone);
mCellPhone = (EditText) findViewById(R.id.contact_edit_cell_phone);
//****************ECT. ETC.
//DECLARE THE BUTTONS AND SET THE DELETE ENABLED FALSE - REMOVED - NOT PERTINANT
Bundle extras = getIntent().getExtras();
// Check if the URI is from a new instance or a saved record
}
// Set the save button to check the required fields, save the contact and finish
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (TextUtils.isEmpty(mLastName.getText().toString()) ||
TextUtils.isEmpty(mFirstName.getText().toString())) {
makeToast();
} else {
setResult(RESULT_OK);
finish();
}
}
});
// Set the delete button to delete the contact and finish - REMOVED - NOT PERTINANT
private void fillData(Uri uri) {
// QUERY PARAMETER projection - A list of which columns to return.
// Passing null will return all columns, which is inefficient (but used now!)
// null, null and null are: selection, selection args, and sort order for specific items
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
String category = cursor.getString(cursor
.getColumnIndexOrThrow(ContactsDB.COLUMN_CATEGORY));
for (int i = 0; i < mCategory.getCount(); i++) {
String s = (String) mCategory.getItemAtPosition(i);
Log.i("CATEGORY", s); ////////////////////////////////////////////
if (s.equalsIgnoreCase(category)) {
mCategory.setSelection(i);
}
};
mLastName.setText(cursor.getString(cursor
.getColumnIndexOrThrow(ContactsDB.COLUMN_LAST_NAME)));
mFirstName.setText(cursor.getString(cursor
.getColumnIndexOrThrow(ContactsDB.COLUMN_FIRST_NAME)));
mHomePhone.setText(cursor.getString(cursor
.getColumnIndexOrThrow(ContactsDB.COLUMN_PHONE_NUMBER)));
mCellPhone.setText(cursor.getString(cursor
.getColumnIndexOrThrow(ContactsDB.COLUMN_CELL_NUMBER)));
mWorkPhone.setText(cursor.getString(cursor
.getColumnIndexOrThrow(ContactsDB.COLUMN_WORK_NUMBER)));
mFax.setText(cursor.getString(cursor
//****************ECT. ETC.
//close the cursor
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putParcelable(whateverContentProvider.CONTENT_ITEM_TYPE, contactUri);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
private void saveState() {
String category = (String) mCategory.getSelectedItem();
String someLAST = mLastName.getText().toString().valueOf(findViewById(R.id.contact_edit_last_name));
String lastName = mLastName.getText().toString();
String firstName = mFirstName.getText().toString();
String someFIRST = mFirstName.getText().toString().valueOf(findViewById(R.id.contact_edit_first_name));
String homePhone = mHomePhone.getText().toString();
String somePhone = mHomePhone.getText().toString().valueOf(findViewById(R.id.contact_edit_home_phone));
String cellPhone = mCellPhone.getText().toString();
String workPhone = mWorkPhone.getText().toString();
//****************ECT. ETC.
//Some logging I used to show that the first name field still came up first
//after changing the order of the editTexts.
Log.i("LAST NAME", lastName);
Log.i("SOME LAST", someLAST);
Log.i("FIRST NAME", firstName);
Log.i("SOME FIRST", someFIRST);
Log.i("Home Phone", homePhone);
Log.i("SOME PHONE", somePhone);
// Save if first name and last name are entered
// The program will save only last name when a user presses back button with text in last name
if (lastName.length() == 0 || firstName.length() == 0) {
return;
}
// ContentValues class is used to store a set of values that the contentResolver can process.
ContentValues values = new ContentValues();
values.put(ContactsDB.COLUMN_CATEGORY, category);
values.put(ContactsDB.COLUMN_LAST_NAME, lastName);//ANNIE
values.put(ContactsDB.COLUMN_FIRST_NAME, firstName);
values.put(ContactsDB.COLUMN_PHONE_NUMBER, homePhone);
//****************ECT. ETC.
if (contactUri == null) {
// Create a new contact
contactUri = getContentResolver().insert(whateverContentProvider.CONTENT_URI, values);
} else {
// Update an existing contact
getContentResolver().update(contactUri, values, null, null);
}
}
//MAKE A TOAST DOWN HERE - REMOVED - NOT PERTINANT
}
Have you tried cleaning the project (regenerating de R).
Also, try restarting your IDE.
This may seem stupid but actually can solve the issue...
try cleaning your project. Weird things happen sometimes within Eclipse.