How to Set an image to lwuit list? - java-me

i want to set a title and an image to lwuit list from Rss feed,i am able to set title ,but i dont know how to set an image?after i set an image and title ,then i need to display it on form...
here my code:,Help...
public void disp() {
//String[] items={newsItem.getTitle()};
for(int i=0;i<news.size();i++){
newsItem=(News)news.elementAt(i);
myNewsList.addItem(newsItem.getTitle().toString());
System.out.println(newsItem.getTitle());
}
try{
System.out.println("hiii");
form1.addComponent(myNewsList);
form1.addCommand(cmdDetails);
form1.setScrollable(true);
form1.setTransitionInAnimator(Transition3D.createRotation(250, true));
form1.show();
}
catch(Exception e){
e.printStackTrace();
}

You can use list renderer to add image and text in single list item.
NewsListRenderer.java
public class NewsListRenderer implements ListCellRenderer {
private Label lblImage;
private TextArea textAreaHeadline;
public Component getListCellRendererComponent(List arg0, Object obj,
int arg2, boolean isSelected) {
Container newsContainer = new Container();
newsContainer.setLayout(new BoxLayout(BoxLayout.X_AXIS));
News newsListObj = (News) obj;
Image img = newsListObj.getThumbnail();
lblImage = new Label(img);
lblImage.getStyle().setBgTransparency(0);
lblImage.setTextPosition(Component.BOTTOM);
newsContainer.addComponent(lblImage);
textAreaHeadline = new TextArea(3, 25);
textAreaHeadline.setSelectedStyle(textAreaHeadline.getStyle());
textAreaHeadline.setText(newsListObj.getHeadLine());
textAreaHeadline.setEditable(false);
textAreaHeadline.getStyle().setBorder(null);
textAreaHeadline.setFocusable(false);
textAreaHeadline.getStyle().setBgTransparency(0);
newsContainer.addComponent(textAreaHeadline);
return newsContainer;
}
public Component getListFocusComponent(List arg0) {
return new Container();
}
}
Members of News Class:
1) News title - getHeadLine() to retrieve title.
2) News Image - getThumbnail() to retrieve image.
myNewsList = new List(news);
myNewsList.setListCellRenderer(new NewsListRenderer());
form1.addComponent(myNewsList);
form1.addCommand(cmdDetails);
form1.setScrollable(true);
form1.setTransitionInAnimator(Transition3D.createRotation(250, true));
form1.show();

Related

Creating a very custom list

I'm developping an application, and now, I don't know what to do next:
I have a list of elements, each element has some informations + an ID + a logo.
What I want to do is creating a list like in the picture
List
Of course, I want it in a single layer, with the logo, some informations, and a button to define an action; where I could use the ID of the selected item.
I did some research, may be I found some relative subjects, but none of what I want.
My list is a
ArrayList<ArrayList<String>>
filled by data from database.
Thank you
Here it is:
public class Avancee extends Activity {
// Log tag
private static final String TAG = MainActivity2.class.getSimpleName();
// Movies json url
private static final String url = "http://blabla.com/movie.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Log.d(TAG, response.toString());
hidePDialog();
String result = getIntent().getStringExtra("ITEM_EXTRAA");
System.out.println(result);
try{
JSONArray ja = new JSONArray(result);
for (int i = 0; i < ja.length(); i++) {
try {
JSONObject obj = ja.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setLocation(obj.getString("location_search_text"));
movie.setId(obj.getInt("id"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#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;
}
}
It's the "id" that I want to get in the OnClick event.
use this code
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Movie movie= movieList.get(position);
}
});
//here position will give you the id of listview cell so you can use it like
Movie movie= movieList.get(position);
then you can use it get all the data inside your moview object

JavaFx ProgressBar Bind SimpleDoubleProperty

I am using a progressbar in a tableview, where I'm using bind on his property so that when the value is changed, progressbar is started:
private SimpleDoubleProperty progressBar;
public Tabela(Double progressBar) {
this.progressBar = new SimpleDoubleProperty(progressBar);
}
public Double getProgressBar() {
return progressBar.get();
}
public DoubleProperty getProgressBarProperty() {
return progressBar;
}
public void setProgressBar(Double progressBar) {
this.progressBar.set(progressBar);
}
public void setProgressBar(SimpleDoubleProperty progressBar) {
this.progressBar = progressBar;
}
And in my Hbox am using progressbar as follows:
final ProgressBar progress = new ProgressBar();
progress.setMinWidth(324.0);
progress.progressProperty().bind(tabela.getProgressBarProperty());
So I'm using a so that after a certain time the value is changed, ie I will control the progressbar. The value is changed, but in my tableview nothing happens, but when I change the column position to another, the progressbar is running.
The same happens with "label", i changed for "text" and it work, but if the progressbar I have to use.
have a way to force the 'tableview' refresh?
You need to follow the JavaFX naming standard to get TableViews and other widgets to properly refresh when an observable object changes. For instance, you should rename getProgressBarProperty() to progressBarProperty().
See: How to update TableView Row using javaFx
There would be something wrong in this source?
class table
...
public Tabela(String nome, Double progressBar, String etapa) {
this.nome = nome;
this.progressBar = new SimpleDoubleProperty(progressBar);
this.etapa = new SimpleStringProperty(etapa);
}
....
Add new line.
private void preencheListaNomeTabelas() {
getLista().add(new Tabela("Test", 0.0, "Test Text"));
Add hbox in table.
columTabela.setCellValueFactory(new PropertyValueFactory<Tabela, String>("nome"));
columSituacao.setCellFactory(new Callback<TableColumn<Tabela, Double>, TableCell<Tabela, Double>>() {
public TableCell<Tabela, Double> call(TableColumn<Tabela, Double> p) {
final HBox box = new HBox();
box.setPrefHeight(25.0);
final ProgressBar progressBar = new ProgressBar(-1);
final Text text = new Text();
**text.textProperty().bind(..); //I would use here the**
BorderPane border = new BorderPane();
border.setTop(text);
border.setBottom(progressBar);
BorderPane.setAlignment(text, Pos.CENTER);
box.getChildren().add(border);
final TableCell cell = new TableCell<Tabela, Double>() {
#Override
protected void updateItem(Double t, boolean bln) {
super.updateItem(t, bln);
if (bln) {
setText(null);
setGraphic(null);
} else {
progressBar.setProgress(t);
progressBar.prefWidthProperty().bind(this.widthProperty());
setGraphic(box);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
}
};
cell.setAlignment(Pos.CENTER);
return cell;
}
});
columSituacao.setCellValueFactory(new PropertyValueFactory<Tabela, Double>("progress"));
columSituacao.setText("Progresso");
tableView.getItems().addAll(lista);
tableView.getSelectionModel().selectFirst();
task
Task t = new Task() {
#Override
protected Object call() throws Exception {
Thread.sleep(10000);
getLista().get(0).setEtapa("Lendo PostgreSQL");
getLista().get(0).setProgressBar(-1.0);
return null;
}
};
new Thread(t).start();

Search Location on Action Bar Android

I want to ask about finding a location using the action bar. I've made ​​the program as shown below :
I've made a class to find location. but at the time I called into the EditText search, class does not work.
// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{
#Override
protected List<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
}
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
// Clears all the existing markers on the map
map.clear();
// Adding Markers on Google Map for each matching address
for(int i=0;i<addresses.size();i++){
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
map.addMarker(markerOptions);
// Locate the first location
if(i==0)
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,10));
}
}
and I had to call the class to the class action bar menu. like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.cost_direction, menu);
/** Get the action view of the menu item whose id is search */
View v = (View) menu.findItem(R.id.search).getActionView();
/** Get the edit text from the action view */
EditText txtSearch = ( EditText ) v.findViewById(R.id.txt_search);
/** Setting an action listener */
txtSearch.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// Getting user input location
String location = v.getText().toString();
if(location!=null && !location.equals("")){
new GeocoderTask().execute(location);
}
Toast.makeText(getBaseContext(), "Search : " + v.getText(), Toast.LENGTH_SHORT).show();
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
please help for those who know about the problems I was having. :)
String strPlace = etSearch.getText().toString();
Geocoder gc = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> adrs = null;
try{
adrs = gc.getFromLocationName(strPlace,5);
}catch(IOException e){
}finally{
if (adrs != null){
if(adrs.size() > 0)
{
LatLng loc = new LatLng(adrs.get(0).getLatitude(), adrs.get(0).getLongitude());
map.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(13), 2000, null);
}

How to identify List item in lwuit Form Screen?

i am not able to display the detailed form information specific to the title user clicked on form1 Screen,when i click on any itemlist on form1 screen,i am able to display the detail of first item only(in my code int index=myNewsList.getSelectedIndex() returns always 0 as value)
Here my Detailed Code for Rss App:
//method called by the parsing thread
public void addNews(News newsItem) {
newsVector.addElement(newsItem);//initialsed list with vector
myNewsList = new List(newsVector);
myNewsList.setListCellRenderer(new NewsListCellRenderer());
form1.addComponent(myNewsList);
form1.show();
myNewsList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int selectedIndex = myNewsList.getSelectedIndex();
if(selectedIndex != -1){
newsItem1 = (News)news.elementAt(selectedIndex);
Label l=new Label();
l.setText(newsItem1.getPubDate());
Form detailedForm=new Form();
detailedForm.addCommand(m_backCommand);
detailedForm.addCommandListener(this);
detailedForm.addComponent(l);
detailedForm.show();
}
}
});
}
Can you help?
Add action listener to the list. It is called only if you click any item of the list. In that action listener, get the selected item and cast it to the News class object because you added News class objects in the list. From that object, get the unique property like news id. Pass it to another screen with the current form object (form1).
myNewsList = new List(news);
myNewsList.setListCellRenderer(new NewsListRenderer());
myNewsList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
News allNewsClassObjs = (News) myNewsList.getSelectedItem();
int newsid = allNewsClassObjs.getNewsId();
displayCompleteNewsScreen(form1,newsid);
}
});
form1.addComponent(myNewsList);
form1.addCommand(cmdDetails);
form1.setScrollable(true);
form1.setTransitionInAnimator(Transition3D.createRotation(250, true));
form1.show();
With the news id, you can display the related data in another screen. Add back command to it. In the back command, just show the form1 object.
public void displayCompleteNewsScreen(Form form1,int newsid){
// Get the related data and add it to another form object(form2).
form2.addCommand("Back");
form2.addCommandListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
form1.show();
}
});
form2.show();
}
Instead of using
int selectedIndex = myNewsList.getSelectedIndex();
if(selectedIndex != -1){
newsItem1 = (News)news.elementAt(selectedIndex);
}
Use the below code
newsItem1 = (News)myNewsList.getSelectedItem();

LWUIT item question

I have a standard com.sun.lwuit.list. I can get the selected item using methods getSelectedItem or getSelectedIndex. The item is a picture and two labels. How do I know if I clicked on the picture or on one of the labels. I admit that it is possible to pass the click event to a child components or perhaps may exists a method for finding component by current mouse coordinates.
public class NewsFeedListRender extends Container implements ListCellRenderer
{
private final Container newsFeedCont = new Container();
private final Container pictureCont = new Container();
private final Label name = new Label();
private final Label message = new Label();
private final Label picture = new Label();
private final Label data = new Label();
....
public NewsFeedListRender()
{
setLayout(new BorderLayout());
newsFeedCont.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
pictureCont.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
Style s = name.getStyle();
s.setFont(font_large);
s = message.getStyle();
s.setFont(font_small);
s = data.getStyle();
s.setFont(font_mini);
.....
}
}
public Component getListCellRendererComponent(List list, Object value, int index, boolean isSelected)
{
if (value instanceof MessageItem)
{
MessageItem newsFeedData = (MessageItem) value;
if (newsFeedData.getSender() != null)
{
if (newsFeedData.getSender().getName() != null)
name.setText(newsFeedData.getSender().getName()); //fixthis
}
else
{
name.setText("Unknown sender");
}
if(newsFeedData.getMessage() != null)
message.setText(newsFeedData.getMessage());
else
{
message.setText("Default message");
}
try
{
data.setText(newsFeedData.getDataReceive().toString());
}
catch (Exception e)
{
System.out.println(e.toString());
}
Image img = null;
img = newsFeedData.getSender().getIcon();
if( img != null)
{
picture.setIcon(img);
}
.......
getSelectedItem() returns the Container object and you can count the value of the Container object. Then you need to get the what are the components you are added into this container. See the sample code,
Container con = (Container) list.getSelectedItem();
for(int i = 0; i < con.getComponentCount(); i++){
Object obj = (Object) con.getComponentAt(i); // typecast component name instead object
}

Resources