0

// Monitoring fragment

all code that retrieve sensor data from the thingSpeak website using fragment on android studio

public class MonitoringFragment extends Fragment {

private static final String TAG = "MONITORINGACTIVITY";
private Button Temperature;
private Button Humidity;
private TextView t1;
private TextView t2;
private static TextView t3;
private static final String THINGSPEAK_CHANNEL_ID = "584296";
private static final String THINGSPEAK_API_KEY = "HXCLHZZKAIQGH944"; //GARBAGE KEY
private static final String THINGSPEAK_API_KEY_STRING = "HXCLHZZKAIQGH944";
/* Be sure to use the correct fields for your own app*/
private static final String THINGSPEAK_FIELD1 = "field1";
private static final String THINGSPEAK_FIELD2 = "field2";
private static final String THINGSPEAK_UPDATE_URL = "https://api.thingspeak.com/update?";
private static final String THINGSPEAK_CHANNEL_URL = "https://api.thingspeak.com/channels/";
private static final String THINGSPEAK_FEEDS_LAST = "/feeds/last?";

private ThingSpeakChannel tsChannel;
private ThingSpeakLineChart tsChart;
private LineChartView chartView;

public MonitoringFragment() {
    // Required empty public constructor
}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_monitoring, container, false);

    t1=(TextView)v.findViewById(R.id.tempNumber);
    t2=(TextView)v.findViewById(R.id.humidNumber);

    Temperature = (Button) v.findViewById(R.id.btnTemperature);
    Humidity = (Button) v.findViewById(R.id.btnHumidity);


    Temperature.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            v.findViewById(R.id.TemperatureLayout).setVisibility(View.VISIBLE);
            v.findViewById(R.id.HumidityLayout).setVisibility(View.GONE);

            final LineChartView chartView = (LineChartView) v.findViewById(R.id.TempChart);
            tsChart = new ThingSpeakLineChart(584296, 1);
            tsChart.setListener(new ThingSpeakLineChart.ChartDataUpdateListener() {
                @Override
                public void onChartDataUpdated(long channelId, int fieldId, String title, LineChartData lineChartData, Viewport maxViewport, Viewport initialViewport) {

                    //Calendar calendar = Calendar.getInstance();
                    //calendar.add(Calendar.MINUTE, -5);

                    tsChart.setNumberOfEntries(200);
                    // Set value axis labels on 10-unit interval
                    tsChart.setValueAxisLabelInterval(10);
                    // Set date axis labels on 5-minute interval
                    tsChart.setDateAxisLabelInterval(1);
                    // Show the line as a cubic spline
                    tsChart.useSpline(true);
                    // Set the line color
                    tsChart.setLineColor(Color.parseColor("#D32F2F"));
                    // Set the axis color
                    tsChart.setAxisColor(Color.parseColor("#455a64"));
                    // Set the starting date (5 minutes ago) for the default viewport of the chart
                    //tsChart.setChartStartDate(calendar.getTime());

                    chartView.setLineChartData(lineChartData);
                    chartView.setMaximumViewport(maxViewport);
                    chartView.setCurrentViewport(initialViewport);
                }
            });
            tsChart.loadChartData();

            try {
                new FetchThingspeakTempTask().execute();
            }
            catch(Exception e){
                Log.e("ERROR", e.getMessage(), e);
            }
        }
    });


    Humidity.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            v.findViewById(R.id.HumidityLayout).setVisibility(View.VISIBLE);
            v.findViewById(R.id.TemperatureLayout).setVisibility(View.GONE);


            final LineChartView chartView = (LineChartView) v.findViewById(R.id.HumidChart);
            tsChart = new ThingSpeakLineChart(584296, 2);
            tsChart.setListener(new ThingSpeakLineChart.ChartDataUpdateListener() {
                @Override
                public void onChartDataUpdated(long channelId, int fieldId, String title, LineChartData lineChartData, Viewport maxViewport, Viewport initialViewport) {

                    //Calendar calendar = Calendar.getInstance();
                    //calendar.add(Calendar.MINUTE, -5);

                    tsChart.setNumberOfEntries(200);
                    // Set value axis labels on 10-unit interval
                    tsChart.setValueAxisLabelInterval(10);
                    // Set date axis labels on 5-minute interval
                    tsChart.setDateAxisLabelInterval(1);
                    // Show the line as a cubic spline
                    tsChart.useSpline(true);
                    // Set the line color
                    tsChart.setLineColor(Color.parseColor("#056604"));
                    // Set the axis color
                    tsChart.setAxisColor(Color.parseColor("#455a64"));
                    // Set the starting date (5 minutes ago) for the default viewport of the chart
                    //tsChart.setChartStartDate(calendar.getTime());

                    chartView.setLineChartData(lineChartData);
                    chartView.setMaximumViewport(maxViewport);
                    chartView.setCurrentViewport(initialViewport);
                }
            });
            tsChart.loadChartData();
            try {
                new FetchThingspeakHumidTask().execute();
            }
            catch(Exception e){
                Log.e("ERROR", e.getMessage(), e);
            }
        }

    });
    return v;
}


public class FetchThingspeakTempTask extends AsyncTask<Void, Void, String> {
    protected void onPreExecute() {
        t1.setText("Fetching Data from Server.Please Wait...");
    }
    protected String doInBackground(Void... urls) {
        try {
            URL url = new URL(THINGSPEAK_CHANNEL_URL + THINGSPEAK_CHANNEL_ID +
                    THINGSPEAK_FEEDS_LAST + THINGSPEAK_API_KEY_STRING + "=" +
                    THINGSPEAK_API_KEY + "");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line).append("\n");
                }
                bufferedReader.close();
                return stringBuilder.toString();
            }
            finally{
                urlConnection.disconnect();
            }
        }
        catch(Exception e) {
            Log.e("ERROR", e.getMessage(), e);
            return null;
        }
    }
    protected void onPostExecute(String response) {
        if(response == null) {
            Toast.makeText(getActivity(), "There was an error", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            JSONObject channel = (JSONObject) new JSONTokener(response).nextValue();
            double v1 = channel.getDouble(THINGSPEAK_FIELD1);
            String field1 = Double.toString(v1);
            t1.setText(field1);


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

public class FetchThingspeakHumidTask extends AsyncTask<Void, Void, String> {
    protected void onPreExecute() {
        t2.setText("Fetching Data from Server.Please Wait...");
    }
    protected String doInBackground(Void... urls) {
        try {
            URL url = new URL(THINGSPEAK_CHANNEL_URL + THINGSPEAK_CHANNEL_ID +
                    THINGSPEAK_FEEDS_LAST + THINGSPEAK_API_KEY_STRING + "=" +
                    THINGSPEAK_API_KEY + "");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line).append("\n");
                }
                bufferedReader.close();
                return stringBuilder.toString();
            }
            finally{
                urlConnection.disconnect();
            }
        }
        catch(Exception e) {
            Log.e("ERROR", e.getMessage(), e);
            return null;
        }
    }
    protected void onPostExecute(String response) {
        if(response == null) {
            Toast.makeText(getActivity(), "There was an error", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            JSONObject channel = (JSONObject) new JSONTokener(response).nextValue();
            double v2 = channel.getDouble(THINGSPEAK_FIELD2);
            String field2 = Double.toString(v2);
            t2.setText(field2);

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

// fragment_monitorong.xml

fragment layout, android studio,

<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mymonitoring.MonitoringFragment">

<fragment
    android:id="@+id/fragment"
    android:name="com.example.mymonitoring.MonitoringFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</fragment>


<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_anchor="@+id/fragment"
    app:layout_anchorGravity="top|center">

    <RelativeLayout
        android:id="@+id/statsLayoutToolbar"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorOrange">


        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar_stats"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:titleTextColor="@color/colorWhite">
        </android.support.v7.widget.Toolbar>
    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/statsLayoutToolbar"
        android:orientation="horizontal"
        android:weightSum="100">


        <Button
            android:id="@+id/btnTemperature"
            android:layout_width="130dp"
            android:layout_height="70dp"
            android:layout_gravity="center"
            android:layout_weight="0"

            android:gravity="center"
            android:text="Temperature" />


        <Button
            android:id="@+id/btnHumidity"
            android:layout_width="130dp"
            android:layout_height="70dp"
            android:layout_gravity="center"
            android:layout_weight="0"

            android:gravity="center"
            android:text="Humidity" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="449dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="118dp"
        android:orientation="vertical">

        <RelativeLayout
            android:id="@+id/TemperatureLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <include layout="@layout/tempdisplay" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:orientation="vertical">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="300dp"
                    android:text="Current Temperature :"
                    android:textColor="@color/colorBlack" />

                <TextView
                    android:id="@+id/tempNumber"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="........"
                    android:textColor="@color/colorBlack" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:text="Suggestion:"
                    android:textColor="@color/colorBlack" />

                <TextView
                    android:id="@+id/suggestionTemp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="........"
                    android:textColor="@color/colorBlack" />
            </LinearLayout>
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/HumidityLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <include layout="@layout/humiddisplay" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:orientation="vertical">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="300dp"
                    android:text="Current Humidity :"
                    android:textColor="@color/colorBlack" />

                <TextView
                    android:id="@+id/humidNumber"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="........"
                    android:textColor="@color/colorBlack" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:text="Suggestion:"
                    android:textColor="@color/colorBlack" />

                <TextView
                    android:id="@+id/suggestionHumid"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="........"
                    android:textColor="@color/colorBlack" />
            </LinearLayout>
        </RelativeLayout>
    </LinearLayout>
</RelativeLayout>

// My Logcat

when i run, then click on monitoring sub menu, the app will stop and go back to the login layout

10-08 10:37:25.561 2899-2899/com.example.safwan.mymonitoring E/JavaBinder 
!!! FAILED BINDER TRANSACTION !!!

10-08 10:37:25.562 2899-2899/com.example.safwan.mymonitoring 
E/AndroidRuntime: Error reporting crash
android.os.TransactionTooLargeException
    at android.os.BinderProxy.transactNative(Native Method)
    at android.os.BinderProxy.transact(Binder.java:496)
    at android.app.ActivityManagerProxy.handleApplicationCrash(ActivityManagerNative.java:4164)
    at com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:89)
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
Faizan Mubasher
  • 4,427
  • 11
  • 45
  • 81
Mr.One
  • 5
  • 6

0 Answers0