Im new to programming and I am having a hard time trying to figure this one out. I'm trying to create two visible separate counters on each side of the tablet. One is the the left of the tablet, the other on the right of the tablet. When i click the left button it updates the count on the left(e.g., 1+1+1 etc) but when I click on the right counter, it adds an additional value to sum up on the left counter. (e.g., click on right (adds 1, then when i click on the left counter it acts such as add 2, instead of 1.)
here is what my code looks like so far
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.Button;
import android.widget.EditText;
import android.view.View;
import android.view.View.OnClickListener;
public class swim2 extends Activity {
// References to UI views
EditText txtCount;
EditText txtCount2;
Button PUp;
Button NUp;
static int Count = 0; // Initial count
static int Count2 = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
setContentView(R.layout.main3);
// TODO Auto-generated method stub
Button previous = (Button) findViewById(R.id.button4);
previous.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), swim1.class);
startActivityForResult(myIntent, 0);
}
});
// Retrieve references to UI views by their id in XML layout
NUp = (Button)findViewById(R.id.incremintationbutton2);
txtCount2 = (EditText)findViewById(R.id.ni);
txtCount2.setText(String.valueOf(Count2)); //Set initial value
NUp = (Button)findViewById(R.id.incremintationbutton2);
// Process the button on-click event
NUp.setOnClickListener(new OnClickListener() {
public void onClick(View Button) {
Count++;
txtCount2.setText(String.valueOf(Count2));
}
});
PUp = (Button)findViewById(R.id.incremintationbutton1);
txtCount = (EditText)findViewById(R.id.pi);
txtCount.setText(String.valueOf(Count)); // Set initial value
PUp = (Button)findViewById(R.id.incremintationbutton1);
PUp.setOnClickListener(new OnClickListener() {
public void onClick(View Button) {
Count++;
txtCount.setText(String.valueOf(Count));
}
});
}
}
Fixed it, had to change one of the count++, to count2++.. took me a while but i figured it out after a cup of coffee.
Related
I'm using javafx tableview with observableList list, I tried to prevent list from holding duplicate items.
After doing some search, i figure out that an observableSet can do this job by overidding thoes methodes:equals() and hashcode().
But the problem that javaFX tableview can't hold an observable set:
tableView.setItems(FXCollections.observableSet(new hashSet<T>());
I also planned to calculate the some for a columns in my tableview so, i need
// After change in element T the total will change
ObservableList<T> listItems = FXCollections.observableArrayList(
T -> new Observable[]{T.doSomeCalculeProperty});
I really confused about the right way to do this. So, i need your hints
You can create an ObservableSet and then add a listener to it which updates an ObservableList which is used as the items list for the table. As long as modifications are not made directly to the table's items (only to the set, which you can enforce by using an unmodifiable list for the table), then the table will always contain exactly the same items as the set.
To track the total of the values of a property of all the items in the list, you need can register a listener with the list, and recompute the total when it changes. If the property itself may change, you can use an extractor when you create the list, so that the list will fire update notifications if that property changes for any of the list elements.
This example pieces all this together. The modification methods associated with the buttons all operate on the ObservableSet. Notice that if you try to add an item which is equal to an existing item, nothing changes (because adding to the set does nothing, and so no updates are fired to the list).
You can select and modify existing items using the increment and decrement buttons, and you'll see the updates reflected in the total.
import java.util.HashSet;
import java.util.Objects;
import java.util.stream.Collectors;
import javafx.application.Application;
import javafx.beans.Observable;
import javafx.beans.binding.Bindings;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.ObservableSet;
import javafx.collections.SetChangeListener.Change;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class UniqueItemTableViewWithTotal extends Application {
// creates a table view which always contains the same items as the provided set
private TableView<Item> createTableView(ObservableSet<Item> items, IntegerProperty total) {
TableView<Item> table = new TableView<>();
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
// Want the table's items list to fire updates if the value of any item changes
// This allows observing the list for tracking the total of all values
ObservableList<Item> itemList = FXCollections.observableArrayList(
item -> new Observable[] {item.valueProperty()});
// register a listener with the set and update the list if the set changes
// this ensures the list will always contain the same elements as the list,
items.addListener((Change<? extends Item> c) -> {
if (c.wasAdded()) {
itemList.add(c.getElementAdded());
}
if (c.wasRemoved()) {
itemList.remove(c.getElementRemoved());
}
});
// usual column setup
TableColumn<Item, String> nameCol = new TableColumn<>("Item");
nameCol.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
TableColumn<Item, Integer> valueCol = new TableColumn<>("Value");
valueCol.setCellValueFactory(cellData -> cellData.getValue().valueProperty().asObject());
table.getColumns().add(nameCol);
table.getColumns().add(valueCol);
// use an unmodifiable list for the table to prevent any direct updates to the
// table's list (updates must go through the set)
table.setItems(FXCollections.unmodifiableObservableList(itemList));
// update total if the items list changes:
itemList.addListener((ListChangeListener.Change<? extends Item> c) ->
total.set(itemList.stream()
.collect(Collectors.summingInt(Item::getValue))));
// add any existing elements:
itemList.addAll(items);
return table ;
}
#Override
public void start(Stage primaryStage) {
ObservableSet<Item> items = FXCollections.observableSet(new HashSet<>());
IntegerProperty total = new SimpleIntegerProperty();
TableView<Item> table = createTableView(items, total);
for (int i = 1; i <=5 ; i++) {
items.add(new Item("Item "+i, 1+(int)(Math.random()*20)));
}
// label to display the total of all values:
Label totalLabel = new Label();
totalLabel.textProperty().bind(total.asString("Total: %d"));
totalLabel.setStyle("-fx-font-size:24; -fx-padding:10;");
// text fields for new item:
TextField itemField = new TextField();
TextField valueField = new TextField();
// restrict value field to valid integers:
valueField.setTextFormatter(new TextFormatter<Integer>(c ->
c.getControlNewText().matches("-?\\d*") ? c : null));
// button to add new item:
Button addButton = new Button("Add");
addButton.setOnAction(e -> {
Item item = new Item(itemField.getText(), Integer.parseInt(valueField.getText()));
items.add(item);
itemField.clear();
valueField.clear();
});
addButton.disableProperty().bind(itemField.textProperty().isEmpty()
.or(valueField.textProperty().isEmpty()));
ObservableList<Item> selection = table.getSelectionModel().getSelectedItems();
// button to remove selected item(s):
Button removeButton = new Button("Delete");
removeButton.setOnAction(e ->
items.removeIf(new HashSet<Item>(selection)::contains));
removeButton.disableProperty().bind(Bindings.isEmpty(selection));
// button to increment selected item(s):
Button incButton = new Button("Increment");
incButton.setOnAction(e -> selection.forEach(Item::increment));
incButton.disableProperty().bind(Bindings.isEmpty(selection));
// button to decrement selected item(s):
Button decButton = new Button("Decrement");
decButton.setOnAction(e -> selection.forEach(Item::decrement));
decButton.disableProperty().bind(Bindings.isEmpty(selection));
HBox controls = new HBox(5, itemField, valueField, addButton, removeButton, incButton, decButton);
controls.setAlignment(Pos.CENTER);
controls.setPadding(new Insets(5));
BorderPane root = new BorderPane(table);
root.setTop(totalLabel);
root.setBottom(controls);
Scene scene = new Scene(root, 800, 800);
primaryStage.setScene(scene);
primaryStage.show();
}
// model item:
public static class Item {
private final StringProperty name = new SimpleStringProperty();
private final IntegerProperty value = new SimpleIntegerProperty();
public Item(String name, int value) {
setName(name);
setValue(value);
}
public final StringProperty nameProperty() {
return this.name;
}
public final String getName() {
return this.nameProperty().get();
}
public final void setName(final String name) {
this.nameProperty().set(name);
}
public final IntegerProperty valueProperty() {
return this.value;
}
public final int getValue() {
return this.valueProperty().get();
}
public final void setValue(final int value) {
this.valueProperty().set(value);
}
public void increment() {
setValue(getValue()+1);
}
public void decrement() {
setValue(getValue()-1);
}
#Override
public int hashCode() {
return Objects.hash(getName(), getValue());
}
#Override
public boolean equals(Object o) {
if (o.getClass() != Item.class) {
return false ;
}
Item other = (Item) o ;
return Objects.equals(getName(), other.getName())
&& getValue() == other.getValue() ;
}
}
public static void main(String[] args) {
launch(args);
}
}
I'm using ActionBarSherlock with a ViewPager with navigation mode set to display my tabs. I have 3 tabs that work fine. My problem is that if I were to try to swipe to a non-existant 4th tab it crashes my app. I'm not sure where this is happening, need some help. This is my first attempt at an app, any feedback is welcome.
fragments:
private ViewPager mViewPager;
private SherlockFragment mFragCodes;
private SherlockFragment mFragDeals;
private SherlockFragment mFragProgInfo;
private SherlockFragment mFragTemp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(new MainPagerAdapter(
getSupportFragmentManager()));
mViewPager.setOnPageChangeListener(this);
//mViewPager.setPageMarginDrawable(R.drawable.border);
mViewPager.setPageMargin(16);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab()
.setText(R.string.tab_codes_title)
.setTabListener(this));
actionBar.addTab(actionBar.newTab()
.setText(R.string.tab_deals_title)
.setTabListener(this));
actionBar.addTab(actionBar.newTab()
.setText(R.string.tab_program_info_title)
.setTabListener(this));
and my pageradapter:
private class MainPagerAdapter extends FragmentPagerAdapter {
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public SherlockFragment getItem(int position) {
switch (position) {
case 0:
return (mFragCodes = new frag_codes());
case 1:
return (mFragDeals = new frag_deals());
case 2:
return (mFragProgInfo = new frag_programming());
}
//if nothing is returned
return mFragTemp = new SherlockFragment();
}
#Override
public int getCount() {
return R.string.tab_count;
}
}
Any other info I should include?
Go over Swipey Tabs example and the example included in the samples folder that comes with the ActionBarSherlock library (FragmentTabsPager) to see working examples of a tabs adapter.
Furthermore, please include additional info, mostly the stack trace from the exception, the layouts and the full classes including the declaration and imports.
From what I see you are missing the implements part where you should be implementing ActionBar.TabListener, ViewPager.OnPageChangeListener.
Just put:
#Override
public int getCount() {
return 3;
}
I was trying to solve my problem with colored progress bars in this thread. The solution was present, but then I ran into another problem: I can't change color dynamically from my code. I want to do it right from my code, not with pre-defined .css. Generally I can do it, but I run into some difficulties when I try to do it with more than one progess bar.
public class JavaFXApplication36 extends Application {
#Override
public void start(Stage primaryStage) {
AnchorPane root = new AnchorPane();
ProgressBar pbRed = new ProgressBar(0.4);
ProgressBar pbGreen = new ProgressBar(0.6);
pbRed.setLayoutY(10);
pbGreen.setLayoutY(30);
pbRed.setStyle("-fx-accent: red;"); // line (1)
pbGreen.setStyle("-fx-accent: green;"); // line (2)
root.getChildren().addAll(pbRed, pbGreen);
Scene scene = new Scene(root, 150, 50);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
}
I always get 2 red progressbars with it! It seems that code in line (1) changes the style of ProgressBar class, not the instance.
Another strange moment is that deleting line (1) don't result in 2 green progress bars. So I can figure that line (2) is completely useless!! WHY?! That's definitely getting odd.
Is there any way to set different colors for separate progressbars?
See also the StackOverflow JavaFX ProgressBar Community Wiki.
There is a workaround you can use until a bug to fix the sample code in your question is filed and fixed.
The code in this answer does a node lookup on the ProgressBar contents, then dynamically modifies the bar colour of the progress bar to any value you like.
import javafx.application.Application;
import javafx.beans.value.*;
import javafx.geometry.Pos;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ProgressBarDynamicColor extends Application {
public static void main(String[] args) { launch(args); }
#Override public void start(Stage stage) {
PickedColorBar aquaBar = new PickedColorBar(0.4, Color.AQUA);
PickedColorBar fireBar = new PickedColorBar(0.6, Color.FIREBRICK);
HBox layout = new HBox(20);
layout.getChildren().setAll(aquaBar, fireBar);
layout.setStyle("-fx-background-color: -fx-box-border, cornsilk; -fx-padding: 15;");
stage.setScene(new Scene(layout));
stage.show();
aquaBar.wasShown();
fireBar.wasShown();
}
class PickedColorBar extends VBox {
private final ProgressBar bar;
private final ColorPicker picker;
private boolean wasShownCalled = false;
final ChangeListener<Color> COLOR_LISTENER = new ChangeListener<Color>() {
#Override public void changed(ObservableValue<? extends Color> value, Color oldColor, Color newColor) {
setBarColor(bar, newColor);
}
};
public PickedColorBar(double progress, Color initColor) {
bar = new ProgressBar(progress);
picker = new ColorPicker(initColor);
setSpacing(10);
setAlignment(Pos.CENTER);
getChildren().setAll(bar, picker);
}
// invoke only after the progress bar has been shown on a stage.
public void wasShown() {
if (!wasShownCalled) {
wasShownCalled = true;
setBarColor(bar, picker.getValue());
picker.valueProperty().addListener(COLOR_LISTENER);
}
}
private void setBarColor(ProgressBar bar, Color newColor) {
bar.lookup(".bar").setStyle("-fx-background-color: -fx-box-border, " + createGradientAttributeValue(newColor));
}
private String createGradientAttributeValue(Color newColor) {
String hsbAttribute = createHsbAttributeValue(newColor);
return "linear-gradient(to bottom, derive(" + hsbAttribute+ ",30%) 5%, derive(" + hsbAttribute + ",-17%))";
}
private String createHsbAttributeValue(Color newColor) {
return
"hsb(" +
(int) newColor.getHue() + "," +
(int) (newColor.getSaturation() * 100) + "%," +
(int) (newColor.getBrightness() * 100) + "%)";
}
}
}
The code uses inlined string processing of css attributes to manipulate Region backgrounds. Future JavaFX versions (e.g. JDK8+) will include a public Java API to manipulate background attributes, making obsolete the string processing of attributes from the Java program.
Sample program output:
From the previous question I asked, I am still having the same question. I do not know how to use database (SQLite) to 'sync' with my application to log in or register
package log1.log2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Login extends Activity {
UserDB db = new UserDB(this);
/** Called when the activity is first created. */
private EditText etUsername;
private EditText etPassword;
private Button btnLogin;
private Button btnRegister;
private TextView lblResult;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the EditText and Button References
etUsername = (EditText)findViewById(R.id.usernametxt);
etPassword = (EditText)findViewById(R.id.passwordtxt);
btnLogin = (Button)findViewById(R.id.btnLogin);
btnRegister = (Button)findViewById(R.id.btnRegister);
lblResult = (TextView)findViewById(R.id.msglbl);
//Cursor c = (Cursor) db.getAllTitles();
//Button btnArrival = (Button) findViewById(R.id.btnRegister);
//btnArrival.setOnClickListener(this);
// Set Click Listener
btnRegister.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(Login.this,Register.class);
startActivity(intent);
}
});
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
db.open();
// Check Login
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
if(username.equals("select username from Users")){
if(password.equals("select password from users where username = username"))
{
Intent intent=new Intent(Login.this,Test.class);
startActivity(intent);
}
else
{
lblResult.setText("Wrong password");
}
} else {
lblResult.setText("Username does not exist. Please register.");
}
db.close();
}
});
}
}
Should I use the 'select' 'from' 'where' statement? Or there is another way?
Where you have
username.equals("select username from Users")
you are actually testing if what the user entered is literally the same object (which it is not). To authenticate against a local database of Users, you would want to try something more like this:
Cursor c = db.rawQuery("SELECT username FROM Users WHERE username='?' AND password='?'", new String[] {username, password});
if(c.moveToFirst()) {
// at least one row was returned, this should signal success
} else {
// authentication failed
}
Where 'db' is the SQLiteDatabase object you are working with. If you need any kind of security, I would also hash the password before you store it in the database!
I've modified my previous code for login.
package log1.log2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Login extends Activity implements OnClickListener{
UserDB db = new UserDB(this);
/** Called when the activity is first created. */
private EditText etUsername;
private EditText etPassword;
private Button btnLogin;//private Button btnRegister;
private TextView lblResult;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the EditText and Button References
etUsername = (EditText)findViewById(R.id.usernametxt);
etPassword = (EditText)findViewById(R.id.passwordtxt);
btnLogin = (Button)findViewById(R.id.btnLogin);
//btnRegister = (Button)findViewById(R.id.btnRegister);
lblResult = (TextView)findViewById(R.id.msglbl);
//Cursor c = (Cursor) db.getAllTitles();
Button btnArrival = (Button) findViewById(R.id.btnRegister);
btnArrival.setOnClickListener(this);
// Set Click Listener
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
db.open();
// Check Login
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
if(username.equals("")){
if(password.equals(""))
onClick();
else
{
lblResult.setText("Wrong password");
}
} else {
lblResult.setText("Username does not exist. Please register.");
}
db.close();
}
});
}
public void onClick(View v)
{
if (v.getId() == R.id.btnLogin)
{
Intent intent = new Intent(this, Test.class);
startActivity(intent);
}
else
{
Intent intent = new Intent(this, Home.class);
startActivity(intent);
}
}
}
As you can see, I've left a blank on my if..else. I do not know how to apply an sql statement to check the user and password.
if(username.equals("sqlstatement")){
if(password.equals("sqlstatement"))
onClick();
else
{
lblResult.setText("Wrong password");
}
} else
lblResult.setText("Username does not exist. Please register.");
I've insert onClick(); to direct to the other method so that the user will be directed to another page by using the onClickListener method, intent. But I'm having trouble doing that and so I thought that my code is wrong or there should be another way to direct to the other page once the user entered the correct username and password.
Before that, what should I do so that there would be a database connection? Or have I created a connection by inserting db.Open()?
I need to know the codes needed to be inserted the if..else statement.
Another basic stuff I want to know is how to set the text on the password edittext box to dots instead of the actual text.
for redirection pleae check my post on this issue
http://android-pro.blogspot.com/2010/06/android-intents-part-2-passing-data-and.html
and to set the password TextView please check this
http://android-pro.blogspot.com/2010/03/android-text-controls.html
thanks