-1

I tried to use a textview like here but I always get the error "cannot resolve method" for findById. I figured out, that it is because my class does not extends the class Activity but I don't know hot to fix it. A getActivity() in front of the setContenview and getView in the onCreate only worked the first time I built the app. Is there a simple way to display a string and an integer in a textview?

My XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.mbientlab.metawear.starter.DeviceSetupActivityFragment"
    tools:showIn="@layout/activity_device_setup">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sync"
        android:id="@+id/acc_start"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="71dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="reset"
        android:id="@+id/acc_stop"
        android:layout_below="@+id/acc_start"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="59dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Steps: 0"
        android:id="@+id/stepView"
        android:layout_below="@+id/acc_stop"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="118dp" />

</RelativeLayout>

My Code:

package com.mbientlab.metawear.starter;

import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.os.Bundle;
import android.view.ViewGroup;
import android.util.Log;
import android.widget.TextView;


import com.mbientlab.metawear.MetaWearBleService;
import com.mbientlab.metawear.MetaWearBoard;
import com.mbientlab.metawear.data.CartesianFloat;
import com.mbientlab.metawear.AsyncOperation;
import com.mbientlab.metawear.module.Gpio;
import com.mbientlab.metawear.module.Timer;
import com.mbientlab.metawear.Message;
import com.mbientlab.metawear.RouteManager;
import static com.mbientlab.metawear.MetaWearBoard.ConnectionStateHandler;
import static com.mbientlab.metawear.AsyncOperation.CompletionHandler;

import com.mbientlab.metawear.UnsupportedModuleException;
import com.mbientlab.metawear.module.Bmi160Accelerometer;

/**
 * A placeholder fragment containing a simple view.
 */
public class DeviceSetupActivityFragment extends Fragment implements ServiceConnection {

    //private MetaWearBoard mwBoard;
    public Bmi160Accelerometer accModule;

    TextView counted_steps; //for showing the steps in the textview


    public interface FragmentSettings {
        BluetoothDevice getBtDevice();
    }

    private MetaWearBoard mwBoard= null;
    private FragmentSettings settings;

    public DeviceSetupActivityFragment() {
    }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        view.findViewById(R.id.acc_start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                accModule.readStepCounter(false);

            }
        });
        view.findViewById(R.id.acc_stop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                accModule.resetStepCounter();
            }
        });
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

       setContentView(R.layout.fragment_device_setup);
       counted_steps = (TextView) findViewById(R.id.stepView);

        Activity owner = getActivity();
        if (!(owner instanceof FragmentSettings)) {
            throw new ClassCastException("Owning activity must implement the FragmentSettings interface");
        }

        settings = (FragmentSettings) owner;
        owner.getApplicationContext().bindService(new Intent(owner, MetaWearBleService.class), this, Context.BIND_AUTO_CREATE);

    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        ///< Unbind the service when the activity is destroyed
        getActivity().getApplicationContext().unbindService(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setRetainInstance(true);
        return inflater.inflate(R.layout.fragment_device_setup, container, false);
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        mwBoard= ((MetaWearBleService.LocalBinder) service).getMetaWearBoard(settings.getBtDevice());

        ready();

        // Route data from the chip's step counter
        accModule.routeData().fromStepCounter(false).stream("step_counter").commit()        
                .onComplete(new CompletionHandler<RouteManager>() {
                    @Override
                    public void success(RouteManager result) {
                        result.subscribe("step_counter", new RouteManager.MessageHandler() {
                            @Override
                            public void process(Message msg) {
                                Log.i("MainActivity", "Steps= " + msg.getData(Integer.class));
                                counted_steps.setText("Steps: " + msg.getData(Integer.class));
                            }
                        });
                    }
                });

        accModule.start();
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }

    /**
     * Called when the app has reconnected to the board
     */
    public void reconnected() { }

    /**
     * Called when the mwBoard field is ready to be used
     */
    public void ready() {
        try {
            accModule = mwBoard.getModule(Bmi160Accelerometer.class);

            accModule.configureStepDetection()

                    .setSensitivity(Bmi160Accelerometer.StepSensitivity.NORMAL)
                            // Enable step counter
                    .enableStepCounter()
                    .commit();


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

    }
}
Community
  • 1
  • 1
hanss
  • 21
  • 7
  • 2
    Firstly, you seem to have "combined" an Activity class into a Fragment... `setContentView` shouldn't resolve either – OneCricketeer Aug 23 '16 at 18:21
  • Save your `view` as a global attribute, and then use it to call `findViewById` – Santiago Gil Aug 23 '16 at 18:22
  • @SantiGil - That isn't how you should use a Fragment. Both, Please see this answer http://stackoverflow.com/a/6496013/2308683 – OneCricketeer Aug 23 '16 at 18:23
  • @cricket_007 In the onCreateView you can save it `root = inflater.inflate(R.layout.your_layout, container, false);` where root is a global attribute `View root;`. And then you can use `findViewById` in all methods. I don't see nothing bad – Santiago Gil Aug 23 '16 at 18:26
  • @SantiGil It's just more preferred to extract out the sub-views rather than save the entire root. That's all – OneCricketeer Aug 23 '16 at 18:28

1 Answers1

0

I always get the error "cannot resolve method" for findById. I figured out, that it is because my class does not extends the class Activity.

Right, you are using a Fragment...

A getActivity() in front of the setContentView and getView in the onCreate only worked the first time I built the app.

You probably shouldn't even be using a onCreate method for the Fragment. At least not to modify the state of the Activity, when that code can actually be in the Activity class. For example, the Fragment shouldn't be changing the content view of the Activity.

The majority of the code that is used for a Fragment can be placed in onCreateView (which is one place you can use findViewById), which leads to...

Is there a simple way to display a string and an integer in a textview?

Yes, there are many places you can do it. For example, you can use view.findViewById from the onViewCreated method to get and set your respective TextView for the layout file that is used within onCreateView.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245