App stopt bei betätigen des Ein Switches

  • 4 Antworten
  • Letztes Antwortdatum
T

Techniker2013

Neues Mitglied
0
Hallo nach Erweiterung meiner eigenen App, schließt diese sich immer wieder automatisch obwohl vom Source dies nicht sein dürfte. Ich habe da schon verschiedene Sachen probiert aber das war jetzt die einzige Möglichkeit, damit die App an ist. Wenn ich die App debugge kann ich nicht einmal den LogCat öffnen.

Kurz und knapp die App öffnet sich, aber wenn Switch und ToggleButton beide geklickt sind schließt sich die app.

Wenn mir jemand helfen könnte... bin total ratlos.

Die rot markierten Stellen sind der Button und Switch woran es happert.
Die blau markierte Stelle ist nicht bzw. noch nicht in der App mit eingebunden.

Code:
package de.poseidon_v2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity implements SensorEventListener {

	
	
	// Variablen
	
	private static final int REQUEST_ENABLE_BT = 1;
	public static final int MESSAGE_READ = 2;
	protected static final int MESSAGE_WRITE = 1;
	// Hardware Variablen
	private SensorManager mSensorManager;
	private Sensor mAccelerometer;
	public BluetoothAdapter btAdapter;
	public BluetoothSocket scSocket;
	//Button, Switch und TextViews
	
	
	
	//Sensor Variablen
	float values[];
	ToggleButton Starten;
	ToggleButton BluetoothEinschalten;
	TextView acceleration;
	Switch SwitchEin;
	
	SendReceiveBytes sendReceiveBT;
	BroadcastReceiver myDiscoverer = new myOwnBroadcastReceiver();
	BroadcastReceiver checkIsConnected = new myOwnBroadcastReceiver();
	private String sendX;
	private String sendY;
	public static Handler mHandler = new Handler() {
		 @Override
		 public void handleMessage(Message msg) {
		 switch (msg.what) {
		 case MESSAGE_WRITE:
		 //Do something when writing
		 break;
		 case MESSAGE_READ:
		 //Get the bytes from the msg.obj
		 byte[] readBuf = (byte[]) msg.obj;
		 // construct a string from the valid bytes in the buffer
		 String readMessage = new String(readBuf, 0, msg.arg1);
		 break;
		 }
		 }
		};
	
	//MAIN-Methode
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		MainActivity Objekt=new MainActivity();
		PoseidonSwitchFreischalten();
		AccelerometerAuslesen();
		BluetoothAdapterSuche();
	}
	
	@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;
	}
//--------------------------------------------------------------------------------------------
	//Poseidon Einschalten
//--------------------------------------------------------------------------------------------
	[COLOR="red"]public boolean PoseidonSwitchFreischalten(){
		SwitchEin=(Switch)findViewById(R.id.Einschalten);
		boolean On;
		if(SwitchEin.isChecked()==true){
			On=true;
		}
		else{
			On=false;
		}
		return On;
	}[/COLOR]
//--------------------------------------------------------------------------------------------
	//Poseidonfreischalten beendet
//--------------------------------------------------------------------------------------------
	
//--------------------------------------------------------------------------------------------
	//Accelerometer
//--------------------------------------------------------------------------------------------
	[COLOR="Red"]public boolean Spielstarten(){
	Starten=(ToggleButton)findViewById(R.id.Starten);
	boolean State;
	if(Starten.isChecked()==true){
		State= true;
	}
	else{
		State=false;
	}
	return State;
	}
	public void AccelerometerAuslesen(){
		mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        
        acceleration=(TextView)findViewById(R.id.acceleration);
	}
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub
		if(Spielstarten()==true){
		double X=(double)(event.values[0]);
		int XAchse=(int)(Math.round(X));	
		double Y=(double)(event.values[1]);
		int YAchse=(int)(Math.round(Y));
		if((Spielstarten()&&PoseidonSwitchFreischalten())==true){
			if(XAchse>=0){
			sendX="g";
			if(sendX=="g"){
				byte[] myByte = stringToBytesUTFCustom(sendX);
				sendReceiveBT.write(myByte);
			}
		}
		else{
			sendX="r";
			if(sendX=="r"){
				byte[] myByte = stringToBytesUTFCustom(sendX);
				sendReceiveBT.write(myByte);
			}
		}	
		if(YAchse>=0){
			sendY="b";
			if(sendY=="g"){
				byte[] myByte = stringToBytesUTFCustom(sendY);
				sendReceiveBT.write(myByte);
			}
		}
		else{
			sendY="w";
			if(sendY=="w"){
				byte[] myByte = stringToBytesUTFCustom(sendY);
				sendReceiveBT.write(myByte);
			}
		}
		}
		acceleration.setText("X-Achse: "+XAchse +" \nY-Achse: "+YAchse);
		}
		else{
			acceleration.setText("X-Achse: "+"\nY-Achse:");
		}
	}
	[/COLOR]
//--------------------------------------------------------------------------------------------
	//Ende des Accelerometers
//--------------------------------------------------------------------------------------------
	
//--------------------------------------------------------------------------------------------
	//BluetoothVerbindung
//--------------------------------------------------------------------------------------------
	[COLOR="Blue"]private boolean BluetoothFreischalten(){
		BluetoothEinschalten=(ToggleButton)findViewById(R.id.BtEinschalten);
		boolean FreischaltenBT;
		if(BluetoothEinschalten.isChecked()==true){
			FreischaltenBT=true;
		}
		else{
			FreischaltenBT=false;
		}
		return FreischaltenBT;
		
	}
	
	private void BluetoothInitializieren() {
		// TODO Auto-generated method stub
		if(BluetoothFreischalten()&&PoseidonSwitchFreischalten()==true){
			
		}
		else{
			
		}
	}[/COLOR]
	public void BluetoothAdapterSuche(){
		btAdapter= BluetoothAdapter.getDefaultAdapter();
		if (btAdapter == null) {
		    Toast.makeText(getApplicationContext(), "Bluetooth ist nicht eingeschaltet! \nBitte einschalten", Toast.LENGTH_LONG).show();
		}
		else if (!btAdapter.isEnabled()) {
		    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
		    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
		    if(btAdapter.isEnabled()){
				btAdapter.startDiscovery();
			}
		}
	}
//--------------------------------------------------------------------------------------------
	//BluetoothVerbindung
//--------------------------------------------------------------------------------------------
	
//--------------------------------------------------------------------------------------------
	//Broadcast Receiver
//--------------------------------------------------------------------------------------------
	public class myOwnBroadcastReceiver extends BroadcastReceiver {
		 ConnectToBluetooth connectBT;

		 @Override
		 public void onReceive(Context context, Intent intent) {
		 String action=intent.getAction();
		 ToastMaster("ACTION:" + action);

		 //Notification that BluetoothDevice is FOUND
		 if (BluetoothDevice.ACTION_FOUND.equals(action)) {
		 //Display the name of the discovered device
		 String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
		 ToastMaster("Discovered: " + discoveredDeviceName);

		 //Display more information about the discovered device
		 BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
		 ToastMaster("getAddress() = " + discoveredDevice.getAddress());
		 ToastMaster("getName() = " + discoveredDevice.getName());

		 int bondyState=discoveredDevice.getBondState();
		 ToastMaster("getBondState() = " + bondyState);

		 String mybondState;
		 switch(bondyState) {
		 case 10: 
		 mybondState="BOND_NONE";
		 break;
		 case 11: 
		 mybondState="BOND_BONDING";
		 break;
		 case 12: 
		 mybondState="BOND_BONDED";
		 break;
		 default: 
		 mybondState="INVALID BOND STATE";
		 break;
		 }
		 ToastMaster("getBondState() = " + mybondState);
		 //Connect to the discovered bluetooth device (SeeedBTSlave)
		 if (discoveredDeviceName.equals("SeeedBTSlave")) {
		 ToastMaster("Connecting you Now !!");
		 unregisterReceiver(myDiscoverer);
		 connectBT = new ConnectToBluetooth(discoveredDevice);
		 //Connect to the the device in a new thread
		 new Thread(connectBT).start();
		 }
		 }

		 //Notification if bluetooth device is connected
		 if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
		 ToastMaster("CONNECTED _ YAY");
		 int counter=0;
		while (scSocket==null) {
		 //do nothing
		 }
		 ToastMaster("scSocket" + scSocket);
		 if (scSocket!=null) {
		 sendReceiveBT = new SendReceiveBytes(scSocket);
		 new Thread(sendReceiveBT).start();
		 String red = "r";
		 byte[] myByte = stringToBytesUTFCustom(red);
		 sendReceiveBT.write(myByte);
		 }
		 }
		 }
		}
	public static byte[] stringToBytesUTFCustom(String str) {
		 char[] buffer = str.toCharArray();
		 byte[] b = new byte[buffer.length << 1];
		 for (int i = 0; i < buffer.length; i++) {
		 int bpos = i << 1;
		 b[bpos] = (byte) ((buffer[i]&0xFF00)>>8);
		 b[bpos + 1] = (byte) (buffer[i]&0x00FF);
		 }
		 return b;
		}
//--------------------------------------------------------------------------------------------
	//Broadcast Receiver Ende
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
	//ConnectThread
//--------------------------------------------------------------------------------------------
	public class ConnectToBluetooth implements Runnable {
		 private BluetoothDevice btShield;
		 private BluetoothSocket mySocket = null;
		 private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

		 public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
		 btShield = bluetoothShield;
		 try {
		 mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
		 }
		 catch(IOException createSocketException) {
		 //Problem with creating a socket
		 Log.e("ConnectToBluetooth", "Error with Socket");
		 }
		 }

		 @Override
		 public void run() {
		 /* Cancel discovery on Bluetooth Adapter to prevent slow connection */
		 btAdapter.cancelDiscovery();

		 try {
		 /*Connect to the bluetoothShield through the Socket. This will block
		 until it succeeds or throws an IOException */
		 mySocket.connect();
		 scSocket=mySocket;
		 } 
		 catch (IOException connectException) {
		 Log.e("ConnectToBluetooth", "Error with Socket Connection");
		 try {
		 mySocket.close(); //try to close the socket
		 }
		 catch(IOException closeException) {
		 }
		 return;
		 }
		 }

		 // Will allow you to get the socket from this class
		 public BluetoothSocket getSocket() {
		 return mySocket;
		 }

		 /* Will cancel an in-progress connection, and close the socket */
		 public void cancel() {
		 try {
		 mySocket.close();
		 } 
		 catch (IOException e) {
		 }
		 }
		}
	//--------------------------------------------------------------------------------------------
		//ConnectThread Ende
	//--------------------------------------------------------------------------------------------
	
	//--------------------------------------------------------------------------------------------
			//ConnectThread
		//--------------------------------------------------------------------------------------------
	private class SendReceiveBytes implements Runnable {
		 private BluetoothSocket btSocket;
		 private InputStream btInputStream = null;
		 ;
		 private OutputStream btOutputStream = null;
		 String TAG = "SendReceiveBytes";

		 public SendReceiveBytes(BluetoothSocket socket) {
		 btSocket = socket;
		 try {
		 btInputStream = btSocket.getInputStream();
		 btOutputStream = btSocket.getOutputStream();
		 } 
		 catch (IOException streamError) { 
		 Log.e(TAG, "Error when getting input or output Stream");
		 }
		 }

		 public void run() {
		 byte[] buffer = new byte[1024]; // buffer store for the stream
		 int bytes; // bytes returned from read()

		 // Keep listening to the InputStream until an exception occurs
		 while (true) {
		 try {
		 // Read from the InputStream
		 bytes = btInputStream.read(buffer);
		 // Send the obtained bytes to the UI activity
		 mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
		 .sendToTarget();
		 } 
		 catch (IOException e) {
		 Log.e(TAG, "Error reading from btInputStream");
		 break;
		 }
		 }
		 }

		 /* Call this from the main activity to send data to the remote device */
		 public void write(byte[] bytes) {
		 try {
		 btOutputStream.write(bytes);
		 } 
		 catch (IOException e) { 
		 Log.e(TAG, "Error when writing to btOutputStream");
		 }
		 }

		 /* Call this from the main activity to shutdown the connection */
		 public void cancel() {
		 try {
		 btSocket.close();
		 } 
		 catch (IOException e) { 
		 Log.e(TAG, "Error when closing the btSocket");
		 }
		 }
		}
		/* My ToastMaster function to display a messageBox on the screen */
		void ToastMaster(String textToDisplay) {
		 Toast myMessage = Toast.makeText(getApplicationContext(), 
		 textToDisplay, 
		 Toast.LENGTH_SHORT);
		 myMessage.setGravity(Gravity.CENTER, 0, 0);
		 myMessage.show();
		}
		//--------------------------------------------------------------------------------------------
			//ConnectThread Ende
		//--------------------------------------------------------------------------------------------
}//End of Class
 
Schließt die APP mit Fehlermeldung oder ohne?

Gesendet von meinem Galaxy Nexus mit der Android-Hilfe.de App
 
Also wenn ich mir deinen Sourcecode so anschauen wird mir ehrlich gesagt schlecht. Du hälst dich ja so gut wie an keine Konventionen. Variablen und Objektinstanzen werden mal groß mal klein geschrieben. Zudem sieht das für mich eher 95 % wie Copy & Paste aus. Es gibt teilweise absoluten Müll in deiner App der für nichts gut ist bzw unnötiger Code:

Warum legst du in der onCreate() Methode nochmals eine Instanz deiner Activity an ohne, dass diese nochmal genutzt wird. Was soll das!?

Oder zum Beispiel in deiner Methode poseidonSwitchFreischalten().. Da reicht doch ein einfaches "return SwitchEin.isChecked()".

Den Rest hab ich mir dann gar nicht weiter angeschaut. Man merkt sehr schnell, dass du 0 Ahnung in der Programmierung hast. Ist ja grundsätzlich kein Problem. Jeder fängt mal klein an. Aber dann arbeite dich doch erstmal durch kleine Tutorials und lerne den Umgang mit Java und vor allem auch mit der Entwicklungsumgebung. Wenn du nicht in der Lage bist, ordentlich zu Debuggen oder ein einfaches Exception-Handling mit Logging einzubauen, solltest du noch die Finger von "Komplexeren" Aufgaben lassen.

Sorry für die harten Worte, ist nicht böse gemeint sondern ein guter Ratschlag.
 
Da ich eig. ein Anfänger bin, habe ich über die Seite Developer mich eingelesen, wie die Sache mit dem Bluetooth funktioniert und hab die Sache so gehandhabt, dass ich den Code Stück für Stück auf das beschränke, was ich für mein Programm benötigte. Ich habe so auch mit der Javaprogrammierung angefangen, ich weis das ist in gewisserweise doof aber so lerne ich wie ich mit der Programmiersprache und ihre Eigenschaften umgehe.

@Vacutainer: Es wird nichts angezeigt, nur "App stoppt" ich denke, dass die app sich schließt, wenn ich die Daten via Bluetooth senden will
 
Guten Abend,

Naja ich wette das die App mit Fehlermeldung im Logcat stoppt.
Alles andere glaub ich iwie nicht...
Und ja, du solltest erst mal mit nem Java Anfängerbuch anfangen, bevor du dich mit Android rumärgert...

lg. Dagobert
 

Ähnliche Themen

G
Antworten
0
Aufrufe
132
Gerdchen07
G
G
Antworten
1
Aufrufe
384
Gerdchen07
G
G
Antworten
13
Aufrufe
599
Gerdchen07
G
L
Antworten
2
Aufrufe
555
Lexub
L
migi01
Antworten
26
Aufrufe
1.991
migi01
migi01
Zurück
Oben Unten