zu vorheriger Ansicht zurückkehren

J

jdajul

Ambitioniertes Mitglied
1
Hallo ich habe bei meiner App einen Button eingebaut über den sich eine neue View öffnet in dem alle Bluetoothgeräte in der Umgebung angezeigt werden. Wenn ich dort ein Gerät auswähle und dann auf die zurück-Taste gehe, so öffnet sich zwar wieder die ursprüngliche View, allerdings sind die Elemente dieser View alle inaktiv. Hier meinen Code: Wäre toll wenn mir jemand helfen könnte.
Viele Grüße,
jdajul

Code:
package jritter.stamer.bluetoothtest;


import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.media.audiofx.Visualizer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.*;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Handler;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.Set;


//https://github.com/TriggerTrap/SeekArc

public class MainActivity extends ActionBarActivity {
    BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
    static final boolean D = true;
    static final int REQUEST_ENABLE_BT = 2;
    static final String TAG = "Bluetooth";
    // SPP UUID service - this should work for most devices
    static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    BluetoothSocket btSocket = null;
    ConnectedThread mConnectedThread;
    VerticalSeekBar Master, Channel1, Channel2, Channel3, Channel4, Channel5, Channel6;
    CheckBox MuteMaster, Mute1, Mute2, Mute3, Mute4, Mute5, Mute6;
    Button connect;
    TextView textView;
    ArrayList arrayList;
    ListView lv;
    BroadcastReceiver mReceiver;
    ArrayAdapter<String> arrayAdapter;
    Spinner effects;
    List<String> spinnerArray = Arrays.asList("no effect", "Hall 1", "Hall 2 ", "Compressor", "Chorus" );

    private static long back_pressed;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        initializeVariables();
        turnBluetoothOn();

        bluetooth = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
        deviceSupportBluetooth();//?
        connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//do something...
                getSurroundingDevicesandConnect();
            }


        });



    }

    private void initializeVariables() {
        Master = (VerticalSeekBar) findViewById(R.id.Seekbar);
        Channel1 = (VerticalSeekBar) findViewById(R.id.Seekbar1);
        Channel2 = (VerticalSeekBar) findViewById(R.id.seekbar2);
        Channel3 = (VerticalSeekBar) findViewById(R.id.seekbar3);
        Channel4 = (VerticalSeekBar) findViewById(R.id.seekbar4);
        Channel5 = (VerticalSeekBar) findViewById(R.id.seekbar5);
        Channel6 = (VerticalSeekBar) findViewById(R.id.seekbar6);
        textView = (TextView) findViewById(R.id.textView);
        MuteMaster = (CheckBox) findViewById(R.id.muteMaster);
        Mute1 = (CheckBox) findViewById(R.id.mute1);
        Mute2 = (CheckBox) findViewById(R.id.mute2);
        Mute3 = (CheckBox) findViewById(R.id.mute3);
        Mute4 = (CheckBox) findViewById(R.id.mute4);
        Mute5 = (CheckBox) findViewById(R.id.mute5);
        Mute6 = (CheckBox) findViewById(R.id.mute6);
        connect = (Button) findViewById(R.id.connect);
        effects = (Spinner) findViewById(R.id.spinner2);

        arrayList = new ArrayList();

        seekbarConfig(Master, "Master");
        seekbarConfig(Channel1, "Channel1");
        seekbarConfig(Channel2, "Channel2");
        seekbarConfig(Channel3, "Channel3");
        seekbarConfig(Channel4, "Channel4");
        seekbarConfig(Channel5, "Channel5");
        seekbarConfig(Channel6, "Channel6");
        muteConfig(MuteMaster);
        muteConfig(Mute1);
        muteConfig(Mute2);
        muteConfig(Mute3);
        muteConfig(Mute4);
        muteConfig(Mute5);
        muteConfig(Mute6);
        effectsConfig(effects);


    }

    //android...
    @Override
    public void onStart() {
        super.onStart();
        if (D) Log.e(TAG, "++ ON START ++");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (D) Log.e(TAG, "++ ON DESTROY ++");
        if (mReceiver!=null){ unregisterReceiver(mReceiver);
            System.out.println("MReceiver closed");}
    }
    @Override
    public void onBackPressed(){
        setContentView(R.layout.activity_main);
        onResume();
        if (back_pressed + 2000 > System.currentTimeMillis()) super.onBackPressed();
        else Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
        back_pressed = System.currentTimeMillis();
    }

//    @Override
//    public synchronized void onResume() {
//        super.onResume();
//
//        if (D) Log.e(TAG, "+ ON RESUME +");
//    }

    @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;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);

    }


    // TODO GUI...
    public void effectsConfig(Spinner spinner){
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_spinner_item, spinnerArray);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        Spinners abc = new Spinners();
        abc.setSpinner(spinner);
        abc.setmConnectedThread(mConnectedThread);
        spinner.setOnItemSelectedListener(abc);
    }
    public void muteConfig(CheckBox mute){
        Checkboxes abc = new Checkboxes();
        abc.setmConnectedThread(mConnectedThread);
        mute.setOnClickListener(abc);
    }
    public void seekbarConfig(VerticalSeekBar seekBar, final String fadername) {
        Seekbars abc = new Seekbars();
        abc.setFadername(fadername);
        abc.setmConnectedThread(mConnectedThread);
        seekBar.setOnSeekBarChangeListener(abc);
    }

    // TODO Bluetooth handling...
    public BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
        return device.createInsecureRfcommSocketToServiceRecord(BTMODULEUUID);
    //creates secure outgoing connecetion with BT device using UUID
    }

    public void getSurroundingDevicesandConnect() {
        setContentView(R.layout.popup);

        bluetooth.startDiscovery();
        if (bluetooth.startDiscovery()) {
            System.out.println("discovery started");
            mReceiver = new BroadcastReceiver() {
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();

                    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        arrayAdapter.add(device.getName() + "\n" + device.getAddress());
                        System.out.println("while onreceive" + arrayList);
                    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                        Log.v(TAG, "Entered the Finished ");
                        bluetooth.cancelDiscovery();

                    } else {
                        System.out.println("hoppala da funktioniert was nciht");
                    }
                }

            };

            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mReceiver, filter);
        }

        setListView();
    }

    public void deviceSupportBluetooth() {
        if (bluetooth == null) {
            Toast.makeText(this, "Your Device does not support Bluetooth", Toast.LENGTH_LONG).show();
            finish();
            return;

        }
    }

    public void turnBluetoothOn() {
        if (!bluetooth.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            // Otherwise, setup the control session
        }
    }


    public void setListView() {
        lv = (ListView) findViewById(R.id.listView);
        arrayAdapter = new ArrayAdapter<String>(
                this,
                android.R.layout.select_dialog_item,
                arrayList
        );
        lv.setAdapter(arrayAdapter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {
                // TODO Auto-generated method stub
                String devicehelper = arrayList.get(position).toString();
                String[] device = devicehelper.split("\n");
                String deviceName = device[0];
                String deviceMAC = device[1];
                boolean connected = connectWithDeviceNow(deviceMAC);
                if (connected) {
                    System.out.println("Connected!");
                    Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
                } else {
                    System.out.println("Connection Failure");
                    Toast.makeText(getApplicationContext(), "Connection Failure", Toast.LENGTH_LONG).show();
                }
                Toast.makeText(getApplicationContext(), "Mit Gerät " + deviceName + " verbunden", Toast.LENGTH_LONG);
            }
        });

    }

    public boolean connectWithDeviceNow(String MAC) {
        //   create device and set the MAC address
        BluetoothDevice device = bluetooth.getRemoteDevice(MAC);//mydeviceaddress
        System.out.println("devicename: " + device + device.getName());
        bluetooth.cancelDiscovery();
        try {
            btSocket = createBluetoothSocket(device);
        } catch (IOException e) {
            System.out.println("socket creation failed");
            return false;
        }
// Establish the Bluetooth socket connection.
        try {
            btSocket.connect();
            System.out.println("mit geraet verbunden");


        } catch (IOException e) {
            System.out.println("geraet nicht in eichweite");
            try {
                btSocket.close();

            } catch (IOException e2) {
                System.out.println("Socket closing doesnt work!");
            }
            return false;

        }
        //  System.out.println("btconn is: "+btconn);
        mConnectedThread = new ConnectedThread(btSocket);
        mConnectedThread.start();
        return true;
    }





}
 
Oh boy so viel code in einer activity file...
Aber gut da du schon etwas geschrieben hast Bringt dir der Tipp setcontentview nur einmal zu benutzen eben nichts

Da du bei jedem Aufruf dieser Methode eine neue view Hierarchie aufspannen zerstörSt du die vorherige also muss alles neu initialisiert werden gehe alles in oncreate nochmal durch vllt funkt es dann ja
 
Aua.
Das sieht nach wildestem zusammenkopieren aus ... Ich lese da so viele Fehler, das ich gar nicht weiß, wo anfangen.

z.b. gleich zu Anfang im onCreate:
Code:
     turnBluetoothOn();

     bluetooth = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
     deviceSupportBluetooth();//?

erst BT einschalten, dann Adapter holen und erst dann fragen, ob überhaupt BT unterstützt wird ... denkste, das kann klappen ?

ich würde sagen, das du
a) erstmal den code in ein logischere Reihenfolge bringst und
b) das ganze erstmal aufsplittest in Layout-Aufgaben und die eigentlichen Funktionen
wenn du das soweit hast, guckst du dir mal "startActivityForResult" an,
und rufst damit deine 2te View auf.
In der 1ten View reagierst du darauf mit onActivityResult.
Sieht für mich so aus, das du nicht wirklich verstehst, was du da machst.
Du solltest dich daher mal mit den Grundlagen (Stichwort lifecycle) und den einzelnen Funktionen vertraut machen.
Bislang wird der obige Code max. auf deinem Gerät laufen, auf allen anderen -> Wundertüte.
 
Ich habe jetzt eine neue Activity gestartet die für die Bluetooth-Verbindung da ist.
Das klappt jetzt soweit auch, jedoch bricht die Verbindung immer dann ab sobald ich in die MainActivity zurückkehre. Ich habe etwas gelesen und es so verstanden dass ich dafür einen Service benutzen sollte, da die Bluetooth Verbindung ja ab diesem Zeitpunk während der gesamten Laufzeit bestehen soll. Jedoch bekomme ich immer ein Nullpointer...
Mein Code sieht jetzt wie folgt aus:
MainActivity.java
Code:
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.media.audiofx.Visualizer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.*;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Handler;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.Set;




public class MainActivity extends ActionBarActivity {
    BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
    static final boolean D = true;
    static final int REQUEST_ENABLE_BT = 2;
    static final String TAG = "Bluetooth";
    // String for MAC address
    static String mydeviceaddress;
    // SPP UUID service - this should work for most devices
    static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    ConnectedThread mConnectedThread;
    VerticalSeekBar Master, Channel1, Channel2, Channel3, Channel4, Channel5, Channel6, FX1, FX2, FX3, FX4;
    CheckBox MuteMaster, Mute1, Mute2, Mute3, Mute4, Mute5, Mute6;
    Button connect;
    TextView textView;
    ArrayList arrayList;
    Spinner effects;
    List<String> spinnerArray =  new ArrayList<String>(Arrays.asList("no effect", "Hall A", "Hall B"));
    VerticalSeekBar vsb;
    private static long back_pressed;
    BroadcastReceiver mReceiver;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        initializeVariables();
        deviceSupportBluetooth();//?
        turnBluetoothOn();


    }
    @Override
    public synchronized void onResume() {
        super.onResume();
        if (D) Log.e(TAG, "+ ON RESUME +");

        effectsConfig(effects);
        connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//do something...
//connect bluetooth activity

                sendMessage(v);
            }


        });


        seekbarConfig(Master, "Master");
        seekbarConfig(Channel1, "Channel1");
        seekbarConfig(Channel2, "Channel2");
        seekbarConfig(Channel3, "Channel3");
        seekbarConfig(Channel4, "Channel4");
        seekbarConfig(Channel5, "Channel5");
        seekbarConfig(Channel6, "Channel6");
        muteConfig(MuteMaster);
        muteConfig(Mute1);
        muteConfig(Mute2);
        muteConfig(Mute3);
        muteConfig(Mute4);
        muteConfig(Mute5);
        muteConfig(Mute6);

    }

    public void sendMessage(View view) {
        Intent intent = new Intent(this, Bluetooth.class);
        intent.putExtra("values", arrayList);
        startActivity(intent);

    }

    private void initializeVariables() {
        Master = (VerticalSeekBar) findViewById(R.id.Seekbar);
        Channel1 = (VerticalSeekBar) findViewById(R.id.Seekbar1);
        Channel2 = (VerticalSeekBar) findViewById(R.id.seekbar2);
        Channel3 = (VerticalSeekBar) findViewById(R.id.seekbar3);
        Channel4 = (VerticalSeekBar) findViewById(R.id.seekbar4);
        Channel5 = (VerticalSeekBar) findViewById(R.id.seekbar5);
        Channel6 = (VerticalSeekBar) findViewById(R.id.seekbar6);
        vsb = (VerticalSeekBar) findViewById(R.id.impulse2);
        textView = (TextView) findViewById(R.id.textView);
        MuteMaster = (CheckBox) findViewById(R.id.muteMaster);
        Mute1 = (CheckBox) findViewById(R.id.mute1);
        Mute2 = (CheckBox) findViewById(R.id.mute2);
        Mute3 = (CheckBox) findViewById(R.id.mute3);
        Mute4 = (CheckBox) findViewById(R.id.mute4);
        Mute5 = (CheckBox) findViewById(R.id.mute5);
        Mute6 = (CheckBox) findViewById(R.id.mute6);
        connect = (Button) findViewById(R.id.connect);
        effects = (Spinner) findViewById(R.id.spinner2);
        arrayList = new ArrayList();


    }

    //android...
    @Override
    public void onStart() {
        super.onStart();
        if (D) Log.e(TAG, "++ ON START ++");

    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        if (D) Log.e(TAG, "++ ON DESTROY ++");
        if (mReceiver!=null){ unregisterReceiver(mReceiver);
            mReceiver=null;
            System.out.println("MReceiver closed");}
    }
    public void onBackPressed(){
        setContentView(R.layout.activity_main);
        onResume();

        if (back_pressed + 2000 > System.currentTimeMillis()) super.onBackPressed();
        else Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
        back_pressed = System.currentTimeMillis();
    }


    @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;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
    }


    // TODO GUI...
    public void effectsConfig(Spinner spinner){
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_spinner_item, spinnerArray);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        Spinners abc = new Spinners();
        abc.setSpinner(spinner);
        abc.setmConnectedThread(mConnectedThread);
        spinner.setOnItemSelectedListener(abc);
    }
    public void muteConfig(CheckBox mute){
        Checkboxes abc = new Checkboxes();
        abc.setmConnectedThread(mConnectedThread);
        mute.setOnClickListener(abc);
    }
    public void seekbarConfig(VerticalSeekBar seekBar, final String fadername) {
        Seekbars abc = new Seekbars();
        abc.setFadername(fadername);
        abc.setmConnectedThread(mConnectedThread);
        seekBar.setOnSeekBarChangeListener(abc);
    }

    // TODO Bluetooth handling...
    public BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
        return device.createInsecureRfcommSocketToServiceRecord(BTMODULEUUID);
    //creates secure outgoing connecetion with BT device using UUID
    }


    public void deviceSupportBluetooth() {
        if (bluetooth == null) {
            Toast.makeText(this, "Your Device does not support Bluetooth", Toast.LENGTH_LONG).show();
            finish();
            return;

        }
    }

    public void turnBluetoothOn() {
        if (!bluetooth.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            // Otherwise, setup the control session
        }
    }








}
bluetoothservice.java
Code:
import android.app.IntentService;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

/**
 * Created by jritter on 24.04.15.
 */
public class BluetoothService extends IntentService {
    Bluetooth bluetootha=new Bluetooth();
    MainActivity ma = new MainActivity();
    BroadcastReceiver mReceiver;

    public BluetoothService() {
        super("BluetoothService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // Normally we would do some work here, like download a file.
        // For our sample, we just sleep for 5 seconds.

        ma.bluetooth.startDiscovery();
        if (ma.bluetooth.startDiscovery()) {
            System.out.println("discovery started");
            mReceiver = new BroadcastReceiver() {
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();

                    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        bluetootha.arrayAdapter.add(device.getName() + "\n" + device.getAddress());
                        System.out.println("while onreceive" + bluetootha.arrayList1);
                    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                        Log.v(bluetootha.TAG, "Entered the Finished ");
                        ma.bluetooth.cancelDiscovery();

                    } else {
                        System.out.println("hoppala da funktioniert was nciht");
                    }
                }

            };
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mReceiver, filter);

        }
    }
}
Bluetooth.java
Code:
import android.app.Fragment;
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.content.IntentFilter;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;


public class Bluetooth extends ActionBarActivity {
    ArrayList arrayList1;
    ListView lv;
    ArrayAdapter<String> arrayAdapter;
    MainActivity ma = new MainActivity();
    static final String TAG = "Bluetooth";
    BluetoothSocket btSocket = null;
    BluetoothService btservice;
    Intent intent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.popup);
         intent = getIntent();
        btservice=new BluetoothService();
        arrayList1=intent.getStringArrayListExtra("values");
        lv= (ListView) findViewById(R.id.listView);

    }
    @Override
    protected void onStart(){
        super.onStart();
        getSurroundingDevicesandConnect();

    }
    public void getSurroundingDevicesandConnect() {
        setContentView(R.layout.popup);

        btservice.onHandleIntent(intent);

        setListView();
    }
    public void setListView() {
        lv = (ListView) findViewById(R.id.listView);
        arrayAdapter = new ArrayAdapter<String>(
                this,
                android.R.layout.select_dialog_item,
                arrayList1
        );
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {
                // TODO Auto-generated method stub
                String devicehelper = arrayList1.get(position).toString();
                String[] device = devicehelper.split("\n");
                String deviceName = device[0];
                String deviceMAC = device[1];
                boolean connected = connectWithDeviceNow(deviceMAC);
                if (connected) {
                    System.out.println("Connected!");
                    Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
                } else {
                    System.out.println("Connection Failure");
                    Toast.makeText(getApplicationContext(), "Connection Failure", Toast.LENGTH_LONG).show();
                }
                //onRestart();
                Toast.makeText(getApplicationContext(), "Mit Gerät " + deviceName + " verbunden", Toast.LENGTH_LONG);
            }
        });

        lv.setAdapter(arrayAdapter);
    }
    public boolean connectWithDeviceNow(String MAC) {
        //   create device and set the MAC address
        BluetoothDevice device = ma.bluetooth.getRemoteDevice(MAC);//mydeviceaddress
        System.out.println("devicename: " + device + device.getName());
        ma.bluetooth.cancelDiscovery();
        try {
            btSocket = ma.createBluetoothSocket(device);
        } catch (IOException e) {
            System.out.println("socket creation failed");
            return false;
        }
// Establish the Bluetooth socket connection.
        try {
            btSocket.connect();
            System.out.println("mit geraet verbunden");


        } catch (IOException e) {
            System.out.println("geraet nicht in eichweite");
            try {
                btSocket.close();

            } catch (IOException e2) {
                System.out.println("Socket closing doesnt work!");
            }
            return false;

        }
        //  System.out.println("btconn is: "+btconn);
        ma.mConnectedThread = new ConnectedThread(btSocket);
        ma.mConnectedThread.start();
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.bluetooth, menu);
        return true;
    }


}

LogCat sagt aus, dass in RegisterReceiver am Ende von BluetoothService den Nullpointer verursacht...
 
Was glaubst du was du damit machst: Mainactivity ma= new Mainactivity (); ?
 
Eine Instanz von MainActivity erzeugen um damit auf die Funktionen und Variablen der MainActivity zuzugreifen. Wieso? Liege ich da falsch?
 
Dann spiele ich mal wieder Spielverderber :p
Vllt solltest du dir erstmal rudimentäre Android Kenntnisse besorgen, bevor du mit Bluetooth rum spielst....

denn du scheinst 0 Verständnis von dem zu haben was du da machst...

lg. Dagobert
 
jdajul schrieb:
Eine Instanz von MainActivity erzeugen um damit auf die Funktionen und Variablen der MainActivity zuzugreifen. Wieso? Liege ich da falsch?

Klar erzeugst du eine neue Instanz ... und nochmal ... und nochmal ... ;)
Und erwartest, das das immer die selbe ist, nur weil du die gleich benennst.

Folge mal Dagoberts Rat und arbeite zumindest mal das hier
Building Your First App | Android Developers
durch, bevor du irgendetwas anderes versuchst. Du wirst ansonsten immer
wieder vor die Wand laufen ;)
 
Wenn du Bluetooth.Discovery () starten möchtest dann gibt es da andere Möglichkeiten. ..btw

ma.bluetooth.startDiscovery();
if (ma.bluetooth.startDiscovery()) {...

Das startet den Vorgang zweimal
und nimm einen Bluetooth Adapter dafür mit BlueTooth.getDefaultAdapter ().startDiscovery ();

Instanziere keine Activities

wenn du schon Activity Objekte hast dann höchstens um eine existierende Activity zu referenzieren...

Lg
 
Danke, habe jetzt alles so verändert wie ihr gesagt habt. Außerdem funktioniert der Service jetzt auch und die Bluetoothverbindung bleibt die ganze zeit bestehen.
Danke für die Hilfe
 

Ähnliche Themen

S
Antworten
0
Aufrufe
587
Sergio13
S
A
Antworten
1
Aufrufe
582
swa00
swa00
SpeedySix
Antworten
13
Aufrufe
1.398
jogimuc
J
Zurück
Oben Unten