I have a listview with two lines of items: user ID and username. How to retrieve only user ID from the listview when one of the rows is clicked?
public class MainActivity extends AppCompatActivity {
private DatabaseReference mUsers;
String getValue = null;
ListView lvUsers = (ListView) findViewById(R.id.lvUsers);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsers = FirebaseDatabase.getInstance.getReference().child(Constants.FIREBASE_USERS);
FirebaseListAdapter<Users> adapter = new FirebaseListAdapter<Users>(
this, Users.class, android.R.layout.two_line_list_item, mUsers
) {
#Override
protected void populateView(View v, Users user, int pos) {
((TextView)v.findViewById(android.R.id.text1)).setText(user.getUserID());
((TextView)v.findViewById(android.R.id.text2)).setText(user.getUsername());
}
};
lvUsers.setAdapter(adapter);
setupListViewMenu();
}
private void setupListViewMenu() {
lvUsers.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
// How to retrieve only User ID from here?
getValue = ((TextView)view).getText().toString();
return true;
}
});
}
}
The listview data is from Firebase database. Is retrieving using for loop the only way? I have to loop through two dimensional array? Thanks
Could you please try the code below?
getValue = ((TextView)item.findViewById(android.R.id.text2)).getText().toString();
I believe that android.R.id.text2 is one of the childs of item(View received in the clickListener)
But need to test... Hope it works
Related
How can I make this custom array list clickable to go to the others activities because I tried the intents but it doesn't work
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Names> namesArrayList = new ArrayList<Names>();
namesArrayList.add(new Names(R.drawable.call_centre, "Call Centre"));
namesArrayList.add(new Names(R.drawable.soco_academy_icon, "Academy"));
NamesAdapter NamesListAdapter = new NamesAdapter(this, namesArrayList);
ListView list = (ListView) findViewById(R.id.List_View);
list.setAdapter(NamesListAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
}
In onItemClick() you can determine which item was clicked by doing this:
Name selectedName = NamesListAdapter.getItem(position);
Then you can do whatever you want with that.
I'm trying to populate my ListView with User objects from Firebase Database. I've seen some people use RecyclerView but I cannot get RecyclerView to work on my Android Studio (maybe i'm using incompatible dependencies).
Anyway here is my code:
// necessary imports
public class List extends AppCompatActivity {
ListView usersList;
private DatabaseReference userDatabase;
ArrayList<String> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
usersList = (ListView) findViewById(R.id.list_users);
userDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
}
#Override
protected void onStart() {
super.onStart();
// Populate ArrayAdapter with User objects from Firebase Database.
ArrayAdapter<Users> Adapter = new ArrayAdapter<Users>(this, Users.class, android.R.layout.simple_expandable_list_item_1, userDatabase){
// Populate here, don't know what to do.
};
usersList.setAdapter(Adapter);
usersList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Users.connectTo = list.get(i);
Intent chatActivity = new Intent(List.this, ChatActivity.class);
startActivity(chatActivity);
}
});
}
}
I know my ArrayList takes a String at the beginning, I will change that to Users.
ArrayAdapter parameters are not working, despite looking at the docs and it telling me this way.
Not sure how to properly implement RecyclerView
Not got much experience with Android Studio/Java.
hello i need some help ... i write this code but i am little confused when i add book to my fav it store to fav when i click on un fav there in fav list the book are still there in that activity until i don't close the activity when i reopen that fav activity the book are removed from there i want to add code that can refresh by self at that time when i un fav the book ... please help me out
public class Favrt extends AppCompatActivity implements AdapterView.OnItemClickListener {
ListView viewF;
Books_Adapter fav_adapter;
String[] name, links, author;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favrt);
fetch_fav();
fav_adapter = new Books_Adapter(this, name, links, author);
viewF = (ListView) findViewById(R.id.favView);
viewF.setAdapter(fav_adapter);
viewF.setOnItemClickListener(this);
}
public void fetch_fav(){
SQLiteDatabase database = openOrCreateDatabase("Pdf_books",MODE_PRIVATE,null);
Cursor db_cursor = database.rawQuery("select * from favourite", null);
name = new String[db_cursor.getCount()];
links = new String[db_cursor.getCount()];
author = new String[db_cursor.getCount()];
int i =0;
if (db_cursor.moveToLast()){
do {
name[i] = db_cursor.getString(db_cursor.getColumnIndex("name"));
links[i] = db_cursor.getString(db_cursor.getColumnIndex("links"));
author[i] = db_cursor.getString(db_cursor.getColumnIndex("author"));
i++;
}while (db_cursor.moveToPrevious());
}
database.close();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent web = new Intent(this, web_activity.class);
web.putExtra("url", links[position]);
startActivity(web);
}
#Override
public void onContentChanged() {
super.onContentChanged();
View empty = findViewById(R.id.empty);
ListView list = (ListView) findViewById(R.id.favView);
list.setEmptyView(empty);
}
}
Try fav_adapter.notifyDataSetChanged() after changing your list items (in this case, when your favorites are changed).
You have to update adapter. to do so fav_adapter.notifyDataSetChanged(). which will make changes to listview.
make function in activity where you do such things like remove from db and update list data.
I have a spinner(dynamic) which contains a list of IDs' and each ID has a product value. When I click on a particular ID, the value needs to be changed associated with that ID.
I have a listView which contains a table. The table consists of product names, product price and product information. When I change the ID, the table information(listview) changes but not the product value (this is a textview and not part of listview).
I'm passing the product value using an intent from a different class. How do I make it such that when I change an item in the spinner, the product value gets changed?
/**
* Listener for flight leg selection of spinner
*/
private OnItemSelectedListener onFlightLegSelectedListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
new ShowSalesReportAsyncTask(flightLegMap.get(flightLegs.get(position)), position).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// Do nothing
}
};
This is my onCreate where I am getting the product value.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sales_report);
salesReportListView = (ListView) findViewById(R.id.sales_report_listview);
spinnerFlightLegs = (Spinner) findViewById(R.id.flight_legs);
noTransactionsWarning = (TextView) findViewById(R.id.no_transactions_warning);
totalValueNetAmount = (TextView) findViewById(R.id.total_currency_net_value);
String salesRevenue = TOTAL_VALUE;
Bundle extras = getIntent().getExtras();
if (extras != null) {
salesRevenue = extras.getString(TOTAL_VALUE);
}
totalValueNetAmount.setText(salesRevenue);
flightLegMap = getAllFlightLegs();
if (!flightLegMap.isEmpty()) {
setFlightLegSpinner();
btnShare.setEnabled(true);
} else {
btnShare.setEnabled(false);
}
spinnerFlightLegs.setOnItemSelectedListener(onFlightLegSelectedListener);
salesReportListAdapter = new SalesReportListAdapter(this);
salesReportListView.setAdapter(salesReportListAdapter);
This is the Async task that I use to populate the view with data.
private class ShowSalesReportAsyncTask extends AsyncTask> {
private String flightLeg;
private int position;
public ShowSalesReportAsyncTask(String flightLeg, int position) {
this.flightLeg = flightLeg;
this.position = position;
}
#Override
protected List<Purchase> doInBackground(Void... params) {
List<Purchase> rows = new ArrayList<Purchase>();
PurchaseDao purchaseDao = new PurchaseDao(flightLeg, MIUtils.getShardDatabaseIndexMap());
LOG.debug(TAG + "Getting report for : {}", flightLeg);
// double netTotal = SalesUtil.calculateFlightTransactionTotal(purchaseDao, refundDao,());
return purchaseDao.getSuccessfulTransactions();
}
#Override
protected void onPostExecute(List<Purchase> result) {
super.onPostExecute(result);
if (!result.isEmpty()) {
noTransactionsWarning.setVisibility(View.GONE);
} else {
noTransactionsWarning.setVisibility(View.VISIBLE);
}
salesReportListAdapter.setRowsAndFlightDetails(result, flightLegMap.get(flightLegs.get(position)),
spinnerFlightLegs.getSelectedItem().toString());
totalValueNetAmount.setText((int) netTotal);
}
}
The item that needs to be changed is "EUR". SPINNER TABLE IMAGE
Add the code to register the listener in the onStart() method of the activity. This should work.
This should better answer your question - How to keep onItemSelected from firing off on a newly instantiated Spinner?
Well, this is the setting:
Code for the activity
public class Users_List extends Activity {
private ArrayList<Users> users;
private ListView lvusers;
private int user_selected;
private DB db;
private ListAdapter adaptador;
private static final int NEW_USER = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.users_list);
DB db = new DB(this);
users = db.getAllUsers();
lvusers = (ListView) findViewById(R.id.listview);
adaptador = new AdaptadorUsersList(this, users);
lvusers.setAdapter(adaptador);
lvusers.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
registerForContextMenu(lvusers);
final Button new_user = (Button) findViewById(R.id.btn_new_user);
nuevo_socio.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Users_List.this,
User_Form.class);
startActivityForResult(intent, NEW_USER);
}
});
lvusers.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> a, View view, int position, long id) {
//HERE...LONG ID IS ALWAYS ZERO, WHY???
Log.d("Selected User--------", "---------------------"+id+"--------");
openContextMenu(lvusers);
return true;
}
});
}
//Here the codes continues....
}
I readed that the long id param. on onItemLongClick is actually the id of the row that was clicked right? so, what's wrong here that the id is returning always "0" as value on logcat?
Thank you!
the ID of the onItemClickListener or onItemLongClickListner is the same as the ID of the row if the adapter extends CursorAdapter or simpleCursorAdapter because the Cursor will take care of putting the Item's ID to the Long ID.
Bare in mind that your ID column or the primary key field should have the name of "_id". here is an example of how to implement Custom CursorAdapter.
Edit
You can use BaseAdapter as CursorAdapter since from the source code of CursorAdapter it extends the BaseAdapter however you will use getView() to call the bindView() and newView() where these two functions are the main functions of the CursorAdapter
so basically you are doing the CursorAdapter from the scratch refer to this question where they explain it more in details.
hope this answer your question.