Sochet Receive Event?

Status
Niet open voor verdere reacties.

murdoch201

Gebruiker
Lid geworden
31 mei 2008
Berichten
336
Hoi,

Ik ben een app aan het schrijven om via de java.socket te communiceren (Android). Het versturen van een bericht gaat perfect, maar als ik wil ontvangen, hoe voeg je dit 'event' dan toe? (Zoals void OnReceive(){...})

Alvast bedankt!
 
Code:
    Button button1 = (Button) findViewById(R.id.button1);
    Button button2 = (Button) findViewById(R.id.button2);
    Button button3 = (Button) findViewById(R.id.button3);
    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        	TextView t = (TextView)findViewById(R.id.textView1);
        	
        	try {
        		s = new Socket("192.168.1.4",4444);
        		mRun = true;
        		} catch (UnknownHostException e) {
        	        e.printStackTrace();
        	        t.setText(t.getText() + "\n" + "unknownhost");
        	} catch (IOException e) {
        	        e.printStackTrace();
        	        
        	        t.setText(t.getText() + "\n" + e.toString());
        	}
             
        	
        }
    });
    
    
    button2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
        	 //bericht sturen
            
			try {
				OutputStream out = s.getOutputStream();       
				PrintWriter output = new PrintWriter(out);             
				output.println("Hello from Android");     
				output.flush();
				output.close();

	            
	            
			} catch (IOException e) {
				e.printStackTrace();
			}
            
        }});

Nu zou ik iets moetten hebben zoals dit bijvoorbeeld:

Code:
public void onReceive(string message) {
//iets doen met message
}
 
Neem hier een kijkje: http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html

Sockets werken (bij mijn weten) op dezelfde manier in Android.

Code:
//We creëren een reader die luistert naar de connectie (een inputstream).
BufferedReader in = new BufferedReader(new InputStreamReader(mijnSocket.getInputStream()));

//nu luisteren we net zo lang totdat we niks meer ontvangen (connectie is gesloten):

StringBuilder ontvangenData = new StringBuilder();
String ontvangenBericht = null;
while((ontvangenBericht = in.readLine()) != null) {   //de in.readLine levert een string op, deze string wordt geassigned aan de variabele ontvangenBericht daarna wordt gekeken of deze variabele de waarde null bevat.
   //we hebben data ontvangen van de server.
   ontvangenData.append(ontvangenBericht);
}
 
Ik heb nu dit:

Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy); 


//We creëren een reader die luistert naar de connectie (een inputstream).
        BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(s.getInputStream()));
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

        //nu luisteren we net zo lang totdat we niks meer ontvangen (connectie is gesloten):

        StringBuilder ontvangenData = new StringBuilder();
        String ontvangenBericht = null;
        try {
			while((ontvangenBericht = in.readLine()) != null) {   //de in.readLine levert een string op, deze string wordt geassigned aan de variabele ontvangenBericht daarna wordt gekeken of deze variabele de waarde null bevat.
			   //we hebben data ontvangen van de server.
			   ontvangenData.append(ontvangenBericht);
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}


}

De app crasht vervolgens in de emulator ("AW Mobile has stopped working") bij het opstarten

Log:
Code:
10-27 15:01:45.691: E/AndroidRuntime(777): FATAL EXCEPTION: main
10-27 15:01:45.691: E/AndroidRuntime(777): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.awmobile/com.example.awmobile.MainActivity}: java.lang.NullPointerException
10-27 15:01:45.691: E/AndroidRuntime(777): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-27 15:01:45.691: E/AndroidRuntime(777): 	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-27 15:01:45.691: E/AndroidRuntime(777): 	at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-27 15:01:45.691: E/AndroidRuntime(777): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-27 15:01:45.691: E/AndroidRuntime(777): 	at android.os.Handler.dispatchMessage(Handler.java:99)
10-27 15:01:45.691: E/AndroidRuntime(777): 	at android.os.Looper.loop(Looper.java:137)
10-27 15:01:45.691: E/AndroidRuntime(777): 	at android.app.ActivityThread.main(ActivityThread.java:5103)
10-27 15:01:45.691: E/AndroidRuntime(777): 	at java.lang.reflect.Method.invokeNative(Native Method)
10-27 15:01:45.691: E/AndroidRuntime(777): 	at java.lang.reflect.Method.invoke(Method.java:525)
10-27 15:01:45.691: E/AndroidRuntime(777): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-27 15:01:45.691: E/AndroidRuntime(777): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-27 15:01:45.691: E/AndroidRuntime(777): 	at dalvik.system.NativeStart.main(Native Method)
10-27 15:01:45.691: E/AndroidRuntime(777): Caused by: java.lang.NullPointerException
10-27 15:01:45.691: E/AndroidRuntime(777): 	at com.example.awmobile.MainActivity.onCreate(MainActivity.java:55)
10-27 15:01:45.691: E/AndroidRuntime(777): 	at android.app.Activity.performCreate(Activity.java:5133)
10-27 15:01:45.691: E/AndroidRuntime(777): 	at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-27 15:01:45.691: E/AndroidRuntime(777): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-27 15:01:45.691: E/AndroidRuntime(777): 	... 11 more
10-27 15:02:45.521: D/AndroidRuntime(822): Shutting down VM
10-27 15:02:45.521: W/dalvikvm(822): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
10-27 15:02:45.531: E/AndroidRuntime(822): FATAL EXCEPTION: main
10-27 15:02:45.531: E/AndroidRuntime(822): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.awmobile/com.example.awmobile.MainActivity}: java.lang.NullPointerException
10-27 15:02:45.531: E/AndroidRuntime(822): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-27 15:02:45.531: E/AndroidRuntime(822): 	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-27 15:02:45.531: E/AndroidRuntime(822): 	at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-27 15:02:45.531: E/AndroidRuntime(822): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-27 15:02:45.531: E/AndroidRuntime(822): 	at android.os.Handler.dispatchMessage(Handler.java:99)
10-27 15:02:45.531: E/AndroidRuntime(822): 	at android.os.Looper.loop(Looper.java:137)
10-27 15:02:45.531: E/AndroidRuntime(822): 	at android.app.ActivityThread.main(ActivityThread.java:5103)
10-27 15:02:45.531: E/AndroidRuntime(822): 	at java.lang.reflect.Method.invokeNative(Native Method)
10-27 15:02:45.531: E/AndroidRuntime(822): 	at java.lang.reflect.Method.invoke(Method.java:525)
10-27 15:02:45.531: E/AndroidRuntime(822): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-27 15:02:45.531: E/AndroidRuntime(822): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-27 15:02:45.531: E/AndroidRuntime(822): 	at dalvik.system.NativeStart.main(Native Method)
10-27 15:02:45.531: E/AndroidRuntime(822): Caused by: java.lang.NullPointerException
10-27 15:02:45.531: E/AndroidRuntime(822): 	at com.example.awmobile.MainActivity.onCreate(MainActivity.java:55)
10-27 15:02:45.531: E/AndroidRuntime(822): 	at android.app.Activity.performCreate(Activity.java:5133)
10-27 15:02:45.531: E/AndroidRuntime(822): 	at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-27 15:02:45.531: E/AndroidRuntime(822): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-27 15:02:45.531: E/AndroidRuntime(822): 	... 11 more


Wat nu? :eek:
 
Je krijgt een nullpointer op regel 55 in de activity.

Code:
Caused by: java.lang.NullPointerException
10-27 15:02:45.531: E/AndroidRuntime(822): 	at com.example.awmobile.MainActivity.onCreate(MainActivity.java:55)
10-27 15:02:45.531: E/AndroidRuntime(822): 	at android.app.Activity.performCreate(Activity.java:5133)
10-27 15:02:45.531: E/AndroidRuntime(822): 	at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-27 15:02:45.531: E/AndroidRuntime(822): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)

Dit betekent dat een variabele / object null is.
 
Ik heb nu dit (het constant instellen van 'null' weggehaald, alles onder 1 try, en ontvangenBericht word pas terug aangepast naar null nadat hij heeft ontvangen):

Code:
//We creëren een reader die luistert naar de connectie (een inputstream).
        BufferedReader in;
        String ontvangenBericht;
        
		
			try {
				in = new BufferedReader(new InputStreamReader(s.getInputStream()));
				 //nu luisteren we net zo lang totdat we niks meer ontvangen (connectie is gesloten):
				StringBuilder ontvangenData = new StringBuilder();
		        while((ontvangenBericht = in.readLine()) != null) {   //de in.readLine levert een string op, deze string wordt geassigned aan de variabele ontvangenBericht daarna wordt gekeken of deze variabele de waarde null bevat.
					   //we hebben data ontvangen van de server.
					  textView1.setText(ontvangenBericht);
					   ontvangenBericht = null;

					}
		        
			} catch (IOException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}

En hij crasht nog altijd...
Code:
10-28 19:23:12.148: E/AndroidRuntime(833): FATAL EXCEPTION: main
10-28 19:23:12.148: E/AndroidRuntime(833): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.awmobile/com.example.awmobile.MainActivity}: java.lang.NullPointerException
10-28 19:23:12.148: E/AndroidRuntime(833): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-28 19:23:12.148: E/AndroidRuntime(833): 	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-28 19:23:12.148: E/AndroidRuntime(833): 	at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-28 19:23:12.148: E/AndroidRuntime(833): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-28 19:23:12.148: E/AndroidRuntime(833): 	at android.os.Handler.dispatchMessage(Handler.java:99)
10-28 19:23:12.148: E/AndroidRuntime(833): 	at android.os.Looper.loop(Looper.java:137)
10-28 19:23:12.148: E/AndroidRuntime(833): 	at android.app.ActivityThread.main(ActivityThread.java:5103)
10-28 19:23:12.148: E/AndroidRuntime(833): 	at java.lang.reflect.Method.invokeNative(Native Method)
10-28 19:23:12.148: E/AndroidRuntime(833): 	at java.lang.reflect.Method.invoke(Method.java:525)
10-28 19:23:12.148: E/AndroidRuntime(833): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-28 19:23:12.148: E/AndroidRuntime(833): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-28 19:23:12.148: E/AndroidRuntime(833): 	at dalvik.system.NativeStart.main(Native Method)
10-28 19:23:12.148: E/AndroidRuntime(833): Caused by: java.lang.NullPointerException
10-28 19:23:12.148: E/AndroidRuntime(833): 	at com.example.awmobile.MainActivity.onCreate(MainActivity.java:58)
10-28 19:23:12.148: E/AndroidRuntime(833): 	at android.app.Activity.performCreate(Activity.java:5133)
10-28 19:23:12.148: E/AndroidRuntime(833): 	at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-28 19:23:12.148: E/AndroidRuntime(833): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-28 19:23:12.148: E/AndroidRuntime(833): 	... 11 more
 
Als je naar de error kijkt zie je dat je op regel 58 een nullpointer krijgt. Ik weet niet welke regel, regel 58 is, omdat je niet de gehele klasse hebt geplaatst. Misschien is de s variabele wel null? Ik denk echter dat je textview variabele niet geïnitialiseerd is. Hoe wordt het object: textView1 gemaakt? Loop eens door het programma met de debugger en bekijk de variabelen op regel 58.
 
Laatst bewerkt:
Bovenaan wordt Textview al geregeld:
Code:
final TextView textView1 = (TextView)findViewById(R.id.textView1);

Regel 58 is deze regel:
Code:
in = new BufferedReader(new InputStreamReader(s.getInputStream()));

Ik veronderstel dat dit dus wordt veroorzaakt omdat s.getinputstream leeg is, laat staan dat er al verbinding is gemaakt.. Hoe zorg ik ervoor dan dat ie controleert of s.getinputstream niet leeg is?

Dit gaat niet, want hij vereist weeral try/catch/... :confused: :
Code:
if(s.getInputStream() == null)
 
Kan je AUB even al je code posten op gist.github.com / pastebin.com?
 
Je s variabele is null (Socket). Je onCreate methode wordt als eerste aangeroepen (bekijk de activity life-cycle eens). Pas als jij op een knop klikt wordt je Socket geinitialiseerd (in de click listener). Initialiseer dus je Socket object voordat je er de output / inputstream van opvraagt.

Code:
  public void onClick(View v) {
                TextView t = (TextView)findViewById(R.id.textView1);
               
                try {
                        s = new Socket("192.168.1.4",4444);
< De socket wordt pas geinitialiseerd als de onClick methode wordt aangeroepen. Dit gebeurd pas als er op button1 wordt geklikt.

Code:
in = new BufferedReader(new InputStreamReader(s.getInputStream()));

< Je initialiseerd de 'in' variabele met een nieuwe buffered reader die een nieuwe inputstreamreader bevat, maar je vraagt ook de inputstream op van de variabele 's' (jouw socket). Deze bestaat nog niet (is null), omdat de klik nog niet is gedaan. De onCreate wordt namelijk automatisch door het android systeem aangeroepen als de activity wordt aangemaakt http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle


Groet,
newbi
 
Laatst bewerkt:
Welke error krijg je? Post je complete error (stack trace). Post ook je code met behulp van code-tags hier op het forum ipv externe sites alstublieft. [ code ] [ /code ]
 
Sorry, heb het gevonden, het de permissies moeten eerst 'aangevraagd' worden voor het gebruik van sockets & internet. Hij start op, hij verbind, maar dan blijft de app wit op de titelbalk na, en krijg ik de melding "AW Mobile isnt responding, do you want to close it?"

log:
Code:
11-09 22:57:20.695: E/SoundPool(287): error loading /system/media/audio/ui/Effect_Tick.ogg
11-09 22:57:20.695: W/AudioService(287): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
11-09 22:57:20.695: E/SoundPool(287): error loading /system/media/audio/ui/Effect_Tick.ogg
11-09 22:57:20.695: W/AudioService(287): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
11-09 22:57:20.705: E/SoundPool(287): error loading /system/media/audio/ui/Effect_Tick.ogg
11-09 22:57:20.705: W/AudioService(287): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
11-09 22:57:20.705: E/SoundPool(287): error loading /system/media/audio/ui/Effect_Tick.ogg
11-09 22:57:20.705: W/AudioService(287): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
11-09 22:57:20.715: E/SoundPool(287): error loading /system/media/audio/ui/Effect_Tick.ogg
11-09 22:57:20.715: W/AudioService(287): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
11-09 22:57:20.715: E/SoundPool(287): error loading /system/media/audio/ui/KeypressStandard.ogg
11-09 22:57:20.715: W/AudioService(287): Soundpool could not load file: /system/media/audio/ui/KeypressStandard.ogg
11-09 22:57:20.715: E/SoundPool(287): error loading /system/media/audio/ui/KeypressSpacebar.ogg
11-09 22:57:20.725: W/AudioService(287): Soundpool could not load file: /system/media/audio/ui/KeypressSpacebar.ogg
11-09 22:57:20.725: E/SoundPool(287): error loading /system/media/audio/ui/KeypressDelete.ogg
11-09 22:57:20.725: W/AudioService(287): Soundpool could not load file: /system/media/audio/ui/KeypressDelete.ogg
11-09 22:57:20.735: W/ActivityManager(287):   Force finishing activity com.example.awmobile/.MainActivity
11-09 22:57:20.746: E/SoundPool(287): error loading /system/media/audio/ui/KeypressReturn.ogg
11-09 22:57:20.746: W/AudioService(287): Soundpool could not load file: /system/media/audio/ui/KeypressReturn.ogg
11-09 22:57:20.746: W/AudioService(287): onLoadSoundEffects(), Error -1 while loading samples

code:
Code:
package com.example.awmobile;


import java.io.*;

import java.net.Socket;
import java.net.UnknownHostException;

import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.os.AsyncTask; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.ListView;
import android.widget.TextView;



@SuppressLint("NewApi") public class MainActivity extends Activity {
	Socket s;
	private boolean mRun = false;
	private Handler handler = new Handler();

	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        TextView t = (TextView)findViewById(R.id.textView1);
    	
    	
        
    
        final TextView textView1 = (TextView)findViewById(R.id.textView1);

        
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy); 
    
        
        

        try {
                s = new Socket("192.168.1.3",4444);
                mRun = true;
                } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                t.setText(t.getText() + "\n" + "unknownhost");

        } catch (IOException e) {

                // TODO Auto-generated catch block
                e.printStackTrace();
                t.setText(t.getText() + "\n" + e.toString());

        }

	     
	    	//We creëren een reader die luistert naar de connectie (een inputstream).
	        BufferedReader in;
	        String ontvangenBericht;
	        
			
				try {
					in = new BufferedReader(new InputStreamReader(s.getInputStream()));
					 //nu luisteren we net zo lang totdat we niks meer ontvangen (connectie is gesloten):
					StringBuilder ontvangenData = new StringBuilder();
			        while((ontvangenBericht = in.readLine()) != null) {   //de in.readLine levert een string op, deze string wordt geassigned aan de variabele ontvangenBericht daarna wordt gekeken of deze variabele de waarde null bevat.
						   //we hebben data ontvangen van de server.
						  textView1.setText(ontvangenBericht);
						   ontvangenBericht = null;

						}
			        
				} catch (IOException e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				}
        
       


    
    Button button1 = (Button) findViewById(R.id.button1);
    Button button2 = (Button) findViewById(R.id.button2);
    Button button3 = (Button) findViewById(R.id.button3);
    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        	
             
        	
        }
    });
    
    
    button2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
        	 //outgoing stream redirect to socket
            
			try {
				OutputStream out = s.getOutputStream();       
				PrintWriter output = new PrintWriter(out);             
				output.println("Hello from Android");     
				output.flush();
				//output.close();

	            
	            
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            
        }});
    
    button3.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
        
        }
        });
        
    }
       
    


    


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}
 
Volgens mij ontstaat deze error, omdat je een socket verbinding op de ui-thread maakt (de thread die ook het scherm toont). Neem een kijkje bij de volgende tutorial: http://examples.javacodegeeks.com/android/core/socket-core/android-socket-example/ De code van de client laat zien hoe je een socket verbinding op een aparte thread (runnable) maakt.

Het idee is dan:
Code:
private final int SERVER_IP = 192.168.2.155; //dit ip moet je aanpassen
private final int SERVER_PORT = 80;
private Socket socket;
@Override
onCreate(...) {
   socket = null; //wordt geinitialiseerd in de andere thread.
   ...
   new Thread(new ClientConnection()).start();
}

//private class
private class ClientConnection implements Runnable {

	        @Override
	        public void run() {

	            try {
	                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
	 
	                socket = new Socket(serverAddr, SERVER_PORT);
	 
	            } catch (UnknownHostException e1) {
	                e1.printStackTrace();
	            } catch (IOException e1) {
	                e1.printStackTrace();
	            }
	 
	        }	 
	    }
}

Groeten,
Newbi
 
Laatst bewerkt:
Status
Niet open voor verdere reacties.
Terug
Bovenaan Onderaan