Android: Listview Items not Showing - android

My items for Listview are not showing, can someone point me where is the error.
There is no error when adding items but its not showing on the Listview. I revised my post, I'm trying to use BaseAdapter to populate the items. I can confirm that the items are added to the database because the total amount is updated everytime i add item.
public class ViewTransactions extends Activity {
private ListView mListViewTransactions;
private TransactionAdapter mAdapter;
private List<TransactionModel> mListTransactions;
/** transactions data source. */
private TransactionDao transactionSource;
/** Currently selected broker, as specified by intent received from ViewBrokers class. */
private BrokerModel currentBroker;
/** The sum total of all transactions for the active broker. */
private BigDecimal brokerTotal;
private ArrayAdapter<TransactionModel> aa;
/** Action mode for the context menu. */
private ActionMode aMode;
/** Call back methods for the context menu. */
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
/** Title which displays broker name. */
private TextView title;
// Called when the action mode is created; startActionMode() was called
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_transactions, menu);
// disable listener here; moved from onPrepareActionMode
title = (TextView) findViewById(R.id.exCat);
title.setClickable(false); // prevent navigation away from activity
return true;
}
// Called each time the action mode is shown. Always called after onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
title = (TextView) findViewById(R.id.exCat);
title.setClickable(false); // prevent navigation away from activity
return false; // Return false if nothing is done
}
// Called when the user selects a contextual menu item
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:
// edit selected expense
editTransaction();
mode.finish(); // Action picked, so close the CAB
return true;
case R.id.action_del:
// delete selected expense
deleteTransaction();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
// Called when the user exits the action mode
#Override
public void onDestroyActionMode(ActionMode mode) {
// unselect item that was selected (if it wasn't deleted)
final ListView lv = (ListView)findViewById(R.id.tList);
lv.clearChoices();
lv.setItemChecked(lv.getCheckedItemPosition(), false);
lv.post(new Runnable() {
#Override
public void run() {
lv.setChoiceMode(ListView.CHOICE_MODE_NONE);
}
});
aMode = null;
title.setClickable(true); // restore broker name click
}
};
/**
* Class to asynchronously retrieve transactions from database.
*/
private class GetTransactions extends AsyncTask<Void, Void, List<TransactionModel>> {
#Override
protected List<TransactionModel> doInBackground(Void... params) {
// retrieve all transactions for the user and broker
return transactionSource.getTransactions(currentBroker);
}
#Override
protected void onPostExecute(final List<TransactionModel> result) {
mAdapter = new TransactionAdapter(ViewTransactions.this, mListTransactions);
mListViewTransactions.setAdapter(mAdapter);
mListViewTransactions.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
// Called when the user long-clicks on an item
public boolean onItemLongClick(AdapterView<?> aView, View view, int i, long l) {
if (aMode != null) {
return false;
}
mListViewTransactions.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// mark item at position i as selected
mListViewTransactions.setItemChecked(i, true);
// Start the CAB using the ActionMode.Callback defined above
aMode = ViewTransactions.this.startActionMode(mActionModeCallback);
return true;
}
});
}
}
/**
* Class to asynchronously add new expense to database.
*/
private class AddTransaction extends AsyncTask<String, Void, TransactionModel> {
#Override
protected TransactionModel doInBackground(String... params) {
return transactionSource.newTransaction(params[0], new BigDecimal(params[1]), params[2],
currentBroker);
}
#Override
protected void onPostExecute(TransactionModel result) {
// ArrayAdapter<TransactionModel> aa = (ArrayAdapter<TransactionModel>) getListAdapter();
mAdapter = new TransactionAdapter(ViewTransactions.this, mListTransactions);
// mAdapter.add(result);
mAdapter.notifyDataSetChanged();
// update total
brokerTotal = brokerTotal.add(result.getTransactionAmount());
TextView total = (TextView) findViewById(R.id.transactionTotal);
NumberFormat formatter = new DecimalFormat("#,##0.00");
total.setText(formatter.format(brokerTotal));
}
}
/**
* Class to asynchronously edit an expense in database.
*/
private class EditTransaction extends AsyncTask<TransactionModel, Void, TransactionModel> {
#Override
protected TransactionModel doInBackground(TransactionModel... params) {
return transactionSource.editTransaction(params[0]);
}
#Override
protected void onPostExecute(TransactionModel result) {
// #SuppressWarnings("unchecked")
// ArrayAdapter<TransactionModel> aa = (ArrayAdapter<TransactionModel>) getListAdapter();
aa.notifyDataSetChanged();
// update total
brokerTotal = brokerTotal.add(result.getTransactionAmount());
TextView total = (TextView) findViewById(R.id.transactionTotal);
NumberFormat formatter = new DecimalFormat("#,##0.00");
total.setText(formatter.format(brokerTotal));
}
}
/**
* Class to asynchronously delete an expense from database.
*/
private class DeleteTransaction extends AsyncTask<TransactionModel, Void, TransactionModel> {
#Override
protected TransactionModel doInBackground(TransactionModel... params) {
return transactionSource.deleteTransaction(params[0]); // delete selected item from db
}
#Override
protected void onPostExecute(TransactionModel result) {
// #SuppressWarnings("unchecked")
// ArrayAdapter<TransactionModel> aa = (ArrayAdapter<TransactionModel>) getListAdapter();
aa.remove(result); // remove selected item from adapter
aa.notifyDataSetChanged();
// update total
brokerTotal = brokerTotal.subtract(result.getTransactionAmount());
TextView total = (TextView) findViewById(R.id.transactionTotal);
NumberFormat formatter = new DecimalFormat("#,##0.00");
total.setText(formatter.format(brokerTotal));
}
}
/**
* Method to record a new expense. Called when Add button in action bar is clicked.
*/
private void addTransaction() {
// build dialog to ask for expense details
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Record Transaction");
builder.setMessage("Please enter transaction details.");
// construct input fields
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
final EditText enterDate = new EditText(this);
final EditText enterCost = new EditText(this);
final EditText enterDesc = new EditText(this);
enterDate.setHint("Date");
enterCost.setHint("Amount");
enterDesc.setHint("Transaction");
enterDate.setInputType(InputType.TYPE_CLASS_DATETIME); // date text
enterDate.setFilters(new InputFilter[]{new InputFilter.LengthFilter(40)});
enterCost.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED); // to accept dollar amount
enterCost.setKeyListener(DigitsKeyListener.getInstance("0123456789.-")); // accept digits
enterDesc.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); // description text
enterDesc.setFilters(new InputFilter[]{new InputFilter.LengthFilter(40)});
ll.addView(enterDate);
ll.addView(enterCost);
ll.addView(enterDesc);
builder.setView(ll);
// add ok and cancel buttons
builder.setPositiveButton(R.string.ok, null);
builder.setNegativeButton(R.string.cancel, null);
// create dialog
final AlertDialog dia = builder.create(); // don't show yet
// set listener to description input field to click OK when done
enterDesc.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_DONE) {
// click dialog's OK when user presses Done on keyboard
dia.getButton(Dialog.BUTTON_POSITIVE).performClick();
handled = true;
}
return handled;
}
});
// set listener to date input field to click OK when done
enterDate.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_DONE) {
// click dialog's OK when user presses Done on keyboard
dia.getButton(Dialog.BUTTON_POSITIVE).performClick();
handled = true;
}
return handled;
}
});
// set input mode to let keyboard appear when dialog is shown
dia.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dia.show();
// override onclick for OK button; must be done after show()ing to retrieve OK button
dia.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// retrieve name entered
String date = enterDate.getText().toString().trim();
String cost = enterCost.getText().toString().trim();
String desc = enterDesc.getText().toString().trim();
// perform checks and add if pass
if (cost.equals("")) { // must not be empty
enterCost.setError("Please enter an amount.");
//} else if (!Pattern.matches("^(\\d{1,10})?(\\.\\d{0,2})?$", cost)) { // must be $$
// enterCost.setError("Please enter a valid amount.");
} else {
// can be added
new AddTransaction().execute(date, cost, desc);
dia.dismiss();
}
}
});
}
/**
* Method to edit selected expense. Called when Edit button is clicked in context menu.
*/
private void editTransaction() {
// retrieve adapter and retrieve selected expense
// ListView lv = getListView();
#SuppressWarnings("unchecked")
// final ArrayAdapter<TransactionModel> aa = (ArrayAdapter<TransactionModel>) getListAdapter();
// final TransactionModel exToEdi = aa.getItem(lv.getCheckedItemPosition()); // get item at checked pos
// build dialog to ask for expense details
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Edit Transaction");
builder.setMessage("Please enter transaction details.");
// construct input fields
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
final EditText enterDate = new EditText(this);
final EditText enterCost = new EditText(this);
final EditText enterDesc = new EditText(this);
// enterDate.setText(exToEdi.getTransactionDate());
// enterCost.setText(exToEdi.getTransactionAmount().toString());
// enterDesc.setText(exToEdi.getTransactionDescription());
enterDate.setInputType(InputType.TYPE_CLASS_DATETIME); // description text
enterDate.setFilters(new InputFilter[]{new InputFilter.LengthFilter(40)});
enterCost.setInputType(InputType.TYPE_CLASS_NUMBER); // to accept dollar amount
enterCost.setKeyListener(DigitsKeyListener.getInstance("0123456789.")); // accept digits
enterDesc.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); // description text
enterDesc.setFilters(new InputFilter[]{new InputFilter.LengthFilter(40)});
ll.addView(enterDate);
ll.addView(enterCost);
ll.addView(enterDesc);
builder.setView(ll);
// add ok and cancel buttons
builder.setPositiveButton(R.string.ok, null);
builder.setNegativeButton(R.string.cancel, null);
// create dialog
final AlertDialog dia = builder.create(); // don't show yet
// set listener to description input field to click OK when done
enterDesc.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_DONE) {
// click dialog's OK when user presses Done on keyboard
dia.getButton(Dialog.BUTTON_POSITIVE).performClick();
handled = true;
}
return handled;
}
});
// set listener to date input field to click OK when done
enterDate.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_DONE) {
// click dialog's OK when user presses Done on keyboard
dia.getButton(Dialog.BUTTON_POSITIVE).performClick();
handled = true;
}
return handled;
}
});
// set input mode to let keyboard appear when dialog is shown
dia.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dia.show();
// override onclick for OK button; must be done after show()ing to retrieve OK button
dia.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// retrieve name entered
String date = enterDate.getText().toString().trim();
String cost = enterCost.getText().toString().trim();
String desc = enterDesc.getText().toString().trim();
// perform checks and add if pass
if (cost.equals("")) { // must not be empty
enterCost.setError("Please enter a dollar amount.");
//} else if (!Pattern.matches("^(\\d{1,10})?(\\.\\d{0,2})?$", cost)) { // must be $$
// enterCost.setError("Please enter a valid dollar amount.");
} else {
// can be changed
// brokerTotal = brokerTotal.subtract(exToEdi.getTransactionAmount());
// exToEdi.setTransactionAmount(new BigDecimal(cost));
// exToEdi.setTransactionDescription(desc);
// exToEdi.setTransactionDate(date);
// new EditTransaction().execute(exToEdi);
dia.dismiss();
}
}
});
}
/**
* Method to delete selected expense. Called when Delete button is clicked in context menu.
*/
private void deleteTransaction() {
// get list view and list adapter
// ListView lv = getListView();
// #SuppressWarnings("unchecked")
// ArrayAdapter<TransactionModel> aa = (ArrayAdapter<TransactionModel>) getListAdapter();
// int pos = lv.getCheckedItemPosition(); // get pos of selected item
// TransactionModel del = aa.getItem(pos); // get item in adapter at position pos
// new DeleteTransaction().execute(del); // delete expense async and update total
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.capital_activity_view_transactions);
initViews();
currentBroker = (BrokerModel) getIntent().getSerializableExtra(IntentTags.CURRENT_BROKER);
// set totalCost = ; here
// set title to broker
TextView title = (TextView) findViewById(R.id.exCat);
title.setText(currentBroker.getBroker());
title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent it = new Intent(ViewTransactions.this, ViewBrokers.class);
startActivity(it);
}
});
// open data source
transactionSource = new TransactionDao(this);
transactionSource.open();
// display total for user, cat, month/year
brokerTotal = transactionSource.getTotalCost(currentBroker);
TextView total = (TextView) findViewById(R.id.transactionTotal);
NumberFormat formatter = new DecimalFormat("#,##0.00");
total.setText(formatter.format(brokerTotal));
new GetTransactions().execute(); // retrieve display transactions for the broker
}
private void initViews(){
this.mListViewTransactions = (ListView)findViewById(R.id.tList);
}
#Override
protected void onResume() {
transactionSource.open();
super.onResume();
}
#Override
protected void onPause() {
transactionSource.close();
super.onPause();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu
getMenuInflater().inflate(R.menu.view_transactions, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_new) {
addTransaction();
return true;
} else if (id == R.id.switch_user) {
// Intent intent = new Intent(this, ViewUsers.class);
// startActivity(intent); // start user activity
return true;
}
return super.onOptionsItemSelected(item);
}
}
public class TransactionAdapter extends BaseAdapter {
public static final String TAG = "ListTransactionsAdapter";
private List<TransactionModel> mItems;
private LayoutInflater mInflater;
public TransactionAdapter(Context context, List<TransactionModel> listBrokers) {
this.setItems(listBrokers);
this.mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return (getItems() != null && !getItems().isEmpty()) ? getItems().size() : 0 ;
}
#Override
public TransactionModel getItem(int position) {
return (getItems() != null && !getItems().isEmpty()) ? getItems().get(position) : null ;
}
#Override
public long getItemId(int position) {
return (getItems() != null && !getItems().isEmpty()) ? getItems().get(position).getId() : position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if(v == null) {
v = mInflater.inflate(R.layout.capital_row_layout_transaction, parent, false);
holder = new ViewHolder();
holder.txtCapitalTransactionDate = (TextView) v.findViewById(R.id.capital_broker_date_transaction);
holder.txtCapitalTransaction = (TextView) v.findViewById(R.id.capital_broker_add_transaction);
holder.txtCapitalTransactionAmount = (TextView) v.findViewById(R.id.capital_broker_add_amount);
v.setTag(holder);
}
else {
holder = (ViewHolder) v.getTag();
}
// fill row data
TransactionModel currentItem = getItem(position);
if(currentItem != null) {
holder.txtCapitalTransactionDate.setText(currentItem.getTransactionDate());
holder.txtCapitalTransaction.setText(String.valueOf(currentItem.getTransactionDescription()));
holder.txtCapitalTransactionAmount.setText(String.valueOf(currentItem.getTransactionAmount()));
}
return v;
}
public List<TransactionModel> getItems() {
return mItems;
}
public void setItems(List<TransactionModel> mItems) {
this.mItems = mItems;
}
class ViewHolder {
TextView txtCapitalTransactionDate;
TextView txtCapitalTransaction;
TextView txtCapitalTransactionAmount;
}
}

Related

Listview OnItemClickListener working on MainActivity but not on similar TaskActivity

In the MainActivity I have both a ContextMenu that responds to Long clicks and a regular OnItemClickListener that responds to regular clicks.
On the TaskActivity which is practically similar to the MainActivity, I also have a ContextMenu that responds to Long clicks, however when trying to set an OnItemClickListener, the items in the list view don't respond (they do respond to long clicks).
What am I missing? I tried various methods like changing clickable status to false and so on - none of them work. And that makes sense because I don't have them on the MainActivity XML's but it does work there.
MainActivity code:
public class MainActivity extends AppCompatActivity {
final Context context = this;
public static final int SIGN_IN = 1;
public static String currentTaskListId;
public static String currentUserId;
private TaskListAdapter mTaskListAdapter;
//TextView that is displayed when the list is empty//
private TextView mEmptyStateTextView;
//The loading indicator //
private View loadingIndicator;
// Firebase instance variables
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mTaskListDatabaseReference;
private ChildEventListener mChildEventListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the content of the activity to use the activity_main.xml layout file - the task lists
setContentView(R.layout.activity_main);
// Initialize Firebase components
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
//Initialize firebase authentication
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// user is signed in
currentUserId=user.getUid();
onSignedInInitialize(user.getUid());
} else {
// user is signed out
onSignedOutCleanup();
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setAvailableProviders(Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build()))
.setTosAndPrivacyPolicyUrls("https://superapp.example.com/terms-of-service.html",
"https://superapp.example.com/privacy-policy.html")
.build(),
SIGN_IN);
}
}
};
//Initialize task list Array, ListView and Adapter.
final ArrayList<TaskList> taskLists = new ArrayList<TaskList>();
// Create an {#link TaskListAdapter}, whose data source is a list of {#link TaskList}s.
mTaskListAdapter = new TaskListAdapter(this, taskLists);
// Locate the {#link ListView} object in the view hierarchy of the {#link Activity}.
ListView listView = (ListView) findViewById(R.id.task_list_view);
//Set the empty view
mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
listView.setEmptyView(mEmptyStateTextView);
//Initialize the loading indicator
loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.INVISIBLE);
// Make the {#link ListView} use the {#link TaskListAdapter} defined above, so that the
// {#link ListView} will display list items for each {#link TaskList} in the list.
listView.setAdapter(mTaskListAdapter);
//Set and create the FAB and it's action listener
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Get add_list.xml view
LayoutInflater li = LayoutInflater.from(context);
View addTaskListView = li.inflate(R.layout.add_list, null);
//Create the prompt to enable the user to create a new task list
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// Set add_list.xml as the layout for alertdialog builder
alertDialogBuilder.setView(addTaskListView);
//Set the user input box
final EditText userInput = (EditText) addTaskListView
.findViewById(R.id.edit_list_name);
// Set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("Create",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// Get list title from user and create a new task list
//Also fetch the FireBase ID and connect it to the new task list.
String mTaskListId = mTaskListDatabaseReference.push().getKey();
TaskList taskList = new TaskList(userInput.getText().toString(),mTaskListId);
mTaskListDatabaseReference.child(mTaskListId).setValue(taskList);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// Create the dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// Show the dialog
alertDialog.show();
}
});
// Set an item click listener on the ListView, which creates an intent to open
//the relevant task list and show the tasks inside.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// Find the current task list that was clicked on
TaskList currentTaskList = mTaskListAdapter.getItem(position);
//get the current task list's ID
currentTaskListId=currentTaskList.getId();
// Create a new intent to view the tasks in the chosen list
Intent taskIntent = new Intent(MainActivity.this, TaskActivity.class);
// Send the intent to launch a new activity
startActivity(taskIntent);
}
});
listView.setLongClickable(true);
registerForContextMenu(listView);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SIGN_IN) {
if (resultCode == RESULT_OK) {
// Sign-in succeeded, set up the UI
Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
// Sign in was canceled by the user, finish the activity
Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mini_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sign_out:
AuthUI.getInstance().signOut(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
#Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null) {
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
mTaskListAdapter.clear();
detachDatabaseReadListener();
}
private void onSignedInInitialize(final String userId) {
//Get reference for the task list for the logged in user and attach the database listener
mTaskListDatabaseReference=mFirebaseDatabase.getReference().child("users").child(userId);
loadingIndicator.setVisibility(View.VISIBLE);
attachDatabaseReadListener();
mEmptyStateTextView.setText("No task lists, add a new one!");
loadingIndicator.setVisibility(View.GONE);
}
private void onSignedOutCleanup() {
mTaskListAdapter.clear();
detachDatabaseReadListener();
}
private void attachDatabaseReadListener() {
if (mChildEventListener == null) {
mChildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
TaskList taskList = dataSnapshot.getValue(TaskList.class);
mTaskListAdapter.add(taskList);
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
public void onChildRemoved(DataSnapshot dataSnapshot) {}
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
public void onCancelled(DatabaseError databaseError) {}
};
}
mTaskListDatabaseReference.addChildEventListener(mChildEventListener);
}
private void detachDatabaseReadListener() {
if (mChildEventListener != null) {
mTaskListDatabaseReference.removeEventListener(mChildEventListener);
mChildEventListener = null;
}
}
public static String getCurrentTaskListId() {
return currentTaskListId;
}
public static String getCurrentUserId() {
return currentUserId;
}
/**
* MENU
*/
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
if (v.getId() == R.id.task_list_view){
AdapterView.AdapterContextMenuInfo info =(AdapterView.AdapterContextMenuInfo)menuInfo;
menu.add(0,0,0,"Delete");
}
}
#Override
public boolean onContextItemSelected(MenuItem menuItem){
AdapterView.AdapterContextMenuInfo info=(AdapterView.AdapterContextMenuInfo)menuItem.getMenuInfo();
TaskList taskListClicked=mTaskListAdapter.getItem(info.position);
Log.d("check","" +taskListClicked.getTitle());
switch (menuItem.getItemId()) {
case 0:
mTaskListDatabaseReference.child(taskListClicked.getId()).removeValue();
mTaskListAdapter.remove(taskListClicked);
Toast.makeText(this, "Task List deleted!", Toast.LENGTH_LONG).show();
break;
default:
break;
}
return true;
}
}
TaskActivity code:
public class TaskActivity extends AppCompatActivity {
final Context context = this;
private TaskAdapter mTaskAdapter;
private int taskCount;
// TextView that is displayed when the list is empty //
private TextView mEmptyStateTextView;
//The loading indicator //
private View loadingIndicator;
//Edit text and button for creating new tasks quickly
private EditText mTaskEditText;
private Button mTaskCreateButton;
// Firebase instance variables
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mTaskDatabaseReference;
private DatabaseReference mTaskNumDatabaseReference;
private ChildEventListener mChildEventListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the content of the activity to use the activity_main.xml layout file - the task lists
setContentView(R.layout.task_activity);
//Set up to allow Up navigation to parent activity
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Initialize Firebase components
mFirebaseDatabase = FirebaseDatabase.getInstance();
// Initialize references to views
mTaskEditText = (EditText) findViewById(R.id.task_edit_text);
mTaskCreateButton = (Button) findViewById(R.id.create_task_button);
// Enable Send button when there's text to send
mTaskEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().length() > 0) {
mTaskCreateButton.setEnabled(true);
} else {
mTaskCreateButton.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
// Create button creates a new task and clears the EditText
mTaskCreateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Get task title from user and create a new task
//Also fetch the FireBase ID and connect it to the new task.
//And finally get the task's creation date
String creationDate ="Created: " + new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
String taskId = mTaskDatabaseReference.push().getKey();
Task task = new Task(mTaskEditText.getText().toString(),false,taskId,creationDate);
mTaskDatabaseReference.child(taskId).setValue(task);
//add that task to the list's task count
mTaskNumDatabaseReference.child("taskNum").setValue(taskCount+1);
// Clear input box
mTaskEditText.setText("");
}
});
//Initialize task Array, ListView and Adapter.
final ArrayList<Task> tasks = new ArrayList<Task>();
// Create an {#link TaskAdapter}, whose data source is a list of {#link Task}s.
mTaskAdapter = new TaskAdapter(this, tasks);
// Locate the {#link ListView} object in the view hierarchy of the {#link Activity}.
ListView listView = (ListView) findViewById(R.id.task_list_view);
//Set the empty view
mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
listView.setEmptyView(mEmptyStateTextView);
//Initialize the loading indicator
loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.INVISIBLE);
// Make the {#link ListView} use the {#link TaskAdapter} defined above, so that the
// {#link ListView} will display list items for each {#link Task} in the list.
listView.setAdapter(mTaskAdapter);
//Set a regular click - opening the TaskInfoFragment
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// Find the current task list that was clicked on
Log.d("clicked here bro","clicikcckckc");
Task currentTask = mTaskAdapter.getItem(position);
//Open the TaskInfoFragment for this task
TaskInfoFragment taskInfo = new TaskInfoFragment();
taskInfo.setCurrentTask(currentTask);
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.frag_container, taskInfo);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
});
//Set context menu for ListView
listView.setLongClickable(true);
registerForContextMenu(listView);
//Get reference for the task list for the logged in user and attach the database listener
mTaskDatabaseReference=mFirebaseDatabase.getReference().child("users")
.child(MainActivity.getCurrentUserId())
.child(MainActivity.getCurrentTaskListId()).child("tasks");
mTaskNumDatabaseReference=mFirebaseDatabase.getReference().child("users")
.child(MainActivity.getCurrentUserId())
.child(MainActivity.getCurrentTaskListId());
//add listener to get the current task count in this specific task list
mTaskNumDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
TaskList taskList = dataSnapshot.getValue(TaskList.class);
taskCount=taskList.getTaskNum();
Log.d("post count: ", "" + taskCount);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
}
#Override
protected void onResume() {
super.onResume();
loadingIndicator.setVisibility(View.VISIBLE);
attachDatabaseReadListener();
mEmptyStateTextView.setText("No tasks, add a new one!");
loadingIndicator.setVisibility(View.GONE);
}
#Override
protected void onPause() {
super.onPause();
mTaskAdapter.clear();
detachDatabaseReadListener();
}
private void attachDatabaseReadListener() {
if (mChildEventListener == null) {
mChildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Task task = dataSnapshot.getValue(Task.class);
mTaskAdapter.add(task);
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
//Task task = dataSnapshot.getValue(Task.class);
//mTaskAdapter.add(task);
}
public void onChildRemoved(DataSnapshot dataSnapshot) {
mTaskNumDatabaseReference.child("taskNum").setValue(taskCount-1);
}
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
public void onCancelled(DatabaseError databaseError) {}
};
}
mTaskDatabaseReference.addChildEventListener(mChildEventListener);
}
private void detachDatabaseReadListener() {
if (mChildEventListener != null) {
mTaskDatabaseReference.removeEventListener(mChildEventListener);
mChildEventListener = null;
}
}
/**
* MENU
*/
#Override
public void onCreateContextMenu(ContextMenu menu,View v, ContextMenu.ContextMenuInfo menuInfo){
if (v.getId() == R.id.task_list_view){
AdapterView.AdapterContextMenuInfo info =(AdapterView.AdapterContextMenuInfo)menuInfo;
menu.add(0,0,0,"Delete");
menu.add(0,1,1,"info");
}
}
#Override
public boolean onContextItemSelected(MenuItem menuItem){
AdapterView.AdapterContextMenuInfo info=(AdapterView.AdapterContextMenuInfo)menuItem.getMenuInfo();
Task taskClicked=mTaskAdapter.getItem(info.position);
Log.d("check","" +taskClicked.getTitle());
switch (menuItem.getItemId()) {
case 0:
mTaskDatabaseReference.child(taskClicked.getId()).removeValue();
mTaskAdapter.remove(taskClicked);
Toast.makeText(this, "Task deleted!", Toast.LENGTH_LONG).show();
break;
case 1:
//Open the TaskInfoFragment for this task
TaskInfoFragment taskInfo = new TaskInfoFragment();
taskInfo.setCurrentTask(taskClicked);
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.frag_container, taskInfo);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
break;
default:
break;
}
return true;
}
//set up the back button - to navigate to the parent activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
//Check if the call came from the TaskInfoFragment or the activity
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.frag_container);
if(currentFragment!=null && currentFragment.isVisible()){
this.onBackPressed();
}
else{
NavUtils.navigateUpFromSameTask(this);
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
TaskAdapter - the TaskActivity Adapter
package com.example.guyerez.todotiger;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.Locale;
/**
* {#link TaskAdapter} is an {#link ArrayAdapter} that can provide the layout for each task item
* based on a data source, which is a list of {#link Task} objects.
*/
public class TaskAdapter extends ArrayAdapter<Task> {
//Define FireBase instance variables
private DatabaseReference mTaskDatabaseReference;
private FirebaseDatabase mFirebaseDatabase;
/**
* Create a new {#link TaskAdapter} object.
*
* #param context is the current context (i.e. Activity) that the adapter is being created in.
* #param tasks is the list of {#link Task}s to be displayed.
*/
public TaskAdapter(Context context, ArrayList<Task> tasks) {
super(context, 0, tasks);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if an existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.task_item, parent, false);
}
// Get the {#link Task} object located at this position in the list
final Task currentTask = getItem(position);
// Locate the TextView in the task_item.xml layout with the ID task_title.
final TextView titleTextView = (TextView) listItemView.findViewById(R.id.task_title);
// Get the task's title from the currentTask object and set it in the text view
titleTextView.setText(currentTask.getTitle());
//If the task is completed - title Strikethrough
titleTextView.setBackgroundResource(strikeCompleted(currentTask.getCompleted()));
//Initialize the check box and check it if the task was completed.
CheckBox checkBox = (CheckBox) listItemView.findViewById(R.id.check_box);
checkBox.setOnCheckedChangeListener(null);
checkBox.setChecked(currentTask.getCompleted());
//Initialize the creation date TextView in the task_item.xml layout with the ID creation_date
TextView creationDateTextView = (TextView) listItemView.findViewById(R.id.creation_date);
//Get the task's creation date from the currentTask object and set it in the text view
creationDateTextView.setText(currentTask.getCreationDate());
// Initialize Firebase DB
mFirebaseDatabase = FirebaseDatabase.getInstance();
//Get the task DB reference to edit task completion status
// Find the CheckBox in the task_item.xml layout with the ID check_box.
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
mTaskDatabaseReference=mFirebaseDatabase.getReference()
.child("users").child(MainActivity.getCurrentUserId())
.child(MainActivity.getCurrentTaskListId()).child("tasks").child(currentTask.getId());
if (isChecked) {
titleTextView.setBackgroundResource(R.drawable.strike_through);
mTaskDatabaseReference.child("completed").setValue(true);
} else {
titleTextView.setBackgroundResource(0);
mTaskDatabaseReference.child("completed").setValue(false);
}
}
}
);
// Return the whole list item layout (containing 1 text view and 1 checkbox) so that it can be shown in the ListView.
return listItemView;
}
private int strikeCompleted(boolean completed){
if (completed){
return R.drawable.strike_through;
}
else{
return 0;
}
}
}
After trying the several recommended workarounds (like here) for ListView rows containing a CheckBox without any success, I'd like to suggest a different approach:
Use another, transparent View which covers the whole row except for a small area around the CheckBox. Let this View have an OnClickListener which triggers the opening of the TaskInfoFragment.
Ideally one would use an interface so the TaskAdapter could pass the clicked Task to the TaskActivity which in turn would show the Fragment.
Several hours later... (#Guy, your hint that you "tried deleting all checkbox related code and xml, and the regular click problem persisted" made me exchange one component after another until I had it narrowed down to the row xml) I found the reason why the ListView's OnItemClickListener in TaskActivity does not fire. The root ConstraintLayout of the Task list has an attribute which the root of the TaskList list does not have: android:longClickable="true"
Removing this attribute makes the ListView behave normally.

Android: How can I make a listview wait for a variable to fill before setting?

So I have a movie trivia game that I am building. The problem I am running into is on the main user profile page I set 3 listviews. One for games where it is your turn, one for games that are waiting for your opponent, and one for completed games. These list views make calls to Parse.com to fetch the game object. In Order to fetch this info from Parse I need to provide my query with a Facebook user id. My code calls Facebook to get the ID, but the listview adapters run about 5 milliseconds before the call to Facebook returns the ID. When the user refreshes the page, the lists load properly, but when first running the app they are blank. Here is the user profile activity code:
public class UserProfileActivity extends AppCompatActivity {
ParseLogic mPl;
private WfoAdapter wfoAdapter;
private WoyAdapter woyAdapter;
private CompletedGameAdapter completedGameAdapter;
private TicketSystem mTicketsSytem;
String mMyFbId;
String mMyFbName;
int mTickets;
ListView mWfoListView;
ListView mWoyListView;
ListView mCompletedGameListView;
TextView mmTicketNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTicketsSytem = new TicketSystem();
mTickets = mTicketsSytem.getTickets();
setContentView(R.layout.activity_user_profile);
new getFbDeets().execute(); //This is where the async task is called
mPl = new ParseLogic();
mWoyListView = (ListView)findViewById(R.id.waitingForYouListView);
mWfoListView = (ListView)findViewById(R.id.waitingForOpponentListView);
mCompletedGameListView = (ListView)findViewById(R.id.completedGameListView);
mmTicketNumber = (TextView)findViewById(R.id.numberOfTickets);
mmTicketNumber.setText(String.valueOf(mTickets));
FaceBookFriends.getFaceBookFriends();
//Testing start game remove when building rest of page
Button button = (Button)findViewById(R.id.startNewGame);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UserProfileActivity.this, GameStart.class);
startActivity(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
mTickets = mTicketsSytem.getTickets();
mmTicketNumber.setText(String.valueOf(mTickets));
populateWoyListView();
populateWfoListView();
populateCompleteListView();
}
#Override
public void onBackPressed(){}
#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.
//create the logout button in action bar
switch (item.getItemId()){
case R.id.logoutButton:
ParseUser.logOut();
ParseUser currentUser = ParseUser.getCurrentUser(); // this will now be null
Intent intent = new Intent(UserProfileActivity.this, WelcomeActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
public void populateUI() {
populateWoyListView();
populateWfoListView();
populateCompleteListView();
mWoyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String goTV = ((TextView) view.findViewById(R.id.gameObjectHiddenTextView)).getText().toString();
String score = ((TextView) view.findViewById(R.id.woyScoreNumber)).getText().toString();
Log.v("Clicked Object Id ", goTV);
Intent intent = new Intent(UserProfileActivity.this, AreYouReady.class);
intent.putExtra("Score", score);
intent.putExtra("Object Id", goTV);
startActivity(intent);
}
});
}
private void populateWoyListView() {
//mMfbId is the variable set by the facebook call
woyAdapter = new WoyAdapter(this ,mMyFbId);
woyAdapter.loadObjects();
mWoyListView.setAdapter(woyAdapter);
}
private void populateWfoListView() {
wfoAdapter = new WfoAdapter(this);
wfoAdapter.loadObjects();
mWfoListView.setAdapter(wfoAdapter);
}
private void populateCompleteListView() {
completedGameAdapter = new CompletedGameAdapter(this, mMyFbId);
completedGameAdapter.loadObjects();
mCompletedGameListView.setAdapter(completedGameAdapter);
}
protected class getFbDeets extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
mMyFbId = FaceBookFriends.getMyFbId();
mMyFbName = FaceBookFriends.getMyFbName();
Log.v("getFbDeets() ", "Is Running");
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
populateUI();
}
}
}
This is the completed gave adapter:
/**
* Created by Tom Schinler on 9/23/2015.
*/
public class CompletedGameAdapter extends ParseQueryAdapter<Game> {
String mWinnerScore;
String mWinnerName;
String mLoserScore;
String mLoserName;
String mFbName;
public CompletedGameAdapter(Context context, final String myFbId) {
super(context, new ParseQueryAdapter.QueryFactory<Game>() {
public ParseQuery<Game> create() {
ParseQuery<Game> queryCreatedBy = new ParseQuery<Game>("Game");
queryCreatedBy.whereEqualTo("Created_By", ParseUser.getCurrentUser());
ParseQuery<Game> queryOppOf = new ParseQuery<Game>("Game");
queryOppOf.whereEqualTo("Opponent_Id", myFbId);
ParseQuery<Game> query = ParseQuery.or(Arrays.asList(queryCreatedBy, queryOppOf));
query.whereNotEqualTo("Creator_Score", "");
query.whereNotEqualTo("Opponent_Score", "");
query.orderByDescending("updatedAt");
query.setLimit(4);
return query;
}
});
}
#Override
public View getItemView(Game game, View view, ViewGroup parent) {
if (view == null) {
view = View.inflate(getContext(), R.layout.completed_game_layout, null);
}
super.getItemView(game, view, parent);
mFbName = FaceBookFriends.getMyFbName();
TextView winOrLose = (TextView)view.findViewById(R.id.winOrLose);
int oppScore = Integer.parseInt(game.getOpponentScore());
int creatScore = Integer.parseInt(game.getCreatorScore());
if(oppScore > creatScore){
mWinnerScore = String.valueOf(oppScore);
mWinnerName = game.getOpponentName();
mLoserScore = String.valueOf(creatScore);
mLoserName = game.getCreatorFbName();
}
else {
mWinnerScore = String.valueOf(creatScore);
mWinnerName = game.getCreatorFbName();
mLoserScore = String.valueOf(oppScore);
mLoserName = game.getOpponentName();
}
TextView winnerName = (TextView)view.findViewById(R.id.winnerName);
winnerName.setText(mWinnerName);
TextView winnerScore = (TextView)view.findViewById(R.id.winnerScore);
winnerScore.setText(mWinnerScore);
TextView loserName = (TextView)view.findViewById(R.id.loserName);
loserName.setText(mLoserName);
TextView loserScore = (TextView)view.findViewById(R.id.loserScore);
loserScore.setText(mLoserScore);
if(mWinnerName.equals(mFbName)){
view.setBackgroundColor(Color.GREEN);
winOrLose.setText("WIN!!");
}
else {
view.setBackgroundColor(Color.RED);
winOrLose.setText("LOSER!!");
}
return view;
}
}
and here is the adapter that sets the listview for games waiting on the user:
/**
* Created by Tom Schinler on 9/22/2015.
*/
public class WoyAdapter extends ParseQueryAdapter<Game>{
public WoyAdapter(Context context, final String fbId) {
super(context, new ParseQueryAdapter.QueryFactory<Game>() {
public ParseQuery<Game> create() {
//Log.v("var fbid is ", fbId);
ParseQuery query = new ParseQuery("Game");
query.whereEqualTo("Opponent_Id", fbId);
query.whereEqualTo("Opponent_Score", "");
query.orderByDescending("updatedAt");
query.setLimit(4);
return query;
}
});
}
#Override
public View getItemView(Game game, View view, ViewGroup parent) {
if (view == null) {
view = View.inflate(getContext(), R.layout.waiting_on_you_layout, null);
Log.v("WOY is this", "running");
}
super.getItemView(game, view, parent);
ProfilePictureView friendPic = (ProfilePictureView) view.findViewById(R.id.woyFbPic);
String friendId = game.getCreatorId();
if(friendId != null){
friendPic.setProfileId(friendId);
}
TextView oppName = (TextView)view.findViewById(R.id.woyNameText);
oppName.setText(game.getCreatorFbName());
TextView oppScore = (TextView)view.findViewById(R.id.woyScoreNumber);
oppScore.setText(game.getCreatorScore());
TextView GOTV = (TextView)view.findViewById(R.id.gameObjectHiddenTextView);
GOTV.setText(game.getObjectId());
return view;
}
}
I set mMyFbId with a Facebook method like this:
mMyFbId = FaceBookFriends.getMyFbId();
but it return about 1 second after the code runs to build the lists views, since they do not have the variable, they populate nothing. Please help.

How to continue typing in edittext in android after poping popupwindow

//imports
public class MainActivity extends Activity implements OnCheckedChangeListener
{
int count=0,ints......;
TextView textviews...;
int itemCode,month;
ArrayList<String> Name = new ArrayList<String>();
AlertDialog alertDialog ;
SharedPreferences sp;
EditText EtItemCode;
Editor editor ;
RadioButton RbForItemCode,RbForItemName;
RadioGroup RgForItemVsName;
PopupWindow popupWindowItems;
String popUpItems[];
ProgressDialog pDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
//shared prefs
sp = this.getSharedPreferences("MySharedPrefsFile", Context.MODE_PRIVATE);
editor = sp.edit();
intForShardPref= sp.getInt("NEW_INSTALLATION",1); // getting Integer(1 is for no)
if(intForShardPref==1){
Intent intent = new Intent(this,Verify.class);
startActivityForResult(intent, 1);
}
else{
//do nothing
}
EtItemCode.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
ToCheckItemCodeOfEdittext = EtItemCode.getEditableText().toString();
DatabaseHandler db=new DatabaseHandler(MainActivity.this);
List<Item> Items = db.getAllItemWithSubString(ToCheckItemCodeOfEdittext,itemNumberOrNameSelectedInRadioButtonOptions);
if(EtItemCode.length()>2){
if(EtItemCode.length()>3||flagForPopUpWindow>EtItemCode.length())
popupWindowItems.dismiss();
Name.clear();
for (Item cn : Items) {
if(RbForItemCode.isChecked()==true){
Name.add(Integer.toString(cn.getItemNumber()));
}
else{
Name.add(cn.getName());
}
}
popUpItems = new String[Name.size()];
Name.toArray(popUpItems);
popupWindowItems = popupWindowItems();
***popupWindowItems.setFocusable(false);***
popupWindowItems.showAsDropDown(findViewById(R.id.et_item_code), -5, 0);
}
else{
if(flagForPopUpWindow==3&&EtItemCode.length()==2)
popupWindowItems.dismiss();
}
flagForPopUpWindow=EtItemCode.length();
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
});
}
private void init() {
// TODO Auto-generated method stub
//some code
}
public PopupWindow popupWindowItems() {
// initialize a pop up window type
PopupWindow popupWindow = new PopupWindow(this);
// the drop down list is a list view
ListView listViewItems = new ListView(this);
// set our adapter and pass our pop up window contents
ArrayAdapter<String> adapter=new ArrayAdapter<String>(
this, //context for activity
android.R.layout.simple_list_item_1, //layout used
Name){ //Items to be displayed
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// setting the ID and text for every items in the list
String item = getItem(position);
String text = item.toString();
// visual settings for the list item
TextView listItem = new TextView(MainActivity.this);
listItem.setText(text);
//listItem.setTag(id);
listItem.setTextSize(22);
listItem.setPadding(10, 10, 10, 10);
listItem.setTextColor(Color.WHITE);
return listItem;
}
};
listViewItems.setAdapter(adapter);
// set the item click listener
listViewItems.setOnItemClickListener(new ItemsDropdownOnItemClickListener());
// some other visual settings
//popupWindow.setFocusable(true);
popupWindow.setWidth(EtItemCode.getWidth());
//popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
Rect r = new Rect();
View rootview = this.getWindow().getDecorView(); // this = activity
rootview.getWindowVisibleDisplayFrame(r);
popupWindow.setHeight(r.height()-3*EtItemCode.getHeight());
// set the list view as pop up window content
popupWindow.setContentView(listViewItems);
return popupWindow;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater blowUp = getMenuInflater();
blowUp.inflate(R.menu.cool_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.phone_number:
Intent p = new Intent(MainActivity.this,PhoneNumber.class);
startActivity(p);
break;
case R.id.exit:
finish();
break;
}
return false;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
//some code
}
class LoadDataBase extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("DataBase Loading..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
DatabaseHandler db = new DatabaseHandler(MainActivity.this);
Log.d("Reading: ", "Reading all Items..");
List<Item> Items = db.getAllItem();
//some code
//DatabaseHandler db1 = new DatabaseHandler(this);
count= db.getItemCount();
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
public class ItemsDropdownOnItemClickListener implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
Toast.makeText(MainActivity.this, "Item is: ", Toast.LENGTH_SHORT).show();
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(EtItemCode.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
// dismiss the pop up
popupWindowItems.dismiss();
// get the text and set it as the button text
String selectedItemText = ((TextView) v).getText().toString();
Toast.makeText(MainActivity.this, "Item is: " + selectedItemText, Toast.LENGTH_SHORT).show();
DatabaseHandler db =new DatabaseHandler(MainActivity.this);
Item item= new Item();
if(RbForItemCode.isChecked()==true){
item = db.getItem(Integer.valueOf(selectedItemText));
}
else if(RbForItemName.isChecked()==true){
item = db.getItem(selectedItemText);
}
itemCode=item.getItemNumber();
}
}
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
// TODO Auto-generated method stub
if(RbForItemCode.isChecked()==true){
itemNumberOrNameSelectedInRadioButtonOptions="id";
//some code
}
}
else if(RbForItemName.isChecked()==true){
//some code
}
}
}
This code is working fine on my phone galaxy note 2(custom rom of note 4.. Android 4.4.4).By fine I mean I can type in edittext and popupwidow shows up after 3rd text(because of condition I have put) and I can select an option from the popupwindow. When I try to run the code on any other phone like galaxy grand then callback to ItemsDropdownOnItemClickListener is not registered and I can only scroll the popupwindow and keep on typing in edittext but cannot select any of the options in the popupwindow. If I set popupWindowItems.setFocusable(false) to true i.e popupWindowItems.setFocusable(true), and then as soon as I type 3rd letter in edittext,edittext looses focus and popwindow gains it. Now I can select anything.. But now I cannot continue to type in edittext.I have to manually select edittext and type.
Now I want that after tying 3rd word in edittext a popupwindow should appear(which currently is appearing) and edittext doesn't loose focus(so that i can continue typing).. Further if I select anything from popupwindow ,ItemsDropdownOnItemClickListener should be called which is currently being not called in other phones when popupWindowItems.setFocusable(false);
I am doing this to load data from sqlite database and show in popupwindow once the user types 3rd word. Any suggestion is recommended
Edit: Problem solved. Now using AutoComplete TextView

How do I make my ArrayList<ColorSaver> persistent in android?

I have the ArrayList...
ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
and I want it so that when the user closes the app or leaves the app, all the ColorSaver objects in the ArrayList will be there when the user reopens the app. I would prefer to use the SharedPreferences but I can't do that because the list is a custom object...
I have looked around and found out that I can do a serializable but I tried that and failed horribly, so if somebody could guide me through the serializable deal that would be great. Oh and where do I put the code, like in onCreate() in my mainActivity or in the activity that is displaying the ArrayList
My mainActivity class
public class MainActivity extends Activity {
ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
private static final String TAG = "Main Activity";
public static final String PREFS_NAME = "MyPrefsFile";
final Intent intent = new Intent();
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
final NumberPicker rednp = (NumberPicker) findViewById(R.id.redNumberPicker1);
final NumberPicker bluenp = (NumberPicker) findViewById(R.id.blueNumberPicker);
final NumberPicker greennp = (NumberPicker) findViewById(R.id.greenNumberPicker);
switch(item.getItemId())
{
case R.id.save:
Log.i(TAG, "Save item clicked!");
Intent intent = new Intent(this, SaveActivity.class);
intent.putExtra("RedValue", rednp.getValue());
intent.putExtra("BlueValue", bluenp.getValue());
intent.putExtra("GreenValue", greennp.getValue());
intent.putExtra("temparray", tempList);
startActivity(intent);
return true;
case R.id.recall:
Log.i(TAG, "Recall item clicked!");
Intent intent2 = new Intent(this, RecallActivity.class);
intent2.putExtra("temparray", tempList);
startActivity(intent2);
return true;
default:
return super.onOptionsItemSelected(item);
}//End Switch
}
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
Bundle extras = getIntent().getExtras();
final SurfaceView sView = (SurfaceView) findViewById(R.id.surfaceView1);
final NumberPicker np = (NumberPicker) findViewById(R.id.redNumberPicker1);
np.setMaxValue(255);
np.setMinValue(0);
final NumberPicker np2 = (NumberPicker) findViewById(R.id.greenNumberPicker);
np2.setMaxValue(255);
np2.setMinValue(0);
final NumberPicker np3 = (NumberPicker) findViewById(R.id.blueNumberPicker);
np3.setMaxValue(255);
np3.setMinValue(0);
if( extras != null )
{
np.setValue(extras.getInt("savedRValue"));
//np.setValue(intent.getIntExtra("savedRValue", 255));
np2.setValue(extras.getInt("savedGValue"));
//np2.setValue(intent.getIntExtra("savedGValue", 255));
np3.setValue(extras.getInt("savedBValue"));
//np3.setValue(intent.getIntExtra("savedBValue", 255));
tempList = (ArrayList<ColorSaver>) extras.getSerializable("array");
sView.setBackgroundColor(Color.argb(255, np.getValue(), np2.getValue(), np3.getValue()));
}
else
{
Log.i(TAG, "I just don't get it...WTF");
}
np.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
//GREEN NUMBERPICKER LISTENER
np2.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
np3.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
}//End onCreate()
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}//END onCreateOptionsMenu()
}//END CLASS
My saveActivity, where the user saves their color combo to the ArrayList...
public class SaveActivity extends Activity implements Serializable {
private static final String TAG = "Save Activity";
public ArrayList<ColorSaver> savedColors = new ArrayList<ColorSaver>();
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save);
// Show the Up button in the action bar.
setupActionBar();
Bundle extras = getIntent().getExtras();
final Intent intent1 = new Intent(this, MainActivity.class);
Button saveButton = (Button) findViewById(R.id.saveButton1);
final EditText nameField = (EditText) findViewById(R.id.colorNameField);
//final Intent intent = new Intent();
savedColors = (ArrayList<ColorSaver>) extras.getSerializable("temparray");
//Making sure the savedColors arrayList has something in it.
if( savedColors.isEmpty() )
{
ColorSaver temp = new ColorSaver("Rockies Purple", 180, 80, 255);
savedColors.add(temp);
}
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Bundle extras = getIntent().getExtras();
int redcolor, greencolor, bluecolor;
redcolor = extras.getInt("RedValue");
greencolor = extras.getInt("GreenValue");
bluecolor = extras.getInt("BlueValue");
String colorName = nameField.getText().toString();
//Build the new color and add it to the arrayList
ColorSaver saver = new ColorSaver(colorName, redcolor, greencolor, bluecolor);
savedColors.add(saver);
intent1.putExtra("array", savedColors);
Log.i(TAG, savedColors.get(savedColors.size()-1).getColorName());
startActivity(intent1);
}
});
}//END OnCreate()
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.save, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}//END CLASS
My recallActivity where the user recalls their color combos...
public class RecallActivity extends SaveActivity {
private static final String TAG = "Recall Activity";
ArrayList<ColorSaver> colorsArray = new ArrayList<ColorSaver>();
SaveActivity sActivity = new SaveActivity();
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recall);
// Show the Up button in the action bar.
setupActionBar();
final Intent intent1 = new Intent(this, MainActivity.class);
final Spinner colorList = (Spinner) findViewById(R.id.colorsSpinner);
Button grabButton = (Button) findViewById(R.id.grabButton);
Bundle extras = getIntent().getExtras();
colorsArray = (ArrayList<ColorSaver>) extras.getSerializable("temparray");
//Load the spinner with the saved colors
addColorNames(colorsArray);
grabButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
ColorSaver selectedItem = (ColorSaver) colorList.getSelectedItem();
int redValue, greenValue, blueValue;
String name;
redValue = selectedItem.getRedValue();
greenValue = selectedItem.getGreenValue();
blueValue = selectedItem.getBlueValue();
name = selectedItem.getColorName();
intent1.putExtra("savedRValue", redValue);
intent1.putExtra("savedGValue", greenValue);
intent1.putExtra("savedBValue", blueValue);
intent1.putExtra("savedName", name);
intent1.putExtra("array", colorsArray);
startActivity(intent1);
}//END onClick
});
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.recall, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}// END onOptionsItemSelected(MenuItem item)
public void addColorNames(ArrayList<ColorSaver> colorsArray1)
{
colorsArray = colorsArray1;
//if( !colorsArray.isEmpty() )
//{
Spinner colorsSpinner = (Spinner) findViewById(R.id.colorsSpinner);
ArrayAdapter<ColorSaver> dataAdapter
= new ArrayAdapter<ColorSaver>
(RecallActivity.this, android.R.layout.simple_spinner_item, colorsArray);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
colorsSpinner.setAdapter(dataAdapter);
Log.i(TAG, savedColors.get(savedColors.size() - 1).toString());
//}
//else
//{
// Log.i(TAG, "colorsSpinner came out to be null....WTF???");
//}
}//End addColorNames()
}//END CLASS
I am greatful of any help!
Take a look at Android's Parcelable implementation.
So, I'm just guessing on your ColorSaver class since it wasn't posted, but you would implement it the following way:
ColorSaver.java
public class ColorSaver implements Parcelable {
private String mName;
private int mRed;
private int mGreen;
private int mBlue;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(mName);
out.writeInt(mRed);
out.writeInt(mGreen);
out.writeInt(mBlue);
}
public static final Parcelable.Creator<ColorSaver> CREATOR
= new Parcelable.Creator<ColorSaver>() {
public ColorSaver createFromParcel(Parcel in) {
return new ColorSaver(in);
}
public ColorSaver[] newArray(int size) {
return new ColorSaver[size];
}
};
private ColorSaver(Parcel in) {
mName = in.readString();
mRed = in.readInt();
mGreen = in.readInt();
mBlue = in.readInt();
}
}
MyActivity.java
public class MyActivity extends Activity {
private static final String COLOR_SAVER_LIST = "com.example.android.ColorSaverList";
private List<ColorSaver> colorSaverList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null && savedInstanceState.containsKey(COLOR_SAVER_LIST)) {
colorSaverList = new ArrayList<ColorSaver>();
colorSaverList = savedInstanceState.getParcelableArrayList(COLOR_SAVER_LIST);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(COLOR_SAVER_LIST, colorSaverList);
}
}

Progress Dialog between to activites/intents

I am trying to pass information form one Activity to the other and while doing that I would like to have a progress dialog show. Mainly when the second activity is processing the information. I have been reading up and the proper way of doing it seems to be asynctask. Or is there another way of doing it?
Here is my code: Activity one
public class SearchActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
final EditText edittext = (EditText) findViewById(R.id.edittext);
edittext.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN)
&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
String query = edittext.getText().toString();
// gets the text and makes sure its a string
Intent intent = new Intent(SearchActivity.this,
DissertationActivity.class);
intent.putExtra("query1", query);
startActivity(intent);
return true;
}
return false;
}
});
final Button button = (Button) findViewById(R.id.searchButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String query = edittext.getText().toString();
// gets the text and makes sure its a string
Intent intent = new Intent(SearchActivity.this,
DissertationActivity.class);
intent.putExtra("query1", query);
startActivity(intent);
}
});
}
}
This is the Second activity:
public class DissertationActivity extends ListActivity {
/** Called when the activity is first created. */
public ArrayList<String> book_Array = new ArrayList<String>();
ArrayAdapter<String> adapter;
String href = "";
String href1 = "";
String search_Word = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
search_Word = extras.getString("query1");
adapter = new ArrayAdapter<String>(this, R.layout.list_item_1,
book_Array);
setListAdapter(adapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
try {
Document doc = null;
Document guestLink = null;
guestLink = Jsoup.connect("https://aulib.abdn.ac.uk:443/F").get();
Element link = guestLink.select("p > a").first();
href1 = link.attr("href");
href = href1.substring(0, href1.length() - 2); // removes -0 from
// the
// href_Array.add(href); //adds href to the array because string
// wont add to the public var.
doc = Jsoup.connect(
href + "&request=" + search_Word
+ "&find_code=WRD&adjacent=N&x=0&y=0").get();
// System.out.println(doc);
Elements headings = doc.select("td:eq(3)");
// System.out.println(headings);
for (Element heading : headings) {
// System.out.println(heading.text());
String j = heading.text();
book_Array.add(j);
}
} catch (IOException e) {
e.printStackTrace();
}
book_Array.remove(0);
adapter.notifyDataSetChanged();
book_Array.remove(1);
adapter.notifyDataSetChanged();
book_Array.remove(2);
adapter.notifyDataSetChanged();
book_Array.remove("Search");
adapter.notifyDataSetChanged();
book_Array.remove(" | ");
adapter.notifyDataSetChanged();
book_Array.remove(0);
adapter.notifyDataSetChanged();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
// Context context = getApplicationContext();
int query = position;
// String text = book_Array.get(position);
// int duration = Toast.LENGTH_SHORT;
// Toast toast = Toast.makeText(context,
// String.valueOf(position), //shows the postion in the array
// list
// duration);
// toast.show();
Intent intent = new Intent(DissertationActivity.this,
FullDetailsActivity.class);
intent.putExtra("href", href);
intent.putExtra("query1", (int) query);
intent.putExtra("search_Word", search_Word);
startActivity(intent);
}
});
}
}
I tried using:
this.pd = ProgressDialog.show(this, "Working..", "Downloading Data...",
true, false);
But that didn't work.
How would I go about, so that it displays a progress dialog in between the activities?
Thanks for your help!
Calling ProgressDialog.show will block the UI thread. So the progress dialog/bar will not show up until the method has returned. So we can create a thread for our method to run within it. This will avoid blocking the main UI Thread.
Sample code -
ProgressDialog spinnerDialog = ProgressDialog.show(
Placeholder.this, "","Your text ", true);
new Thread(new Runnable() {
public void run() {
//your method code
return;
}
}).start();

Categories

Resources