I have a custom adapter with a listview. I query the items from SQL Server and display them as a list using my listview. I have item click listener on my list view in order to get the item position.
public void getData() {
String query = "SELECT * FROM Table";
List<Map<String, String>> data = new ArrayList<>();
data = filterData(query);
adapter = new ContactListAdapter(this, data, R.layout.items, from, to);
listView.setAdapter(adapter);
listView.invalidateViews();
listView.setOnItemClickListener((adapterView, view, i, l) -> {
HashMap<String, String> retreive = (HashMap<String, String>) adapterView.getAdapter().getItem(i);
callerID = retreive.get("CallerDetailID");
.
.
});
}
I store the values using hashmap strings in a list as follows.
// filter the contact details from sql server
List<Map<String, String>> filterData(String query) {
List<Map<String, String>> contact_details = new ArrayList<>();
try {
connect = connectionClass.CONN(); // Connect to database
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Map<String, String> datanum = new HashMap<>();
datanum.put("CallerDetailID", rs.getString("CallerID"));
.
.
.
contact_details.add(datanum);
}
} catch (Exception e) {
e.printStackTrace();
}
return contact_details;
}
I am aware that I can get the items to the position by clicking on it (since I already use setOnItemClickListener). But my question here is how can I scroll to the newly added item's position in my list view, without clicking the item?
Once I get the position of the item, I can use one of the following methods in the listview to scroll.
listView.smoothScrollToPosition();
listView.smoothScrollToPosition();
listView.smoothScrollToPositionFromTop();
Is it possible to get the item's to position without clicking on the item in the listview? Any ideas folks.
To achieve the behaviour you need to add a property to scroll listview automatically.
android:transcriptMode="alwaysScroll"
You just have to call notifyDataSetChanged() and your list will be auto scrolled.
Related
I am building a football league management system, I built the user interface using javaFx, I created this class to populate the table using a database.
public class TableHandler {
public static ObservableList<Team> getTeams() {
ObservableList<Team> list = FXCollections.observableArrayList();
DBConnection db;
try {
db = new DBConnection();
String sql = "Select * from teams";
ResultSet result = db.read(sql);
while (result.next()) {
list.add(new Team(result.getInt(1), result.getString(2), result.getString(3), result.getInt(4),
result.getDouble(5)));
}
} catch (Exception e) {
e.getMessage();
}
return list;
}
public static TableView<Team> getTable(ObservableList<Team> list) {
TableView<Team> table;
TableColumn<Team, String> idColumn = new TableColumn<>("ID");
idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
TableColumn<Team, String> nameColumn = new TableColumn<>("Name");
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
TableColumn<Team, String> phoneNumberColumn = new TableColumn<>("phoneNumber");
phoneNumberColumn.setCellValueFactory(new PropertyValueFactory<>("phoneNumber"));
TableColumn<Team, Integer> pointsColumn = new TableColumn<>("Points");
pointsColumn.setCellValueFactory(new PropertyValueFactory<>("points"));
TableColumn<Team, Double> budgetColumn = new TableColumn<>("Budget");
budgetColumn.setCellValueFactory(new PropertyValueFactory<>("budget"));
table = new TableView<>();
table.setItems(list);
table.getColumns().addAll(idColumn, nameColumn, phoneNumberColumn, pointsColumn, budgetColumn);
return table;
}
and I created a button to add teams to the table by the user, what I can't figuer out is how to refresh the table when the user hit the add button, any help would be appriciated.
You don't have to. The very idea of an observable list is that the TableView observes for changes in it and renders the value change accordingly.
The thing you have to make sure of is that you're adding elements to the collection that was actually bound to the TableView and not some other one. You didn't post the code that adds the items, so it's hard to tell, but if you're using getTeams() and then adding to that, then it's wrong (since it's a new ObservableList and not the one bound to the TableView). You should always be using table.getItems().add(...) to add items to a TableView.
I am trying to display contact list in autoCompleteTextView so far I have successfully achieved that but I need to use the contact_id related to name how Should I bind id with name?
I have used hashmap to store the contact list.
here is my code to get contact and add them to hashmap
Cursor cursor_number=getActivity().getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
if(cursor_number!=null){
if (cursor_number.moveToFirst()){
do{
contact_id=cursor_number.getString(cursor_number.getColumnIndex(ContactsContract.Data._ID));
if(Integer.parseInt(cursor_number.getString(cursor_number.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)))>0) {
Cursor cursor_number1 = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID + " = ? ", new String[]{contact_id}, null);
if (cursor_number1 != null) {
while (cursor_number1.moveToNext()) {
String name=cursor_number1.getString(cursor_number1.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
String id=contact_id;
HashMap<String, String> contact_data=new HashMap<String, String>();
contact_data.put(id,name);
}
cursor_number1.close();
}
}
}
while (cursor_number.moveToNext());
cursor_number.close();
}
}
and this is how i'm adding adapter to autoComplete textView
autoCompleteTextView =(AutoCompleteTextView) this.getActivity().findViewById(R.id.act_network_auto_search);
autoCompleteTextView.setThreshold(2);
checkContacts();
Collection<String> collection=contact_data.values();
String[] array= collection.toArray(new String[collection.size()]);
adapter = new ArrayAdapter<String>(getContext(),
android.R.layout.simple_dropdown_item_1line,array);
autoCompleteTextView.setAdapter(adapter);
How should I get the id associated with name
any help would be great!
Update :
LinkedHashMap<String, String> contact_data=new LinkedHashMap<String, String>();
contact_data.put(id,name);
Check this example AutocompleteTextView
If it is compulsary for you to use key valu pair than
I will sugest use LinkedHashMap insted of Hasmap because hashmap do not have ordering.
you can put data in linkedhasmap same as hashmap like follows
LinkedHashMap<String,String> lH = new LinkedHashMap<String,String>();
lH.put(id,name);
while in your auto complete text view do folowing
autoCompleteTextView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View arg1, int pos,
long id) {
String key = (new ArrayList<String>(lH.keySet())).get(pos);
you will have your id in key
}
});
also you can make above efficient by just initializing lH.keySet out of listner
also look at this
http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html
for LinkedHashMap
you can get id from contact_data ,if you are sure the names are uniqe
public String getIdByName(String name) {
for (Entry<String,String> entry : contact_data.entrySet()) {
if (name.equals(value, entry.getValue())) {
return entry.getKey();
}
}
return null;
}
check this answer too
I am currently retrieving data from an online MySQL database and displaying it with in the application, but i have been having trouble formatting it to even a basic standard.
Code Snippet below showing the JSON Objects being retrieved and cycled through, then applied to a list view adapter.
private void showJSON(String response){
String CurrentUser="";
String Benchpress="";
String Squat="";
String Deadlift="";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(ConfigLeaderboard.JSON_ARRAY);
JSONObject leaderboards;
for(int i = 0; i<result.length(); i++) {
leaderboards = result.getJSONObject(i);
CurrentUser = leaderboards.getString(ConfigLeaderboard.KEY_CURRENTUSER);
Benchpress = leaderboards.getString(ConfigLeaderboard.KEY_BENCHPRESS);
Squat = leaderboards.getString(ConfigLeaderboard.KEY_SQUAT);
Deadlift = leaderboards.getString(ConfigLeaderboard.KEY_DEADLIFT);
dataList.add(CurrentUser + " " + Benchpress );
adapter.notifyDataSetChanged();
Log.d("JSONArray length ",result.length() + "");
}
}
catch (JSONException e) {
e.printStackTrace();
}
ListView lv = (ListView) findViewById(R.id.list);
lv.setAdapter(adapter);
ArrayAdapter<String> adapter =new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);
}
#Override
public void onClick(View v) {
getLeaderboardData();
The main thing im really stuck on is actually just obtaining a basic layout where the retrieved data is separated neatly almost like columns. Now for this i understand a custom listview adapter would be required, but would a data model also be required? Given that im retreiving data from Json would this still apply. I just feel so fustrated and stuck
Any help would be much appreciated
Thank you!
The preferred solution is a combination of the following
A custom "row" layout to replace android.R.layout.simple_list_item_1 because that will only get you a single String item, not aligned columns
A simple Java class (commonly known as a POJO), to "bind" this JSON data to that view
An Adapter that extends ArrayAdapter<Foobar> where Foobar is the name of the class from step 2
Now, you could just add tabs to your string data to simulate columns, however you can't guarantee the data will align vertically.
I'm going to ask a huge favor here.
I have a view that when it opens, it should show every beverage from the database, and show that on the screen.
It also has to add a + button, an amount label next to it, and a - button. This should be done for every item.
The tables I'm getting the items from is called dhh_item by the way.
Now, I've got this:
public ArrayList<Item> getBeverages(Item item) {
ArrayList<Item> items = new ArrayList<>();
if (item != null) {
// First open a database connnection
DatabaseConnection connection = new DatabaseConnection();
if (connection.openConnection()) {
// If a connection was successfully setup, execute the SELECT statement.
ResultSet resultset = connection.executeSQLSelectStatement(
"SELECT * FROM dhh_item ");
if (resultset != null) {
try {
while (resultset.next()) {
String itemName = resultset.getString("itemName");
String status = resultset.getString("status");
String description = resultset.getString("description");
int price = resultset.getInt("price");
Item newItem = new Item(itemName, status, description, price);
items.add(newItem);
}
} catch (SQLException e) {
System.out.println(e);
items.clear();
}
}
// else an error occurred leave array list empty.
// We had a database connection opened. Since we're finished,
// we need to close it.
connection.closeConnection();
}
}
return items;
}
Is this correct in any way. Would I retrieve any data at all? (The .getString()'s are correct.)
Now, this method is inside of another Class (ItemDAO).
Can I call this from my view? How would I get it to make a new label + button for each?
Thanks a lot for those who could help me out on this one!
At the end, it should be looking like this:
for each beverage in the table.
Sounds rather straigh forward
Collection<Item> items=dao.getBeverages(someItem) // get all items
for(Item item:items){
label=new JLabel(item.getYourItemNameOrLabelOrhatever) // this will be the "coca-cola"
incButton=new JButton(incrementButtonAction); // craete/get some action
decButton=new JButton(decrementButtonAction); // same here
counter=new JLabel("0");
yourContainer.add(label);
yourContainer.add(incButton);
yourContainer.add(label);
yourContainer.add(decButton);
yourContainer.revalidate();
}
I am creating a sample gallery app, I am trying to store Gallery Items in local sqlite database
Methods for Adapter.class :
public List<String> getImagePath()
{
ArrayList<String> paths = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + Databaseconnect.TABLE_FILE;
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst())
{
do {
paths.add(cursor.getString(3).toString());
// Log.d("getPathImage:", cursor.getString(0).toString());
} while (cursor.moveToNext());
}
return paths;
}
than
MuAdapter= new muadapter(Activityname.this);
mudapter.open();
ArrayList<String> list =getImagePath();
but I'm having an error On
ArrayList<String> list =getImagePath();
How to initialize this method? Please Give me a solution.
MuAdapter= new muadapter(Activityname.this);
// this line is broke. Use something like "MuAdapter muAdapter = new ..."
mudapter.open();
// then this line can work
ArrayList<String> list =getImagePath();
// not sure about this, but don't you need an objectrefernece here, that you call getImagePath() on?!