I used a keywordfilter for a list which is populated from db .Its working good .Imagine the list contains a phrase 'A big bat' and there are other words starting with 'b' like books etc .But when I give 'b' in the search field the phrase 'A big bat' appears first and then only words starting with 'b'.Please help me to fix it
please see my code
public final class KeywordFilter
{
private KeywordFilterField _keywordFilterField;
private WordList _wordList;
private Vector _words;
public KeywordFilter()
{
_words = getDataFromDatabase();
if(_words != null)
{
_wordList = new WordList(_words);
_keywordFilterField = new KeywordFilterField();
_keywordFilterField.setSourceList(_wordList, _wordList);
CustomKeywordField customSearchField = new CustomKeywordField();
_keywordFilterField.setKeywordField(customSearchField);
KeywordFilterScreen screen = new KeywordFilterScreen(this);
screen.setTitle(_keywordFilterField.getKeywordField());
screen.add(_keywordFilterField);
UiApplication ui = UiApplication.getUiApplication();
ui.pushScreen(screen);
}
else
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("Error reading data file.");
System.exit(0);
}
});
}
}
KeywordFilterField getKeywordFilterField()
{
return _keywordFilterField;
}
private Vector getDataFromDatabase()
{
Vector words = new Vector();
Database d;
for(;;)
{
try
{
URI myURI=URI.create("file:///SDCard/Databases/MyTestDatabase.db");
d=DatabaseFactory.open(myURI);
Statement st=d.createStatement("select (select distinct group_concat(eng) fromEnglish),group_concat(mal) from English e ,Malayalam m where e.Ecode=m.Mcode group by eng");
st.prepare();
net.rim.device.api.database.Cursor c=st.getCursor();
Row r;
while(c.next())
{
r=c.getRow();
String w=r.getString(0);
String meaning=r.getString(1);
words.addElement(new Word(w,meaning));
}
st.close();
d.close();
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
e.printStackTrace();
}
return words;
}
}
void addElementToList(Word w)
{
_wordList.addElement(w);
_keywordFilterField.updateList();
}
final static class CustomKeywordField extends BasicEditField
{
CustomKeywordField()
{
super(USE_ALL_WIDTH|NON_FOCUSABLE|NO_LEARNING|NO_NEWLINE);
setLabel("Search: ");
}
protected boolean keyChar(char ch, int status, int time)
{
switch(ch)
{
case Characters.ESCAPE:
if(super.getTextLength() > 0)
{
setText("");
return true;
}
}
return super.keyChar(ch, status, time);
}
protected void paint(Graphics graphics)
{
super.paint(graphics);
getFocusRect(new XYRect());
drawFocus(graphics, true);
}
}
}
class KeywordFilterScreen extends MainScreen
{
private KeywordFilter _app;
private KeywordFilterField _keywordFilterField;
public KeywordFilterScreen(KeywordFilter app)
{
_app = app;
_keywordFilterField = _app.getKeywordFilterField();
}
protected boolean keyChar(char key, int status, int time)
{
if (key == Characters.ENTER)
{
displayInfoScreen();
// Word w = (Word)_keywordFilterField.getSelectedElement();
// Status.show(w.getMeaning());
return true;
}
return super.keyChar(key, status, time);
}
public boolean invokeAction(int action)
{
switch(action)
{
case ACTION_INVOKE:
displayInfoScreen();
return true;
}
return super.invokeAction(action);
}
private void displayInfoScreen()
{
Word w = (Word)_keywordFilterField.getSelectedElement();
if(w != null)
{
InfoScreen infoScreen = new InfoScreen(w);
UiApplication ui=UiApplication.getUiApplication();
ui.pushScreen(infoScreen);
}
}
public boolean onSavePrompt()
{
return true;
}
private final static class InfoScreen extends MainScreen
{
InfoScreen(Word w)
{
setTitle(w.toString());
BasicEditField popField = new BasicEditField(" ",w.getMeaning(),300,Field.NON_FOCUSABLE);
FontManager.getInstance().load("DC124.TTF", "MyFont", FontManager.APPLICATION_FONT) ;
{
try {
FontFamily typeface = FontFamily.forName("MyFont");
Font myFont = typeface.getFont(Font.PLAIN, 25);
popField.setFont(myFont);
add(popField);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();}
}
}
}
}
This query is useful for you:
SELECT Name FROM Employee where Name like '%d%' order by Name;
Here Name is my column-name;
Try this;
I think you are using query like following
select colomname from tablename where colomname GLOB '%b%';
here you get all names which are contain letter 'b' (case sensitive)
if you want all words which are strted with letter 'b' use should writr query like
select colomname from tablename where colomname GLOB 'b%' order by colomname ;
here i am using "GLOB" it gives case sensitive to the out put records if you dont need case sensitive then you can use "LIKE" key word
thanks
Related
I have a AutoCompleteTextView that I give it 2 different adapters depending on the amount of text that is being present at the textview - if it has 0 characters I want it to display a list of "recently searched" strings adapter, while if it has more than 1 characters I want it to display auto completion list.
My getRecentlySearchedQueries method along with the RecentSearchedViewModel-
private List<String> recentlySearchedQueries = new ArrayList<>(); // pasted from the top of the class
#Override
public void getRecentlySearchedQueries() {
recentSearchViewModel.getAllQueries().observe(getActivity(), databaseRecentlySearchList -> {
if (databaseRecentlySearchList == null) {
return;
}
for (int i = 0; i < databaseRecentlySearchList.size(); i++) {
Log.d("localDBValue", "Added value - " + databaseRecentlySearchList.get(i).toString() + "\n");
String query = databaseRecentlySearchList.get(i).getQuery();
recentlySearchedQueries.add(query);
}
//Log.d("localDBValue", "recent search list value - " + recentlySearchedQueries);
});
}
public class RecentSearchViewModel extends AndroidViewModel {
private RecentSearchRepository recentSearchRepository;
private LiveData<List<RecentSearchModel>> allRecentlySearched;
public RecentSearchViewModel(#NonNull Application application) {
super(application);
recentSearchRepository = new RecentSearchRepository(application);
allRecentlySearched = recentSearchRepository.getAllRecentSearches();
}
public void insert(RecentSearchModel model) {
recentSearchRepository.insert(model);
}
public void update(RecentSearchModel model) {
// add implementation in the future if needed
}
public void delete(RecentSearchModel model) {
// add implementation in the future if needed
}
public LiveData<List<RecentSearchModel>> getAllQueries() {
return allRecentlySearched;
}
}
public class RecentSearchRepository {
private RecentSearchDao recentSearchDao;
private LiveData<List<RecentSearchModel>> allRecentSearches;
public RecentSearchRepository(Application application) {
MarketplaceDatabase database = MarketplaceDatabase.getRecentSearchInstance(application);
recentSearchDao = database.recentSearchDao();
allRecentSearches = recentSearchDao.getRecentSearchList();
}
public void insert(RecentSearchModel model) {
new RecentSearchRepository.InsertRecentSearchAsyncTask(recentSearchDao).execute(model);
}
public void update (RecentSearchModel model) {
//TODO - implement in future if needed
}
public void delete(RecentSearchModel model) {
//TODO - implement in future if needed
}
public LiveData<List<RecentSearchModel>> getAllRecentSearches() {
return allRecentSearches;
}
private static class InsertRecentSearchAsyncTask extends AsyncTask<RecentSearchModel, Void, Void> {
private RecentSearchDao recentSearchDao;
public InsertRecentSearchAsyncTask(RecentSearchDao recentSearchDao) {
this.recentSearchDao = recentSearchDao;
}
#Override
protected Void doInBackground(RecentSearchModel... recentSearchModels) {
recentSearchDao.insert(recentSearchModels[0]);
return null;
}
}
private static class UpdateRecentSearchAsyncTask extends AsyncTask<RecentSearchModel, Void, Void> {
private RecentSearchDao recentSearchDao;
public UpdateRecentSearchAsyncTask(RecentSearchDao recentSearchDao) {
this.recentSearchDao = recentSearchDao;
}
#Override
protected Void doInBackground(RecentSearchModel... recentSearchModels) {
recentSearchDao.update(recentSearchModels[0]);
return null;
}
}
}
#Dao
public interface RecentSearchDao {
#Insert()
void insert(RecentSearchModel model);
#Update
void update(RecentSearchModel model);
#Delete
void delete(RecentSearchModel model);
#Query("select * from recent_search_table")
LiveData<List<RecentSearchModel>> getRecentSearchList();
}
#Entity(tableName = "recent_search_table")
public class RecentSearchModel {
#PrimaryKey(autoGenerate = true)
private int ID;
private String query;
public RecentSearchModel(){
}
public RecentSearchModel(String query) {
this.query = query;
}
public void setID(int ID) {
this.ID = ID;
}
public int getID() {
return ID;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
#Override
public String toString() {
return "RecentSearchModel{" +
"query='" + query + '\'' +
'}';
}
#Override
public boolean equals(#Nullable Object obj) {
if (obj instanceof RecentSearchModel)
return this.query.equalsIgnoreCase(((RecentSearchModel) obj).query);
return false;
}
}
So, what I am doing here is for start getting all values inside my local DB and adding them to my String list that is part of the adapter. So far so good.
The issue I am facing is that the adapter won't show the amount of strings available in the list that populates it. In fact, it sometimes shows a view half-cut with wierd information, sometimes does not show anything and sometimes shows part of the corrent information. What am I missing?
Another thing I am facing is that the "recently searched" adapter won't work when clicking on the AutoCompleteTextView - it only works when typing and deleting values so the char length is 0. How can I make it work from start of focus?
Here is the way I am populating the information to the ViewModel -
/**
* Shows the searched products following
*/
#Override
public void getSearchedProducts(String searchedQuery) {
MarketplaceUtils.getSearchedProducts(searchedQuery, marketApiCalls, false, initialSearchTake, initialMarketplacePage, new MarketplaceUtils.OnProductsFetchCompleteListener() {
#Override
public void onSuccess(List<MiniProductModel> list) {
if (!searchedQuery.equals(currentSearchedText))
return;
if (list == null) {
//reaching here means we do not have a result to show to the UI so we empty the list.
currentProductList.clear();
productsAdapter.notifyDataSetChanged();
return;
}
if (searchedQuery.length() > 3 && searchAutoCompleteStrings.contains(searchedQuery)) {
Log.d("localDBValue", "searchedValue - " + searchedQuery);
recentSearchViewModel.insert(new RecentSearchModel(searchedQuery));
}
mPresenter.setDiscoverProductsLayoutVisibility(View.GONE);
currentProductList.clear();
currentProductList.addAll(list);
productsAdapter.notifyDataSetChanged();
}
#Override
public void onError(Throwable throwable) {
Log.d("searchedProducts", throwable.getMessage());
}
});
}
The default behaviour for #Insert method of Room is OnConflictStrategy.ABORT - so what I did is to implement equals() method to verify that the RecentSearchModels that are being compared are compared by their string value. Still does seems to effect anything.
I am trying to replicate Gmail behavior in Javafx TableView. Row of new Unread message should be shown in bold. Here is what I was able to do so far:
I can change background of the whole row, and bold a cell, but can't bold the whole row.
How to explain Javafx to do this?
for each Cell cell in tableview:
get Message m corresponding to row.
String style = m.isUnread() ? "
cell.setStyle("-fx-font-weight: 800" : "-fx-font-weight: 100")
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class Message {
final static public ObservableList<Message> data = FXCollections.observableArrayList(
new Message("Bob", "Where are you?", true, true),
new Message("Elise", "Payment", false, false),
new Message("Charlie", "Read this book: 'Clean code'", true, true),
new Message("Oscar", "Golf class tonight", true, false),
new Message("Sam", "How is your TableView progress?", false, true),
new Message("Alice", "Latte", true, true)
);
final private String name;
final private String title;
private boolean isUnread;
private boolean isArchived;
public Message(String name, String title, boolean isUnread, boolean isArchived) {
this.name = name; this.title = title; this.isUnread = isUnread;this.isArchived = isArchived;
}
public String getName() { return name; }
public String getTitle() { return title; }
public boolean getIsUnread() { return isUnread; }
public boolean getisArchived() { return isArchived; }
public void setIsUnread(boolean isUnread) { this.isUnread = isUnread; }
}
MyTable.java
import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import javafx.util.Callback;
public class MyTable extends Application {
public static void main(String[] args) throws Exception { launch(args); }
public void start(final Stage stage) throws Exception {
stage.setTitle("Inbox");
// create a table.
TableView<Message> table = new TableView(Message.data);
table.getColumns().addAll(makeStringColumn("Name", "name", 150), makeStringColumn("Title", "title", 300), makeBooleanColumn("New", "isUnread", 150));
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
table.setPrefHeight(250);
stage.setScene(new Scene(table));
stage.getScene().getStylesheets().add(getClass().getResource("message.css").toExternalForm());
stage.show();
// highlight the table rows depending upon whether we expect to get paid.
int i = 0;
for (Node n: table.lookupAll("TableRow")) {
if (n instanceof TableRow) {
TableRow row = (TableRow) n;
if (table.getItems().get(i).getIsUnread()) {
row.getStyleClass().add("isReadRow");
} else {
row.getStyleClass().add("isUnreadRow");
}
i++;
if (i == table.getItems().size())
break;
}
}
}
private TableColumn<Message, String> makeStringColumn(String columnName, String propertyName, int prefWidth) {
TableColumn<Message, String> column = new TableColumn<>(columnName);
column.setCellValueFactory(new PropertyValueFactory<Message, String>(propertyName));
column.setCellFactory(new Callback<TableColumn<Message, String>, TableCell<Message, String>>() {
#Override public TableCell<Message, String> call(TableColumn<Message, String> soCalledFriendStringTableColumn) {
return new TableCell<Message, String>() {
#Override public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
setText(item);
}
}
};
}
});
column.setPrefWidth(prefWidth);
column.setSortable(false);
return column;
}
private TableColumn<Message, Boolean> makeBooleanColumn(String columnName, String propertyName, int prefWidth) {
TableColumn<Message, Boolean> column = new TableColumn<>(columnName);
column.setCellValueFactory(new PropertyValueFactory<Message, Boolean>(propertyName));
column.setCellFactory(new Callback<TableColumn<Message, Boolean>, TableCell<Message, Boolean>>() {
#Override public TableCell<Message, Boolean> call(TableColumn<Message, Boolean> soCalledFriendBooleanTableColumn) {
return new TableCell<Message, Boolean>() {
#Override public void updateItem(final Boolean item, final boolean empty) {
super.updateItem(item, empty);
if (item != null) {
setText(item.toString());
this.getStyleClass().add(item ? "isUnreadCell" : "isReadCell");
}
}
};
}
});
column.setPrefWidth(prefWidth);
column.setSortable(false);
return column;
}
}
(Message.css)
.column-header-background { -fx-background-color: azure; }
.isReadRow { -fx-background-color: palegreen; }
.isUnreadRow { -fx-background-color: yellow; }
.isReadCell { -fx-font-weight: 100 ; -fx-text-fill: darkgreen;}
.isUnreadCell { -fx-font-weight: 800 ; -fx-text-fill: red;}
To bold a row associate a RowFactory as shown below.
table.setPrefHeight(250);
table.setRowFactory(new Callback<TableView<Message>, TableRow<Message>>() {
#Override
public TableRow<Message> call(TableView<Message> param) {
final TableRow<Message> row = new TableRow<Message>() {
#Override
protected void updateItem(Message row, boolean empty) {
super.updateItem(row, empty);
if (!empty)
styleProperty().bind(Bindings.when(row.selectedProperty())
.then("-fx-font-weight: bold; -fx-font-size: 16;")
.otherwise(""));
}
};
return row;
}
});
stage.setScene(new Scene(table));
In the above sample, selectedProperty() function has been called by the Message row. The selectedProperty() function returns the value of boolean variable isUnread. If the isUnread value is true then the whole row will be bolded else it won't be.
final private String title;
private boolean isUnread;
private boolean isArchived;
private BooleanProperty selected;
public boolean getSelected() {return selected.get();}
public BooleanProperty selectedProperty(){return selected;}
public Message(String name, String title, boolean isUnread, boolean isArchived) {
this.name = name; this.title = title; this.isUnread = isUnread;this.isArchived = isArchived;
this.selected = new SimpleBooleanProperty(isUnread);
}
Setting the font style as bold and size to 16 gives following output:
I'd recommend using PseudoClasses to denote read/unread rows. Use a rowFactory to set the PseudoClasses. Also using a property for the read/unread state would be preferable, since this allows you to update the rows without refreshing the whole table:
private final BooleanProperty unread;
public void setUnread(boolean value) {
this.unread.set(value);
}
public boolean isUnread() {
return this.unread.get();
}
public BooleanProperty unreadProperty() {
return unread;
}
public Message(String name, String title, boolean isUnread, boolean isArchived) {
this.name = name;
this.title = title;
this.unread = new SimpleBooleanProperty(isUnread);
this.isArchived = isArchived;
}
final PseudoClass read = PseudoClass.getPseudoClass("read");
final PseudoClass unread = PseudoClass.getPseudoClass("unread");
table.setRowFactory(tv -> new TableRow<Message>() {
private void setState(boolean readState, boolean unreadState) {
pseudoClassStateChanged(unread, unreadState);
pseudoClassStateChanged(read, readState);
}
private void setUnreadState(boolean unreadState) {
setState(!unreadState, unreadState);
}
private final ChangeListener<Boolean> unreadListener = (observable, oldValue, newValue) -> setUnreadState(newValue);
#Override
protected void updateItem(Message item, boolean empty) {
// remove listener from old item
Message oldItem = getItem();
if (oldItem != null) {
oldItem.unreadProperty().removeListener(unreadListener);
}
super.updateItem(item, empty);
if (empty || item == null) {
setState(false, false);
} else {
// set appropriate state & add listener
setUnreadState(item.isUnread());
item.unreadProperty().addListener(unreadListener);
}
}
});
stage.setScene(new Scene(table));
.table-row-cell:read {
-fx-background-color: palegreen;
}
.table-row-cell:unread {
-fx-background-color: yellow;
}
.table-row-cell:read>.table-cell {
-fx-font-weight: 100;
-fx-text-fill: darkgreen;
}
.table-row-cell:unread>.table-cell {
-fx-font-weight: 800;
-fx-text-fill: red;
}
Also make sure to set the text of TableCells even if they become empty. Otherwise you could see "ghost content":
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
setText(item);
} else {
setText("");
}
}
#Override
public void updateItem(final Boolean item, final boolean empty) {
super.updateItem(item, empty);
if (item != null) {
setText(item.toString());
} else {
setText("");
}
}
I'm new to android development and I have been struggling to parse more than one tag at a time and display it in a ListView.
I'm using SAX parser, here is my RssParseHandler code.
public class RssParseHandler extends DefaultHandler {
private List<RssItem> rssItems;
private RssItem currentMessage;
//private StringBuilder builder;
private boolean parseLink;
private boolean parseTitle;
private boolean parseDate;
private boolean parseDes;
public RssParseHandler() {
rssItems = new ArrayList();
}
public List<RssItem> getItems() {
return this.rssItems;
}
#Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, name, attributes);
if (localName.equalsIgnoreCase("item")) {
this.currentMessage = new RssItem();
} else if (localName.equalsIgnoreCase("title")) {
//currentMessage.setTitle(builder.toString());
parseTitle = true;
} else if (localName.equalsIgnoreCase("link")) {
//currentMessage.setLink(builder.toString());
parseLink = true;
} else if (localName.equalsIgnoreCase("description")) {
//currentMessage.setDescription(builder.toString());
parseDes = true;
} else if (localName.equalsIgnoreCase("pubDate")) {
//currentMessage.setDate(builder.toString());
parseDate = true;
}
//parsing enclosure tag
else if ("enclosure".equals(localName)) {
// Get tags attributes number
int attrsLength = attributes.getLength();
for (int i = 0; i < attrsLength; i++) {
String attrName = attributes.getQName(i); // attribute name
if ("url".equals(attrName)) // This tag has only one attribute but it is better to check it name is correct
currentMessage.getLink();
}
}
}
#Override
public void endElement(String uri, String localName, String name)
throws SAXException {
super.endElement(uri, localName, name);
if (this.currentMessage != null) {
if (localName.equalsIgnoreCase("item")) {
rssItems.add(currentMessage);
//currentMessage = null;
} else if (localName.equalsIgnoreCase("link")) {
//currentMessage.setLink(builder.toString());
//parseLink = false;
} else if (localName.equalsIgnoreCase("description")) {
//currentMessage.setDescription(builder.toString());
//parseDes = false;
} else if (localName.equalsIgnoreCase("pubDate")){
//currentMessage.setDate(builder.toString());
parseDate = false;
} else if (localName.equalsIgnoreCase("title")) {
//currentMessage.setTitle(builder.toString());
parseTitle = false;
}
//builder.setLength(0);
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
//builder.append(ch, start, length);
if (parseTitle) {
if (currentMessage != null)
currentMessage.setTitle(new String(ch, start, length));
} else if (parseLink) {
if (currentMessage != null) {
currentMessage.setLink(new String(ch, start, length));
//parseLink = false;
}
} else if (parseDes) {
if (currentMessage != null)
currentMessage.setDescription(new String(ch, start, length));
//parseLink = false;
} else if (parseDate) {
if (currentMessage != null) {
currentMessage.setDate(new String(ch, start, length));
//currentMessage.setDate(new String(ch, start, length));
//parseDesc = false;
}
}
}
}
Here is the code for the Listview:
public class ReaderAppActivity extends Fragment {
private ReaderAppActivity local;
private ListView mList;
/**
* This method creates main application view
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//super.onCreate(savedInstanceState);
// Set view
//setContentView(R.layout.fragment_rss);
local = this;
//int position = getArguments().getInt("position");
// String url = getArguments().getString("url");
// List of rivers
String[] menus = getResources().getStringArray(R.array.menus);
// Creating view corresponding to the fragment
View v = inflater.inflate(R.layout.fragment_rss, container, false);
// Set reference to this activity
//local = this;
GetRSSDataTask task = new GetRSSDataTask();
// Start download RSS task
task.execute("http://thechurchofwhatshappeningnow.libsyn.com/rss");
//task.execute(url);
// Debug the thread name
Log.d("ITCRssReader", Thread.currentThread().getName());
//mList = (ListView) findViewById(R.id.rssListMainView);
return v;
}
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
#Override
protected List<RssItem> doInBackground(String... urls) {
// Debug the task thread name
Log.d("ITCRssReader", Thread.currentThread().getName());
try {
// Create RSS reader
RssReader rssReader = new RssReader(urls[0]);
// Parse RSS, get items
return rssReader.getItems();
} catch (Exception e) {
Log.e("ITCRssReader", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(List<RssItem> result) {
// Get a ListView from main view
ListView mList = (ListView) getView().findViewById(R.id.rssListMainView);
// Create a list adapter
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(getActivity(),R.layout.rss_text, result);
//ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(getActivity(),R.layout.fragment_rss, result);
// Set list adapter for the ListView
mList.setAdapter(adapter);
// Set list view item click listener
mList.setOnItemClickListener(new ListListener(result, getActivity()));
}
}
}
What am I doing wrong? I can't figure it out. I would like to parse, the link, description, pubDate, and pass them into the ListView. Ideally I would only display the title and episode number in the listview, and pass the other tags into String, so I can display them when I click an item in the listView.
I've created another class called SingleMenuItem to be called when I click an item in the ListView, it's just filler code right now, it does not display anything because the items aren't parsed.
Any help would be appreciated. Here is a RSS link to the feed:
public class SingleMenuItem extends Activity {
// XML node keys
static final String KEY_NAME = "name";
static final String KEY_DATE = "pubdate";
static final String KEY_DESC = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent
String name = in.getStringExtra(KEY_NAME);
String date = in.getStringExtra(KEY_DATE);
String description = in.getStringExtra(KEY_DESC);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblDate = (TextView) findViewById(R.id.date_label);
TextView lblDesc = (TextView) findViewById(R.id.description_label);
lblName.setText(name);
lblDate.setText(date);
lblDesc.setText(description);
}
}
Here is the code for my ReaderAppActivty that puts the results of the parsing into the ListView:
public class ReaderAppActivity extends Fragment {
private ReaderAppActivity local;
private ListView mList;
/**
* This method creates main application view
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//super.onCreate(savedInstanceState);
// Set view
//setContentView(R.layout.fragment_rss);
local = this;
//int position = getArguments().getInt("position");
// String url = getArguments().getString("url");
// List of rivers
String[] menus = getResources().getStringArray(R.array.menus);
// Creating view corresponding to the fragment
View v = inflater.inflate(R.layout.fragment_rss, container, false);
// Set reference to this activity
//local = this;
GetRSSDataTask task = new GetRSSDataTask();
// Start download RSS task
task.execute("http://thechurchofwhatshappeningnow.libsyn.com/rss");
//task.execute(url);
// Debug the thread name
Log.d("ITCRssReader", Thread.currentThread().getName());
//mList = (ListView) findViewById(R.id.rssListMainView);
return v;
}
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
#Override
protected List<RssItem> doInBackground(String... urls) {
// Debug the task thread name
Log.d("ITCRssReader", Thread.currentThread().getName());
try {
// Create RSS reader
RssReader rssReader = new RssReader(urls[0]);
// Parse RSS, get items
return rssReader.getItems();
} catch (Exception e) {
Log.e("ITCRssReader", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(List<RssItem> result) {
// Get a ListView from main view
ListView mList = (ListView) getView().findViewById(R.id.rssListMainView);
// Create a list adapter
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(getActivity(),R.layout.rss_text, result);
//ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(getActivity(),R.layout.fragment_rss, result);
// Set list adapter for the ListView
mList.setAdapter(adapter);
// Set list view item click listener
mList.setOnItemClickListener(new ListListener(result, getActivity()));
}
}
}
Based on the amount of commented-out code in your RssParseHandler, you've clearly been struggling with this for a bit, and some early attempts were closer to right than what you've got now.
The issue with your current code appears to be that you're not consistently resetting the booleans that drive which part of the item you're setting. Debugging through it, I saw it setting a date into the link field at some point.
But you're actually doing some of that setting in the wrong method, as the characters method doesn't necessarily give you the full contents of the tag. You need to use a Stringbuilder, and I can see from commented-out code that you tried that at some point.
If you collect the text in a stringbuilder and do all the setting in the endElement method, you don't really need the booleans at all, as the endElement method has knowledge of which tag you're ending.
Here's a working version that's perhaps not too far from something you had at some point but which gets rid of all those flag fields.
public class RssParseHandler extends DefaultHandler {
private List<RssItem> rssItems;
private RssItem currentMessage;
private StringBuilder builder;
public RssParseHandler() {
rssItems = new ArrayList<>();
builder = new StringBuilder();
}
public List<RssItem> getItems() {
return this.rssItems;
}
#Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, name, attributes);
builder.setLength(0);
if (localName.equalsIgnoreCase("item")) {
this.currentMessage = new RssItem();
}
}
#Override
public void endElement(String uri, String localName, String name)
throws SAXException {
super.endElement(uri, localName, name);
if (this.currentMessage != null) {
if (localName.equalsIgnoreCase("item")) {
rssItems.add(currentMessage);
currentMessage = null;
} else if (localName.equalsIgnoreCase("link")) {
currentMessage.setLink(builder.toString());
} else if (localName.equalsIgnoreCase("description")) {
currentMessage.setDescription(builder.toString());
} else if (localName.equalsIgnoreCase("pubDate")){
currentMessage.setDate(builder.toString());
} else if (localName.equalsIgnoreCase("title")) {
currentMessage.setTitle(builder.toString());
}
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
builder.append(ch, start, length);
}
}
How can i implement Customized lookup in Report Dialog box.
for example i have two fields in my report dialog 1) Custgroup 2) CustAccount
if i have selected a particuler cust group in first field then second field lookup should show only customers those come under this cust groups.
//class
public class ReportRun extends ObjectRun
{
DialogField dialogcustGroup,dialogcustaccount ;
CustTable obj_CustTable ;
}
//dialog method
public Object dialog(Object _dialog)
{
DialogRunbase dialog = _dialog;
DialogGroup toFromGroup;
Args _args;
str accountnum,custGroup;
;
// _args = new Args();
// obj_dev_CustTable = _args.record();
//accountnum = obj_dev_CustTable.AccountNum;
dialogcustGroup = dialog.addFieldValue(extendedTypeStr(CustGroup),CustGroup,"");
while select obj_CustTable
where obj_CustTable.AccountNum == dialogcustGroup .value()
{
CID = obj_dev_CustTable.CID;
dialogcustaccount =dialog.addFieldValue(ExtendedTypeStr(AccountNum),accountnum,"CID");
}
return dialog;
}
Any help would be great!!!!
The best way to do it is to override the lookup() method on the specified DialogField. See the example below - it works just fine.
class CustomizedLookup extends RunBase
{
DialogRunbase dialog;
DialogField dFieldCustGroup;
DialogField dFieldCustAccount;
CustGroupId fetchedCustGroup;
CustAccount fetchedAccountNum;
}
protected Object dialog()
{
dialog = super();
FieldCustGroup = dialog.addField(extendedTypeStr(CustGroupId),"sysLabel1");
dFieldCustGroup.allowEdit(true);
dFieldCustAccount = dialog.addField(extendedTypeStr(CustAccount),"sysLabel1");
dFieldCustAccount.allowEdit(false);
return dialog;
}
public void dialogPostRun(DialogRunbase _dialog)
{
super(_dialog);
// allow to call the event methods
// of this class (e.g. Fld1_1_modified() method)
_dialog.dialogForm().formRun().controlMethodOverload(true);
_dialog.dialogForm().formRun().controlMethodOverloadObject(this);
}
private boolean Fld1_1_modified() // dFieldCustGroup
{
FormStringControl control;
boolean isFieldModified;
control = dialog.formRun().controlCallingMethod();
isFieldModified = control.modified();
if(isFieldModified)
{
fetchedCustGroup = dFieldCustGroup.value();
dFieldCustAccount.allowEdit(true);
}
return isFieldModified;
}
private void Fld2_1_lookup() //dFieldCustAccount
{
FormStringControl control = dialog.formRun().controlCallingMethod();
SysTableLookup sysTableLookup = SysTableLookup::newParameters(tablenum(CustTable),control);
Query query = new Query();
QueryBuildDataSource queryBuildDataSource;
QueryBuildRange queryBuildRange;
queryBuildDataSource = query.addDataSource(TableNum(CustTable));
queryBuildRange = queryBuildDataSource.addRange(FieldNum(CustTable, CustGroup));
queryBuildRange.value(fetchedCustGroup);
sysTableLookup.addLookupfield(fieldnum(CustTable, AccountNum));
sysTableLookup.addLookupfield(fieldnum(CustTable, CustGroup));
sysTableLookup.parmQuery(query);
sysTableLookup.performFormLookup();
}
public boolean getFromDialog()
{
boolean ret;
ret = super();
fetchedAccountNum = dFieldCustAccount.value();
return ret;
}
static void main(Args _e)
{
CustomizedLookup customizedLookup;
customizedLookup = new CustomizedLookup();
if (customizedLookup.prompt())
{
customizedLookup.run();
// do some actions with your data
customizedLookup.theAction();
}
}
private void theAction()
{
info(strFmt("Customer Group: %1",fetchedCustGroup));
info(strFmt("Account Number: %1",fetchedAccountNum));
}
Some more methods like pack , unpack and main method should be declared
public class CustAmountCalculation extends RunBase
{
DialogField fieldAccount;
CustAccount custAccount;
}
public Object dialog()
{
Dialog dialog;
DialogGroup groupCustomer;
dialog = super();
fieldAccount = dialog.addField(extendedTypeStr(custAccount), "CustomerAccount");
return dialog;
}
public boolean getFromDialog()
{
custAccount = fieldAccount.value();
return super();
}
public container pack()
{
return conNull();
}
public void run()
{
CustTable custTable;
CustTrans custTrans;
;
select sum(AmountMST) from custTrans where custTrans.AccountNum == custAccount;
info("You have enetered customer information");
info(strfmt("Account: %1", custAccount));
info(strFmt("Amount: %1", custTrans.AmountMST));
}
public boolean unpack(container _packedClass)
{
return true;
}
public static void main(Args _args)
{
CustAmountCalculation custAmountCalculation = new CustAmountCalculation();
if (CustAmountCalculation.prompt())
{
CustAmountCalculation.run();
}
}
In screen1 i have 2 buttons a and b.i have given field change listener for both such that each pushes corresponding screen .When i press button 'a' it pushes say screen2 where i have used a keywordFilter to search words from sqlite database and is listed.These all are perfect when i run the application ,but when i press the back(or previous key) and then press the button 'a' from screen1 again i dont find any results from database.same thing happens to button b also .What cud b the pblm pls help.
Thank u so much in advance
Below is the class called after button 'a' is clicked
import net.rim.device.api.ui.*;
import net.rim.device.api.io.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.system.*;
import java.util.*;
import net.rim.device.api.database.Database;
import net.rim.device.api.database.DatabaseFactory;
import net.rim.device.api.database.Row;
import net.rim.device.api.database.Statement;
public final class KeywordFilter
{
private KeywordFilterField _keywordFilterField;
private WordList _wordList;
private Vector _words;
public KeywordFilter()
{
_words = getDataFromDatabase();
if(_words != null)
{
_wordList = new WordList(_words);
_keywordFilterField = new KeywordFilterField();
_keywordFilterField.setSourceList(_wordList, _wordList);
CustomKeywordField customSearchField = new CustomKeywordField();
_keywordFilterField.setKeywordField(customSearchField);
KeywordFilterScreen screen = new KeywordFilterScreen(this);
screen.setTitle(_keywordFilterField.getKeywordField());
screen.add(_keywordFilterField);
UiApplication ui = UiApplication.getUiApplication();
ui.pushScreen(screen);
}
else
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("Error reading data file.");
System.exit(0);
}
});
}
}
KeywordFilterField getKeywordFilterField()
{
return _keywordFilterField;
}
private Vector getDataFromDatabase()
{
Vector words = new Vector();
Database d;
for(;;)
{
try
{
URI myURI=URI.create("file:///SDCard/Databases/MyTestDatabase.db");
d=DatabaseFactory.open(myURI);
Statement st=d.createStatement("SELECT eng,mal FROM Malayalam m,English e where e.Ecode=m.Mcode");
st.prepare();
net.rim.device.api.database.Cursor c=st.getCursor();
Row r;
while(c.next())
{
r=c.getRow();
String w=r.getString(0);
String meaning=r.getString(1);
words.addElement(new Word(w,meaning));
}}
catch ( Exception e )
{
System.out.println( e.getMessage() );
e.printStackTrace();
}
return words;
}
}
void addElementToList(Word w)
{
_wordList.addElement(w);
_keywordFilterField.updateList();
}
final static class CustomKeywordField extends BasicEditField
{
CustomKeywordField()
{
super(USE_ALL_WIDTH|NON_FOCUSABLE|NO_LEARNING|NO_NEWLINE);
setLabel("Search: ");
}
protected boolean keyChar(char ch, int status, int time)
{
switch(ch)
{
case Characters.ESCAPE:
if(super.getTextLength() > 0)
{
setText("");
return true;
}
}
return super.keyChar(ch, status, time);
}
protected void paint(Graphics graphics)
{
super.paint(graphics);
getFocusRect(new XYRect());
drawFocus(graphics, true);
}
}
}
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.system.*;
final class KeywordFilterScreen extends MainScreen
{
private KeywordFilter _app;
private KeywordFilterField _keywordFilterField;
public KeywordFilterScreen(KeywordFilter app)
{
_app = app;
_keywordFilterField = _app.getKeywordFilterField();
}
protected boolean keyChar(char key, int status, int time)
{
if (key == Characters.ENTER)
{
displayInfoScreen();
return true;
}
return super.keyChar(key, status, time);
}
public boolean invokeAction(int action)
{
switch(action)
{
case ACTION_INVOKE:
displayInfoScreen();
return true;
}
return super.invokeAction(action);
}
private void displayInfoScreen()
{
Word w = (Word)_keywordFilterField.getSelectedElement();
if(w != null)
{
InfoScreen infoScreen = new InfoScreen(w);
UiApplication ui = UiApplication.getUiApplication();
ui.pushScreen(infoScreen);
ui.popScreen(this);
}
}
private final static class InfoScreen extends MainScreen
{
InfoScreen(Word w)
{
setTitle(w.toString());
BasicEditField popField = new BasicEditField(":",w.getMeaning(),20,Field.NON_FOCUSABLE);
add(popField);
}
}
}
public class Word
{
private String _word;
private String _meaning;
public Word(String word, String meaning)
{
_word = word;
_meaning = meaning;
}
String getMeaning()
{
return _meaning;
}
public String toString()
{
return _word;
}
}
import net.rim.device.api.ui.component .*;
import net.rim.device.api.collection.util.*;
import net.rim.device.api.util.*;
import java.util.*;
public class WordList extends SortedReadableList implements KeywordProvider
{
public WordList(Vector words)
{
super(new WordListComparator());
loadFrom(words.elements());
}
void addElement(Object element)
{
doAdd(element);
}
public String[] getKeywords( Object element )
{
if(element instanceof Word )
{
return StringUtilities.stringToWords(element.toString());
}
return null;
}
final static class WordListComparator implements Comparator
{
public int compare(Object o1, Object o2)
{
if (o1 == null || o2 == null)
throw new IllegalArgumentException("Cannot compare null words");
return o1.toString().compareTo(o2.toString());
}
}
}
add st.close(); and d.close() after accessing db in private Vector getDataFromDatabase() method just before closing the try block