N
N
Nikita2014-05-27 08:42:28
Java
Nikita, 2014-05-27 08:42:28

How to assemble the class correctly and how to run its function from the button via OnClickListener?

I am writing in eclipce. The purpose of the application is to send certain commands over udp when a button is clicked.
Having dealt with buttons, text input and output fields, I ran into the problem of binding the packing and sending function itself to the button.
In the main application file I have the following class tree:

public class MainActivity extends Activity 
{
     public class Sender      //класс отправки
       {
            public void sendMessage(String mes)
               {
                //код создания и упаковки датаграммы который и нужно запустить
                }
            public void main(String[] text)
               {
                //код создания отправителя
               }
        }

     public void onCreate(Bundle savedInstanceState) //метод описывающий такие элементы как кнопка, поле ввода и вывода
        {
          OnClickListener oclBtnUdp = new OnClickListener() //слушатель нажатия кнопки
              {
                public void onClick(View v) 
                  {
                   //код который выполнится при нажатии кнопки. 
                   //Именно здесь нужно указать что запустить. (Сама проблема)
                   }
               }

        }
}

I am studying the Java language myself recently and managed to learn only some basic concepts, so I still did not fully understand what needs to be put in so that it sends a command via udp. I humbly ask for help and, if possible, explain what I'm doing wrong. I enclose the full code of the MainActivity.java file:
public void onClick(View v)
spoiler
package com.exampletestudp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class MainActivity extends Activity {
 public String asd;
 public EditText editText12;
 public TextView tvOut;
 public Button btnOk;
 public Button btnCancel;
 public Button btnUdp;
 public Button btnAdd;
 public Button myMenu;
   
 byte[] text = null;
 
 
//сам класс отправки	   
 public class Sender {
    
    public String host; 

    public int port; 

    Sender(String host, int port){ 

    this.host = host; 

    this.port = port; 
    }
    public String mes = "comanda";
    
    public void sendMessage(String mes){ 
   	mes = "comanda";
     		   	
    try{

    byte[] data = mes.getBytes();
    port = 50000;
    host = asd ; //"10.0.1.5"
    InetAddress addr = InetAddress.getByName(host);
    asd = null;
    text = mes.getBytes();
     DatagramPacket pack =

    new DatagramPacket( data, data.length, addr, port); 

    DatagramSocket ds = new DatagramSocket(port); 

    ds.send(pack); 

    ds.close();

    }catch(IOException e){

    System.err.println(e); 

    } 

    } 

    
    public void main(String[] text){
           	
    Sender sndr = new Sender(asd, 50000); 
    
    for (int k = 0; k < text.length; k++)
    
    sndr.sendMessage(text[k]); 
    }
}
 
  
   
     @Override
     public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.fragment_main);
   
       // найдем View-элементы
       editText12 = (EditText) findViewById(R.id.editText1) ;
       tvOut = (TextView) findViewById(R.id.tvOut);
       btnAdd = (Button) findViewById(R.id.btnAdd);
       btnOk = (Button) findViewById(R.id.btnOk);
       btnCancel = (Button) findViewById(R.id.btnCancel);
       btnUdp = (Button) findViewById(R.id.btnUdp);
       myMenu = (Button) findViewById(R.id.myMenu);
         
       // создаем кнопку отправки сообщения
       OnClickListener oclBtnUdp = new OnClickListener() {
           @Override
            public void onClick(View v) {
          // сюда нужно подставить ссылку на функцию отправки
             tvOut.setText("отправлено на "+ asd  );
             
           }
         }; 
       // создаем кнопку приема и сохранения из поля ввода IP назначения 
       OnClickListener oclBtnAdd = new OnClickListener() {
           @Override
           public void onClick(View v) {
             // Меняем текст в TextView (tvOut)
        	    asd = editText12.getText().toString();
        	    
        	    tvOut.setText(asd+" сохранен");
           }
         };
       
       
       OnClickListener oclBtnOk = new OnClickListener() {
         @Override
         public void onClick(View v) {
           // Меняем текст в TextView (tvOut)
           tvOut.setText("Нажата кнопка ОК");
         }
       };
       
       OnClickListener oclBtnCancel = new OnClickListener() {
           @Override
           public void onClick(View v) {
             // Меняем текст в TextView (tvOut)
             tvOut.setText("Нажата кнопка Cancel");
           }
         };
      
         
        
       // присвоим обработчик кнопкам
     btnAdd.setOnClickListener(oclBtnAdd);     
       btnOk.setOnClickListener(oclBtnOk);
       btnCancel.setOnClickListener(oclBtnCancel);
       btnUdp.setOnClickListener(oclBtnUdp);
     }
     
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita, 2014-05-28
@sparks327

rummaged through the entire send code completely and found the problem
now for the place

public class Sender {
    
    public String host; 

    public int port; 

    Sender(String host, int port){ 

    this.host = host; 

    this.port = port; 
    }
    public String mes = "comanda";
    
    public void sendMessage(String mes){ 
   	mes = "comanda";
     		   	
    try{

    byte[] data = mes.getBytes();
    port = 50000;
    host = asd ; //"10.0.1.5"
    InetAddress addr = InetAddress.getByName(host);
    asd = null;
    text = mes.getBytes();
     DatagramPacket pack =

    new DatagramPacket( data, data.length, addr, port); 

    DatagramSocket ds = new DatagramSocket(port); 

    ds.send(pack); 

    ds.close();

    }catch(IOException e){

    System.err.println(e); 

    } 

    } 

    
    public void main(String[] text){
           	
    Sender sndr = new Sender(asd, 50000); 
    
    for (int k = 0; k < text.length; k++)
    
    sndr.sendMessage(text[k]); 
    }
}

set this code
void SendMessage()
  {
    
    String host;
    int port;
     
   	String mes = "commanda";
     		   	
    try{
    
    byte[] data = mes.getBytes();
    port = 50000;
    host = asd ; 
    
    InetAddress addr = InetAddress.getByName(host);
    
     DatagramPacket pack =

    new DatagramPacket( data, data.length, addr, port); 

    DatagramSocket ds = new DatagramSocket(port); 

    ds.send(pack); 

    ds.close();

    }catch(IOException e){

    System.err.println(e); 

    } 
    
    
    
    
  }

and is called by a simple SendMessage(); .

S
svd71, 2014-05-27
@svd71

public void onCreate(Bundle savedInstanceState) //метод описывающий такие элементы как кнопка, поле ввода и вывода
        {
          OnClickListener oclBtnUdp = new OnClickListener() //слушатель нажатия кнопки
              {
                public void onClick(View v) 
                  {
                   Sender senderInstance = new Sender();
                   senderInstance.sendMessage("my message");
                   }
               }

        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question