How to add Default value in spinner in android? - spinner

How to add the default value in spinner like selectone? I want to add one value in spinner that is visible on spinne,r but when I click on spinner all the values of adapter get displayed in front of me but not selectone which is the default value.
try {
json = new JSONObject(Status);
// nameArray = json.names();
valArray = json.getJSONArray("Machines");
} catch (JSONException e) {
e.printStackTrace();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
for (int i = 0; i < valArray.length(); i++) {
try {
String machineName = valArray.getJSONObject(i)
.getString("MachineName").toString();
// Integer machineID = Integer.parseInt(valArray.getJSONObject(
// 0).getString("MachineID"));
// Entities.machineID = machineID;
adapter.add(machineName);
} catch (JSONException e) {
e.printStackTrace();
}
}
sp_Machine.setAdapter(adapter);

If you are getting the values of the spinner dynamically, then this is the way to add select at first of the spinner value:
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/android/classname_spinner.php");
try{
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,responseHandler);
JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("output");
arr = new String[jArray.length()+1];
arr[0] = "-select-";
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String sclass = json_data.getString("spinner");
arr[i+1] = sclass;
}
}catch (Exception e) {
Log.e("log_tag","Error parsing classname data"+e.toString());
}
}catch (Exception e) {
Log.e("log_tag","Request failed"+e.toString());
}
now add the value you got to the spinner as shown below:
classSpinner = (Spinner) findViewById(R.id.editClass);
ArrayAdapter<String> classNameAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,arr);
classNameAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
classSpinner.setAdapter(classNameAdapter);
Now when want the spinner to get back to its default value on on click event, then just write in your on click event as:
reset.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
classSpinner.setSelection(0);
}
});
Hope this helps you.

here is a solution i came up with a while back. just use this adapter instead of a regular one:
package perelman.yuval.carsapp;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class SpinnerDualAdapter<T> extends ArrayAdapter<T> {
private ArrayAdapter<String> myAdapter;
private boolean isPromptAdapter;
private SpinnerDualAdapter(Context context, int textViewResourceId,
List<T> objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
}
public SpinnerDualAdapter(Context context,
int textViewResourceIdForDropdownView,
int textViewResourceIdForDefaultView, List<T> objects,
String defaultValue) {
this(context, textViewResourceIdForDropdownView, objects);
ArrayList<String> myArrayList = new ArrayList<String>();
myArrayList.add(defaultValue);
myAdapter = new ArrayAdapter<String>(context,
textViewResourceIdForDefaultView, myArrayList);
isPromptAdapter=true;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(isPromptAdapter){
isPromptAdapter=false;
return myAdapter.getView(position, convertView, parent);
}
TextView tv=new TextView(getContext());
tv.setText(this.getItem(position).toString());
return tv;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent){
isPromptAdapter=false;
return(super.getDropDownView(position, convertView, parent));
}
}

Related

How do I implement multiple intent from each Card from CardView with RecyclerView?

I would like to implement a new intent when my card from CardView is clicked. I have already implemented for one of the cards. Is there any other way in which the adapter is able to identify the position and bring to a new activity for each card? Like linking the each card to their individual activity with a template layout. (The new activity for each card will be of the same layout, just different texts and images).
I have added an ImageButton on my cards. However, when I click on the ImageButton, it does not bring me to the new activity. Clicking on the card edges/portion and not the image itself would work. Is there something I missed out on my code? I can't seem to get it.
Here are my codes:
MuaActivity.java
package android.com.example.weddingappfinale;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import Adapters.MuaAdapter;
import CustomerActivities.ShimaMatinActivity;
public class MuaActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private MuaAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mua_list);
getSupportActionBar().setTitle("Make Up Artists");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ArrayList<MuaView> muaView = new ArrayList<>();
muaView.add(new MuaView(R.drawable.mua_image, "Shima Matin Bridal Services"));
muaView.add(new MuaView(R.drawable.mua_image, "Aake Up Artist Pte Ltd"));
muaView.add(new MuaView(R.drawable.mua_image, "Lake Up Artist 3Pte Ltd"));
muaView.add(new MuaView(R.drawable.mua_image, "f Up Artist Pte Ltd"));
// ArrayList
mRecyclerView = findViewById(R.id.recycler_view_list);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new MuaAdapter(muaView);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new MuaAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
Intent i = new Intent (MuaActivity.this, ShimaMatinActivity.class);
startActivity(i);
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setImeOptions(EditorInfo.IME_ACTION_DONE);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
mAdapter.getFilter().filter(newText);
return false;
}
});
return true;
}
}
MuaAdapter.java
package Adapters;
import android.com.example.weddingappfinale.MuaView;
import android.com.example.weddingappfinale.R;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MuaAdapter extends RecyclerView.Adapter<MuaAdapter.MuaViewHolder> implements Filterable {
private ArrayList<MuaView> mMuaView;
private ArrayList<MuaView> mMuaViewFull;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public static class MuaViewHolder extends RecyclerView.ViewHolder {
public ImageButton mImageButton;
public TextView mTextView1;
public MuaViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
mImageButton = itemView.findViewById(R.id.mua_imageButton);
mTextView1 = itemView.findViewById(R.id.mua_title);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
}
}
public MuaAdapter(ArrayList<MuaView> muaView) {
this.mMuaView = muaView;
mMuaViewFull = new ArrayList<>(muaView);
}
#NonNull
#Override
public MuaViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.mua_view, parent, false);
MuaViewHolder mvh = new MuaViewHolder(v, mListener);
return mvh;
}
#Override
public void onBindViewHolder(#NonNull MuaViewHolder holder, int position) {
MuaView currentView = mMuaView.get(position);
holder.mImageButton.setImageResource(currentView.getImageResource());
holder.mTextView1.setText(currentView.getText1());
}
#Override
public int getItemCount() {
return mMuaView.size();
}
public Filter getFilter() {
return MuaFilter;
}
private Filter MuaFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<MuaView> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(mMuaViewFull);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (MuaView item : mMuaViewFull) {
if (item.getText1().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mMuaView.clear();
mMuaView.addAll((ArrayList) results.values);
notifyDataSetChanged();
}
};
}
Answer for first question:
You could pass the position of the item to the new activity with intent.putExtra().
In the new activity you can read out the number with intent.getExtra() and setup your layout content as you want depending on the number you got.
This way you only have one Activity instead of many.
Activity 1
Intent intent = new Intent(this, Shima.class);
intent.putExtra("position_value", position);
startActivity(intent);
Activity 2
Intent intent = getIntent();
int position = intent.getIntExtra("position_value", 0); // 0 is the default value
// set a layout based on position with switch case or if...
switch (position){
case 1:
setContentView(R.layout.activity_card_one);
break;
case 2:
setContentView(R.layout.activity_card_two);
break;
....
Second question:
See here.
Basicaly the same way like
itemView.setOnClickListener(new View.OnClickListener() {...
You can set a image depending on what item has been clicked using something like this
private Integer images[] = {R.drawable.pic1, R.drawable.pic2, R.drawable.pic3}
and
imageView.setImageResource(images[position]);
(maybe position -1, not sure if first item in recyclerView is 1 or 0)

How can i clear an android viewholder cache when i close my activity (Images repeating)

I'm new on Android Studio, I showed a listview of images and text in my main activity, everything worked fine until I started to have performance issues, those were solved following this tutorial:
https://www.youtube.com/watch?v=cKUxiqNB5y0 (the app showed in the video is almost the same as mine)
My problem now is that when I create new objects that are added to the listview the images are duplicated when I update the app (I think that is a cache issue because I am using universal image loader).
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import java.util.List;
public class CharacterListAdapter extends ArrayAdapter<AnimeCharacter> {
private static final String TAG = "AnimeCharacterAdapter";
private Context context;
private int mResource;
static class ViewHolder {
TextView character_name;
TextView character_anime;
ImageView img;
}
public CharacterListAdapter(#NonNull Context context, int resource, #NonNull List<AnimeCharacter> objects) {
super(context, resource, objects);
this.context = context;
mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
setup_image_loader();
String character_name = getItem(position).getCharacter_name();
String character_anime = getItem(position).getCharacter_anime();
String img_url = getItem(position).getCharacter_img();
ViewHolder view_holder;
view_holder = new ViewHolder();
if (convertView == null) {
LayoutInflater layout_inflater = LayoutInflater.from(context);
convertView = layout_inflater.inflate(mResource, parent, false);
view_holder.character_name = convertView.findViewById(R.id.txt_character_name);
view_holder.character_anime = convertView.findViewById(R.id.txt_anime_name);
view_holder.img = convertView.findViewById(R.id.character_img);
convertView.setTag(view_holder);
} else {
view_holder = (ViewHolder) convertView.getTag();
}
int default_img = context.getResources().getIdentifier("#drawable/img_default", null, context.getPackageName());
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(default_img)
.showImageOnFail(default_img)
.showImageOnLoading(default_img).build();
imageLoader.displayImage(img_url, view_holder.img, options);
view_holder.character_name.setText(character_name);
view_holder.character_anime.setText(character_anime);
// ImageLoader.getInstance().clearMemoryCache();
// ImageLoader.getInstance().clearDiskCache();
return convertView;
}
private void setup_image_loader() {
// UNIVERSAL IMAGE LOADER SETUP
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
context)
.defaultDisplayImageOptions(defaultOptions)
.memoryCache(new WeakMemoryCache())
.discCacheSize(100 * 1024 * 1024).build();
ImageLoader.getInstance().init(config);
// END - UNIVERSAL IMAGE LOADER SETUP
}
}
I found other posts where the solution was clearing the cache with this lines of code:
ImageLoader.getInstance().clearMemoryCache();
ImageLoader.getInstance().clearDiskCache();
My problem is that i dont know how to override the method "onDestroy" inside the Adapter, in this post, they implented it in the MainActivity
android universal image loader clear cache
The last thing, when i unistall the app on my phone, and i rebuild it, the problem is gone (until i add another object to the listview)
I solved with this code:
#Override
protected void onDestroy() {
super.onDestroy();
try {
trimCache(this);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}

How to get JSONArray which has no JSONArray keyword in Android Studio

I am new to this JSON, I am trying to get the JSON values, it is actually as JSONArray with No name. I have gone through some tutorials where they accessed through JSONArray Keyword. But in my JSON File there is no such ArrayName. Kindly help me to solve this. This is my JSON Value:
[
{"id":"4","name":"Trichy"},
{"id":"5","name":"Pondy"},
{"id":"6","name":"Kovai"},
{"id":"7","name":"Madurai"},
{"id":"8","name":"Chennai"},
{"id":"9","name":"Hyderabad"}
]
I need to get "name" from this. Here comes my MainActivity file.
try {
// Locate the NodeList name
JSONArray json=new JSONArray(???); //I dont know what to give here
for (int i = 0; i < json.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Cites worldpop = new Cites();
worldpop.setCity(jsonobject.optString("name"));
cit.add(worldpop);
// Populate spinner with country names
worldlist.add(jsonobject.optString("name"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
This is my City.java file.
package com.example.user.spinnercontrol;
public class Cites {
private String city;
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city=city;
}
}
This is my JSON.java file (for reference)
package com.example.user.spinnercontrol;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONCity {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
MainActivity class should be like this ::
public class MainActivity extends Activity {
JSONObject jsonobject;
ArrayList<String> worldlist = new ArrayList<>();
ArrayList<Cites> cit = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONArray arr = JSONCity.getJSONfromURL("http://www.prateektechnosoft.com/justcall/cities/getall");
for (int i = 0; i < arr.length(); i++) {
try {
jsonobject = arr.getJSONObject(i);
Cites worldpop = new Cites();
worldpop.setCity(jsonobject.optString("name"));
cit.add(worldpop);
// Populate spinner with country names
worldlist.add(jsonobject.optString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);
// Spinner adapter
mySpinner
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
worldlist));
// Spinner on item click listener
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}

JavaFX 2 TableView how to update cell when object is changed

I'm creating a TableView to show information regarding a list of custom objects (EntityEvents).
The table view must have 2 columns.
First column to show the corresponding EntityEvent's name.
The second column would display a button. The button text deppends on a property of the EntityEvent. If the property is ZERO, it would be "Create", otherwise "Edit".
I managed to do it all just fine, except that I can't find a way to update the TableView line when the corresponding EntityEvent object is changed.
Very Important: I can't change the EntityEvent class to use JavaFX properties, since they are not under my control. This class uses PropertyChangeSupport to notify listeners when the monitored property is changed.
Note:
I realize that adding new elements to the List would PROBABLY cause the TableView to repaint itself, but that is not what I need. I say PROBABLY because I've read about some bugs that affect this behavior.
I tried using this approach to force the repaint, by I couldn't make it work.
Does anyone knows how to do it?
Thanks very much.
Here is a reduced code example that illustrates the scenario:
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javafx.application.Application;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TableView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Callback;
public class Main extends Application {
//=============================================================================================
public class EntityEvent {
private String m_Name;
private PropertyChangeSupport m_NamePCS = new PropertyChangeSupport(this);
private int m_ActionCounter;
private PropertyChangeSupport m_ActionCounterPCS = new PropertyChangeSupport(this);
public EntityEvent(String name, int actionCounter) {
m_Name = name;
m_ActionCounter = actionCounter;
}
public String getName() {
return m_Name;
}
public void setName(String name) {
String lastName = m_Name;
m_Name = name;
System.out.println("Name changed: " + lastName + " -> " + m_Name);
m_NamePCS.firePropertyChange("Name", lastName, m_Name);
}
public void addNameChangeListener(PropertyChangeListener listener) {
m_NamePCS.addPropertyChangeListener(listener);
}
public int getActionCounter() {
return m_ActionCounter;
}
public void setActionCounter(int actionCounter) {
int lastActionCounter = m_ActionCounter;
m_ActionCounter = actionCounter;
System.out.println(m_Name + ": ActionCounter changed: " + lastActionCounter + " -> " + m_ActionCounter);
m_ActionCounterPCS.firePropertyChange("ActionCounter", lastActionCounter, m_ActionCounter);
}
public void addActionCounterChangeListener(PropertyChangeListener listener) {
m_ActionCounterPCS.addPropertyChangeListener(listener);
}
}
//=============================================================================================
private class AddPersonCell extends TableCell<EntityEvent, String> {
Button m_Button = new Button("Undefined");
StackPane m_Padded = new StackPane();
AddPersonCell(final TableView<EntityEvent> table) {
m_Padded.setPadding(new Insets(3));
m_Padded.getChildren().add(m_Button);
m_Button.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent actionEvent) {
// Do something
}
});
}
#Override protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
setGraphic(m_Padded);
m_Button.setText(item);
}
}
}
//=============================================================================================
private ObservableList<EntityEvent> m_EventList;
//=============================================================================================
#SuppressWarnings("unchecked")
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Table View test.");
VBox container = new VBox();
m_EventList = FXCollections.observableArrayList(
new EntityEvent("Event 1", -1),
new EntityEvent("Event 2", 0),
new EntityEvent("Event 3", 1)
);
final TableView<EntityEvent> table = new TableView<EntityEvent>();
table.setItems(m_EventList);
TableColumn<EntityEvent, String> eventsColumn = new TableColumn<>("Events");
TableColumn<EntityEvent, String> actionCol = new TableColumn<>("Actions");
actionCol.setSortable(false);
eventsColumn.setCellValueFactory(new Callback<CellDataFeatures<EntityEvent, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<EntityEvent, String> p) {
EntityEvent event = p.getValue();
event.addActionCounterChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent event) {
// TODO: I'd like to update the table cell information.
}
});
return new ReadOnlyStringWrapper(event.getName());
}
});
actionCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<EntityEvent, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<EntityEvent, String> ev) {
String text = "NONE";
if(ev.getValue() != null) {
text = (ev.getValue().getActionCounter() != 0) ? "Edit" : "Create";
}
return new ReadOnlyStringWrapper(text);
}
});
// create a cell value factory with an add button for each row in the table.
actionCol.setCellFactory(new Callback<TableColumn<EntityEvent, String>, TableCell<EntityEvent, String>>() {
#Override
public TableCell<EntityEvent, String> call(TableColumn<EntityEvent, String> personBooleanTableColumn) {
return new AddPersonCell(table);
}
});
table.getColumns().setAll(eventsColumn, actionCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
// Add Resources Button
Button btnInc = new Button("+");
btnInc.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent ev) {
System.out.println("+ clicked.");
EntityEvent entityEvent = table.getSelectionModel().getSelectedItem();
if (entityEvent == null) {
System.out.println("No Event selected.");
return;
}
entityEvent.setActionCounter(entityEvent.getActionCounter() + 1);
// TODO: I expected the TableView to be updated since I modified the object.
}
});
// Add Resources Button
Button btnDec = new Button("-");
btnDec.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent ev) {
System.out.println("- clicked.");
EntityEvent entityEvent = table.getSelectionModel().getSelectedItem();
if (entityEvent == null) {
System.out.println("No Event selected.");
return;
}
entityEvent.setActionCounter(entityEvent.getActionCounter() - 1);
// TODO: I expected the TableView to be updated since I modified the object.
}
});
container.getChildren().add(table);
container.getChildren().add(btnInc);
container.getChildren().add(btnDec);
Scene scene = new Scene(container, 300, 600, Color.WHITE);
primaryStage.setScene(scene);
primaryStage.show();
}
//=============================================================================================
public Main() {
}
//=============================================================================================
public static void main(String[] args) {
launch(Main.class, args);
}
}
Try the javafx.beans.property.adapter classes, particularly JavaBeanStringProperty and JavaBeanIntegerProperty. I haven't used these, but I think you can do something like
TableColumn<EntityEvent, Integer> actionCol = new TableColumn<>("Actions");
actionCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<EntityEvent, Integer> ev) {
return new JavaBeanIntegerPropertyBuilder().bean(ev.getValue()).name("actionCounter").build();
});
// ...
public class AddPersonCell extends TableCell<EntityEvent, Integer>() {
final Button button = new Button();
public AddPersonCell() {
setPadding(new Insets(3));
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
button.setOnAction(...);
}
#Override
public void updateItem(Integer actionCounter, boolean empty) {
if (empty) {
setGraphic(null);
} else {
if (actionCounter.intValue()==0) {
button.setText("Create");
} else {
button.setText("Add");
}
setGraphic(button);
}
}
}
As I said, I haven't used the Java bean property adapter classes, but the idea is that they "translate" property change events to JavaFX change events. I just typed this in here without testing, but it should at least give you something to start with.
UPDATE: After a little experimenting, I don't think this approach will work if your EntityEvent is really set up the way you showed it in your code example. The standard Java beans bound properties pattern (which the JavaFX property adapters rely on) has a single property change listener and an addPropertyChangeListener(...) method. (The listeners can query the event to see which property changed.)
I think if you do
public class EntityEvent {
private String m_Name;
private PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private int m_ActionCounter;
public EntityEvent(String name, int actionCounter) {
m_Name = name;
m_ActionCounter = actionCounter;
}
public String getName() {
return m_Name;
}
public void setName(String name) {
String lastName = m_Name;
m_Name = name;
System.out.println("Name changed: " + lastName + " -> " + m_Name);
pcs.firePropertyChange("name", lastName, m_Name);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcs.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcs.removePropertyChangeListener(listener);
}
public int getActionCounter() {
return m_ActionCounter;
}
public void setActionCounter(int actionCounter) {
int lastActionCounter = m_ActionCounter;
m_ActionCounter = actionCounter;
System.out.println(m_Name + ": ActionCounter changed: " + lastActionCounter + " -> " + m_ActionCounter);
pcs.firePropertyChange("ActionCounter", lastActionCounter, m_ActionCounter);
}
}
it will work with the adapter classes above. Obviously, if you have existing code calling the addActionChangeListener and addNameChangeListener methods you would want to keep those existing methods and the existing property change listeners, but I see no reason you can't have both.

implementing grid view with in a horizontal scroll(view flipper)

i want to implement a horizontal slide to my grid view so that one slide displays 9 images and next slide displays the other 9 images and so on. The images here are took from sd card. can any one help out please..!!
after a trying for a long time i got the right code as
package flipper.view;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
public class NewflipperActivity extends Activity implements OnClickListener,OnTouchListener{
ViewFlipper flip;
Animation animFlipInForeward;
Animation animFlipOutForeward;
Animation animFlipInBackward;
Animation animFlipOutBackward;
int filepos=0;
int y;
private GestureDetector gestureDetector;
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
RelativeLayout rl1,rl2;
TextView tv1,tv2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Display dip=getWindowManager().getDefaultDisplay();
int width=dip.getWidth();
int actualheight=dip.getHeight();
System.out.println("width is--->"+width);
System.out.println("height is--->"+actualheight);
int layoutheight=(actualheight)/8;
int flipheight=6*layoutheight;
RelativeLayout.LayoutParams params1=new RelativeLayout.LayoutParams(width,layoutheight-30);
params1.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
tv1=(TextView)findViewById(R.id.textView1);
tv1.setLayoutParams(params1);
RelativeLayout.LayoutParams params2=new RelativeLayout.LayoutParams(width,layoutheight-30);
params2.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
tv2=(TextView)findViewById(R.id.textView2);
tv2.setLayoutParams(params2);
gestureDetector = new GestureDetector(new MyGestureDetector());
flip=(ViewFlipper)findViewById(R.id.viewFlipper1);
flip.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return false;
}
return true;
}
});
LinearLayout mylay=(LinearLayout)findViewById(R.id.linearlay);
LinearLayout.LayoutParams layparam=new LinearLayout.LayoutParams(width,flipheight);
mylay.setLayoutParams(layparam);
animFlipInForeward = AnimationUtils.loadAnimation(this, R.anim.flipin);
animFlipOutForeward = AnimationUtils.loadAnimation(this, R.anim.flipout);
animFlipInBackward = AnimationUtils.loadAnimation(this, R.anim.flipin_reverse);
animFlipOutBackward = AnimationUtils.loadAnimation(this, R.anim.flipout_reverse);
String folderpath=Environment.getExternalStorageDirectory()+"/New Folder/";
File filepath=new File(folderpath);
File[] mylist=filepath.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
// TODO Auto-generated method stub
return (filename.toLowerCase().endsWith(".jpg")||filename.toLowerCase().endsWith(".png")||filename.toLowerCase().endsWith(".jpeg"));
}
});
Arrays.sort(mylist);
int folderlength=mylist.length;
int mylength=folderlength/9;
if(folderlength%9==0)
{
y=mylength;
}
else
{
y=(mylength)+1;
}
for(int i=0;i<y;i++)
{System.out.println("abc"+i);
TableLayout mtable=new TableLayout(this);
TableLayout.LayoutParams myparams=new TableLayout.LayoutParams(width,flipheight);
mtable.setLayoutParams(myparams);
mtable.setWeightSum(3);
mtable.setOnTouchListener(NewflipperActivity.this);
for(int j=0;j<3;j++)
{
TableRow mrow=new TableRow(this);
mrow.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
mrow.setOnTouchListener(NewflipperActivity.this);
for(int k=0;k<3;k++)
{
if(filepos<folderlength)
{
Log.i("displaying","image at file pos"+mylist[filepos]);
final ImageView imageView = new ImageView(this);
Bitmap imgBitmap,b1;
try
{
if(mylist[filepos].length()>1500){
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inSampleSize = 4;
imgBitmap = BitmapFactory.decodeFile(mylist[filepos] + "",bounds);
b1=Bitmap.createScaledBitmap(imgBitmap, ((int)(width/3))-20, ((int)(flipheight/3))-20, true);
}
else
{
imgBitmap=BitmapFactory.decodeFile(mylist[filepos] + "");
b1=Bitmap.createScaledBitmap(imgBitmap, ((int)(width/3))-20,((int)(flipheight/3))-20, true);
}
imageView.setImageBitmap(b1);
imageView.setAdjustViewBounds(true);
imageView.setPadding(10,10,10,10);
imageView.setTag(mylist[filepos]+"");
imageView.setOnTouchListener(NewflipperActivity.this);
imageView.setOnClickListener(NewflipperActivity.this);
// final String imagename=mylist[filepos].getName();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
mrow.addView(imageView);
filepos++;
}
}
mtable.addView(mrow);
}
flip.addView(mtable);
}
}
private void SwipeRight(){
flip.setInAnimation(animFlipInBackward);
flip.setOutAnimation(animFlipOutBackward);
flip.showPrevious();
}
private void SwipeLeft(){
flip.setInAnimation(animFlipInForeward);
flip.setOutAnimation(animFlipOutForeward);
flip.showNext();
}
class MyGestureDetector extends SimpleOnGestureListener {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(NewflipperActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show();
SwipeLeft();
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(NewflipperActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show();
SwipeRight();
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
#Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ImageView imagename1 = (ImageView)v;
String imgName = (String) imagename1.getTag();
Toast.makeText(NewflipperActivity.this, "clicked on image-->"+imgName, Toast.LENGTH_SHORT).show();
Log.e("displaying","clicked onimage::::::"+imgName);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (gestureDetector.onTouchEvent(event)) {
return true;
}
return false;
}
}

Resources