I am writing a quiz application which will feature multiple different classes including a separate class for each question. I want to use Alert Boxes to give the user the option to move onto the next question, so when I press proceed to move onto the first question, however it wont change to the next scene and I dont quite understand how the buttonType works?
Any help would be appreciated
package pkg1;
import java.io.*;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Alert.*;
import javafx.scene.layout.*;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
import javafx.stage.Window;
public class Register {
Stage stage;
public Register (Stage b){
stage = b;
}
public void start(Stage stage){
stage.setTitle("Registration");
GridPane gridPane = createRegisterPane();
addUIControls(gridPane);
Scene scene = new Scene(gridPane, 800, 500);
stage.setScene(scene);
stage.show();
}
private GridPane createRegisterPane() {
GridPane gridPane = new GridPane();
gridPane.setAlignment(Pos.CENTER);
gridPane.setPadding(new Insets(40, 40, 40, 40));
gridPane.setHgap(10);
gridPane.setVgap(10);
return gridPane;
}
private void addUIControls(GridPane gridPane) {
// Add Header
Label headerLabel = new Label("Registration");
headerLabel.setFont(Font.font("Arial", FontWeight.BOLD, 24));
gridPane.add(headerLabel, 0,0,2,1);
GridPane.setHalignment(headerLabel, HPos.CENTER);
GridPane.setMargin(headerLabel, new Insets(20, 0,20,0));
// FULL NAME
Label fnamelabel = new Label("Full Name : ");
gridPane.add(fnamelabel, 0,1);
// FULL NAME TEXT
TextField fnamefield = new TextField();
fnamefield.setPrefHeight(40);
gridPane.add(fnamefield, 1,1);
fnamefield.setPromptText(" - Enter your full name - ");
// EMAIL
Label emaillabel = new Label("Email: ");
gridPane.add(emaillabel, 0, 2);
// EMAIL TEXT
TextField emailfield = new TextField();
emailfield.setPrefHeight(40);
gridPane.add(emailfield, 1, 2);
emailfield.setPromptText(" - Enter your Email - ");
// USERNAME
Label usernamelabel = new Label("Username: ");
gridPane.add(usernamelabel, 0, 3);
// USERNAME TEXT
TextField usernamefield = new TextField();
usernamefield.setPrefHeight(40);
gridPane.add(usernamefield, 1, 3);
usernamefield.setPromptText(" - Enter your username - ");
// PASSWORD
Label passwordlabel = new Label("Password: ");
gridPane.add(passwordlabel, 0, 4);
// PASSWORD TEXT
PasswordField passwordfield = new PasswordField();
passwordfield.setPrefHeight(40);
gridPane.add(passwordfield, 1, 4);
passwordfield.setPromptText(" - Enter your password - ");
// SUBMIT BUTTON
Button submitButton = new Button("Submit");
submitButton.setPrefHeight(40);
submitButton.setDefaultButton(true);
submitButton.setPrefWidth(100);
gridPane.add(submitButton, 0, 5, 4, 2);
GridPane.setHalignment(submitButton, HPos.CENTER);
GridPane.setMargin(submitButton, new Insets(20, 0,20,0));
submitButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if(fnamefield.getText().isEmpty()) {
ErrorAlert(Alert.AlertType.ERROR,
gridPane.getScene().getWindow(), "Error!", "Please enter your full name.");
return;
}
if(usernamefield.getText().isEmpty()) {
ErrorAlert(Alert.AlertType.ERROR,
gridPane.getScene().getWindow(), "Error!", "Please enter your username");
return;
}
if(emailfield.getText().isEmpty()) {
ErrorAlert(Alert.AlertType.ERROR,
gridPane.getScene().getWindow(), "Error!", "Please enter your Email");
return;
}
if(passwordfield.getText().isEmpty()) {
ErrorAlert(Alert.AlertType.ERROR,
gridPane.getScene().getWindow(), "Error!", "Please enter your password");
return;
}
String fullname = fnamefield.getText();
String email = emailfield.getText();
String username = usernamefield.getText();
String password = passwordfield.getText();
String all = fullname + "," + email + "," + username + "," + password;
try{
FileWriter fw = new FileWriter ("F:/NEW/1/src/pkg1/Register.txt",true);
PrintWriter out = new PrintWriter (fw);
out.println(all);
out.close();
}
catch (Exception e){
System.out.println("Error " + e);
}
showAlert(Alert.AlertType.CONFIRMATION, gridPane.getScene().getWindow(), "Registration Succesful!", "Welcome " + fnamefield.getText());
}
});
}
//alert box which is called
private void ErrorAlert(Alert.AlertType alertType, Window owner, String
title, String message){
Alert AlertError = new Alert (AlertType.ERROR);
AlertError.setTitle(title);
AlertError.setHeaderText(null);
AlertError.setContentText(message);
AlertError.initOwner(owner);
AlertError.show();
}
private void showAlert(Alert.AlertType alertType, Window owner, String title, String message) {
Alert alert = new Alert(alertType.CONFIRMATION);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(message);
alert.initOwner(owner);
alert.show();
ButtonType b1 = new ButtonType ("Proceed");
ButtonType b2 = new ButtonType ("Cancel");
ButtonType b3 = new ButtonType ("Back to Main Menu");
alert.getButtonTypes().setAll(b1,b2,b3);
if (alert.getResult() == b1) {
new QuestionOne(stage).start(stage);
}else if (alert.getResult() == b2){
new Register(stage).start(stage);
}else {
new Register(stage).start(stage);
//new Main (stage).start(stage);
}
}
public static void main(String[] args) {
launch(args);
}
}
Set the button types before showing the alert and use Dialog.showAndWait to "wait" for the result:
...
alert.initOwner(owner);
ButtonType b1 = new ButtonType("Proceed");
ButtonType b2 = new ButtonType("Cancel");
ButtonType b3 = new ButtonType("Back to Main Menu");
alert.getButtonTypes().setAll(b1,b2,b3);
Optional<ButtonType> result = alert.showAndWait();
ButtonType resButton = result.orElse(null);
if (resButton == b1) {
...
} else if (resButton == b2) {
...
} else if (resButton == b3) {
...
}
Also as mentioned previously: A Application class without a constructor that takes no parameters cannot be launched. Your main method won't work.
Related
I was able to send message to clients connected to server but when
When Client Bunny sends message to Joel(receives message) and vice versa.
When second time Bunny sends message to Joel (doesn't receive message).
How do I iterate hashtable loop again to send and receive messages.
Server Class
import java.io.*; //Input and output to read and write data.
import java.net.*; //serversocket and initaddress
import java.util.Date; //to get date
import java.util.Enumeration; //enumeration
import java.util.Hashtable; // hashtable
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javafx.application.Application; //
import javafx.application.Platform; //platformrun later to append text
import javafx.event.EventHandler; // on click actions
import javafx.geometry.Insets; //insets
import javafx.geometry.Pos; //position
import javafx.scene.Scene; //scene
import javafx.scene.control.TextArea; //textarea
import javafx.scene.layout.StackPane; //stackpane
import javafx.stage.Stage; //stage
import javafx.stage.WindowEvent; //event close
public class Server extends Application { //class server
static InetAddress inetAddress; //inetaddress
private final Hashtable<Object, Object> outputStreams = new Hashtable(); //hashtable
TextArea textarea = new TextArea(); //textarea
static DataInputStream inputFromClient = null; //datainputstream
static DataOutputStream outputToClient = null; //dataoutputstream
static int clientNo = 0; //client connected
static ServerSocket serverSocket; //server socket
Hashtable<Object, Object> hmap = new Hashtable<>();
#Override // Override the start method in the Application class
public void start(Stage primaryStage) { //Stage to show everything
StackPane root = new StackPane(); //root add all the elements
root.setPadding(new Insets(10, 10, 10, 10)); //padding
root.setAlignment(textarea, Pos.CENTER); //positioning textarea to center
textarea.setMaxSize(400, 400); //maxsize of textarea
textarea.setWrapText(true); //wraptext for the textarea
new Thread(() -> { //thread to hold the server for the connections
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8001); //The server creates a server socket and, once a connection to a client is established, connects to the client with a client socket.
textarea.appendText("MultiThreadServer started at " + new Date() + '\n'); //server started with date.
while (true) { //accept multiple connections
// Listen for a new connection request
Socket socket = serverSocket.accept(); //listening for new connection from server port.
// inputFromClient = new DataInputStream(socket.getInputStream());
outputToClient = new DataOutputStream(socket.getOutputStream()); //outputstream to output to client
// Increment clientNo
clientNo++;
Platform.runLater(() -> {
// Display the client number
textarea.appendText("Starting thread for client " + clientNo + " at " + new Date() + '\n');
// Find the client's host name, and IP address
InetAddress inetAddress = socket.getInetAddress();
textarea.appendText("Client " + clientNo + "'s host name is " + inetAddress.getHostName() + "\n");
textarea.appendText("Client " + clientNo + "'s IP Address is " + inetAddress.getHostAddress() + "\n");
});
HandleAClient hd = new HandleAClient(socket);
hmap.put(socket, outputToClient);
hd.start();
// outputStreams.put(socket, outputToClient); //using hashtable to store client socket and outputstream
// Create and start a new thread for the connection
// new HandleAClient(this, socket);
}
} catch (IOException ex) {
textarea.appendText(ex + " \n");
}
}).start();
root.getChildren().addAll(textarea); // add UI elements to the root
Scene scene = new Scene(root, 450, 400); // creating scene of size 450 width and height 500
primaryStage.setTitle("Server"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() { //close scene
#Override
public void handle(WindowEvent t) {
primaryStage.close();
Platform.exit();
System.exit(0);
}
});
}
// Used to get the output streams
Enumeration getOutputStreams() {
return outputStreams.elements();
}
// Used to send message to all clients
void sendToAll(String message) {
// Go through hashtable and send message to each output stream
for (Enumeration e = getOutputStreams(); e.hasMoreElements();) {
DataOutputStream dout = (DataOutputStream) e.nextElement();
try {
// Write message
dout.writeUTF(message);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
class HandleAClient extends Thread {
private Socket socket; // A connected socket
private String text = "";
/**
* Construct a thread
*/
public HandleAClient(Socket socket) throws IOException {
this.socket = socket;
}
/**
* Run a thread
*/
public void run() {
try {
// Create data input stream
inputFromClient = new DataInputStream(socket.getInputStream()); //receive input from client
textarea.appendText(new Date() + " Connection from " + socket + "\n");//showing connection from client
text = inputFromClient.readUTF(); // read string or message from client
// serversocket.sendToAll(text);
Set set = hmap.entrySet();
Iterator it = set.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
System.out.println("key " + entry.getKey() + " : " + entry.getValue());
DataOutputStream dout = (DataOutputStream) entry.getValue();
dout.writeUTF(text);
dout.flush();
}
Platform.runLater(() -> {
textarea.appendText(new Date() + " " + text + "\n");//append text
});
} catch (IOException e) {
textarea.appendText("Error " + e + " \n");
try {
this.socket.close(); //socket close
} catch (IOException ex) {
textarea.appendText("Error " + e + " \n");
}
e.printStackTrace();
}
}
}
public static void main(String[] args) { //The keyword void simply tells the compiler that main( ) does not return a value.
launch(args);
}
}
Client Class
import java.io.*; //Input and output to read and write data.
import java.net.*; //serversocket and initaddress
import javafx.application.Application; //
import javafx.application.Platform; //platformrun later to append text
import javafx.event.EventHandler; // on click actions
import javafx.geometry.Insets; //insets
import javafx.geometry.Pos; //position
import javafx.scene.Scene; //scene
import javafx.scene.control.TextArea; //textarea
import javafx.scene.layout.StackPane; //stackpane
import javafx.stage.Stage; //stage
import javafx.stage.WindowEvent; //event close
import javafx.scene.control.Button; // button
import javafx.scene.control.Label; //label
import javafx.scene.control.TextField; //textfield
public class Client extends Application {
// IO streams
static DataOutputStream toServer = null; //datainputstream
static DataInputStream fromServer = null; //dataoutputstream
Label usernamelabel = new Label("Set your name :"); //set name label
Label textarealabel = new Label("Type your message in the textarea"); //text label
Label textlabel = new Label("Enter Text :"); //enter text
TextField textfield = new TextField(); //textfield
TextField namefield = new TextField(); //name field
Button send = new Button("Send"); //sendbutton
TextArea messagefield = new TextArea(); //textarea
static ServerSocket serverSocket; //serversocket
// Override the start method in the Application class
public void start(Stage primaryStage) throws IOException {
StackPane root = new StackPane(); //stacpane
root.setPadding(new Insets(10, 10, 10, 10));
StackPane.setAlignment(usernamelabel, Pos.TOP_LEFT);
namefield.setMaxWidth(200);
StackPane.setAlignment(namefield, Pos.TOP_CENTER);
StackPane.setMargin(textlabel, new Insets(30, 0, 0, 0));
StackPane.setMargin(textfield, new Insets(30, 0, 0, 0));
StackPane.setAlignment(textlabel, Pos.TOP_LEFT);
textfield.setMaxWidth(200);
StackPane.setAlignment(textfield, Pos.TOP_CENTER);
StackPane.setAlignment(send, Pos.BOTTOM_CENTER);
messagefield.setMaxSize(450, 250);
StackPane.setAlignment(textarealabel, Pos.BOTTOM_CENTER);
StackPane.setMargin(textarealabel, new Insets(0, 0, 35, 0));
StackPane.setAlignment(messagefield, Pos.CENTER);
root.getChildren().addAll(usernamelabel, namefield, send, messagefield, textarealabel, textlabel, textfield); //adding all the UI elements
// Create a scene and place it in the stage
Scene scene = new Scene(root, 500, 400);
primaryStage.setTitle("Client"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
send.setOnAction(e -> { //send button action
try {
if (namefield.getText().trim().length() == 0) { //name field is empty
messagefield.appendText("Name field is empty. Please enter your name\n");
} else if (textfield.getText().trim().length() == 0) { //message field is empty
messagefield.appendText("Message field is empty. Please enter your message to send\n");
}
// Send the radius to the server
if (namefield.getText().trim().length() > 0 && textfield.getText().trim().length() > 0) {
toServer.writeUTF(namefield.getText().trim() + " : " + textfield.getText().trim());
toServer.flush();
}
} catch (IOException ex) {
messagefield.appendText(ex+" \n");
}
});
try {
// Create a socket to connect to the server
Socket socket = new Socket("localhost", 8001); //socket with port number to connect server
// Create an output stream to send data to the server
toServer = new DataOutputStream(socket.getOutputStream());
new ReceiveMessage(socket); // send socket receieve class
// }
} catch (Exception ex) {
messagefield.setText(ex.toString() + '\n');
}
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() { //scene close
#Override
public void handle(WindowEvent t) {
Platform.exit();
System.exit(0);
}
});
}
class ReceiveMessage implements Runnable { //class receive message
private final Socket socket;//socket
public ReceiveMessage(Socket socket) { // constructor
this.socket = socket; //socket intializes
Thread thread = new Thread(this);
thread.setDaemon(true);
thread.start();
}
public void run() {
try {
fromServer = new DataInputStream(socket.getInputStream()); //to read from server
while (true) { // to continously receieve messages
// Get area from the server
String textmessage = fromServer.readUTF(); //read message from server
toServer.flush(); // flush
Platform.runLater(() -> {
messagefield.appendText(textmessage + " \n"); //append to textarea
});
}
} catch (IOException e) {
messagefield.appendText("Error " + e);
}
}
}
public static void main(String[] args) { //The keyword void simply tells the compiler that main( ) does not return a value.
launch(args);
}
}
Server class executed and taking clients
Client one connected
Client Two connected
Thank you.
The mistake I made in the code was after client sends message to server and sends message to all the clients connected to the server after that server connection is paused or halted I don't know why. I have used enumeration method to send messages to all the clients connected to the server. This is how I solved the issue. Hope my answer will help someone who is trying to implement client-server (multiple clients) chat application using thread.
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
public class Server extends Application {
static InetAddress inetAddress;
private final Hashtable<Object, Object> outputStreams = new Hashtable();
TextArea textarea = new TextArea();
static int clientNo = 0;
static ServerSocket serverSocket;
Hashtable<Object, Object> hmap = new Hashtable<>();
ArrayList<Object> clients = new ArrayList<Object>();
public void start(Stage primaryStage) {
StackPane root = new StackPane();
root.setPadding(new Insets(10, 10, 10, 10));
root.setAlignment(textarea, Pos.CENTER);
textarea.setMaxSize(400, 400);
textarea.setWrapText(true);
root.getChildren().addAll(textarea);
Scene scene = new Scene(root, 450, 400);
primaryStage.setTitle("Server");
primaryStage.setScene(scene);
primaryStage.show(); // Display the stage
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent t) {
primaryStage.close();
Platform.exit();
System.exit(0);
}
});
new Thread(() -> {
listen();
}).start();
}
private void listen() {
try {
// Create a server socket
serverSocket = new ServerSocket(8001);
textarea.appendText("MultiThreadServer started at " + new Date() + '\n');
while (true) {
Socket socket = serverSocket.accept();
inputFromClient = new DataInputStream(socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
clientNo++;
Platform.runLater(() -> {
textarea.appendText("Starting thread for client " + clientNo + " at " + new Date() + '\n');
InetAddress inetAddress = socket.getInetAddress();
textarea.appendText("Client " + clientNo + "'s host name is " + inetAddress.getHostName() + "\n");
textarea.appendText("Client " + clientNo + "'s IP Address is " + inetAddress.getHostAddress() + "\n");
});
hmap.put(socket, outputToClient);
new HandleAClient(socket);
}
} catch (IOException ex) {
textarea.appendText(ex + " \n");
}
}
Enumeration getOutputStreams() {
return hmap.elements();
}
void sendToAll(String message) {
for (Enumeration e = getOutputStreams(); e.hasMoreElements();) {
DataOutputStream dout = (DataOutputStream) e.nextElement();
try {
dout.writeUTF(message);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
void All(String text) throws IOException {
Set set = hmap.entrySet();
Iterator it = set.iterator();
System.out.println("Text " + text);
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
System.out.println("key " + entry.getKey() + " : " + entry.getValue());
DataOutputStream dout = (DataOutputStream) entry.getValue();
dout.writeUTF(text);
dout.flush();
}
}
class HandleAClient extends Thread {
private final Socket socket; // A connected socket
private String text = "";
/**
* Construct a thread
*/
public HandleAClient(Socket socket) throws IOException {
this.socket = socket;
start();
}
/**
* Run a thread
*/
public void run() {
try {
DataInputStream inputFromClient = new DataInputStream(socket.getInputStream()); //receive input from client
while (true) {
textarea.appendText(new Date() + " Connection from " + socket + "\n");
text = inputFromClient.readUTF();
serversocket.sendToAll(text);
All(text);
Platform.runLater(() -> {
textarea.appendText(new Date() + " " + text + "\n");
});
}
} catch (IOException e) {
textarea.appendText("Error " + e + " \n");
try {
this.socket.close();
} catch (IOException ex) {
textarea.appendText("Error " + e + " \n");
}
e.printStackTrace();
}
}
}
public static void main(String[] args) { //The keyword void simply tells the compiler that main( ) does not return a value.
launch(args);
}
}
I have converted Many Activities to Fragment, all are working fine except one. In the Previous version of this java file, it was extending ListActivity, now I have replaced it with ListFragment. Initially it was giving a nullPointerException, but with help of this post, I managed to remove error. Now it is fetching data in Adapter but not in listview (which I checked by printing it in log). So I need to show data in listview.
Here is Java code:
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import java.io.InputStreamReader;
import java.net.URL;
import java.io.BufferedReader;
import java.net.URLConnection;
import android.support.v4.app.Fragment;
public class listtojson extends ListFragment {
private ProgressDialog pDialog;
// URL to get contacts JSON
// public static String url = "http://www.newsvoice.in/upload_audio_sawdhan/listFileDir.php";
public static String url = "http://www.newsvoice.in/upload_audio_sawdhan/listnews.php";
//public static String url = "http://www.newsvoice.in/sites/listNewsSites.php";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_SIZE = "size";
private static final String TAG_PHONE_URL = "url";
private static final String TAG_FILETYPE = "filetype";
private static final String TAG_FILETYPETXT = "filetypetxt";
private static final String TAG_DETAILS = "details";
private static final String TAG_FILEPATH = "filepath";
private static final String TAG_LOCATION = "location";
private static final String TAG_DATETIME = "datetime";
private static final String TAG_USERNAME = "username";
private static final String TAG_HIGHALERT= "highalert";
// public ImageLoader imageLoader;
public int ssid ;
// contacts JSONArray
JSONArray contacts = null;
public TextView view1;
ListView lv;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
View fragment;
LinearLayout llLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FragmentActivity faActivity = (FragmentActivity) super.getActivity();
llLayout = (LinearLayout) inflater.inflate(R.layout.listnewsjson, container, false);
contactList = new ArrayList<HashMap<String, String>>();
fragment = inflater.inflate(R.layout.listnewsjson, container, false);
return llLayout;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
lv = (ListView) fragment.findViewById(android.R.id.list);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String size = ((TextView) view.findViewById(R.id.size))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.url))
.getText().toString();
String details = ((TextView) view.findViewById(R.id.details))
.getText().toString();
String location = ((TextView) view.findViewById(R.id.location))
.getText().toString();
String datetime = ((TextView) view.findViewById(R.id.datetime))
.getText().toString();
String filetype = ((TextView) view.findViewById(R.id.filetypetxt))
.getText().toString();
String username = ((TextView) view.findViewById(R.id.username))
.getText().toString();
//String highalert = ((TextView) view.findViewById(R.id.highalert)).getText().toString();
//ImageView thumb_image=(ImageView)view.findViewById(R.id.filetype);
// ImageView image = (ImageView) view.findViewById(R.id.filetype);
// thumb image
//= String filetype = ((ImageView) view.findViewById(R.id.filetype))
//= .getText().toString();
// Starting single contact activity
/* Intent in = new Intent(getApplicationContext(),
fileDownloader.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_SIZE, cost);
in.putExtra(TAG_PHONE_URL, description);
startActivity(in);
*/
Intent in = new Intent(getActivity().getApplicationContext(), jsondetailActivity.class);
// passing sqlite row id
//= in.putExtra(TAG_ID, sqlite_id);
in.putExtra(TAG_ID, String.valueOf(id));
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_DETAILS, details);
in.putExtra(TAG_LOCATION, location);
in.putExtra(TAG_DATETIME, datetime);
in.putExtra(TAG_FILETYPE, filetype);
in.putExtra(TAG_PHONE_URL, description);
in.putExtra(TAG_SIZE, size);
in.putExtra(TAG_USERNAME, username);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
//return llLayout;
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading People News");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
try {
// Making a request to url and getting response
// String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
URL requestUrl = new URL(url);
Log.e("Debug", " Sapp 1 : " + requestUrl.toString());
URLConnection con = requestUrl.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb=new StringBuilder();
//Reader rd=new Readable(in);
int cp;
try {
while((cp=in.read())!=-1){
sb.append((char)cp);
}}
catch(Exception e){
}
String jsonStr=sb.toString();
Log.e("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String size = c.getString(TAG_SIZE);
String url = c.getString(TAG_PHONE_URL);
String details = c.getString(TAG_DETAILS);
String location = c.getString(TAG_LOCATION);
String datetime = c.getString(TAG_DATETIME);
String filetype = c.getString(TAG_FILETYPE);
String username = c.getString(TAG_USERNAME);
String highalert = c.getString(TAG_HIGHALERT);
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_SIZE, size);
contact.put(TAG_PHONE_URL, url);
contact.put(TAG_DETAILS, details);
contact.put(TAG_LOCATION, location);
contact.put(TAG_DATETIME, datetime);
contact.put(TAG_FILETYPE, filetype);
contact.put(TAG_FILETYPETXT, filetype);
contact.put(TAG_USERNAME, username);
contact.put(TAG_HIGHALERT, highalert);
// Log.e("Debug", " Sapp 7 : " + name);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}catch(Exception ec){
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.list_selector, new String[] { TAG_NAME, TAG_SIZE,
TAG_PHONE_URL,TAG_FILETYPE, TAG_FILETYPETXT,TAG_DETAILS,TAG_LOCATION,TAG_DATETIME, TAG_USERNAME, TAG_HIGHALERT}, new int[] { R.id.name,
R.id.size, R.id.url, R.id.filetype,R.id.filetypetxt, R.id.details, R.id.location, R.id.datetime, R.id.username, R.id.highalert });
Log.e("Debug", " Sapp 10" + TAG_NAME+contactList.toString());
//Here it is printing the array in Log
//Problem seems here
SimpleAdapter.ViewBinder viewBinder = new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
Log.e("Debug", " Sapp 11"+view.getId());
if (view.getId() == R.id.name) {
((TextView) view).setText((String) data);
return true;
} else if (view.getId() == R.id.size) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.url) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.details) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.location) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.datetime) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.filetypetxt) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.username) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.highalert) {
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xffff0000); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(0);
gd.setSize(10,20);
// view.findViewById(R.id.name).setBackgroundDrawable(gd);
String halert=(String.valueOf((String) data));
if(halert.equals("1")) {
((TextView) view).setText(" ");
((TextView) view).setBackgroundDrawable(gd);
return true;
}
else { return true; }
} else if (view.getId() == R.id.filetype) {
// (view1 = (TextView) findViewById(R.id.filetypetxt)).setText((String) data);
Resources res =getResources();
String tnew=(String.valueOf((String) data));
String tst=tnew;
int sidd=0;
// Log.e("Debug", " Sapp 7:"+(String)data+":");
if(tst.equals("c")) { ssid = R.drawable.ca; }
else if(tst.equals("d")) { ssid = R.drawable.da; }
else if(tst.equals("e")) { ssid = R.drawable.ea; }
//s=2130837566;
Log.e("Debug", " Sapp 8 :"+ssid+":");
Bitmap bmp = BitmapFactory.decodeResource(res, ssid);
BitmapDrawable ob = new BitmapDrawable(getResources(), bmp);
((ImageView) view).setImageDrawable(ob);
((ImageView) view).setImageBitmap(bmp);
return true;
}
return false;
}
};
((SimpleAdapter) adapter).setViewBinder(viewBinder);
lv.setAdapter(adapter);
registerForContextMenu(lv);
}
}
public static String getFileSize(long size) {
if (size <= 0)
return "0";
final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
}
and Here is xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
/>
</LinearLayout>
Some suggestions:
No need for View fragment; and its initialization: fragment = inflater.inflate(R.layout.listnewsjson, container, false); Remove them.
Replace lv = (ListView) fragment.findViewById(android.R.id.list); with lv = getListView();. getListView() is a method defined by ListFragment that returns the fragment's ListView.
IMPORTANT: Replace lv.setAdapter(adapter); in onPostExecute() with setListAdapter(adapter);. From documentation of ListFragment:
You must use ListFragment.setListAdapter() to associate the list with an adapter. Do not directly call ListView.setAdapter() or else important initialization will be skipped.
Modify setViewValue() method of viewBinder to:
#Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
Log.e("Debug", " Sapp 11" + view.getId());
if (view.getId() == R.id.highalert) {
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xffff0000); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(0);
gd.setSize(10, 20);
// view.findViewById(R.id.name).setBackgroundDrawable(gd);
String halert = (String.valueOf((String) data));
if (halert.equals("1")) {
((TextView) view).setText(" ");
((TextView) view).setBackgroundDrawable(gd);
} else {
// TODO: Should remove gradient color here because views are recycled.
}
return true;
}
if (view.getId() == R.id.filetype) {
// (view1 = (TextView) findViewById(R.id.filetypetxt)).setText((String) data);
Resources res = getResources();
String tnew = (String.valueOf((String) data));
String tst = tnew;
int sidd = 0;
// Log.e("Debug", " Sapp 7:"+(String)data+":");
if (tst.equals("c")) {
ssid = R.drawable.ca;
} else if (tst.equals("d")) {
ssid = R.drawable.da;
} else if (tst.equals("e")) {
ssid = R.drawable.ea;
}
//s=2130837566;
Log.e("Debug", " Sapp 8 :" + ssid + ":");
Bitmap bmp = BitmapFactory.decodeResource(res, ssid);
BitmapDrawable ob = new BitmapDrawable(getResources(), bmp);
((ImageView) view).setImageDrawable(ob);
((ImageView) view).setImageBitmap(bmp);
return true;
}
return false;
}
ViewBinder only needs to handle cases where you need to do something extra (like setting background color or loading images based on passed-in data values in your case) than just simply binding values to views. Ordinary binding of values to views is provided by SimpleAdapter by default.
I have a tabbed editor with TextArea and I want to save the selected file's textarea content.
But how can I do this?
Here I have my items defined (or what it's called on english. I'm danish) :
public static TabPane pane = new TabPane();
public static TextArea area;
public static ListView lines;
public static VBox box;
public static Tab tabs;
public static BorderPane bps;
My code for adding a tab:
public static void AddTab(String title, String con) {
area = new TextArea();
lines = new ListView();
box = new VBox();
bps = new BorderPane();
bps.setLeft(lines);
bps.setRight(area);
box.getChildren().addAll(bps);
tabs = new Tab(title);
tabs.setContent(box);
pane.getTabs().add(tabs);
}
When i add a tab i use this code :
int i;
for (i = 0; i < GUI.Editor.pane.getTabs().size(); i++) {
}
String title = "New File (" + i + ")";
GUI.Editor.AddTab(title, null);
GUI.Editor.pane.getSelectionModel().select(i);
But how can I save a file on this way?.
Oh and of course I know I need a file dialog (and I have try to save file).
The only thing I will need is how to get the content from the selected tab (when I mean content I mean the TextArea's content).
As you are setting tab content is VBox it's bit difficult to get the TextArea directly. One way is by doing multiple type casts from VBox to Textarea we can get the selected area.
private static TextArea getSelectedTabContent() {
Node selectedTabContent = pane.getSelectionModel().getSelectedItem().getContent();
if(selectedTabContent instanceof VBox){
Node borderPane = ((VBox) selectedTabContent).getChildren().get(0);
if(borderPane instanceof BorderPane){
Node textAreaNode = ((BorderPane) borderPane).getRight();
if(textAreaNode instanceof TextArea){
return (TextArea) textAreaNode;
}
}
}
return null;
}
Below is the complete code to save to file.
package com.pw.jnotepad.app;
import com.pw.jnotepad.app.providers.AlertBox;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
public class StackOverflowAnswer extends Application {
public static TabPane pane = new TabPane();
public static TextArea area;
public static ListView lines;
public static VBox box;
public static Tab tabs;
public static BorderPane bps;
public static Stage window;
#Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
area = new TextArea();
lines = new ListView();
box = new VBox();
bps = new BorderPane();
bps.setTop(createMenuBar());
bps.setLeft(lines);
bps.setRight(area);
box.getChildren().addAll(bps);
tabs = new Tab("tab-1");
tabs.setContent(box);
pane.getTabs().add(tabs);
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
}
// to create menu bar with file menu
private static MenuBar createMenuBar(){
Menu fileMenu = new Menu("File");
MenuItem saveFile = new MenuItem("Save");
saveFile.setOnAction(event -> {
System.out.println("Save file action triggered");
FileChooser fileChooser = createFileChooser("Save File");
File selectedFile = fileChooser.showSaveDialog(window);
if(selectedFile != null){
File savedFile = saveTextToFile(selectedFile);
if(savedFile!= null){
System.out.println("file saved successfully");
updateTabTitle(savedFile.getName());
}
}
});
fileMenu.getItems().addAll(saveFile);
return new MenuBar(fileMenu);
}
// to open save dialog window
private static FileChooser createFileChooser(String title) {
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter onlyTextFilesFilter = new FileChooser.ExtensionFilter("Txt files(*.txt)", "*.txt");
fileChooser.getExtensionFilters().add(onlyTextFilesFilter);
fileChooser.setTitle(title);
fileChooser.setInitialDirectory(Paths.get("").toAbsolutePath().toFile());
return fileChooser;
}
// to save the file into disk
public static File saveTextToFile(File file) {
TextArea selectedTabContent = getSelectedTabContent();
if(selectedTabContent!=null){
try(BufferedWriter buffer = new BufferedWriter(new FileWriter(file));) {
ObservableList<CharSequence> paragraphs = selectedTabContent.getParagraphs();
paragraphs.forEach(charSequence -> {
try {
buffer.append(charSequence);
buffer.newLine();
} catch (IOException e) {
System.out.println("failed to write to text file.");
AlertBox.display("File Save Error", "failed to write to text file.");
e.printStackTrace();
}
});
buffer.flush();
return file;
} catch (IOException e) {
System.out.println("failed to write to text file.");
AlertBox.display("File Save Error", "failed to write to text file.");
e.printStackTrace();
}
}
return null;
}
// to get selected text area
private static TextArea getSelectedTabContent() {
Node selectedTabContent = pane.getSelectionModel().getSelectedItem().getContent();
if(selectedTabContent instanceof VBox){
Node borderPane = ((VBox) selectedTabContent).getChildren().get(0);
if(borderPane instanceof BorderPane){
Node textAreaNode = ((BorderPane) borderPane).getRight();
if(textAreaNode instanceof TextArea){
return (TextArea) textAreaNode;
}
}
}
return null;
}
// to update tab title by saved file name
private static void updateTabTitle(String name){
pane.getSelectionModel().getSelectedItem().setText(name);
}
}
I have a test application that I draw a Polygon using google maps API.
The problem is that, when I have no cache of any maps (new installed application) the Polygon does not draw.
Its not a problem not having the maps loaded, but I do need the Polygons drawn in my screen.
Is there a way I can do that?
Sry for my bad english
Heres the code I have:
package ngvl.testegmaps_v2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import ngvl.testegmaps_v2.VO.GeoPosicionamento;
import ngvl.testegmaps_v2.VO.Layer;
import ngvl.testegmaps_v2.VO.Secao;
import ngvl.testegmaps_v2.VO.Talhao;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class MainActivity extends FragmentActivity {
private List<Secao> secoes;
private List<Polygon> poligonos = new ArrayList<Polygon>();
private HashMap<String,Object[]> informacoes = new HashMap<String,Object[]>();
private GoogleMap map;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
map = fragment.getMap();
map.getUiSettings().setRotateGesturesEnabled(false);
// Setting a click event handler for the map
LatLng latLng = new LatLng(-20.9957152, -47.3241304);
// map.addMarker(new
// MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)).title("Av. Paulista").snippet("São Paulo"));
configuraPosicao(map, latLng);
Button button = (Button)findViewById(R.id.button1);
// Register the onClick listener with the implementation above
button.setOnClickListener(mCorkyListener);
}
private void configuraPosicao(GoogleMap map, LatLng latLng) {
/*
* 3D map.moveCamera( CameraUpdateFactory.newLatLngZoom(latLng, 15));
* map.animateCamera( CameraUpdateFactory.zoomTo(10), 2000, null);
*
* CameraPosition cameraPosition = new CameraPosition.Builder()
* .target(latLng) .zoom(17) .bearing(90) .tilt(45) .build();
*
* map.animateCamera( CameraUpdateFactory.newCameraPosition(
* cameraPosition));
*/
map.setMapType(GoogleMap.MAP_TYPE_NONE);
// map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17.0f));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
try {
String json = readFileAsString("geo.json");
Gson gson = new Gson();
this.secoes = gson.fromJson(json, new TypeToken<List<Secao>>() {
}.getType());
json = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
escrevePoligons(map);
}
private String readFileAsString(String fileName) throws IOException {
InputStream is = getAssets().open(fileName);
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
is.close();
}
return sb.toString();
} else {
return "";
}
}
private void escrevePoligons(GoogleMap map) {
float stroke = (float) 1.5;
for (Secao secao : secoes) {
for (Talhao talhao : secao.getTalhoes()) {
for (Layer layer : talhao.getLayers()) {
// PolygonOptions rectOptions = new PolygonOptions();
List<LatLng> latlngs = new ArrayList<LatLng>();
for (GeoPosicionamento geoPosicionamento : layer.getGeoPosicionamentos()) {
latlngs.add(new LatLng(geoPosicionamento.getLatitude()
.setScale(7, BigDecimal.ROUND_HALF_EVEN)
.doubleValue(), geoPosicionamento
.getLongitude()
.setScale(7, BigDecimal.ROUND_HALF_EVEN)
.doubleValue()));
}
int color = 0x1F00FF00;
int color2 = 0x5F000000;
PolygonOptions polygonOptions = new PolygonOptions()
.fillColor(color).addAll(latlngs)
.strokeColor(color2).strokeWidth(stroke);
Polygon p = map.addPolygon(polygonOptions);
poligonos.add(p);
informacoes.put( p.getId(), new Object[]{ secao, talhao , layer } );
//System.out.println(polygonOptions.getPoints());
polygonOptions = null;
latlngs = null;
}
}
}
this.secoes = null;
// String mUrl =
// "https://khms0.google.com.br/kh/v=124&src=app&z={z}&x={x}&y={y}";
// MyUrlTileProvider mTileProvider = new MyUrlTileProvider(256, 256,
// mUrl);
// mTileProvider.tilesRange();
// map.addTileOverlay(new
// TileOverlayOptions().tileProvider(mTileProvider).zIndex(-1f));
//String mUrl = "http://a.tile.openstreetmap.org/{z}/{x}/{y}.png";
//MyUrlTileProvider mTileProvider = new MyUrlTileProvider(256, 256, mUrl);
//map.addTileOverlay(new TileOverlayOptions().tileProvider(mTileProvider).zIndex(-1f));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-20.9957152, -47.3241304), 14));
// TileProvider tileProvider = TileProviderFactory.getTileProvider();
// map.addTileOverlay(new
// TileOverlayOptions().tileProvider(tileProvider));
// map.moveCamera(CameraUpdateFactory.newLatLngZoom(new
// LatLng(-20.9957152, -47.3241304), 15));
map.setOnMapClickListener(new OnMapClickListener()
{
public void onMapClick(LatLng point)
{
Polygon p = isPointInPolygon(point);
if( p != null){
p.setFillColor(getRandomColor());
Object[] clicado = informacoes.get( p.getId() );
Secao secao_clicada = (Secao) clicado[0];
Talhao talhao_clicada = (Talhao) clicado[1];
Layer layer_clicada = (Layer) clicado[2];
//System.out.println(secao_clicada);
//System.out.println(talhao_clicada);
//System.out.println(layer_clicada);
//System.out.println("=======================");
StringBuilder texto = new StringBuilder();
texto.append("Seção: " + secao_clicada.getDesc() + "\n");
texto.append("Talhão: " + talhao_clicada.getTalhao() + "\n");
texto.append("Variedade: " + talhao_clicada.getVariedade() + " - " + talhao_clicada.getDescVariedade() + "\n");
texto.append("Layer: " + layer_clicada.getSequencia() + "\n");
//Toast.makeText(MainActivity.this, texto , Toast.LENGTH_LONG).show();
addMarker(point,texto);
}//else
//Toast.makeText(MainActivity.this,"Clicou fora da Área de um Poligono", Toast.LENGTH_LONG).show();
}
});
}
public void addMarker(LatLng point, StringBuilder texto) {
/*map.addMarker(new MarkerOptions().position(point).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
.title("Caracteristicas: ")
.snippet( texto );
*/
Toast.makeText(MainActivity.this, texto , Toast.LENGTH_LONG).show();
}
private Polygon isPointInPolygon(LatLng tap) {
for( Polygon p : poligonos){
int intersectCount = 0;
List<LatLng> vertices = p.getPoints();
for(int j=0; j<vertices.size()-1; j++) {
if( rayCastIntersect(tap, vertices.get(j), vertices.get(j+1)) ) {
intersectCount++;
}
}
if(((intersectCount % 2) == 1)){
return p;
}
}
return null;// odd = inside, even = outside;
}
private boolean rayCastIntersect(LatLng tap, LatLng vertA, LatLng vertB) {
double aY = vertA.latitude;
double bY = vertB.latitude;
double aX = vertA.longitude;
double bX = vertB.longitude;
double pY = tap.latitude;
double pX = tap.longitude;
if ( (aY>pY && bY>pY) || (aY<pY && bY<pY) || (aX<pX && bX<pX) ) {
return false; // a and b can't both be above or below pt.y, and a or b must be east of pt.x
}
double m = (aY-bY) / (aX-bX); // Rise over run
double bee = (-aX) * m + aY; // y = mx + b
double x = (pY - bee) / m; // algebra is neat!
return x > pX;
}
private OnClickListener mCorkyListener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-20.9957152, -47.3241304), 14));
}
};
public int getRandomColor() {
int color;
Random rnd = new Random();
color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256),
rnd.nextInt(256));
return color;
}
}
Setting map type to MAP_TYPE_NONE like example above does not solve the problem
I will this as marked solved by using Maps Forge Open Source API
If someone did with Google Maps Api please share and I would change the answer.
The answer I found is that its impossible to render or access anything without rendering the map first (online or via cache)
This is actually a bug of GoogleMaps Api v2 for Android.
It is referenced here:
https://code.google.com/p/gmaps-api-issues/issues/detail?id=5017
Star it if you want to accelerate the bug fix!
I have 2 buttons in my code, 'Clear' and 'Login', the problem is the login button can't be clicked, but the clear button works just fine.
Where is my mistake?
The code below is the entire project
public MyScreen()
{
// Set the displayed title of the screen
Bitmap logo = Bitmap.getBitmapResource("icon.png");
bitField = new BitmapField(logo, Field.FIELD_HCENTER);
userField = new EditField("Username :", "");
passField = new PasswordEditField("Password :", "");
ddlDomain = new ObjectChoiceField("Domain :", new String[] {"Home", "Work"});
chkRemember = new CheckboxField("Remember Password", false);
btnClear = new ButtonField("Clear", ButtonField.CONSUME_CLICK);
btnLogIn = new ButtonField("Log In", ButtonField.CONSUME_CLICK);
add(bitField);
add(new SeparatorField());
add(new LabelField("Please enter your credentials:"));
add(userField);
add(passField);
add(ddlDomain);
add(chkRemember);
HorizontalFieldManager btnManager = new HorizontalFieldManager(Field.FIELD_RIGHT);
btnManager.add(btnClear);
btnManager.add(btnLogIn);
add(btnManager);
btnClear.setChangeListener(this);
}
public void fieldChanged(Field field, int context) {
if(field == btnClear){
clearTextFields();
}
else if(field == btnLogIn){
login();
}
}
private void clearTextFields(){
userField.setText("");
passField.setText("");
}
private void login(){
if(userField.getTextLength() == 0 || passField.getTextLength() == 0){
Dialog.alert("You must enter a username and password");
}
else{
String username = userField.getText();
String selectedDomain = (String)ddlDomain.getChoice(ddlDomain.getSelectedIndex());
SuccessScreen loginSuccess = new SuccessScreen(username, selectedDomain);
UiApplication.getUiApplication().pushScreen(loginSuccess);
}
}
Hi dear you need to add
btnLogIn.setChangeListener(this);
try this