Using an Android Spinner - android-spinner

I'm new to Android and Java. I want to create an application with one spinner. I want it to: select an element form the spinner, for example element1, and I want it to show in a text view case, a definite text.
Spinner id: `Spinner_Elemente`
Spinner Items: String Array: `Elemente`
Text View id: edtElemente
Can you help me with some simple code? I looked on the developer site but I don't understand it. So, I would be grateful if you can help me with an simple code for my example.
sorry for my eng. :)

There are certain steps to be followed for Spinner to work
Create an array in res/values/array.xml or strings.xml
e.g.
<resources>
<string-array name="colors">
<item>Red</item>
<item>Green</item>
<item>Blue</item>
<item>White</item>
</string-array>
</resources>
Create a Spinner element in main layout file
e.g.
<Spinner
android:id="#+id/spin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="#array/colors"
android:prompt="#string/SPrompt"/>
Implement OnItemSelectedListener interface in java activity
Create java object:
e.g.
Spinner s=(Spinner) findViewById(R.id.spin);
s.setOnItemSelectedListener(this);
Override two methods and do the work you want when something is selected from the spinner:
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){}
public void onNothingSelected(AdapterView<?> arg0){}

This is the suggested java file for your example.
public class SpinnerExActivity extends Activity implements OnItemSelectedListener
{
Spinner s;
TextView tv;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
s=(Spinner) findViewById(R.id.Spinner_Elemente);
s.setOnItemSelectedListener(this);
tv=(TextView) findViewById(R.id.edtElemente);
}
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
tv.setText(s.getItemAtPosition(arg2));
}
public void onNothingSelected(AdapterView<?> arg0)
{
}
}

SOLVED, #Rishi,there was a little problem in the code.... The corect code
public class ChimExpressMainActivity extends Activity implements OnItemSelectedListener {
Spinner Spinner_Elemente_Java;
TextView Text_Despre_Element_Afisare;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chim_express_main);
Spinner_Elemente_Java=(Spinner) findViewById(R.id.Spinner_Elemente);
Spinner_Elemente_Java.setOnItemSelectedListener(this);
Text_Despre_Element_Afisare=(TextView) findViewById(R.id.edtElement);
Text_Despre_Element_Afisare.setMovementMethod(new ScrollingMovementMethod());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_chim_express_main, menu);
return true;
}
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
////////////////////////----TEST SPINNEER----////////////////////////////////////////////////////////////////////////////////////
//Text_Despre_Element_Afisare.setText((CharSequence) Spinner_Elemente_Java.getItemAtPosition(arg2));
//Text_Despre_Element_Afisare.setText("Hidrogenul este elementul chimic în tabelul periodic al elementelor cu simbolul H și numărul atomic 1. Este un gaz ușor inflamabil, incolor, insipid, inodor, iar în natură se întâlnește mai ales sub formă de moleculă diatomică, H2. Având masa atomică egală cu 1,00794 u.a.m. , hidrogenul este cel mai ușor element chimic. Etimologic, cuvântul hidrogen este o combinație a două cuvinte grecești, având semnificația de „a face apă”.Hidrogenul elementar este principala componentă a Universului, având o pondere de 75 % din masa acestuia.[1] În starea de plasmă, se găsește ca element majoritar în alcătuirea stelelor. Hidrogenul elementar este foarte puțin răspândit pe Pământ.Pentru necesități industriale există diferite procedee de fabricație, puse la punct din punct de vedere tehnologic sau aflate în fază de laborator. Hidrogenul poate fi obținut prin electroliza apei, procesul necesitând costuri mai mari decât cel de producere prin procesarea gazelor naturale.[2]Cel mai răspândit izotop al hidrogenului este protiul, care este alcătuit dintr-un singur proton în nucleu și un electron în învelișul electronic. În compușii ionici poate avea sarcină negativă (anion cunoscut sub numele de hidrură, H-) sau sarcină pozitivă H+ (cation). Hidrogenul formează compuși chimici cu majoritatea elementelor din sistemul periodic și este prezent în apă și în mulți dintre compușii organici. Are un rol important în reacțiile acido-bazice, acestea bazându-se pe schimbul de protoni între molecule. Fiind singurul atom pentru care soluția analitică a ecuației lui Schrödinger este pe deplin cunoscută, prezintă un rol major în fundamentarea teoriei mecanicii cuantice.Hidrogenul este un gaz puternic reactiv și își găsește aplicații datorită capacității sale chimice de reducător.[3] Hidrogenul se folosește în industria petrochimică la producerea benzinelor, în industria chimico-alimentară pentru hidrogenarea grăsimilor (de exemplu producerea margarinei), în prelucrările mecanice ale metalelor și în tratamentul termic al acestora.[4]Hidrogenul reprezintă o alternativă pentru înlocuirea benzinei drept combustibil pentru vehiculele echipate cu motoare cu ardere internă.[5] Avantajele sale principale constau în faptul că este ecologic, din arderea sa rezultând vapori de apă, iar randamentul termic al motoarelor cu hidrogen este ridicat. Dezavantajele constau în pericolul mare de explozie, dificultatea stocării în vehicul și lipsa unor rețele de stații de alimentare cu hidrogen. Una dintre cele mai promițătoare soluții tehnice o reprezintă conversia directă a energiei chimice din hidrogen în electricitate, prin intermediul pilelor de combustie.[6]");
//Text_Despre_Element_Afisare.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>"));
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(arg0.getSelectedItem().toString().equals("Hidrogen")){
Text_Despre_Element_Afisare.setText((CharSequence) Spinner_Elemente_Java.getItemAtPosition(arg2));
}
else{
if(arg0.getSelectedItem().toString().equals("Heliu"))
{
Text_Despre_Element_Afisare.setText((CharSequence) Spinner_Elemente_Java.getItemAtPosition(arg2));
}
else{
Text_Despre_Element_Afisare.setText("Close");
}
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}

Related

How to open JavaFX browser in a separate thread

i have a simple JavaFx browser that is launched through a JButton that it's placed into a JFrame. Now, i wanted to put the JavaFx broser into a separate thread that should run even if the JFrame is closed. Now, if i close the JFrame with that JButton, the JavaFx browser also closes. I've tried multiple combinations, done research over internet, but with no success. Hope you guys can help me with a little example. Thanks !
browser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == browser) {
// create a JFXPanel, which will start the FX toolkit
// if it's not already started: - folosit pt a integra componente de tip FX Stage in componente swing (mai vechi) (JFrame)
JFXPanel fxPanel = new JFXPanel();
Platform.runLater(new Runnable() {
#Override
public void run() {
Scene scene;
TextField addressField;
WebView webView;
WebEngine webEngine;
Stage stage = null;
Button reloadButton, goButton, backButton , forwardButton, historyList;
HBox hBox = new HBox(5);
hBox.setAlignment(Pos.CENTER);
//The TextField for entering web addresses.
addressField = new TextField("Ionutz says: Enter the address here....");
addressField.setPrefColumnCount(50); //make the field at least 50 columns wide.
//Add all out navigation nodes to the vbox.
reloadButton = new Button("Reload page");
goButton = new Button("Search");
backButton = new Button("Back");
forwardButton = new Button("Forward");
historyList = new Button("History");
String urlSearch = "http://icons.iconarchive.com/icons/ampeross/qetto-2/24/search-icon.png";
String urlReload = "http://icons.iconarchive.com/icons/graphicloads/colorful-long-shadow/24/Arrow-reload-2-icon.png";
String URLBack = "http://icons.iconarchive.com/icons/custom-icon-design/flatastic-1/24/back-icon.png";
String URLForward = "http://icons.iconarchive.com/icons/custom-icon-design/flatastic-1/24/forward-icon.png";
String URLHistory = "http://icons.iconarchive.com/icons/delacro/id/24/History-icon.png";
goButton.setGraphic(new ImageView(urlSearch));
reloadButton.setGraphic(new ImageView(urlReload));
forwardButton.setGraphic(new ImageView(URLForward));
backButton.setGraphic(new ImageView(URLBack));
historyList.setGraphic(new ImageView(URLHistory));
hBox.getChildren().addAll(backButton, forwardButton, addressField, reloadButton, goButton, historyList);
//Our weiv that display ther page.
webView = new WebView();
//the engine that manages our pages.
webEngine = webView.getEngine();
webEngine.setJavaScriptEnabled(true);
webEngine.load("http://www.google.ro");
//our main app layout with 5 regions.
BorderPane root = new BorderPane();
root.setPrefSize(1280, 720);
//Add every node to the BorderPane.
root.setTop(hBox);
root.setCenter(webView);
//Our scene is where all the action in JavaFX happens. A scene holds all Nodes, and its root node is our BorderPane.
scene = new Scene(root);
//the stage manages the scene.
fxPanel.setScene(scene);
JFrame browserFrame = new JFrame();
browserFrame.add(fxPanel);
browserFrame.setTitle("Ionutz Asaftei Browser");
browserFrame.setBounds(200, 200, 1280, 720);
browserFrame.setVisible(true);
// adaugam event handlers !!!! - cele mai simple pt Buttons
reloadButton.setOnAction(new EventHandler<javafx.event.ActionEvent>() {
public void handle(javafx.event.ActionEvent event) {
webEngine.reload();
}
});
goButton.setOnAction(new EventHandler<javafx.event.ActionEvent>() {
public void handle(javafx.event.ActionEvent event) {
webEngine.load("http://"+addressField.getText());
}
});
forwardButton.setOnAction(new EventHandler<javafx.event.ActionEvent>() {
public void handle(javafx.event.ActionEvent event) {
webEngine.getHistory().go(1); //avanseaza cu o pagina in functie de intrarile din history
}
});
backButton.setOnAction(new EventHandler<javafx.event.ActionEvent>() {
public void handle(javafx.event.ActionEvent ev) {
webEngine.getHistory().go(-1); //merge in urma cu o pagina in functie de intrarile din history
}
});
}
});
}
}
});
The JavaFX toolkit is single threaded from a user application point of view. It is not possible to spawn multiple threads launching WebView instances.

How to send string data to socket connection via telnet or any other program?

I am trying to send and receive string data to socket connection via telnet, but I am not able to type or see anything in the telnet window. I am able to connect to the server via telnet, but not able to send the string data.
Is there any other alternate method to send string data over socket connection.
Telnet, unless it negotiates parameters to the contrary, does "remote echo" meaning that you won't see anything you type unless the server echos it back.
A lot of people use the term "Telnet" when really it is a raw socket connection that does no configuration negotiation upon connect.
If you're sending data from a file or source other than the keyboard (and even often when sending from the keyboard), you're better of using a program like socket or nc (netcat) which don't attempt to do any processing of the data stream and so provide simple 8-bit clean connections.
In the case of both those problems, you can simply redirect stdin from a file or echo a string to them through a pipe.
i have a example of a server that talks to with many telnet client.
You must use the class DataInputStream and DataOutputStream
You must use A Class Implements Runnable for establish multiple sessions
You must use a ServerSocket Class.
Good, this is the code of the main class called SocketServerExample:
import java.net.*;
import java.io.*;
import socketserverexample.ThreadServer;
/**
*
* #author JuanLuisHiciano
*/
public class SocketServerExample {
public static void main(String args[]) throws InterruptedException {
ServerSocket mi_servicio = null;
String linea_recibida;
DataInputStream entrada = null;
DataOutputStream salida = null;
Socket socket_conectado = null;
try {
mi_servicio = new ServerSocket(2017);
}
catch (IOException excepcion) {
System.out.println(excepcion);
}
try {
int n=1;
while(n<2){
socket_conectado = mi_servicio.accept();
System.out.println("Un cliente se a conectado "+socket_conectado.getPort());
entrada= new DataInputStream(socket_conectado.getInputStream());
String nombre = entrada.readUTF();
// Se instancia una clase para atender al cliente y se lanza en
// un hilo aparte.
Runnable nuevoCliente = new ThreadServer(nombre, socket_conectado); //Input and Output data Channels
Thread hilo = new Thread(nuevoCliente);
hilo.start();
}
salida.writeUTF("Fin de la conexion....");
salida.close();
entrada.close();
socket_conectado.close();
}
catch (IOException excepcion) {
System.out.println(excepcion);
}
}
}
ok,This run de Main Server with the UTP port (2017) and delivering sessions to other threads to receive new connections.
Good , below is the code of the class Called ThreadServer :
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author JuanLuisHiciano
*/
public class ThreadServer implements Runnable{
DataInputStream entrada;
DataOutputStream salida;
Socket socket_conectado = null;
String linea_recibida;
String cliente;
ThreadServer(String cliente,Socket socket) {
socket_conectado = socket;
this.cliente=cliente;
}
#Override
public void run() {
int n=0;
while(n<3){
try {
salida = new DataOutputStream(socket_conectado.getOutputStream());
entrada = new DataInputStream(socket_conectado.getInputStream());
//System.out.println("Confirmando Conexion al cliente .....");
salida.writeUTF("Conexion Exitosa\n");
salida.writeUTF("Puede compartir un mensaje : ");
//recepcion de mensaje
linea_recibida = entrada.readUTF();
System.out.println(cliente+" dice: "+linea_recibida);
System.out.println(socket_conectado.getPort());
n++;
} catch (IOException ex) {
Logger.getLogger(ThreadServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
With this code you can talk to each of the clients connecting.
Goodbye Saludos de Republica Dominicana
I hope you serve something this code.

Redirect to page in liferay Login

I am creating a Hook to check-user on login, and depending on some parameters it will be redirected to one custom page or another.
I am doing this:
Portal.properties
#Gestion evento login
login.events.post=com.liferay.portal.events.AccionLogin
auth.forward.by.last.path=true
Action Class
public class AccionLogin extends Action {
#Override
public void run(HttpServletRequest request, HttpServletResponse response) throws ActionException {
try {
doRun(request, response);
} catch (Exception e) {
throw new ActionException(e);
}
}
protected void doRun(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession sesion = request.getSession();
User usuarioLogin = PortalUtil.getUser(request);
// Recupero la lista de roles
ArrayList<Role> roles = UtilRoles.getIntExtRol();
// Compruebo si el usuario pertenece al grupo
if (UtilLdap.esGrupo(request, usuarioLogin.getScreenName())) {
Constantes._log.info("El usuario es Interno en el Ldap vector. Gestiono su rol");
UtilRoles.setRoleIfNotHave(usuarioLogin, roles, Constantes.INTERNOS);
sesion.setAttribute(WebKeys.LAST_PATH, UtilUrls.generaLasthPath(request, Constantes.INTERNOS));
} else {
Constantes._log.info("El usuario es externo en el Ldap vector. Gestiono su rol");
UtilRoles.setRoleIfNotHave(usuarioLogin, roles, Constantes.EXTERNOS);
sesion.setAttribute(WebKeys.LAST_PATH, UtilUrls.generaLasthPath(request, Constantes.EXTERNOS));
}
}
}
This method:
sesion.setAttribute(WebKeys.LAST_PATH, UtilUrls.generaLasthPath(request, Constantes.EXTERNOS));
do it:
return new LastPath(StringPool.BLANK,Constantes.GROUPINTRANET+Constantes.SEPARADOR+Constantes.INICIOINTERNOS,
new HashMap<String, String[]>());
Generates group/intranet/pageforexterns, and same for interns but when I login I have a cookies error and a redirect error.
What am I doing wrong?
Thanks
Instead creating new instance of LastPath, you just get LastPath object by LastPath lastPath=(LastPath)session.getAttribute(WebKeys.LAST_PATH); and use lastPath.setPath(PATH) to avoid any errors.

SPListTemplate not found via Event Receiver in SharePoint 2007

I have a custom site template which activates a feature with an event receiver, the only thing that receiver does is to activate some other features, all in the same receiver.
The first feature I activate is a ListTemplate called "Audits".
In the third feature I activate, I try to use that template via the object model, however it isn't found, so it throws an exception.
I tried to update the site with a web.Update() but that didn´t work either.
The code doesn´t work when its activated via the site template, that means, if I activate my feature from an already created site, it works fine.
Is there a way to access the ListTemplate when the site is created¿?
Thanks in advance
EDIT: This is the main feature
/// <summary>
/// Evento disparado al activar la feature
/// </summary>
/// <param name="properties"></param>
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
//Obteniendo el sitio (web) en donde fue activada la feature
SPWeb web = (SPWeb)properties.Feature.Parent;
//Guid a utilizar para instalar las features
Guid g;
//GUID de Feature de list template de auditorías
g = new Guid("{3b91e461-e8c9-49dd-857a-671eb031017c}");
if (web.Features[g] == null)
web.Features.Add(g);
//GUID de Feature Catalogos
g = new Guid("{d102dd61-0aaf-4a18-8bcc-2260e78cc87c}");
if (web.Features[g] == null)
web.Features.Add(g);
//GUID de Feature Content type de auditorías
g = new Guid("{a5c3defb-bcbf-41e5-aefc-2617814d25d6}");
if (web.Features[g] == null)
web.Features.Add(g);
//GUID de Feature CheckList template
g = new Guid("{63fa11ba-e8e2-414d-bb7e-a3cdbce11cfe}");
if (web.Features[g] == null)
web.Features.Add(g);
//GUID de Feature asocia eventos
g = new Guid("{bbc32500-034d-4d9e-a048-558d62edfe53}");
if (web.Features[g] == null)
web.Features.Add(g);
//GUID de Feature para crear preguntas
g = new Guid("{ee66eb41-57a4-400a-9c50-8db0e6beeb80}");
if (web.Features[g] == null)
web.Features.Add(g);
//GUID de Feature para ECB
g = new Guid("{9bbdb06c-4ea1-4328-8b3d-828ea2043d3e}");
if (web.Features[g] == null)
web.Features.Add(g);
//GUID de Feature para hallazgos
g = new Guid("{acfdda27-58d5-4f7e-a6de-0a7fe190bc74}");
if (web.Features[g] == null)
web.Features.Add(g);
//GUID de Feature para resultados
g = new Guid("{a9a804dd-18a3-47a0-80bf-25e785a8cac8}");
if (web.Features[g] == null)
web.Features.Add(g);
}
The first feature is the list template.
The third feature has a receiver in which i look for the template
//Obteniendo el template
SPListTemplate ltAuditorias = sitio.ListTemplates["Auditoria"];
However, I get an Index out of range exception, because it's not found.
As I said, it only happens when the main feature is activated via the site template in the Feature tag.
If I create a Blank site and then activate the main feature, everything works.
Thanks
Your site is probably not fully provisioned at the time your feature receiver is fired. This means not all site elements (e.g. the list templates) are available.
As a workaround you could implement a provisioning provider.
The SPWebProvisioningProvider lets you take control of the SPWeb (Web site) or SPSite (Site Collection) that your are provisioning. Instead of just using a Site Template and the changes that can be applied through a Site Template you can add your own custom code to the solution.
from The mystery that is SPWebProvisioningProvider.

ksoap connection with web service, no android (using ksoap)

well i am doing a connection... sql server with web service, web service with j2me, but now i am doing one helloworld...i could it, but now than i want to do one "hello world "+nombre...
parameter is not receive in web service, here the web service
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// Para permitir que se llame a este servicio web desde un script, usando ASP.NET AJAX, quite la marca de comentario de la línea siguiente.
// [System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
public Service () {
}
[WebMethod]
public string HelloWorld(String nombre)
{
return "Que onda " + nombre;
}
}
and this is the code for call it with ksoap...
String nombremetodo="HelloWorld";
String url="http://localhost:49175/WebSite1/Service.asmx";
String namespace="http://tempuri.org/";
String SOAP_ACTION=namespace+nombremetodo;
public void traer()
{
SoapObject busqueda =new SoapObject(namespace,nombremetodo);
HttpTransport transportacion = new HttpTransport(url);
busqueda.addProperty(new String("nombre"),new String("Angel"));
System.out.println("parametro agregado");
//busqueda.addProperty(PropertyInfo.OBJECT_TYPE, "Angel");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
transportacion.debug=true;
envelope.bodyOut=busqueda;
System.out.println("todo ok");
try{
System.out.println("comenzando transportacion");
transportacion.call(SOAP_ACTION, envelope);
System.out.println("transportacion ok");
respuesta = envelope.getResponse().toString();
System.out.println("respuesta ok");
}
catch(Exception e)
{
texto.setString("fallo");
System.out.println("falla en el try");
System.out.println(e);
}
}
i get it returns "que onda " with a space, because so i put it in web service, but never it returns "que onda "+nombre ... it is a application for j2me not for
android, i watch for android it is soo...
PropertyInfo p1 = new PropertyInfo();
p1.setName("nombre");
p11.setValue("Angel");
busqueda.addProperty(p1);
but ksoap for j2me doesn't have those methods.. "setName, setValue";
i have downloades this library but i get a ugly bug and application doesn't run...
with this i see parameter is added so..
busqueda.addProperty("nombre","Angel");
but this it doesn't work...
it does run it doesn't have any bug, but web service never receive the parameter...
thank you people of STACKOVERFLOW
my english is not very well sorry
i solved it, it is necesary write
envelope.dotNet=true;

Resources