Update UI Android - android

before writing this I looked at other post but have not found any solution, I would appreciate your help.
In the onCreate method of the class of the application launcher creates a thread TCPServer and display a table with information.
The problem is that this information varies and must be updated when the thread detects TCPServer have sent a new message control.
Then I show the code if I expressed myself well.
//launcher class
public class profesor extends Activity implements OnClickListener {
static TableLayout alumnsTable;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
.
.
.
Thread serverThread = new Thread(null, new TCPServer(), "BackgroundService");
serverThread.start();
.
.
.
//information is added to the table
alumnsTable = (TableLayout)findViewById(R.id.alumnsTable);
List<Alumnos> listaAlumnos = Alumnos.ReadList();
for(Alumnos al:listaAlumnos){
alumnsTable.addView(filaAlumno(al));
}
}
//Eliminates the above information and reloads the table with the new information
public void actualiza(){
alumnsTable.removeAllViews();
setContentView(R.layout.main);
alumnsTable = (TableLayout)findViewById(R.id.alumnsTable);
List<Alumnos> listaAlumnos = Alumnos.ReadList();
for(Alumnos al:listaAlumnos){
alumnsTable.addView(filaAlumno(al));
}
}
}
//TCPServer class
public class TCPServer implements Runnable {
private static Handler handler = new Handler();
public void run() {
ServerSocket serverSocket;
String file;
int filesizeMb = 4;
int filesize = filesizeMb * (1024 * 1024); // filesize temporary hardcoded
int bytesRead;
int current = 0;
try {
serverSocket = new ServerSocket(profesor.COMUNICATION_PORT);
Log.d(profesor.LOG_TAG,"S: Servidor Iniciado.");
while (true) {
final Socket sock = serverSocket.accept();
String ClientAddr=sock.getInetAddress().toString();
ClientAddr = ClientAddr.substring(ClientAddr.indexOf('/') + 1, ClientAddr.length());
final String contacto=DeviceList.getDeviceName(ClientAddr);
Log.d(profesor.LOG_TAG,"S: Conectado con: " + ClientAddr);
// Conection type
DataInputStream dis = new DataInputStream(sock.getInputStream());
final String connectionType =dis.readUTF();
Log.d(profesor.LOG_TAG,"S: Tipo de Conexion " + connectionType);
.
.
.
.
// RECEIVING CONTROL MESSAGE
if (connectionType.contains("CONTROL")) {
String ControlText =dis.readUTF();
String[] Control = ControlText.split(":");
Log.d(profesor.LOG_TAG,"S: Recibido nuevo progreso de prueba. IP: "+Alumnos.getIdAlumno(ClientAddr)+"->"+Integer.parseInt(Control[0])+" ->"+Integer.parseInt(Control[1]));
Alumnos.setProgress(Alumnos.getIdAlumno(ClientAddr), Integer.parseInt(Control[0]), Integer.parseInt(Control[1]));
/****************************************************/
//Here is where I need to call the update method of the
//class teacher to delete the old data and fill the table
//again.
/****************************************************/
}
dis.close();
sock.close();
}
} catch (IOException e) {
Log.d(profesor.LOG_TAG, "IOException"+e);
e.printStackTrace();
}
}
}
Can anyone give me some idea?, I have seen examples handlers but not in a class declaration and the call in another.
I hope that you understand what I mean, my English is not very good.
Thanks for the help

You can try to create the TCPServer with a Handler or Activity references and then use it when you want to update the UI:
refHandler.post(new Runnable(){
public void run() {
//Update
}
});
refActivity.runOnUiThread(new Runnable() {
public void run() {
//Update
}
});

use runOnUiThread for updating ui from Thread:
// RECEIVING CONTROL MESSAGE
if (connectionType.contains("CONTROL")) {
String ControlText =dis.readUTF();
String[] Control = ControlText.split(":");
Log.d(profesor.LOG_TAG,"S: Recibido nuevo progreso de prueba. IP: "+Alumnos.getIdAlumno(ClientAddr)+"->"+Integer.parseInt(Control[0])+" ->"+Integer.parseInt(Control[1]));
Alumnos.setProgress(Alumnos.getIdAlumno(ClientAddr), Integer.parseInt(Control[0]), Integer.parseInt(Control[1]));
/****************************************************/
//Here is where I need to call the update method of the
//class teacher to delete the old data and fill the table
//again.
/****************************************************/
profesor.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// refresh ui here
}
});
}

Related

AsyncTask in an android socket application

i am making an android socket app to communicate with the server for creating accounts, and i noticed i have to do this in AsyncTask sub class, even when i seperate it to another class without UI,but i am terribly confused how can i use AsyncTask on this, is there any one expert here who can help me please?
this is the code:
public class AccountCreator extends Activity {
public AccountCreator(){
super();
}
// for I/O
ObjectInputStream sInput; // to read from the socket
ObjectOutputStream sOutput; // to write on the socket
Socket socket;
public static String LOGTAG="Lifemate";
public String server = "localhost";
public String username = "user";
public String password = "rezapassword" ;
public int port = 1400;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(LOGTAG,"oncreate called");
this.start();
}
AccountCreator(String server, int port, String username,String password) {
this.server = "localhost";
this.port = 1400;
this.username = username;
Log.i(LOGTAG,"first accountcreator called");
}
public boolean start() {
// try to connect to the server
//this method returns a value of true or false when called
try {
socket = new Socket(server, port);
}
// if it failed not much I can so
catch(Exception ec) {
// display("Error connectiong to server:" + ec);
Log.i(LOGTAG,"Error connectiong to server:" + ec);
return false;
}
String msg = "Connection accepted " + socket.getInetAddress() + ":" +
socket.getPort();
// display(msg);
Log.i(LOGTAG, msg);
/* Creating both Data Stream */
try
{
sInput = new ObjectInputStream(socket.getInputStream());
sOutput = new ObjectOutputStream(socket.getOutputStream());
}
catch (IOException eIO) {
// display("Exception creating new Input/output Streams: " + eIO);
Log.i(LOGTAG,"Exception creating new Input/output Streams: " +
eIO);
return false;
}
// creates the Thread to listen from the server
// Send our username to the server this is the only message that we
// will send as a String. All other messages will be ChatMessage objects
try
{
sOutput.writeObject(username);
sOutput.writeObject(password);
}
catch (IOException eIO) {
// display("Exception doing login : " + eIO);
Log.i(LOGTAG,"Exception doing login : " + eIO);
disconnect();
return false;
}
// success we inform the caller that it worked
return true;
}
// private void display(String msg) {
// TextView screenprint = (TextView)findViewById(R.id.systemmessages);
// screenprint.setText(msg);
// }
private void disconnect() {
Log.i(LOGTAG,"reached disconnect");
try {
if(sInput != null) sInput.close();
}
catch(Exception e) {} // not much else I can do
try {
if(sOutput != null) sOutput.close();
}
catch(Exception e) {} // not much else I can do
try{
if(socket != null) socket.close();
}
catch(Exception e) {} // not much else I can do
}
public void Begin() {
Log.i(LOGTAG,"it begun");
int portNumber = 1400;
String serverAddress = server;
String userName = username;
String newpassword = password;
AccountCreator accountcreator = new AccountCreator(serverAddress, portNumber,
userName,password);
if(!accountcreator.start())
return;
}
}
i was trying to put whole code in Async, i dont know if was i right, do i need to do that also or just some parts of it?
In brief, AsyncTask contains a few methods which may be helpful:
onPreExecute:
This method is the first block of code executed when calling asyncTask.execute(); (runs on mainUIThread).
doInBackground:
Here you put all the code which may suspend you main UI (causes hang for your application) like internet requests, or any processing which may take a lot of memory and processing. (runs on background thread), contains one parameter taken from the asyncTask.execute(ParameterType parameter);
onPostExecute
Runs after doInBackground(). Its parameter is the return value of the doInBackground function, and mainly you put the changes in UI need to be done after the connection is finished (runs on mainUIThread)
You have to declare another class within the class you have already created.
class SomeName extends Async<Void, String, Void>{
protected void OnPreExecute(){
// starts the task runs on main UI thread
// Can be used to start a progress dialog to show the user progress
}
#Override
protected Void doInBackground(Void... params){
// does what you want it to do in the background
// Connected to the server to check a log-in
return result;
}
protected void OnPostExecute(Void result){
// finishes the task and can provide information back on the main UI thread
// this would be were you would dismiss the progress dialog
}
}

Using view elements inside thread

I'm trying to do a simple HTTP request in Android. It has to be in separate theread. But how can I operate on the view controls inside the thread?
Here's what I have now:
public void saveData(final View v)
{
Button btn = (Button) v.findViewById(R.id.button);
btn.setText("Saving...");
new Thread() {
public void run()
{
HttpURLConnection connection = null;
try {
URL myUrl = new URL("http://example.com");
connection = (HttpURLConnection)myUrl.openConnection();
InputStream inputStream = connection.getInputStream();
final String fResponse = IOUtils.toString(inputStream);
}
catch (MalformedURLException ex) {
Log.e("aaa", "Invalid URL", ex);
}
catch (IOException ex) {
Log.e("aaa", "IO Exception", ex);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
// How can I access v and btn here?
// btn.getText("Saved, thanks.");
// btn.setText("Saved, thanks.");
}
}.start();
}
To elaborate what I'm trying to achieve:
I have a text box and a button. Once the button is clicked, I want to get the text from text box, use in the URL, wich returns a value, then update the button text with this value.
Here's an example on how you could do it.
public class YourClass extends Activity {
private Button myButton;
//create an handler
private final Handler myHandler = new Handler();
final Runnable updateRunnable = new Runnable() {
public void run() {
//call the activity method that updates the UI
updateUI();
}
};
private void updateUI()
{
// ... update the UI
}
private void doSomeHardWork()
{
//update the UI using the handler and the runnable
myHandler.post(updateRunnable);
}
private OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
new Thread(new Runnable() {
doSomeHardWork();
}).start();
}
};
}
As you can see, you need to update the UI with yet another Runnable object. This is one way of doing it.
Another option is via the runOnUiThread function
runOnUiThread(new Runnable()
{
#Override
public void run() {
updateActivity();
}
});
If you try to access your Views directly from another thread like that, you will get an exception because all UI operations must be performed on the main thread.
One method that the Android SDK provides for performing background tasks that need to update the UI is the AsyncTask.
The onPostExecute() method of an AsyncTask is called after doInBackground() returns, and is run on the UI thread.
Your AsyncTask might look something like this:
public class MyBackgroundTask extends AsyncTask<URL, Void, String> {
protected String doInBackground(URL... urls) {
URL myUrl = new URL("http://example.com");
connection = (HttpURLConnection)myUrl.openConnection();
InputStream inputStream = connection.getInputStream();
return IOUtils.toString(inputStream);
}
protected void onPostExecute(String result) {
// Call back to your Activity with the result here
}
}

Android update TextView with Handler

I am having problems with updating the TextView, I used the Handler method to pass the message to the UI. My application receives data(type integers) true io stream and shows in TextView.
My Activity class looks like this:
public class DeviceView extends Activity {
TextView dataX;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.device_view);
dataX = (TextView) findViewById(R.id.datax);
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
dataX.setText(String.valueOf(msg.arg1));
}
};
}
}
I also have a separate class it extends Thread:
public class IOThread extends Thread {
public void run() {
byte[] buffer = new byte[1024];
int data;
while (true) {
try {
data = in.read(buffer);
Message message= Message.obtain();
message.arg1= data;
DeviceView.handler.sendMessage(message);
} catch (IOException ex) {
break;
}
}
}
}
Do I have to make a separate variable type String and point it to variable data and at last calling the count? Would that be enough to update TextView?
Can you try using an interface. Let the Activity implement it, pass it to the IOThread class. Once you get the result, pass the result to the Activity.
Interface named InterfaceData
public void getData(int data);
public class DeviceView extends Activity implements InterfaceData{
TextView dataX;
Handler handler;
IOThread ioThread;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.device_view);
handler = new Handler();
ioThread = new IOThread(this);
dataX = (TextView) findViewById(R.id.datax);
}
#Override
public void getData(int data){
handler.postDelayed(new Runnable(){
public void run(){
dataX.setText(data);
};
},100);
}
}
> Thread class
public class IOThread extends Thread {
InterfaceData interfaceData;
public IOThread(InterfaceData interfaceData){
this.interfaceData = interfaceData;
}
public void run() {
byte[] buffer = new byte[1024];
int data;
while (true) {
try {
data = in.read(buffer);
interfaceData.getData(data);
} catch (IOException ex) {
break;
}
}
}
}
I have found my problem it was not the Handler issue. THe code i posted at the beginning is coorect. The problem lyis on the way i read the received bytes[] array from the InputStream. I have tested by sending an integer int numbers = (int) 2 and when print this receivd data in terminal in Android app, it receivs only 1, even if i send int 3 or 4, i stil receive 1.
So i preceiated your example code #dcanh121 , but my question is actualy how do i read properly the integers that the server sends?
public void run() {
byte[] buffer = new byte[1024];
int data;
while (true) {
try {
data = in.read(buffer);
Log.d(TAG + data, "test");
Message message = Message.obtain();
message.arg1 = data;
Log.d(TAG + message.arg1, "test");
DeviceView.handler.sendMessageDelayed(message, 100);
} catch (IOException ex) {
Log.e(TAG_IOThread, "disconnected", ex);
break;
}
}
}

Issue about using Async with an Android Client

I am currently creating a project that needs to have a simple async task to take care of a thread running behind the scenes. The user needs to login. I am using another class called PVAndroid Client that supplies useful methods and has an XML serializer form packets for me. I am completely new to working with threads or doing anything with servers, so this may be completely wrong or somewhat right.
I get the data the user entered: the ip address and port, their username (I split this into first and last name), their region they selected. I encrypt their password, and attempt to connect to the tcp using ip address and port number. I am trying to work in the async task but am kind of confused on what I should do. Can anyone guide me in the right direction and help me out?
Thank you I really appreciate it.
private TcpClient myTcpClient = null;
private UdpClient udpClient;
private static final String USERNAME_SHARED_PREFS = "username";
private static final String PASSWORD_SHARED_PREFS = "password";
private static final String IP_ADDRESS_SHARED_PREFS = "ipAddressPref";
private static final String PORT_SHARED_PREFS = "portNumberPref";
private String encryptedNameLoginActivity, encryptPassLoginActivity;
private EditText userText, passText;
private String getIpAddressSharedPrefs, getPortNumberPrefs;
private String getUserNameValue;
private String getPasswordValue;
private String fName, lName;
private SharedPreferences settings;
private Editor myEditor;
private boolean getCheckedRemember;
private boolean resultCheck = false;
private int portNum;
private Button submitButton;
private String userMACVARIABLE = "";
private String regionSelected, gridSelected;
private Spinner regSpinner, gridSpinner;
PVDCAndroidClient client;
private int userNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
client = new PVDCAndroidClient();
}
#Override
protected void onStart() {
super.onStart();
// Take care of getting user's login information:
submitButton = (Button) findViewById(R.id.submitButton);
userText = (EditText) findViewById(R.id.nameTextBox);
passText = (EditText) findViewById(R.id.passwordTextBox);
regSpinner = (Spinner) findViewById(R.id.regionSpinner);
// grid selected as well? sometime?
regSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v,
int position, long rowId) {
regionSelected = regSpinner.getItemAtPosition(position)
.toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
submitButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
settings = PreferenceManager
.getDefaultSharedPreferences(AndroidClientCompnt.this);
getIpAddressSharedPrefs = settings.getString(
IP_ADDRESS_SHARED_PREFS, "");
portNum = Integer.parseInt(settings.getString(
PORT_SHARED_PREFS, ""));
if (getIpAddressSharedPrefs.length() != 0 && portNum != 0) {
if (userText.length() != 0 && passText.length() != 0) {
try {
try {
// encrypting the user's password.
encryptPassLoginActivity = Secure.encrypt(passText
.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// first connect attempt.
myTcpClient = new TcpClient();
myTcpClient.connect(getIpAddressSharedPrefs,
portNum);
// here is where I want to call Async to do login
// or do whatever else.
UploadTask task = new UploadTask();
task.execute();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Could not connect.", Toast.LENGTH_LONG)
.show();
e.printStackTrace();
}
}
}
}
});
}
private class UploadTask extends AsyncTask<String, Integer, Void>
{
#Override
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "Loading...",
Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(String... names) {
resultCheck = myTcpClient.connect(getIpAddressSharedPrefs,
portNum);
if (resultCheck == true) {
while (myTcpClient.getUserNum() < 0) {
// num set? session? with proxy server?
}
String[] firstAndLast;
String spcDelmt = " ";
firstAndLast = userText.toString().split(spcDelmt);
fName = firstAndLast[0];
lName = firstAndLast[1];
// set up the tcp client to sent the information to the
// server.
client.login(fName, lName, encryptPassLoginActivity,regionSelected, 128, 128, 20);
} else {
Toast.makeText(getApplicationContext(),
"Connection not successful", Toast.LENGTH_LONG)
.show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Toast.makeText(getApplicationContext(), "Connected",
Toast.LENGTH_LONG).show();
}
}
}
First
#Override
protected Void doInBackground(String...params) {
new Thread (new Runnable() {
// ...
}
}
Never do this again. There is no need to create new Thread in doInBackground method which actually running on background Thread. So remove it.
The advice to you is tricky because you need to read about Threads, work with Connection etc. So the best advice to you is to read some tutorials, examples of basic applications and read references. So you can start here:
Android TCP Client and Server Communication Programming–Illustrated with Example
I cannot see, where you are yoursing your Task, but I see that you are doing something weired inside doInBackground()! There is absolutely NO reason, to create your own Thread inside it.
remove that, and you could just use your Task like this:
UploadTask task = new UploadTask();
task.execute("someString", "anotherString", "addAsManyStringsYouNeed");
The docs from AsyncTask are very helpfull, too.

Handler will not bind to main thread

So my code seems to run just fine until it hits this line
adapter.notifyDataSetChanged();
The error that pops up in the logcat is CalledFromWrongThreadException. The debug also shows the handler being run in the Background thread. How do I get the handler to bind to the main thread, and not the background one? I thought I just had to create the handler in the main thread, but I guess I am wrong, quite possible I am new to andriod. How do I fix this?
//Imports are included
public class DirectoryActivity extends ListActivity {
private ProgressDialog ProgressDialog = null;
private ArrayList<DirectoryListing> listing = null;
private DirectoryAdapter adapter;
private Runnable viewOrders;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.directory);
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (listing != null && listing.size() > 0) {
adapter.notifyDataSetChanged();
for (int i = 0; i < listing.size(); i++)
adapter.add(listing.get(i));
Log.e("log_tag", "\nStill running\n");
}
ProgressDialog.dismiss();
adapter.notifyDataSetChanged();
}
};
listing = new ArrayList<DirectoryListing>();
adapter = new DirectoryAdapter(this, R.layout.rows, listing);
setListAdapter(adapter);
ProgressDialog = ProgressDialog.show(DirectoryActivity.this, "Please wait...", "Retrieving data ...", true);
viewOrders = new Runnable() {
#Override
public void run() {
listing = PreparePage.getArrayList();
handler.handleMessage(null);
}
};
Thread thread = new Thread(null, viewOrders, "Background");
thread.start();
}
private static class PreparePage {
protected static ArrayList<DirectoryListing> getArrayList() {
ArrayList<DirectoryListing> listings = new ArrayList<DirectoryListing>();
JSONObject information = GetPageData.getJSONFromURL(url);
Iterator key = information.keys();
while (key.hasNext()) {
String id = (String) key.next();
JSONObject info = null;
try {
info = information.getJSONObject(id);
} catch (JSONException e) {
e.printStackTrace();
}
String name = "", title = "", photo = "";
try {
name = info.get("firstName") + " " + info.get("lastName");
title = info.getJSONObject("position").getString("name");
photo = info.optString("photoPath", "none");
} catch (JSONException e) {
e.printStackTrace();
}
listings.add(new DirectoryListing(name, title, photo));
}
return listings;
}
}
}
Try calling handler.sendEmptyMessage(0); instead of handler.handleMessage(null);
I don't know why this would cause the errors you are seeing, but this is how I have it set up when I use handler and thread instead of AsyncTask. And I have have never seen that error doing it this way.
#Nguyen is right though AsyncTask is the preferred way to handle these types of things now. And it actually makes it much easier to do.
AsyncTask docs
AsyncTask Example
In my experience, you should create your own class that extends AsyncTask class to do something at background. This is a simpler and more effectively than using thread + handler.

Categories

Resources