My app crashes when i try to launch it - arrays

My app crashes when i tried to launch it.
I'm trying to learn how to make the app cycle through an array of strings and then repeats once everything has been picked. This is done with a press of a button. But it crashes when i try to launch it on my phone. Any suggestions or help would be greatly appreciated.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MainActivity extends Activity {
TextView textOne = (TextView) findViewById(R.id.TextView1);
Button pushMe = (Button) findViewById(R.id.button);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pushMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textOne.setText(pick());
}
List<String> myStrings = new ArrayList<String>() {{
add("b");
add("a");
add("z");
add("y");
add("x");
}};
List<String> dupeList = new ArrayList<String>() {{
addAll(myStrings);
}};
Random r = new Random();
public String pick() {
String retval = "";
int pos;
switch (dupeList.size()) {
case 1:
retval = dupeList.get(0);
dupeList.clear();
dupeList.addAll(myStrings);
return retval;
default:
pos = r.nextInt(dupeList.size());
retval = dupeList.get(pos);
dupeList.remove(pos);
return retval;
}
}
});
}
#Override
public boolean onCreateOptionsMenu (Menu menu){
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
//this opens another activity
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()) {
case R.id.RulesButton:
startActivity(new Intent(this, RulesActivity.class));
break;
}
return true;
}
}

found the problem. i just needed to change "TextView textOne...." to "final TextView textOne..." and place it below the onCreate method.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textOne = (TextView) findViewById(R.id.TextView1);
Button pushMe = (Button) findViewById(R.id.button);
pushMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textOne.setText(pick());
}
List<String> myStrings = new ArrayList<String>() {{
add("b");
add("a");
add("z");
add("y");
add("x");
}};
List<String> dupeList = new ArrayList<String>() {{
addAll(myStrings);
}};
Random r = new Random();
public String pick() {
String retval = "";
int pos;
switch (dupeList.size()) {
case 1:
retval = dupeList.get(0);
dupeList.clear();
dupeList.addAll(myStrings);
return retval;
default:
pos = r.nextInt(dupeList.size());
retval = dupeList.get(pos);
dupeList.remove(pos);
return retval;
}
}
});
}
#Override
public boolean onCreateOptionsMenu (Menu menu){
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
//this opens another activity
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()) {
case R.id.RulesButton:
startActivity(new Intent(this, RulesActivity.class));
break;
}
return true;
}
}

Just for information as you are new in Android logs will help you more.
Log will be in eclipse tool (developing tool you are using) not on your device.
Change perspective to DDMS -> Go to LogCat.
There will be error logs in it.

Related

Remove item from a RecyclerView list based on status of a checkbox

I have a list application what is uses RecyclerView.
Each line has got a button, a checkbox and 2 textview.
All object is defined the RecyclerView clas, but I would like to check the checkbox status in the Main class and evaluate the status and remove the item from the list and from the SharedPreferences where the checkbox is checked
Main class is here:
package com.example.homehandling;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class ToDoList extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener, View.OnClickListener {
public MyRecyclerViewAdapter adapter;
public Button btn;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor myEdit;
public LinkedList<String> items, remain_days, prio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoppinglist);
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
myEdit = sharedPreferences.edit();
btn = findViewById(R.id.button);
items = new LinkedList<>();
remain_days = new LinkedList<>();
prio = new LinkedList<>();
RecyclerView recyclerView = findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this,items,remain_days,prio);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
btn.setOnClickListener(this);
StartDisplay();
}
#Override
public void onItemClick(View view, int position) {
}
#Override
public void onClick(View v) {
Intent NewTLItem = new Intent(ToDoList.this, NewTLItem.class);
startActivity(NewTLItem);
}
#Override
public void onResume() {
super.onResume();
StartDisplay();
}
public void StartDisplay()
{
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
Map<String, ?> allEntries = sharedPreferences.getAll();
items.clear();
prio.clear();
remain_days.clear();
for (Map.Entry<String, ?> entry : allEntries.entrySet())
{
String key_word = entry.getKey();
String [] item_total = entry.getValue().toString().split(";");
if(key_word.contains("_")) key_word = key_word.replace("_"," ");
items.add(key_word);
remain_days.add(Long.toString(DateCalc(item_total[0])));
prio.add(item_total[1]);
}
adapter.notifyDataSetChanged();
}
public long DateCalc(String startdate)
{
Date system_date, due_date;
long diff_date = 0;
String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
try {
system_date = dates.parse(currentDate);
due_date = dates.parse(startdate);
diff_date = (due_date.getTime()-system_date.getTime())/86400000;
} catch (ParseException e) {
e.printStackTrace();
}
return diff_date;
}
}
At now the item is removed when the whole line is touched. I would like to exchange to if only the Checkbox is "true".
At now the remove method is in the public void onItemClick(View view, int position) function.
I would like to put the content of the OnItemClick method to "if" part of CheckBox status.
Here is the RecyclerView class:
package com.example.homehandling;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder>
{
public List<String> mData, subdata, subdata2;
public LayoutInflater mInflater;
public ItemClickListener mClickListener;
public Context context;
public CheckBox done;
MyRecyclerViewAdapter(Context context, List<String> data, List<String> subdata, List<String> subdata2) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
this.subdata = subdata;
this.subdata2 = subdata2;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String meta_data = mData.get(position);
String meta_subdata = subdata.get(position);
String meta_subdata2 = subdata2.get(position);
holder.myTextView.setText(meta_data);
holder.subtext.setText(meta_subdata +" "+ meta_subdata2);
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] item_param = holder.myTextView.getText().toString().split(" ");
final Intent intent;
intent = new Intent(context, NewSLItem.class);
intent.putExtra("param",item_param[0]);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
public TextView myTextView, subtext;
public Button add;
public ViewHolder(View itemView)
{
super(itemView);
context = itemView.getContext();
myTextView = itemView.findViewById(R.id.tvAnimalName);
subtext = itemView.findViewById(R.id.subtext);
add = itemView.findViewById(R.id.add);
done = itemView.findViewById(R.id.done);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
String getItem(int id) {return mData.get(id);
}
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
public interface ItemClickListener
{
void onItemClick(View view, int position);
}
}
if(adapter.done.isChecked())should work I think, but I got null opbject reference exception.
Maybe the problem is that the checkbox is in the RecyclerView layout and not in Main class layout, but I am not sure.
Is it possible to handle the Checkbox methods from other class, and if yes, then where should I improve the code?

DocumentsContract.copyDocument

I have a problem with DocumentsContract.copyDocument
Each time my program crashes: "java.lang.UnsupportedOperationException: Copy not supported"
The curious thing is the below-listed actions are working fine!!
DocumentsContract.moveDocument
DocumentsContract.deleteDocument
DocumentsContract.renameDocument
DocumentsContract.createDocument
Permission to SD card access is apparently granted (above actions would fail without permission)
How come document moving, deleting and renaming is supported but not copying?
Can anyone help me with this issue?
Is there a great conceptual difference between copyDocument and moveDocument. Why move does work and copy does not?
Any hint will be highly appreciated
package com.example.forum14_11_2020;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.documentfile.provider.DocumentFile;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.UriPermission;
import android.net.Uri;
import android.os.Bundle;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.provider.DocumentsContract;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Uri uri;
DocumentFile pickedDir;
Button Button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button1 = new Button(MainActivity.this);
Button1 = findViewById(R.id.button1);
Button1.setOnClickListener(onClickListener_Button1);
takeCardUriPermission("storage/1619-0D07");
}
View.OnClickListener onClickListener_Button1 = new View.OnClickListener() {
#Override
public void onClick(View v) {
uri = getUri();
pickedDir = DocumentFile.fromTreeUri(getBaseContext(), uri);
DocumentFile file = pickedDir.findFile("attempt.txt");
DocumentFile folder = pickedDir.findFile("folder");
try {
//DocumentsContract.moveDocument(getContentResolver(), file.getUri(), folder.getUri(), folder.getUri()); // does work!
//DocumentsContract.deleteDocument(getContentResolver(), file.getUri()); // does work!
//DocumentsContract.renameDocument(getContentResolver(), file.getUri(), file.getName() + "_rename"); // does work!
DocumentsContract.copyDocument(getContentResolver(), file.getUri(), folder.getUri()); // does not work
} catch (UnsupportedOperationException | FileNotFoundException e) {
e.printStackTrace();
e.getMessage();
}
}
};
public void takeCardUriPermission(String sdCardRootPath) {
int stop=1;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
File sdCard = new File(sdCardRootPath);
StorageManager storageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
StorageVolume storageVolume = storageManager.getStorageVolume(sdCard);
Intent intent = storageVolume.createAccessIntent(null);
try {
startActivityForResult(intent, 4010);
} catch (ActivityNotFoundException e) {
}
}
}
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 4010) {
Uri uri = data.getData();
grantUriPermission(getPackageName(), uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION |
Intent.FLAG_GRANT_READ_URI_PERMISSION);
final int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_WRITE_URI_PERMISSION |
Intent.FLAG_GRANT_READ_URI_PERMISSION);
getContentResolver().takePersistableUriPermission(uri, takeFlags);
}
}
public Uri getUri() {
List<UriPermission> persistedUriPermissions = getContentResolver().getPersistedUriPermissions();
if (persistedUriPermissions.size() > 0) {
UriPermission uriPermission = persistedUriPermissions.get(0);
return uriPermission.getUri();
}
return null;
}
}

How to save entire object for a checkbox in javafx

I have number of objects. Let's say i have 10 Books object and i want user to select any number of the book. When user press the submit button i want to retrieve all the books "object" that user selected.
As of now, while showing screen to user i use
CheckBox cb= new CheckBox(book.getName());
this shows bookname to user and user selects the book. But on runtime i will be needing bookid and other properties of book object as well.
Is there anyway through which i can save the book object in the checkbox?
Basic Examle. if you want more sepecifc you need to post your code, we can set object to node using setUserDate, then we can use that object when we need. here i am using object id for example, in yor case save that object i hope this will solve your problem ,?s post a comment
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class UserData extends Application {
public void start(Stage primaryStage) {
VBox root = new VBox();
Book book = new Book(22, "firstBok");
Book book1 = new Book(2, "secondBok");
CheckBox checkB = new CheckBox(book.getName());
checkB.setUserData(book);
CheckBox checkB1 = new CheckBox(book1.getName());
checkB1.setUserData(book1);
Button btn = new Button("Submit");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if (checkB.isSelected()) {
int firstCheckBxId = ((Book) checkB.getUserData()).getId();
System.out.println("id:" + firstCheckBxId);
}
if (checkB1.isSelected()) {
int secondCheckBxId = ((Book) checkB1.getUserData()).getId();
System.out.println("id:" + secondCheckBxId);
}
}
});
root.getChildren().addAll(checkB, checkB1, btn);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
class Book {
int id;
private String name;
Book(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return this.id;
}
public String getName() {
return name;
}
}
public static void main(String[] args) {
launch(args);
}
}
Consider using a control with built-in selection functionality, such as a ListView. Then you can just check the selection model.
import java.util.stream.IntStream;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class BookSelection extends Application {
#Override
public void start(Stage primaryStage) {
ListView<Book> bookList = new ListView<>();
bookList.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
bookList.setCellFactory(lv -> new ListCell<Book>() {
#Override
public void updateItem(Book book, boolean empty) {
super.updateItem(book, empty);
if (empty) {
setText(null);
} else {
setText(book.getTitle());
}
}
});
IntStream.rangeClosed(1, 10).mapToObj(i -> new Book("Book "+i)).forEach(bookList.getItems()::add);
Button submit = new Button("Submit selection");
submit.setOnAction(e ->
bookList.getSelectionModel().getSelectedItems().forEach(book -> System.out.println(book.getTitle())));
BorderPane root = new BorderPane(bookList, null, null, submit, null);
BorderPane.setAlignment(submit, Pos.CENTER);
BorderPane.setMargin(submit, new Insets(10));
Scene scene = new Scene(root, 600, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
public static class Book {
private final StringProperty title = new SimpleStringProperty() ;
public Book(String title) {
setTitle(title);
}
public final StringProperty titleProperty() {
return this.title;
}
public final java.lang.String getTitle() {
return this.titleProperty().get();
}
public final void setTitle(final java.lang.String title) {
this.titleProperty().set(title);
}
}
public static void main(String[] args) {
launch(args);
}
}
If for some reason you really want to implement this with check boxes, you can keep a Set<Book> representing the selected books, and update it when each check box is selected/unselected. Note this is similar to #user99370's answer, but is more robust as it avoids downcasting the (essentially unknown-type) userData to your data type.
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class BookSelection extends Application {
#Override
public void start(Stage primaryStage) {
GridPane grid = new GridPane();
grid.setHgap(5);
grid.setVgap(5);
grid.setPadding(new Insets(10 ));
List<Book> books = IntStream.rangeClosed(1, 10).mapToObj(i -> new Book("Book "+i)).collect(Collectors.toList());
Set<Book> selectedBooks = new HashSet<>();
int row = 0 ;
for (Book book : books) {
CheckBox checkBox = new CheckBox();
checkBox.selectedProperty().addListener((obs, wasSelected, isNowSelected) -> {
if (isNowSelected) {
selectedBooks.add(book);
} else {
selectedBooks.remove(book);
}
});
grid.addRow(row, checkBox, new Label(book.getTitle()));
row++ ;
}
Button submit = new Button("Submit selection");
submit.setOnAction(e ->
selectedBooks.forEach(book -> System.out.println(book.getTitle())));
GridPane.setHalignment(submit, HPos.CENTER);
grid.add(submit, 0, row, 2, 1);
Scene scene = new Scene(grid, 600, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
public static class Book {
private final StringProperty title = new SimpleStringProperty() ;
public Book(String title) {
setTitle(title);
}
public final StringProperty titleProperty() {
return this.title;
}
public final java.lang.String getTitle() {
return this.titleProperty().get();
}
public final void setTitle(final java.lang.String title) {
this.titleProperty().set(title);
}
}
public static void main(String[] args) {
launch(args);
}
}
This is just a simplified version of the accepted answer.
We can use setUserData(Object) to set data and getUserData() to retrieve the previously set data of any JavaFX node (including CheckBox).
Reference:
https://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html#setUserData-java.lang.Object-

Combobox refresh value and listview when object content change

I would like to update my combobox when the content of the object used to display text in combo changes.
Here is a sample:
package com.javafx.example.combobox;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class ComboboxSample extends Application {
class Sequence {
public StringProperty name = new SimpleStringProperty();
public Sequence(String name) {
super();
this.name.set(name);
}
#Override
public String toString() {
return "null";
}
}
#Override
public void start(Stage stage) throws Exception {
stage.setTitle("ComboBoxSample");
ComboBox<Sequence> combo = new ComboBox<>();
combo.setItems(FXCollections.observableArrayList(
new Sequence("Toto"),
new Sequence("Titi")));
combo.getSelectionModel().selectFirst();
combo.setConverter(new StringConverter<ComboboxSample.Sequence>() {
#Override
public String toString(Sequence sequence) {
return sequence.name.get();
}
#Override
public Sequence fromString(String string) {
System.out.println("call fromString");
return null;
}
});
TextField text = new TextField();
Button renameButton = new Button("Rename");
renameButton.setOnAction(evt -> combo.getValue().name.set(text.getText()));
HBox root = new HBox(combo, text, renameButton);
HBox.setHgrow(text, Priority.ALWAYS);
stage.setScene(new Scene(root));
stage.show();
}
public static void main(String... args) {
launch(args);
}
}
The combobox contains objects with a property name. If i rename this property, the display do not change or sometimes it changes but not all the time. It is the standard behavior as the combobox update when the object changes, and not when its content changes.
How can i do to force the combobox to refresh its value and the listview on change?
Thanks
EDIT1:
Using a callback in an observaleList seems to be a solution.
package com.javafx.example.combobox;
import javafx.application.Application;
import javafx.beans.Observable;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.StringConverter;
public class ComboboxSample extends Application {
ObservableList<Sequence> sequences;
class Sequence {
public StringProperty name = new SimpleStringProperty();
public Sequence(String name) {
super();
this.name.set(name);
}
#Override
public String toString() {
return "null";
}
}
#Override
public void start(Stage stage) throws Exception {
stage.setTitle("ComboBoxSample");
Callback<Sequence, Observable[]> extractor = new Callback<Sequence, Observable[]>() {
#Override
public Observable[] call(Sequence s) {
return new Observable[] {s.name};
}
};
sequences = FXCollections.observableArrayList(extractor);
sequences.addAll(
new Sequence("Toto"),
new Sequence("Titi"));
ComboBox<Sequence> combo = new ComboBox<>();
combo.setItems(sequences);
combo.getSelectionModel().selectFirst();
combo.setConverter(new StringConverter<ComboboxSample.Sequence>() {
#Override
public String toString(Sequence sequence) {
return sequence.name.get();
}
#Override
public Sequence fromString(String string) {
System.out.println("call fromString");
return null;
}
});
combo.valueProperty().addListener((obs, oldValue, newValue) -> System.out.println("Change from " + oldValue.name.get() + " to " + newValue.name.get()));
TextField text = new TextField();
Button renameButton = new Button("Rename");
renameButton.setOnAction(evt -> {
combo.getValue().name.set(text.getText());
});
HBox root = new HBox(combo, text, renameButton);
HBox.setHgrow(text, Priority.ALWAYS);
stage.setScene(new Scene(root));
stage.show();
}
public static void main(String... args) {
launch(args);
}
}
Everytime a new value is added to the object list, set the combobox value again. Works for me. I did a small example to show this. Hope it is helpful
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ComboTest extends Application {
int i =0;
ObservableList<String> list = FXCollections.observableArrayList("A","B");
ComboBox<String> combo = new ComboBox();
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
combo.setPromptText("Testing combobox");
combo.setPrefWidth(300);
btn.setText("Add items to list");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
list.add(String.valueOf(i));
System.out.println("size of list " + list.size() );
i++;
combo.setItems(list);
}
});
combo.setItems(list);
VBox root = new VBox();
root.getChildren().addAll(btn,combo);
root.setSpacing(20);
root.setAlignment(Pos.CENTER);
Scene scene = new Scene(root);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}

Compile error with two different fragmenttransaction types

I'm using AIDE on my phone, and trying to open a fragment from the navigation drawer in-app, but I get this error when I try to build the app:
An instance of type 'android.app.fragmenttransaction' cannot be assigned to a variable of type 'android.support.v4.app.fragmenttransaction'
Here is the code in the MainActivity.Java file:
package com.nickdgreen.net.act1;
import android.content.*;
import android.content.res.*;
import android.os.*;
import android.support.v4.app.*;
import android.support.v4.widget.*;
import android.view.*;
import android.widget.*;
import android.app.ActionBar.*;
import android.app.Activity.*;
import android.content.res.Configuration.*;
import android.os.Bundle.*;
import android.support.v4.app.ActionBarDrawerToggle.*;
import android.support.v4.app.Fragment.*;
import android.support.v4.app.FragmentActivity.*;
import android.support.v4.app.FragmentManager.*;
import android.support.v4.app.FragmentTransaction.*;
import android.support.v4.widget.DrawerLayout.*;
import android.view.Menu.*;
import android.view.MenuInflater.*;
import android.view.MenuItem.*;
import android.view.View.*;
import android.widget.AdapterView.*;
import android.widget.ArrayAdapter.*;
import android.widget.ListView.*;
public class MainActivity extends FragmentActivity
{
private ActionBarDrawerToggle drawerToggle;
final String fragments[] = {
"com.nickdgreen.net.act1.MainFragment",
"com.nickdgreen.net.act1.OneFragment",
"com.nickdgreen.net.act1.TwoFragment",
"com.nickdgreen.net.act1.ThreeFragment",
};
final String menuEntries[] = {
"Main", "One", "Two", "Three"
};
public MainActivity()
{
}
public void onConfigurationChanged(Configuration configuration)
{
super.onConfigurationChanged(configuration);
drawerToggle.onConfigurationChanged(configuration);
}
protected void onCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(0x7f030000);
ArrayAdapter arrayadapter = new ArrayAdapter(getActionBar().getThemedContext(), 0x1090003, menuEntries);
final DrawerLayout drawer = (DrawerLayout)findViewById(0x7f080000);
final ListView navList = (ListView)findViewById(0x7f080002);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
drawerToggle = new ActionBarDrawerToggle(this, drawer, 0x7f020000, 0x7f050003, 0x7f050002) {
final MainActivity this$0;
public void onDrawerClosed(View view)
{
}
public void onDrawerOpened(View view)
{
}
{
this$0 = MainActivity.this;
}
};
drawer.setDrawerListener(drawerToggle);
navList.setAdapter(arrayadapter);
navList.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
final MainActivity this$0;
final DrawerLayout val$drawer;
final ListView val$navList;
public void onItemClick(AdapterView adapterview, View view, int i, long l)
{ {
}
drawer.closeDrawer(navList);
}
{
}
});
FragmentTransaction fragmenttransaction = getSupportFragmentManager().beginTransaction();
fragmenttransaction.replace(0x7f080001, Fragment.instantiate(this, fragments[0]));
fragmenttransaction.commit();
}
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(0x7f070000, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem menuitem)
{
if (drawerToggle.onOptionsItemSelected(menuitem))
{
return true;
} else
{
return super.onOptionsItemSelected(menuitem);
}
}
protected void onPostCreate(Bundle bundle)
{
super.onPostCreate(bundle);
drawerToggle.syncState();}
private class DrawerItemClickListener
implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id)
{ selectItem(position); }
/** Swaps fragments in the main content view */
private void
selectItem(int position) {
//Fragment fragment = new PlanetFragment(); Bundle args = new Bundle(); // args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
Intent intent = new Intent(MainActivity.this, OneFragment.class); startActivity(intent); } }
public class
ProductListActivity extends MainActivity {
#Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate main_menu.xml
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.mainMenuAbout:
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
case R.id.mainMenuExit:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override public void onClick(Bundle b) { super.onCreate(b); setContentView(R.layout.primary);}
public void
selectItem(int position) {
Fragment newFragment;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
switch (position) {
case 0:
newFragment = new OneFragment();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null); transaction.commit();
break;
case 1:
newFragment = new TwoFragment();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 2:
newFragment = new ThreeFragment();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 3:
newFragment = new FourFragment();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
}
//DrawerList.setItemChecked(position, true);
CharSequence[] ListTitles = null;
setTitle(ListTitles[position]);
View DrawerList = null;
}
}
}
import android.support.v4.app.FragmentTransaction.*;
This line means that you are using FragmentTransaction; note that you are using the support lib's version, not the system's.
However, later in the code, you are assigning the support lib's FragmentTransaction to the native FragmentTransaction. They are incompatible and thus won't work. (Actually, it's what the error message itself is telling you.)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// ^^^ support lib's version ^^^ this code returns a native FragmentTransaction
You should instead get the support lib's fragment manager, which will return the support FragmentTransaction.

Resources