android - trying to create listview - android-activity

i'm trying to write data from sqlite to a listview. the compiler doesn't show error, but when I run the app on my phone, it crashes. please help me
Cursor resultSet = db.rawQuery("Select * from weight_listview ORDER BY `id` DESC",null);
resultSet.moveToFirst();
String[] list = new String[] {};
String[] weighttolist={};
String[] datetolist={};
ArrayList<String> List=new ArrayList<String>();
ArrayList<String> List2=new ArrayList<String>();
resultSet.moveToFirst();
int x = 0;
while(resultSet.moveToNext()){
String data = resultSet.getString(resultSet.getColumnIndex("weight"));
String data2 = resultSet.getString(resultSet.getColumnIndex("date"));
String id = resultSet.getString(resultSet.getColumnIndex("ID"));
List.add(data + " " + data2);
x++;
}
final ListView listView = (ListView) findViewById(R.id.listView1);
if(List != null){
weighttolist=(String[])List.toArray(new String[0]);
String[] from = { "weight", "date" };
int[] to = { R.id.weight, R.id.date };
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,R.layout.row, resultSet, from, to);
listView.setAdapter(cursorAdapter);
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1, android.R.id.text1, weighttolist);
// ListView.setAdapter(adapter);
}
edit:
I successed to fix the problem but now I have another problem. I want that the listview will show 2 columns , not only 1 . I created fill row.xml , as you can see in the first code.
Cursor resultSet = db.rawQuery("Select * from weight_listview ORDER BY `id` DESC",null);
resultSet.moveToFirst();
String[] list = new String[] {};
String[] weighttolist={};
String[] datetolist={};
ArrayList<String> List=new ArrayList<String>();
ArrayList<String> List2=new ArrayList<String>();
resultSet.moveToFirst();
int x = 0;
while(resultSet.moveToNext()){
String data = resultSet.getString(resultSet.getColumnIndex("weight"));
String data2 = resultSet.getString(resultSet.getColumnIndex("date"));
List.add(data + " " + data2);
x++;
}
final ListView listView = (ListView) findViewById(R.id.listView1);
if(List != null){
weighttolist=(String[])List.toArray(new String[0]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, weighttolist);
listView.setAdapter(adapter);
}

Well without the exact error it is hard to see what is going wrong. Here is my guess you are using a SimpleAdapter who's constructor looks like this
SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
For your second parameter you are using a Cursor not a list, your from variable are keys so you need to use a hash map I believe
Comment out your code and try this
List<HashMap<String, String>> List = new ArrayList<HashMap<String, String>>();
int x = 0;
while(resultSet.moveToNext()){
HashMap<String, String> map = new HashMap<String, String>();
String weight = resultSet.getString(resultSet.getColumnIndex("weight"));
String date = resultSet.getString(resultSet.getColumnIndex("date"));
String id = resultSet.getString(resultSet.getColumnIndex("ID"));
map.put("weight", weight);
map.put("date", date);
List.add(map);
x++;
}
final ListView listView = (ListView) findViewById(R.id.listView1);
if(List != null){
weighttolist=(String[])List.toArray(new String[0]);
String[] from = { "weight", "date" };
int[] to = { R.id.weight, R.id.date };
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,R.layout.row, List, from, to);
listView.setAdapter(cursorAdapter);

Related

NatTable filtering row header layer for dynamic list

When I use dynamic list for Nattable the filtering via filter header layer it does not work for me.
I want to be able to filter all columns. I have respective code for each column in the filter row configuration class and it works if the input is a static list.
Attached my code snippet:
public Control createPeopleTable(Composite parent) {
// create a new ConfigRegistry which will be needed for GlazedLists
configRegistry = new ConfigRegistry();
peopleTableColumns = PeopleTableColumnDefinition.getPeopleTableColumns();
final Map<String, String> propertyToLabelMap = new HashMap<>();
final String[] propertyNames = new String[peopleTableColumns.size()];
for (int i = 0; i < peopleTableColumns.size(); ++i) {
final PeopleTableColumnDefinition col = peopleTableColumns.get(i);
propertyNames[i] = col.getProperty();
propertyToLabelMap.put(propertyNames[i], col.getDisplayName());
}
columnPropertyAccessor = new ExtendedReflectiveColumnPropertyAccessor<>(propertyNames);columnPropertyAccessor = new ExtendedReflectiveColumnPropertyAccessor<>(propertyNames);
peopleList = new ArrayList<>();
eventList = GlazedLists.eventList(peopleList);
dynamicValues = GlazedLists.threadSafeList(eventList);
bodyLayerStack = new BodyLayerStack(dynamicValues, columnPropertyAccessor);
.....
IFilterStrategy<People> filterStrategy = new DefaultGlazedListsFilterStrategy<>(
bodyLayerStack.getFilterList(), columnPropertyAccessor, configRegistry);
// Note: The column header layer is wrapped in a filter row composite.
// This plugs in the filter row functionality
FilterRowHeaderComposite<People> filterRowHeaderLayer = new FilterRowHeaderComposite<>(filterStrategy,
sortHeaderLayer, bodyLayerStack.getBodyDataProvider(), configRegistry);
// build the row header layer
IDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyLayerStack.getBodyDataProvider());
DataLayer rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider);
ILayer rowHeaderLayer = new RowHeaderLayer(rowHeaderDataLayer, bodyLayerStack,
bodyLayerStack.getSelectionLayer());
// build the corner layer
IDataProvider cornerDataProvider = new DefaultCornerDataProvider(columnHeaderDataProvider,
rowHeaderDataProvider);
DataLayer cornerDataLayer = new DataLayer(cornerDataProvider);
cornerLayer = new CornerLayer(cornerDataLayer, rowHeaderLayer, filterRowHeaderLayer);
// build the grid layer
GridLayer gridLayer = new GridLayer(bodyLayerStack, filterRowHeaderLayer, rowHeaderLayer, cornerLayer);
// turn the auto configuration off as we want to add our header menu
// configuration
natTable = new NatTable(parent, gridLayer, false);
.....
natTable.addConfiguration(new FilterRowConfiguration());
natTable.configure();
...
return natTable;
}
class FilterRowConfiguration extends AbstractRegistryConfiguration {
#Override
public void configureRegistry(IConfigRegistry configRegistry) {
// register the FilterRowTextCellEditor in the first column which
// immediately commits on key press
configRegistry.registerConfigAttribute(EditConfigAttributes.CELL_EDITOR, new FilterRowTextCellEditor(),
DisplayMode.NORMAL, FilterRowDataLayer.FILTER_ROW_COLUMN_LABEL_PREFIX
+ PeopleTableColumnDefinition.Name.columnIndex());
.....
}
class BodyLayerStack extends AbstractLayerTransform {
private FilterList<People> filterList;
private final SelectionLayer selectionLayer;
private SortedList<People> sortedList;
private ViewportLayer viewportLayer;
public BodyLayerStack(EventList<People> values,
IColumnPropertyAccessor<People> columnPropertyAccessor) {
// use the SortedList constructor with 'null' for the Comparator
// because the Comparator
// will be set by configuration
sortedList = new SortedList<>(values, null);
// wrap the SortedList with the FilterList
filterList = new FilterList<>(sortedList);
peopleListDataProvider = new PeopleListDataProvider<>(filterList, columnPropertyAccessor);
bodyDataLayer = new DataLayer(peopleListDataProvider);
final ColumnOverrideLabelAccumulator columnLabelAccumulator = new ColumnOverrideLabelAccumulator(
bodyDataLayer);
for (int i = 0; i < peopleTableColumns.size(); i++) {
PeopleTableColumnDefinition peopleTableColumnDefinition = peopleTableColumns.get(i);
columnLabelAccumulator.registerColumnOverrides(i, peopleTableColumnDefinition.getTableLabel());
}
bodyDataLayer.setConfigLabelAccumulator(columnLabelAccumulator);
// layer for event handling of GlazedLists and PropertyChanges
GlazedListsEventLayer<People> glazedListsEventLayer = new GlazedListsEventLayer<>(bodyDataLayer,
filterList);
selectionLayer = new SelectionLayer(glazedListsEventLayer);
viewportLayer = new ViewportLayer(selectionLayer);
FreezeLayer freezeLayer = new FreezeLayer(selectionLayer);
compositeFreezeLayer = new CompositeFreezeLayer(freezeLayer, viewportLayer, selectionLayer);
setUnderlyingLayer(compositeFreezeLayer);
}
public SortedList<People> getSortedList() {
return sortedList;
}
public SelectionLayer getSelectionLayer() {
return this.selectionLayer;
}
public FilterList<People> getFilterList() {
return this.filterList;
}
public PeopleListDataProvider<People> getBodyDataProvider() {
return peopleListDataProvider;
}
}
public void setListOfPeople(List<People> listOfPeople) {
this.eventList.getReadWriteLock().writeLock().lock();
this.dynamicValues.getReadWriteLock().writeLock().lock();
try {
peopleList.clear();
eventList.clear();
dynamicValues.clear();
peopleList.addAll(listOfPeople);
eventList.addAll(listOfPeople);
dynamicValues.addAll(listOfPeople);
peopleListDataProvider.setPeopleList(peopleList);
} finally {
eventList.getReadWriteLock().writeLock().unlock();
dynamicValues.getReadWriteLock().writeLock().unlock();
}
}
It seems you haven't understood the principles of GlazedLists and Java object references.
First you don't have to call clear() and addAll() on all lists. The GlazedLists are views on the base list, so it should be enough to call on the EventList or a higher list like the FilterList.
Second mistake is that you set another list on the IDataProvider. And that list is not the FilterList. So actually you disable the filter as the FilterList is doing the filter magic. And setting the list is not necessary as you performed a list modification. So why changing it then?

How I can make dynamic header column and dynamic data to export to Excel/CSV/PDF using MongoDB, Spring Boot, and apache poi

I want to make export function using Spring Boot, I have data on MongoDB NoSQL, and then want to export my document on MongoDB Dynamically using Apache POI ( If any better dependency you can recommend to me).
I don't want to declare header column, entity model, etc., I want to export data dynamically as shown as in my Document database, any one can give me an example for it?
Please try these code may be help for you.
->add Gson Depandencies in porm.xml
Controller code
MasterController.java
#Autowired
MasterServiceImpl masterServiceImpl;
#GetMapping(value="/dynamicfile/{flag}/{fileType}/{fileName}")
public ResponseEntity<InputStreamResource> downloadsFiles(#PathVariable("flag") int flag,#PathVariable("fileType") String fileType,#PathVariable("fileName") String fileName) throws IOException{
List<?> objects=new ArrayList<>();
if(flag==1) {
objects=masterServiceImpl.getData();
}
ByteArrayInputStream in = masterServiceImpl.downloadsFiles(objects,fileType);
HttpHeaders headers = new HttpHeaders();
if(fileType.equals("Excel")) {
headers.add("Content-Disposition", "attachment; filename="+fileName+".xlsx");
}else if(fileType.equals("Pdf")){
headers.add("Content-Disposition", "attachment; filename="+fileName+".pdf");
}else if(fileType.equals("Csv")) {
headers.add("Content-Disposition", "attachment; filename="+fileName+".csv");
}
return ResponseEntity.ok().headers(headers).body(new InputStreamResource(in));
}
Service code :
MasterServiceImpl.java
public static List<HashMap<Object, Object>> getListOfObjectToListOfHashMap(List<?> objects) {
List<HashMap<Object,Object>> list=new ArrayList<>();
for(int i=0;i<objects.size();i++) {
HashMap<Object,Object> map=new HashMap<>();
String temp=new Gson().toJson(objects.get(i)).toString();
String temo1= temp.substring(1, temp.length()-1);
String[] temp2=temo1.split(",");
for(int j=-1;j<temp2.length;j++) {
if(j==-1) {
map.put("SrNo",i+1);
}else {
String tempKey=temp2[j].toString().split(":")[0].toString();
String tempValue=temp2[j].toString().split(":")[1].toString();
char ch=tempValue.charAt(0);
if(ch=='"') {
map.put(tempKey.substring(1, tempKey.length()-1), tempValue.substring(1, tempValue.length()-1));
}else {
map.put(tempKey.substring(1, tempKey.length()-1), tempValue);
}
}
}
list.add(map);
}
return list;
}
public static ByteArrayInputStream downloadsFiles(List<?> objects,String fileType) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
List<HashMap<Object, Object>> list = getListOfObjectToListOfHashMap(objects);
String[] COLUMNs = getColumnsNameFromListOfObject(objects);
try{
if(fileType.equals("Excel")) {
generateExcel(list, COLUMNs,out);
}else if(fileType.equals("Pdf")) {
generatePdf(list, COLUMNs,out);
}else if(fileType.equals("Csv")) {
generatePdf(list, COLUMNs,out);
}
}catch(Exception ex) {
System.out.println("Error occurred:"+ ex);
}
return new ByteArrayInputStream(out.toByteArray());
}
public static final String[] getColumnsNameFromListOfObject(List<?> objects) {
String strObjects=new Gson().toJson(objects.get(0)).toString();
String[] setHeader= strObjects.substring(1, strObjects.length()-1).split(",");
String header="SrNo";
for(int i=0;i<setHeader.length;i++) {
String str=setHeader[i].toString().split(":")[0].toString();
header=header+","+str.substring(1, str.length()-1);
}
return header.split(",");
}
public static final void generateExcel(List<HashMap<Object, Object>> list, String[] COLUMNs,ByteArrayOutputStream out) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Excelshit");
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setColor(IndexedColors.BLUE.getIndex());
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
Row headerRow = sheet.createRow(0);
for (int col = 0; col < COLUMNs.length; col++) {
Cell cell = headerRow.createCell(col);
cell.setCellValue(COLUMNs[col]);
cell.setCellStyle(headerCellStyle);
}
int rowIdx = 1;
for(int k = 0; k < list.size(); k++){
Row row =sheet.createRow(rowIdx++);
for (Map.Entry<Object, Object> entry : list.get(k).entrySet()){
Object key = entry.getKey();
Object value = entry.getValue();
for (int col = 0; col < COLUMNs.length; col++) {
if(key.toString().equals(COLUMNs[col].toString())) {
row.createCell(col).setCellValue(value.toString());
}
}
}
}
workbook.write(out);
System.out.println(workbook);
}
private static final void generatePdf(List<HashMap<Object, Object>> list, String[] COLUMNs,ByteArrayOutputStream out) throws DocumentException {
Document document = new Document();
com.itextpdf.text.Font headerFont =FontFactory.getFont(FontFactory.HELVETICA_BOLD,8);
com.itextpdf.text.Font dataFont =FontFactory.getFont(FontFactory.TIMES_ROMAN,8);
PdfPCell hcell=null;
PdfPTable table = new PdfPTable(COLUMNs.length);
for (int col = 0; col < COLUMNs.length; col++) {
hcell = new PdfPCell(new Phrase(COLUMNs[col], headerFont));
hcell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(hcell);
}
for(int index = 0; index < list.size(); index++){
PdfPCell cell = null;
for (Map.Entry<Object, Object> entry : list.get(index).entrySet()){
Object key = entry.getKey();
Object value = entry.getValue();
for (int col = 0; col < COLUMNs.length; col++) {
if(key.toString().equals(COLUMNs[col].toString())) {
cell = new PdfPCell(new Phrase(value.toString(),dataFont));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
}
}
table.addCell(cell);
}
}
PdfWriter.getInstance(document, out);
document.open();
document.add(table);
document.close();
}
public List<TblDepartment> getData() {
List<TblDepartment> list = new ArrayList<>();
departmentRepository.findAll().forEach(list::add);
return list;
}

android listview with item and sub item not working properly

I have a database which i select 2 strings one as an item other one is description.I am trying to map these 2 strings into a listview item-subitem layout. the following code is what i tried so far.
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
Map<String, String> datum = new HashMap<String, String>(2);
SimpleAdapter adapter = new SimpleAdapter(this, data,
android.R.layout.simple_list_item_2,
new String[] { "item","descr" },
new int[] { android.R.id.text1, android.R.id.text2 });
itemList.setAdapter(adapter);
Cursor cours = MainActivity.mydb.query("sub_menu", null, "cat_id = "
+ menuid + " AND sub_flag = 1", null, null, null, null);
if (cours.moveToFirst()) {
do {
datum.put("item", cours.getString(cours.getColumnIndex("sub_label")));
datum.put("descr", cours.getString(cours.getColumnIndex("sub_description")));
data.add(datum);
Log.d("testt", datum.toString());
adapter.notifyDataSetChanged();
} while (cours.moveToNext());
}
the problem now it will add 5 entries to the listview with the same values which are the last row selected form the database which is not what. any idea how to fix this ?
EDIT.
after experimenting with it i found that i was overwriting the object datum which end up having the save value for all the entries. the fix was as easy as moving the intializition line for datum into the loop. here is the final code
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
String[] from = new String[] { "rowid", "col_1" };
int[] to = new int[] { android.R.id.text1, android.R.id.text2 };
Cursor cours = MainActivity.mydb.query("sub_menu", null, "cat_id = "
+ menuid + " AND sub_flag = 1", null, null, null, null);
if (cours.moveToFirst()) {
do {
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("rowid",
cours.getString(cours.getColumnIndex("sub_label")));
datum.put("col_1", cours.getString(cours
.getColumnIndex("sub_description")));
data.add(datum);
} while (cours.moveToNext());
}
SimpleAdapter adapter = new SimpleAdapter(this, data,
android.R.layout.simple_list_item_2, from, to);
itemList.setAdapter(adapter);
make custom ListView and use CursorAdapter
Here is a good example will help you.

clickable Imagemap in Gwt

hii i want clickable image map in gwt project...i have created a simple XY map but now i want clickable imagemap...please help me for that
i just want to create a chart where mouse over effect take place....
here is my code
public class ChartGenerator extends ApplicationFrame{
private List<String> trainTypeArray = new ArrayList<String>();
private String lineType;
private List<Long> startTimeOfTrain = new ArrayList<Long>();
private List<Boolean> labelVisibility = new ArrayList<Boolean>();
private List<Integer> stationDistance= new ArrayList<Integer>();
private List<String> lineColorArray = new ArrayList<String>();
private List<String> lineShadeArray = new ArrayList<String>();
private List<String> stationNames = new ArrayList<String>();
private List<String> trainArray = new ArrayList<String>();
private JFreeChart chart =null;
private int startTimeLong;
private int endTimeLong;
private String timezone;
private boolean prediction;
public ChartGenerator(String title, Date dt, String startTime, String endTime, String serviceDirection, String lineType, int delay, boolean prediction) throws BombardierBaseException, BombardierException {
/*super(title)*/;
String[] startSplit = startTime.split(":");
String[] endTimeSplit = endTime.split(":");
this.timezone = startTime +"-"+endTime;
startTimeLong = Integer.parseInt(startSplit[0])*60*60*1000+Integer.parseInt(startSplit[1])*60*1000;
endTimeLong = Integer.parseInt(endTimeSplit[0])*60*60*1000+Integer.parseInt(endTimeSplit[1])*60*1000;
endTimeLong = endTimeLong+(60*1000);
this.prediction = prediction;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy");
String dtOfJourney = "'" +sdf.format(dt)+"'";
this.lineType = lineType;
System.out.println("Create data-set now");
final XYDataset dataset = createDataset(dtOfJourney, startTimeLong,endTimeLong,serviceDirection);
chart= createChart(dataset, dtOfJourney, serviceDirection);
}
public int getStartTimeLong() {
return startTimeLong;
}
public void setStartTimeLong(int startTimeLong) {
this.startTimeLong = startTimeLong;
}
public int getEndTimeLong() {
return endTimeLong;
}
public JFreeChart getChart(){
return chart;
}
public BufferedImage getBufferedImage(int width, int height){
ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
return this.chart.createBufferedImage(width,height, info);
}
private double getStationDistion(String name){
return InitializeProperties.getStationDistance(name);
}
private XYDataset createDataset(String dtOfJourney, long startTime,long endTime,String serviceDirection) throws BombardierBaseException {
ResultSet resultSet =null;
Statement readstatement = null;
Connection con = null;
System.out.println("Entering get Connection now");
System.out.flush();
try{
System.out.println("Getting connection");
System.out.flush();
con = InitializeProperties.getConnection();
System.out.println("Connection initialized");
System.out.flush();
readstatement= con.createStatement();
final XYSeriesCollection dataset1 = new XYSeriesCollection();
String lineTypeFilter = "";
if(!this.lineType.equals("A")){
if(lineType.equals("L")){
lineTypeFilter = "and lt.act_lineType like ' '";
}else{
lineTypeFilter = "and lt.act_lineType like '" + this.lineType + "'";
}
}
int n = 0;
String serviceDirectionClause = "";

CheckedTextView Behaving Erratically

Has anyone else had a problem with CheckedTextView showing multiple checked items when only 1 is checked? When a CheckedTexView item is clicked, the response from the OnClickListener is to check the entries before and after the clicked item.
Here's the code:
mFriendDoneButton = (Button) findViewById(R.id.doneAddAFriendButton);
mListView = (ListView)findViewById(R.id.contactList);
populateContactList();
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mListView.setItemsCanFocus(false);
mListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int arg2, long arg3) {
int selectedPosition = arg2;
CheckedTextView textView = (CheckedTextView)view.findViewById(R.id.friendEntryText);
String mtext = textView.getText().toString();
Log.i("AddAFriendActivity", "Click on position "+selectedPosition);
Toast t = new Toast(AddAFriendActivity.this);
t = Toast.makeText(AddAFriendActivity.this, "Clicked on " + arg2+mtext+arg3, Toast.LENGTH_LONG);
t.show();
}
});
private void populateContactList() {
// Build adapter with contact entries
Cursor cursor = getContacts();
String[] fields = new String[] {
ContactsContract.Data.DISPLAY_NAME
};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.friend_entry, cursor, fields, new int[] {R.id.friendEntryText});
mListView.setAdapter(adapter);
}
private Cursor getContacts()
{
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME
};
String selection = null;
String[] selectionArgs = null;
String sortOrder = null;
return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
}
The XML is as follows:
Found the problem... textView needs to be declared as a field, otherwise the managedQuery results cycle through the onClickListener.