NullPointerException beim Aufrufen einer Service Methode

  • Antworten:3
  • GeschlossenBentwortet
Sercan Savran
  • Forum-Beiträge: 2

14.04.2017, 22:01:50 via Website

Hallo an alle,

ich bin ein blutiger Anfänger in Sachen Android Development und versuche es mir Anhand tutorials selbst beizubringen. In meinem App war es mir bis jetzt möglich ein eigenen Service zu erstellen, welches sich mit einem Bluetooth-Modul erfolgreich verbinden und Bytes senden konnte. Ich versuche (erfolglos) zusätzlich einen weiteren Service zu erstellen, welches mit einem Webserver kommuniziert. Ich habe mehr oder weniger von dem bestehenden, funktionierenden BluetoothService ein wenig Copy & Paste betrieben und bekomme ein NullPointerException wenn ich versuche mein Service zu nutzen.

Ich hoffe hier können die erfahrenen Nutzer sagen, wo ich genau ein Fehler mache. Mein Programmcode sieht wie folgt aus:

Service:

   import android.annotation.TargetApi;
    import android.app.Service;
    import android.content.Intent;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.os.Binder;
    import android.os.Build;
    import android.os.IBinder;
    import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;




public class ClientService extends Service {
    private String LOG_TAG = null;


//private Intent broadcastIntent = new Intent();
private final IBinder mBinder = new LocalBinder();
private final String url_string = "receive_script.php";

@Override
public void onCreate() {
    super.onCreate();
}

public void sendToServer(final String text){

    new Thread(new Runnable() {
        @Override
        public void run() {
            if(internetAvailable()){
                try {
                    String textParam = "text1" + URLEncoder.encode(text,"UTF-8");
                    URL scriptUrl = new URL(url_string);
                    HttpURLConnection connection = (HttpURLConnection) scriptUrl.openConnection();
                    connection.setDoOutput(true);
                    connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                    connection.setFixedLengthStreamingMode(textParam.getBytes().length);
                    OutputStreamWriter contextWriter = new OutputStreamWriter(connection.getOutputStream());

                    contextWriter.write(textParam);
                    contextWriter.flush();
                    contextWriter.close();


                    InputStream answerInputStream = connection.getInputStream();
                    String answer = read(answerInputStream);

                    answerInputStream.close();
                    connection.disconnect();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();

}

private String read(InputStream is){
    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    StringBuilder sb = new StringBuilder();

    String currentLine;
    try {
        while((currentLine = br.readLine()) != null){
            sb.append(currentLine+"\n");
        }
    }catch (IOException e){
        e.printStackTrace();
    }
    return sb.toString().trim();


}
private boolean internetAvailable(){
    ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    return ni != null && ni.isConnectedOrConnecting();
}

@Override
public IBinder onBind(Intent intent) {
    // Wont be called as service is not bound
    Log.i(LOG_TAG, "In onBind");
    return mBinder;
}


public class LocalBinder extends Binder {
    ClientService getService() {
        // Return this instance of LocalService so clients can call public methods
        Log.i(LOG_TAG, "In onBind");
        return ClientService.this;
    }
}

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void onTaskRemoved(Intent rootIntent) {
    super.onTaskRemoved(rootIntent);
    Log.i(LOG_TAG, "In onTaskRemoved");
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.i(LOG_TAG, "In onDestroy");
}

}

Activity:

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.text.SimpleDateFormat;


public class loggedInActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener{
    public static final String mBroadcastStringAction = "com.truiton.broadcast.string";
    public static final String mBroadcastIntegerAction = "com.truiton.broadcast.integer";
    public static final String mBroadcastArrayListAction = "com.truiton.broadcast.arraylist";
    private TextView mTextView;
    private IntentFilter mIntentFilter;

    BluetoothService bService;
    ClientService cService;

    boolean btBound = false;
    boolean clientBound = false;


   // private View startButton;


    Button testButton
    EditText et;
    static final int CAM_REQUEST = 1;


    SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy_HHmmss");
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_logged_in);

        //DEKLARIEREN VON BT-AKTIONEN
        mTextView = (TextView) findViewById(R.id.textview1);
        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(mBroadcastStringAction);
        mIntentFilter.addAction(mBroadcastIntegerAction);
        mIntentFilter.addAction(mBroadcastArrayListAction);
        //Intent serviceIntent = new Intent(this, BluetoothService.class);
       // startService(serviceIntent);
        //


        et = (EditText) findViewById(R.id.editText);
        testButton = (Button) findViewById(R.id.camtest);

        Intent btIntent = new Intent(this, BluetoothService.class);
        startService(btIntent);
        bindService(btIntent, btServiceConnection, Context.BIND_AUTO_CREATE);

        Intent clientIntent = new Intent(this, ClientService.class);
        startService(clientIntent);
        bindService(clientIntent, clientServiceConnection, Context.BIND_AUTO_CREATE);


        testButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                // GENAU HIER TRETET DER NULLPOINTER EXCEPTION AUF, cService ist aus irgendeinem Grund
               // null
                cService.sendToServer(et.getText().toString());
            }
        });
    }



    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.logged_in, 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);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onResume() {
        super.onResume();
        registerReceiver(mReceiver, mIntentFilter);
    }


    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {


            if (intent.getAction().equals(mBroadcastStringAction)) {
                if(intent.getStringExtra("Data").equals("Still")){
                    recText.setText("STILLER ALARM");
                }else if(intent.getStringExtra("Data").equals("Laut")){
                    recText.setText("LAUTER ALARM");
                }else if(intent.getStringExtra("Data").equals("Zentral")){
                    recText.setText("ZENTRALER ALARM");
                }else if(intent.getStringExtra("Data").equals("nStill")){
                    recText.setText("STILLER ALARM AUS");
                }else if(intent.getStringExtra("Data").equals("nLaut")){
                    recText.setText("LAUTER ALARM AUS");
                }else if(intent.getStringExtra("Data").equals("nZentral")){
                    recText.setText("ZENTRALER ALARM AUS");
                }
                else if(intent.getStringExtra("Data").substring(0,6).toLowerCase().equals("betrag")){
                    recText.setText(intent.getStringExtra("Data"));

                }
            } 
        }
    };

    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection btServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                                       IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance

            BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
            bService = binder.getService();
            btBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            btBound = false;
        }
    };

    private ServiceConnection clientServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            ClientService.LocalBinder binder = (ClientService.LocalBinder) service;
            cService = binder.getService();
            clientBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            clientBound = false;
        }
    };

    @Override
    protected void onPause() {
        unregisterReceiver(mReceiver);
        super.onPause();
    }
}

Sercan Savran
  • Forum-Beiträge: 2

14.04.2017, 22:43:23 via Website

Ich könnte meinen Kopf die ganze Nacht gegen die Wand donnern. Ich habe den Fehler gefunden, Stichwort für die Lösung :
: AndroidManifest
war nicht eingetragen... -.-

swa00
  • Forum-Beiträge: 3.704

14.04.2017, 23:04:18 via Website

Hallo Secran,

willkommen im Club der "Entwickler-Chaoten", die aufgrund de Bäume den Wald nicht sehen :-)

P.S. Manchmal hilft ein Blick ins ErrorLog von AS :-) - ist mir auch schon des öfteren passiert :-)

Liebe Grüße - Stefan
[ App - Entwicklung ]

Sercan Savran

Ludy
  • Admin
  • Forum-Beiträge: 7.958

14.04.2017, 23:44:11 via App

Hallo Sercan,

herzlich willkommen hier im Forum (*)

ich habe deinen Thread in den passenden Bereich verschoben.

Ich denke dann kann hier zu gemacht werden.

Gruß Ludy (App Entwickler)

Mein Beitrag hat dir geholfen? Lass doch ein "Danke" da.☺

☕ Buy Me A Coffee ☕

Lebensmittelwarnung-App

✨Meine Wunschliste✨

📲Telegram NextPit News📲

Sercan Savranswa00