Results 1 to 4 of 4
  1. #1
    Ethanonline is offline Member
    Join Date
    Mar 2013
    Posts
    2
    Rep Power
    0

    Cool calling Threads?

    I am programing an android phone using java to send and receive messages over TCP from a server. I got that working great. Now I am trying to check received messages for certain strings and if a certain string is received, a thread is run. The thread sends commands to a IOIO board on a robot.
    The problem I am having is calling this thread. I have searched many sites and tried several ways to do this with no luck. I get either Cannot start ComponentInfo or NullPointerException. I have example programs that do different things with threads and they work, so I have essentially copied the thread parts of the code and inserted my own code... still doesn't work... My classes are below... Please help, I have been stuck at this point for a week!!!

    Main Activity:
    Java Code:
    package com.example.androidtcp;
    
    import java.util.ArrayList;
    
    import android.app.Activity;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ListView;
    //import ioio.lib.api.IOIOFactory;
     
    public class MyActivity extends Activity
    {
        private ListView mList;
        private ArrayList<String> arrayList;
        private MyCustomAdapter mAdapter;
        private TCPClient mTcpClient;
    	protected ioio.lib.api.IOIO ioio_;
    	int left_val = 1500;
    	int right_val= 1500;
    	//private PwmOutput left_, right_;
    	ioio_class nIOIO;
     
        @Override
        public void onCreate(Bundle savedInstanceState)
        {   	
        	//start ioio_class thread
        	Log.d("ioio_My", "start nIOIO");
            nIOIO.run();
        	Log.d("Returns", "returns from ioio_class");
        	
        	
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_my);
     
            arrayList = new ArrayList<String>();
     
            final EditText editText = (EditText) findViewById(R.id.editText);
            Button send = (Button)findViewById(R.id.send_button);
     
            //relate the listView from java to the one created in xml
            mList = (ListView)findViewById(R.id.list);
            mAdapter = new MyCustomAdapter(this, arrayList);
            mList.setAdapter(mAdapter);
     
            // connect to the server
            new connectTask().execute("");
     
            send.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
     
                    String message = editText.getText().toString();
     
                    //add the text in the arrayList
                    arrayList.add("c: " + message);
     
                    //sends the message to the server
                    if (mTcpClient != null) {
                        mTcpClient.sendMessage(message);
                    }
     
                    //refresh the list
                    mAdapter.notifyDataSetChanged();
                    editText.setText("");
                }
            });
     
        }
    	public class connectTask extends AsyncTask<String,String,TCPClient>  {
     
            @Override
            protected TCPClient doInBackground(String... message) {
            	 
                //create a TCPClient object and
                mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
                    @Override
                    //here the messageReceived method is implemented
                    public void messageReceived(String message) {
                        //this method calls the onProgressUpdate
                        publishProgress(message);
                        Log.d("Message received", message);
                        
                        if ("left".equals(message) && (left_val < 2000 && left_val > 1000) && (right_val < 2000 && right_val > 1000))
                    	{
                        	left_val = 1500;
                        	right_val = 1900;
                    	}
                    	if ("right".equals(message) && (left_val < 2000 && left_val > 1000) && (right_val < 2000 && right_val > 1000))
                    	{
                    		left_val = 1900;
                    		right_val = 1500;
                    	}
                    	if ("foward".equals(message) && (left_val < 2000 && left_val > 1000) && (right_val < 2000 && right_val > 1000))
                    	{
                    		left_val = 1600;
                    		right_val = 1600;
                    	}
                    	if ("backward".equals(message) && (left_val < 2000 && left_val > 1000) && (right_val < 2000 && right_val > 1000))
                    	{
                    		left_val = 1400;
                    		right_val = 1400;
                    	}
                	}
                });
               
                mTcpClient.run();
     
                return null;                
            }  	
            
            @Override
            protected void onProgressUpdate(String... values) {
                super.onProgressUpdate(values);
     
                //in the arrayList we add the messaged received from server
                arrayList.add(values[0]);
                // notify the adapter that the data set has changed. This means that new message received
                // from server was added to the list
                mAdapter.notifyDataSetChanged();
            }
        }	
    	
    	
        }
    TCPClient:
    Java Code:
    package com.example.androidtcp;
    
    import android.util.Log;
    import java.io.*;
    import java.net.InetAddress;
    import java.net.Socket;
     
     
    public class TCPClient {
     
        private String serverMessage;
        public static final String SERVERIP = "192.168.0.9"; //your computer IP address
        public static final int SERVERPORT = 4444;
        private OnMessageReceived mMessageListener = null;
        private boolean mRun = false;
        ioio_class nIOIO;
     
        PrintWriter out;
        BufferedReader in;
     
        /**
         *  Constructor of the class. OnMessagedReceived listens for the messages received from server
         */
        public TCPClient(OnMessageReceived listener) {
            mMessageListener = listener;
        }
     
        /**
         * Sends the message entered by client to the server
         * @param message text entered by client
         */
        public void sendMessage(String message){
            if (out != null && !out.checkError()) {
                out.println(message);
                out.flush();
            }
        }
     
        public void stopClient(){
            mRun = false;
        }
     
        public void run() {
     
            mRun = true;
     
            try {
                //here you must put your computer's IP address.
                InetAddress serverAddr = InetAddress.getByName(SERVERIP);
     
                Log.e("TCP Client", "C: Connecting...");
     
                //create a socket to make the connection with the server
                Socket socket = new Socket(serverAddr, SERVERPORT);
     
                try {
     
                    //send the message to the server
                    out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
     
                    Log.e("TCP Client", "C: Sent.");
     
                    Log.e("TCP Client", "C: Done.");
     
                    //receive the message which the server sends back
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     
                    //in this while the client listens for the messages sent by the server
                    while (mRun) {
                        serverMessage = in.readLine();
     
                        if (serverMessage != null && mMessageListener != null) {
                            //call the method messageReceived from MyActivity class
                            mMessageListener.messageReceived(serverMessage);
                            
                        }
             	
                        serverMessage = null;
     
                    }
     
     
                    Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
     
     
                } catch (Exception e) {
     
                    Log.e("TCP", "S: Error, Still!", e);
     
                } finally {
                    //the socket must be closed. It is not possible to reconnect to this socket
                    // after it is closed, which means a new socket instance has to be created.
                    socket.close();
                }
     
            } catch (Exception e) {
     
                Log.e("TCP", "C: Error", e);
     
            }
     
        }
     
        //Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
        //class at on asynckTask doInBackground
        public interface OnMessageReceived {
            public void messageReceived(String message);
        }
    }
    ioio_class (the thread, trust that the ioio coding in this class works... already tested):
    Java Code:
    package com.example.androidtcp;
    import ioio.lib.api.DigitalOutput;
    import ioio.lib.api.PwmOutput;
    import ioio.lib.api.exception.ConnectionLostException;
    import android.util.Log;
    
    
    public class ioio_class extends MyActivity implements Runnable {
    	private PwmOutput left_, right_;
    	protected ioio.lib.api.IOIO ioio_;
    	
    	public void setup() throws ConnectionLostException {
    		try {
    			right_= ioio_.openPwmOutput(5, 100);
    			left_=ioio_.openPwmOutput(7, 100);
    			/*
    			right_ = ioio_.openPwmOutput(new DigitalOutput.Spec(5, DigitalOutput.Spec.Mode.OPEN_DRAIN), 50);
    			left_ = ioio_.openPwmOutput(new DigitalOutput.Spec(7, DigitalOutput.Spec.Mode.OPEN_DRAIN), 50);
    			*/
    		} catch (ConnectionLostException e) {
    			Log.d("Caught", "ohshit");
    			//throw e;
    		}
    	}
    	
    	public void run()
        {    
    		try {
    			left_.setPulseWidth(left_val);		// pulse is between 1000 and 2000
    			right_.setPulseWidth(right_val);
    		} catch (ConnectionLostException e) {
    			Log.d("ioio", "Exception in try...");
    			e.printStackTrace();
    		}
    		
    		Log.d("ioio", "pulse: "+ left_val);
    		Log.d("ioio", "pulse: "+ right_val);
        }
    
    }
    To clarify, i am really only concerned with getting the thread to run successfully.
    The program receives messages fine when I take out the
    Java Code:
    //start ioio_class thread
        	Log.d("ioio_My", "start nIOIO");
            nIOIO.run();
        	Log.d("Returns", "returns from ioio_class");
    and I have tried placing it in many different areas with the same NullPointerException

    Thank you.

  2. #2
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: calling Threads?

    First of all, you don't start a thread by calling its run() method. That will just run the run() method in the current thread. You want to create a Thread with the Runnable as the argument, and then call the Thread's start() method.

    Edit: I just noticed that you posted the ioio_class code. I cannot think of any sensible reason why a class would extend Activity and implement Runnable. What are you trying to do here?

    BTW, ioio_class is a horrible name for a class. See the link in my sig.
    Last edited by kjkrum; 03-24-2013 at 11:56 PM.
    Get in the habit of using standard Java naming conventions!

  3. #3
    Ethanonline is offline Member
    Join Date
    Mar 2013
    Posts
    2
    Rep Power
    0

    Default Re: calling Threads?

    I extended MyActivity so ioio_class would have access to the variables from MyActivity, just seemed easier than using a get and set. I switched .run() with .start() and eclipse gives error saying to replace with a method from ioio_class... also i looked up .start() and it is just supposed to execute the run() method in a thread, so wouldn't it be the same thing?
    Last edited by Ethanonline; 03-25-2013 at 12:33 AM.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: calling Threads?

    Yes, it is the same thing, only one method, start(), actually calls run on a different thread (the whole purpose of threading) while calling run() directly doesn't. You will want to read a basic tutorial on threading before going much further.

Similar Threads

  1. Threads
    By dylan in forum New To Java
    Replies: 5
    Last Post: 01-07-2013, 10:25 AM
  2. Threads per Connection or Threads per Request
    By Felic in forum New To Java
    Replies: 4
    Last Post: 11-22-2011, 09:15 PM
  3. threads
    By brindha1688 in forum New To Java
    Replies: 3
    Last Post: 05-24-2011, 08:07 PM
  4. Threads
    By nsr2008.mca in forum New To Java
    Replies: 7
    Last Post: 10-18-2010, 11:47 AM
  5. Threads
    By one198 in forum Threads and Synchronization
    Replies: 1
    Last Post: 11-20-2007, 06:15 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •