nullPointerException with getSupportFragmentManager function - android

I need your help. I am trying to read the data from the sensors of the smart phone. That is why i tried to write some codes. After a while , i found a code on the Internet. But it does not work i do not know why. In this code , there are two pages for one to select a sensor and the other for the getting the data .
I am copying the codes here . And at the end i will tell you what the problem is.
Here is the MAIN activity code.
package com.example.sensorlistactivity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class SensorListActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sensor_main);
SensorSelectorFragment sensorSelect = (SensorSelectorFragment) getSupportFragmentManager()
.findFragmentById(R.id.frag_sensor_select);
SensorDisplayFragment sensorDisplay = (SensorDisplayFragment) getSupportFragmentManager()
.findFragmentById(R.id.frag_sensor_view);
sensorSelect.setSensorDisplay(sensorDisplay);
}
}
Here is the SENSOR SELECTOR CODE.
package com.example.sensorlistactivity;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class SensorSelectorFragment extends ListFragment {
private static final String TAG = "SensorSelectorFragment";
private SensorDisplayFragment sensorDisplay;
public void setSensorDisplay(SensorDisplayFragment sensorDisplay) {
this.sensorDisplay = sensorDisplay;
SensorManager sensorManager = (SensorManager) getActivity()
.getSystemService(Activity.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
this.setListAdapter(new SensorListAdapter(getActivity()
.getApplicationContext(), android.R.layout.simple_list_item_1,
sensors));
}
private void showSensorFragment(Sensor sensor) {
sensorDisplay.displaySensor(sensor);
FragmentTransaction ft = getActivity().getSupportFragmentManager()
.beginTransaction();
ft.hide(this);
ft.show(sensorDisplay);
ft.addToBackStack("Showing sensor: " + sensor.getName());
ft.commit();
}
private class SensorListAdapter extends ArrayAdapter<Sensor> {
public SensorListAdapter(Context context, int textViewResourceId,
List<Sensor> sensors) {
super(context, textViewResourceId, sensors);
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final Sensor selectedSensor = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
android.R.layout.simple_list_item_1, null);
}
((TextView) convertView).setText(selectedSensor.getName());
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (BuildConfig.DEBUG) {
Log.d(TAG,
"display sensor! " + selectedSensor.getName());
}
showSensorFragment(selectedSensor);
}
});
return convertView;
}
}
}
Here is the DISPLAYMENT CODE .
package com.example.sensorlistactivity;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.content.Context;
import android.hardware.Sensor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
public class SensorDisplayFragment extends Fragment implements
SensorEventListener {
private static final String TAG = "SensorDisplayFragment";
private static final String THETA = "\u0398";
private static final String ACCELERATION_UNITS = "m/s\u00B2";
private SensorManager sensorManager;
private Sensor sensor;
private TextView name;
private TextView type;
private TextView maxRange;
private TextView minDelay;
private TextView power;
private TextView resolution;
private TextView vendor;
private TextView version;
private TextView accuracy;
private TextView timestampLabel;
private TextView timestamp;
private TextView timestampUnits;
private TextView dataLabel;
private TextView dataUnits;
private TextView xAxis;
private TextView xAxisLabel;
private TextView yAxis;
private TextView yAxisLabel;
private TextView zAxis;
private TextView zAxisLabel;
private TextView singleValue;
private TextView cosLabel;
private TextView cos;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.sensor_view, null);
sensorManager = (SensorManager) getActivity().getSystemService(
Context.SENSOR_SERVICE);
name = (TextView) layout.findViewById(R.id.name);
type = (TextView) layout.findViewById(R.id.type);
maxRange = (TextView) layout.findViewById(R.id.maxRange);
minDelay = (TextView) layout.findViewById(R.id.minDelay);
power = (TextView) layout.findViewById(R.id.power);
resolution = (TextView) layout.findViewById(R.id.resolution);
vendor = (TextView) layout.findViewById(R.id.vendor);
version = (TextView) layout.findViewById(R.id.version);
accuracy = (TextView) layout.findViewById(R.id.accuracy);
timestampLabel = (TextView) layout.findViewById(R.id.timestampLabel);
timestamp = (TextView) layout.findViewById(R.id.timestamp);
timestampUnits = (TextView) layout.findViewById(R.id.timestampUnits);
dataLabel = (TextView) layout.findViewById(R.id.dataLabel);
dataUnits = (TextView) layout.findViewById(R.id.dataUnits);
xAxis = (TextView) layout.findViewById(R.id.xAxis);
xAxisLabel = (TextView) layout.findViewById(R.id.xAxisLabel);
yAxis = (TextView) layout.findViewById(R.id.yAxis);
yAxisLabel = (TextView) layout.findViewById(R.id.yAxisLabel);
zAxis = (TextView) layout.findViewById(R.id.zAxis);
zAxisLabel = (TextView) layout.findViewById(R.id.zAxisLabel);
singleValue = (TextView) layout.findViewById(R.id.singleValue);
cosLabel = (TextView) layout.findViewById(R.id.cosLabel);
cos = (TextView) layout.findViewById(R.id.cos);
layout.findViewById(R.id.delayFastest).setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
sensorManager
.unregisterListener(SensorDisplayFragment.this);
sensorManager.registerListener(
SensorDisplayFragment.this, sensor,
SensorManager.SENSOR_DELAY_FASTEST);
}
});
layout.findViewById(R.id.delayGame).setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
sensorManager
.unregisterListener(SensorDisplayFragment.this);
sensorManager.registerListener(
SensorDisplayFragment.this, sensor,
SensorManager.SENSOR_DELAY_GAME);
}
});
layout.findViewById(R.id.delayNormal).setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
sensorManager
.unregisterListener(SensorDisplayFragment.this);
sensorManager.registerListener(
SensorDisplayFragment.this, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
});
layout.findViewById(R.id.delayUi).setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
sensorManager
.unregisterListener(SensorDisplayFragment.this);
sensorManager.registerListener(
SensorDisplayFragment.this, sensor,
SensorManager.SENSOR_DELAY_UI);
}
});
return layout;
}
public void displaySensor(Sensor sensor) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "display the sensor");
}
this.sensor = sensor;
name.setText(sensor.getName());
type.setText(String.valueOf(sensor.getType()));
maxRange.setText(String.valueOf(sensor.getMaximumRange()));
// minDelay.setText(String.valueOf(sensor.getMinDelay()));
power.setText(String.valueOf(sensor.getPower()));
resolution.setText(String.valueOf(sensor.getResolution()));
vendor.setText(String.valueOf(sensor.getVendor()));
version.setText(String.valueOf(sensor.getVersion()));
sensorManager.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
switch (accuracy) {
case SensorManager.SENSOR_STATUS_ACCURACY_HIGH:
this.accuracy.setText("SENSOR_STATUS_ACCURACY_HIGH");
break;
case SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM:
this.accuracy.setText("SENSOR_STATUS_ACCURACY_MEDIUM");
break;
case SensorManager.SENSOR_STATUS_ACCURACY_LOW:
this.accuracy.setText("SENSOR_STATUS_ACCURACY_LOW");
break;
case SensorManager.SENSOR_STATUS_UNRELIABLE:
this.accuracy.setText("SENSOR_STATUS_UNRELIABLE");
break;
}
}
#Override
public void onSensorChanged(SensorEvent event) {
onAccuracyChanged(event.sensor, event.accuracy);
timestampLabel.setVisibility(View.VISIBLE);
timestamp.setVisibility(View.VISIBLE);
timestamp.setText(String.valueOf(event.timestamp));
timestampUnits.setVisibility(View.VISIBLE);
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
showEventData("Acceleration - gravity on axis", ACCELERATION_UNITS,
event.values[0], event.values[1], event.values[2]);
break;
case Sensor.TYPE_MAGNETIC_FIELD:
showEventData("Abient Magnetic Field", "uT", event.values[0],
event.values[1], event.values[2]);
break;
case Sensor.TYPE_GYROSCOPE:
showEventData("Angular speed around axis", "radians/sec",
event.values[0], event.values[1], event.values[2]);
break;
case Sensor.TYPE_LIGHT:
showEventData("Ambient light", "lux", event.values[0]);
break;
case Sensor.TYPE_PRESSURE:
showEventData("Atmospheric pressure", "hPa", event.values[0]);
break;
case Sensor.TYPE_PROXIMITY:
showEventData("Distance", "cm", event.values[0]);
break;
case Sensor.TYPE_GRAVITY:
showEventData("Gravity", ACCELERATION_UNITS, event.values[0],
event.values[1], event.values[2]);
break;
case Sensor.TYPE_LINEAR_ACCELERATION:
showEventData("Acceleration (not including gravity)",
ACCELERATION_UNITS, event.values[0], event.values[1],
event.values[2]);
break;
case Sensor.TYPE_ROTATION_VECTOR:
showEventData("Rotation Vector", null, event.values[0],
event.values[1], event.values[2]);
xAxisLabel.setText("x*sin(" + THETA + "/2)");
yAxisLabel.setText("y*sin(" + THETA + "/2)");
zAxisLabel.setText("z*sin(" + THETA + "/2)");
if (event.values.length == 4) {
cosLabel.setVisibility(View.VISIBLE);
cos.setVisibility(View.VISIBLE);
cos.setText(String.valueOf(event.values[3]));
}
break;
case Sensor.TYPE_ORIENTATION:
showEventData("Angle", "Degrees", event.values[0], event.values[1],
event.values[2]);
xAxisLabel.setText(R.string.azimuthLabel);
yAxisLabel.setText(R.string.pitchLabel);
zAxisLabel.setText(R.string.rollLabel);
break;
case Sensor.TYPE_RELATIVE_HUMIDITY:
showEventData("Relatice ambient air humidity", "%", event.values[0]);
break;
case Sensor.TYPE_AMBIENT_TEMPERATURE:
showEventData("Ambien temperature", "degree Celcius",
event.values[0]);
break;
}
}
private void showEventData(String label, String units, float x, float y,
float z) {
dataLabel.setVisibility(View.VISIBLE);
dataLabel.setText(label);
if (units == null) {
dataUnits.setVisibility(View.GONE);
} else {
dataUnits.setVisibility(View.VISIBLE);
dataUnits.setText("(" + units + "):");
}
singleValue.setVisibility(View.GONE);
xAxisLabel.setVisibility(View.VISIBLE);
xAxisLabel.setText(R.string.xAxisLabel);
xAxis.setVisibility(View.VISIBLE);
xAxis.setText(String.valueOf(x));
yAxisLabel.setVisibility(View.VISIBLE);
yAxisLabel.setText(R.string.yAxisLabel);
yAxis.setVisibility(View.VISIBLE);
yAxis.setText(String.valueOf(y));
zAxisLabel.setVisibility(View.VISIBLE);
zAxisLabel.setText(R.string.zAxisLabel);
zAxis.setVisibility(View.VISIBLE);
zAxis.setText(String.valueOf(z));
}
private void showEventData(String label, String units, float value) {
dataLabel.setVisibility(View.VISIBLE);
dataLabel.setText(label);
dataUnits.setVisibility(View.VISIBLE);
dataUnits.setText("(" + units + "):");
singleValue.setVisibility(View.VISIBLE);
singleValue.setText(String.valueOf(value));
xAxisLabel.setVisibility(View.GONE);
xAxis.setVisibility(View.GONE);
yAxisLabel.setVisibility(View.GONE);
yAxis.setVisibility(View.GONE);
zAxisLabel.setVisibility(View.GONE);
zAxis.setVisibility(View.GONE);
}
#Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (hidden) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Unregistering listener");
}
sensorManager.unregisterListener(this);
}
}
#Override
public void onPause() {
super.onPause();
if (BuildConfig.DEBUG) {
Log.d(TAG, "onPause");
Log.d(TAG, "Unregistering listener");
}
sensorManager.unregisterListener(this);
}
}
Here is the problem : when I run this code , there is nullPointerExpection .
In the main activity , "sensorSelect" and "sensorDisplay" are null. In other words , this part does not work.
SensorSelectorFragment sensorSelect = (SensorSelectorFragment) getSupportFragmentManager()
.findFragmentById(R.id.frag_sensor_select);
SensorDisplayFragment sensorDisplay = (SensorDisplayFragment) getSupportFragmentManager()
.findFragmentById(R.id.frag_sensor_view);
Why is that so ?
Also i am using two layout .xml file . one of them sensor_main which is called by main code and the other one is sensor_view .
I am putting these codes also here , there could be a problem also with these since i do not understand how could it be possible two layout xml files.
SENSOR_MAIN.XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<fragment
android:id="#+id/frag_sensor_select"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="root.gast.playground.sensor.SensorSelectorFragment" />
<fragment
android:id="#+id/frag_sensor_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="root.gast.playground.sensor.SensorDisplayFragment" />
</LinearLayout>
SENSOR_VIEW.XML
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RadioGroup android:id="#+id/sensorRateSelector"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true" >
<RadioButton android:id="#+id/delayFastest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SENSOR_DELAY_FASTEST"
android:checked="false"/>
<RadioButton android:id="#+id/delayGame"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SENSOR_DELAY_GAME"
android:checked="false"/>
<RadioButton android:id="#+id/delayNormal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SENSOR_DELAY_NORMAL"
android:checked="true"/>
<RadioButton android:id="#+id/delayUi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SENSOR_DELAY_UI"
android:checked="false"/>
</RadioGroup>
<View android:id="#+id/seperator"
style="#style/line_separator"
android:layout_below="#id/sensorRateSelector" />
<TextView android:id="#+id/nameLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/seperator"
android:layout_alignParentLeft="true"
android:text="Name:"
android:layout_marginRight="5dip" />
<TextView android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/nameLabel"
android:layout_alignTop="#id/nameLabel"
android:layout_alignBottom="#id/nameLabel" />
<TextView android:id="#+id/typeLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/nameLabel"
android:layout_below="#id/nameLabel"
android:text="Type:"
android:layout_marginRight="5dip" />
<TextView android:id="#+id/type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/typeLabel"
android:layout_alignTop="#id/typeLabel"
android:layout_alignBottom="#id/typeLabel"/>
<TextView android:id="#+id/maxRangeLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/nameLabel"
android:layout_below="#id/typeLabel"
android:text="Max Range:"
android:layout_marginRight="5dip" />
<TextView android:id="#+id/maxRange"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/maxRangeLabel"
android:layout_alignTop="#id/maxRangeLabel"
android:layout_alignBottom="#id/maxRangeLabel"/>
<TextView android:id="#+id/minDelayLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/maxRangeLabel"
android:layout_below="#id/maxRangeLabel"
android:text="Min Delay:"
android:layout_marginRight="5dip" />
<TextView android:id="#+id/minDelay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/minDelayLabel"
android:layout_alignTop="#id/minDelayLabel"
android:layout_alignBottom="#id/minDelayLabel"/>
<TextView android:id="#+id/powerLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/minDelayLabel"
android:layout_below="#id/minDelayLabel"
android:text="Power:"
android:layout_marginRight="5dip" />
<TextView android:id="#+id/power"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/powerLabel"
android:layout_alignTop="#id/powerLabel"
android:layout_alignBottom="#id/powerLabel"
android:layout_marginRight="5dip"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/power"
android:layout_alignTop="#id/power"
android:layout_alignBottom="#id/power"
android:text="mA"/>
<TextView android:id="#+id/resolutionLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/powerLabel"
android:layout_below="#id/powerLabel"
android:text="Resolution:"
android:layout_marginRight="5dip" />
<TextView android:id="#+id/resolution"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/resolutionLabel"
android:layout_alignTop="#id/resolutionLabel"
android:layout_alignBottom="#id/resolutionLabel"/>
<TextView android:id="#+id/vendorLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/resolutionLabel"
android:layout_below="#id/resolutionLabel"
android:text="Vendor:"
android:layout_marginRight="5dip" />
<TextView android:id="#+id/vendor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/vendorLabel"
android:layout_alignTop="#id/vendorLabel"
android:layout_alignBottom="#id/vendorLabel"/>
<TextView android:id="#+id/versionLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/versionLabel"
android:layout_alignLeft="#id/vendorLabel"
android:layout_below="#id/vendorLabel"
android:text="Version:"
android:layout_marginRight="5dip" />
<TextView android:id="#+id/version"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/versionLabel"
android:layout_alignTop="#id/versionLabel"
android:layout_alignBottom="#id/versionLabel"/>
<TextView android:id="#+id/accuracyLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/versionLabel"
android:layout_below="#id/versionLabel"
android:text="Accuracy:"
android:layout_marginRight="5dip" />
<TextView android:id="#+id/accuracy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/accuracyLabel"
android:layout_alignTop="#id/accuracyLabel"
android:layout_alignBottom="#id/accuracyLabel"/>
<!-- timestamp -->
<TextView android:id="#+id/timestampLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/accuracyLabel"
android:layout_below="#id/accuracyLabel"
android:layout_marginRight="5dip"
android:text="Timestamp:" />
<TextView android:id="#+id/timestamp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/timestampLabel"
android:layout_alignTop="#id/timestampLabel"
android:layout_alignBottom="#id/timestampLabel"
android:layout_marginRight="5dip"
android:visibility="gone" />
<TextView android:id="#+id/timestampUnits"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/timestamp"
android:layout_alignTop="#id/timestamp"
android:layout_alignBottom="#id/timestamp"
android:visibility="gone"
android:text="(ns)" />
<TextView android:id="#+id/dataLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/accuracyLabel"
android:layout_below="#id/timestampLabel"
android:layout_marginRight="5dip"
android:visibility="gone"/>
<TextView android:id="#+id/dataUnits"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/dataLabel"
android:layout_alignTop="#id/dataLabel"
android:layout_alignBottom="#id/dataLabel"
android:visibility="gone" />
<TextView android:id="#+id/singleValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/dataUnits"
android:layout_alignTop="#id/dataUnits"
android:layout_alignBottom="#id/dataUnits"
android:visibility="gone" />
<!-- X axis -->
<TextView android:id="#+id/xAxisLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/dataLabel"
android:layout_below="#id/dataLabel"
android:layout_marginRight="5dip"
android:visibility="gone"
android:text="#string/xAxisLabel" />
<TextView android:id="#+id/xAxis"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/xAxisLabel"
android:layout_alignTop="#id/xAxisLabel"
android:layout_alignBottom="#id/xAxisLabel"
android:layout_marginRight="5dip"
android:visibility="gone" />
<!-- Y axis -->
<TextView android:id="#+id/yAxisLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/xAxisLabel"
android:layout_below="#id/xAxisLabel"
android:layout_marginRight="5dip"
android:visibility="gone"
android:text="#string/yAxisLabel" />
<TextView android:id="#+id/yAxis"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/yAxisLabel"
android:layout_alignTop="#id/yAxisLabel"
android:layout_alignBottom="#id/yAxisLabel"
android:layout_marginRight="5dip"
android:visibility="gone" />
<!-- Z axis -->
<TextView android:id="#+id/zAxisLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/yAxisLabel"
android:layout_below="#id/yAxisLabel"
android:layout_marginRight="5dip"
android:visibility="gone"
android:text="#string/zAxisLabel" />
<TextView android:id="#+id/zAxis"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/zAxisLabel"
android:layout_alignTop="#id/zAxisLabel"
android:layout_alignBottom="#id/zAxisLabel"
android:layout_marginRight="5dip"
android:visibility="gone" />
<!-- cos value (for rotation vector only) -->
<TextView android:id="#+id/cosLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/zAxisLabel"
android:layout_below="#id/zAxisLabel"
android:layout_marginRight="5dip"
android:visibility="gone"
android:text="cos(\u0398/2):" />
<TextView android:id="#+id/cos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/cosLabel"
android:layout_alignTop="#id/cosLabel"
android:layout_alignBottom="#id/cosLabel"
android:layout_marginRight="5dip"
android:visibility="gone" />
</RelativeLayout>
</ScrollView>

Without seeing your manifest, I cannot answer this 100%, but I think what is going on is the app cannot build the display because it cannot reference your Sensor Fragments. Here is your package declaration for SensorDisplayFragment:
package com.example.sensorlistactivity;
so to use then in an xml file, you should have this as your class:
class="com.example.sensorlistactivity.SensorDisplayFragment" />

Related

How to create nested child on firebase android

[Solved. I solved it myself]
Tips: if you want to access a child in the firebase realtime database for collecting data and then by using that data u store or upload something at that child on the firebase realtime database again, then you can't access it. Either u have to create another child or u must not use that child. (I don't no the actual solution but It works for me)]
I want to create a child under the reference of the user phone number. That child will store one or more childs. These child will be called "serialNo" of the item. And under serialNo child, the item name and amount of piece will store. I want to create like this:
[N: B: I've created this on firebase directly, not by my application.]
But when I put my data object as .setValue(dtObject) the previous one will always be replaced.
"orderNo: 1" child was replaced by "orderNo: 2" child
I also use .updateChildren(dtMap) but everytime previous orderNo child was replaced.
My Code of confirm Fragment(from where I upload):
package com.binarysoftwareltd.airaid;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
import java.util.Map;
public class AddressFragment extends Fragment {
private int orderNo = 1;
private int orderSerial = 0;
private DatabaseReference dbReference, dbr;
private static final String STATE_USER = "user";
private String mUser;
private View oldView;
private TextView numWarning;
private EditText nameField, phoneField, areaField, addressField,
detailsField;
private CardView confirmCV;
private int len;
private String nameOfPerson, phoneNumber, areaName, addressOfOrder,
detailsOfOrder;
private int[] serialNos = new int[100];
private String[] names = new String[100];
private int[] pieces = new int[100];
private String imageUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mUser = savedInstanceState.getString(STATE_USER);
} else {
// Probably initialize members with default values for a new
instance
mUser = "NewUser";
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(STATE_USER, mUser);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
if (oldView != null) {
return oldView;
}
View v = inflater.inflate(R.layout.fragment_address, container,
false);
initializeAll(v);
Bundle bundle = getArguments();
if (bundle != null) {
len = bundle.getInt("cValue");
imageUri = bundle.getString("imgUri");
serialNos = bundle.getIntArray("mSerialNos");
names = bundle.getStringArray("mNames");
pieces = bundle.getIntArray("mPieces");
}
confirmCV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
collectAllData();
if (!phoneNumber.equals("")) {
checkOrderSerial();
} else {
phoneField.requestFocus();
Toast.makeText(getContext(), orderSerial,
Toast.LENGTH_SHORT).show();
}
}
});
oldView = v;
return v;
}
private void checkOrderSerial() {
dbr=FirebaseDatabase.getInstance().getReference(phoneNumber).
child("currentOrderSerial");
dbr.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Integer value = dataSnapshot.getValue(Integer.class);
if (value != null)
orderSerial = value;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
showConfirmDialog();
}
private void showConfirmDialog() {
AlertDialog.Builder alb = new AlertDialog.Builder(getContext());
alb.setIcon(R.drawable.question);
alb.setTitle("Confirm");
alb.setMessage("Are you sure want to order?");
alb.setPositiveButton(R.string.exit_no, new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alb.setNegativeButton(R.string.exit_yes, new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
setOrderSerial();
}
});
AlertDialog ald = alb.create();
ald.show();
}
private void setOrderSerial() {
dbr = FirebaseDatabase.getInstance().getReference(phoneNumber);
if (orderNo <= orderSerial) {
orderNo = orderSerial;
orderNo += 1;
}
OrderSerial osObject = new OrderSerial(orderNo);
dbr.setValue(osObject);
uploadAllData();
}
private void uploadAllData() {
dbReference =
FirebaseDatabase.getInstance().getReference(phoneNumber).child("orderNo:
"+orderNo);
DataTemplate dtObject;
int i;
for (i = 0; i < len; i++) {
if (pieces[i] != 0) {
dtObject = new DataTemplate(names[i],pieces[i]);
dbReference.child("serialNo:
"+serialNos[i]).setValue(dtObject);
}
}
}
private void collectAllData() {
nameOfPerson = nameField.getText().toString();
phoneNumber = phoneField.getText().toString();
areaName = areaField.getText().toString();
addressOfOrder = addressField.getText().toString();
detailsOfOrder = detailsField.getText().toString();
}
private void initializeAll(View v) {
numWarning = v.findViewById(R.id.numWarning);
nameField = v.findViewById(R.id.nameField);
phoneField = v.findViewById(R.id.phoneField);
areaField = v.findViewById(R.id.areaField);
addressField = v.findViewById(R.id.addressField);
detailsField = v.findViewById(R.id.detailsField);
confirmCV = v.findViewById(R.id.confirmCV);
}
}
My OrderSerial Class::
package com.binarysoftwareltd.airaid;
public class OrderSerial {
private int currentOrderSerial;
public OrderSerial() {
}
public OrderSerial(int currentOrderSerial) {
this.currentOrderSerial = currentOrderSerial;
}
public int getCurrentOrderSerial() {
return currentOrderSerial;
}
public void setCurrentOrderSerial(int currentOrderSerial) {
this.currentOrderSerial = currentOrderSerial;
}
}
The XML code of the AddressFragment:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/app_main_bg"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="120dp"
android:text="#string/address_fragment_title"
android:textColor="#color/pureBlack"
android:textSize="25sp"
android:textStyle="bold" />
<TextView
android:gravity="center"
android:id="#+id/numWarning"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="15dp"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:text="#string/number_warning"
android:textColor="#color/img_warning"
android:textSize="15sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="15dp"
android:gravity="center_vertical"
android:weightSum="8"
android:orientation="horizontal">
<ImageView
android:contentDescription="#string/name_field"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:src="#drawable/ic_person"/>
<EditText
android:id="#+id/nameField"
android:layout_marginStart="5dp"
android:layout_width="0dp"
android:layout_weight="7"
android:layout_height="70dp"
android:hint="#string/name_field" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="15dp"
android:gravity="center_vertical"
android:weightSum="8"
android:orientation="horizontal">
<ImageView
android:contentDescription="#string/phone_field"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:src="#drawable/ic_phone"/>
<EditText
android:id="#+id/phoneField"
android:layout_marginStart="5dp"
android:inputType="phone"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="4"
android:hint="#string/phone_field" />
<EditText
android:id="#+id/areaField"
android:layout_marginStart="10dp"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="3"
android:hint="#string/area_field" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="15dp"
android:gravity="center_vertical"
android:weightSum="8"
android:orientation="horizontal">
<ImageView
android:contentDescription="#string/address_fragment_title"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:src="#drawable/ic_location"/>
<EditText
android:id="#+id/addressField"
android:layout_marginStart="5dp"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="7"
android:hint="#string/address_fragment_title" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="15dp"
android:gravity="center_vertical"
android:weightSum="8"
android:orientation="horizontal">
<ImageView
android:contentDescription="#string/details_field"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:src="#drawable/ic_details"/>
<EditText
android:id="#+id/detailsField"
android:layout_marginStart="5dp"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="7"
android:hint="#string/details_field" />
</LinearLayout>
<androidx.cardview.widget.CardView
android:id="#+id/confirmCV"
android:layout_width="match_parent"
android:layout_height="40dp"
android:clickable="true"
android:focusable="true"
android:layout_marginStart="15dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="15dp"
app:cardCornerRadius="18dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/card_view_bg"
android:gravity="center">
<ImageView
android:contentDescription="#string/order_now"
android:layout_width="30dp"
android:layout_height="30dp"
android:src="#drawable/ic_confirm" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:text="#string/order_now"
android:textColor="#color/pureWhite"
android:textSize="18sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
</ScrollView>
here my JSON::
{
"23" : {
"currentOrderSerial" : 2,
"orderNo: 2" : {
"serialNo: 1" : {
"name" : "napa Extra",
"piece" : 200
}
}
}
}
[I use phone number as primary Identifier for every user. That's why phone numbers must be required.]
Please help to fix this...
Thanks in Advance...

Android: disable button when TextView match value

I am learning android and here struggling to disable the button id btnWicketIndia when TextView id wicketsIndiaText has " \ 10 " value.
Also please tell me the way I write code is correct or can optimize.
MainActivity.java
package me.jatinsoni.cricketscorecard;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
int scoreIndia = 0;
int wicketsIndia = 0;
int scoreSA = 0;
int wicketsSA = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// India Buttons
Button btnSixerIndia = findViewById(R.id.sixerIndia);
Button btnFourIndia = findViewById(R.id.fourIndia);
Button btnSingleIndia = findViewById(R.id.singleIndia);
Button btnTwoIndia = findViewById(R.id.twoIndia);
Button btnNoIndia = findViewById(R.id.noIndia);
Button btnWideIndia = findViewById(R.id.wideIndia);
Button btnWicketIndia = findViewById(R.id.wicketIndia);
// South Africa Buttons
Button btnSixerSA = findViewById(R.id.sixerSA);
Button btnFourSA = findViewById(R.id.fourSA);
Button btnSingleSA = findViewById(R.id.singleSA);
Button btnTwoSA = findViewById(R.id.twoSA);
Button btnNoSA = findViewById(R.id.noSA);
Button btnWideSA = findViewById(R.id.wideSA);
Button btnWicketSA = findViewById(R.id.wicketSA);
// Reset button
Button btnResetScore = findViewById(R.id.resetScore);
btnSixerIndia.setOnClickListener(this);
btnFourIndia.setOnClickListener(this);
btnSingleIndia.setOnClickListener(this);
btnTwoIndia.setOnClickListener(this);
btnNoIndia.setOnClickListener(this);
btnWideIndia.setOnClickListener(this);
btnWicketIndia.setOnClickListener(this);
btnSixerSA.setOnClickListener(this);
btnFourSA.setOnClickListener(this);
btnSingleSA.setOnClickListener(this);
btnTwoSA.setOnClickListener(this);
btnNoSA.setOnClickListener(this);
btnWideSA.setOnClickListener(this);
btnWicketSA.setOnClickListener(this);
btnResetScore.setOnClickListener(this);
displayScoreIndia(scoreIndia, wicketsIndia);
displayScoreSA(scoreSA, wicketsSA);
}
#Override
public void onClick(View v) {
// Get Buttons IDs
switch (v.getId()) {
// India Buttons
case R.id.sixerIndia: {
scoreIndia += 6;
displayScoreIndia(scoreIndia, wicketsIndia);
break;
}
case R.id.fourIndia: {
scoreIndia += 4;
displayScoreIndia(scoreIndia, wicketsIndia);
break;
}
case R.id.singleIndia: {
scoreIndia += 1;
displayScoreIndia(scoreIndia, wicketsIndia);
break;
}
case R.id.twoIndia: {
scoreIndia += 2;
displayScoreIndia(scoreIndia, wicketsIndia);
break;
}
case R.id.noIndia: {
scoreIndia += 1;
displayScoreIndia(scoreIndia, wicketsIndia);
break;
}
case R.id.wideIndia: {
scoreIndia += 1;
displayScoreIndia(scoreIndia, wicketsIndia);
break;
}
case R.id.wicketIndia: {
if (String.valueOf(wicketsIndia).equals(" / 10")) {
btnWicketIndia.setEnabled(false);
}
wicketsIndia += 1;
displayScoreIndia(scoreIndia, wicketsIndia);
break;
}
// South Africa Buttons
case R.id.sixerSA: {
scoreSA += 6;
displayScoreSA(scoreSA, wicketsSA);
break;
}
case R.id.fourSA: {
scoreSA += 4;
displayScoreSA(scoreSA, wicketsSA);
break;
}
case R.id.singleSA: {
scoreSA += 1;
displayScoreSA(scoreSA, wicketsSA);
break;
}
case R.id.twoSA: {
scoreSA += 2;
displayScoreSA(scoreSA, wicketsSA);
break;
}
case R.id.noSA: {
scoreSA += 1;
displayScoreSA(scoreSA, wicketsSA);
break;
}
case R.id.wideSA: {
scoreSA += 1;
displayScoreSA(scoreSA, wicketsSA);
break;
}
case R.id.wicketSA: {
wicketsSA += 1;
displayScoreSA(scoreSA, wicketsSA);
break;
}
case R.id.resetScore: {
scoreIndia = 0;
scoreSA = 0;
wicketsIndia = 0;
wicketsSA = 0;
displayScoreIndia(scoreIndia, wicketsIndia);
displayScoreSA(scoreSA, wicketsSA);
break;
}
}
}
#SuppressLint("SetTextI18n")
public void displayScoreIndia(int score, int wickets) {
TextView scoreIndiaText = findViewById(R.id.scoreIndiaText);
TextView wicketsIndiaText = findViewById(R.id.wicketsIndiaText);
scoreIndiaText.setText(String.valueOf(score));
wicketsIndiaText.setText(" / " + String.valueOf(wickets));
}
#SuppressLint("SetTextI18n")
public void displayScoreSA(int score, int wickets) {
TextView scoreSAText = findViewById(R.id.scoreSAText);
TextView wicketsSAText = findViewById(R.id.wicketsSAText);
scoreSAText.setText(String.valueOf(score));
wicketsSAText.setText(" / " + String.valueOf(wickets));
}
}
XML Code
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="#drawable/cricketground" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#99000000">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<!-- INDIA COLUMN -->
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:layout_marginTop="16dp"
android:src="#drawable/ic_india" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="INDIA"
android:textColor="#FFFFFF"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginBottom="32dp"
android:gravity="center_horizontal">
<TextView
android:id="#+id/scoreIndiaText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="40sp"
android:fontFamily="sans-serif-thin"
android:textColor="#FFFFFF"/>
<TextView
android:id="#+id/wicketsIndiaText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" / 0"
android:textSize="20sp"
android:fontFamily="sans-serif-thin"
android:textColor="#FFFFFF"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<Button
android:id="#+id/sixerIndia"
style="#style/CircleButton"
android:text="Sixer"/>
<Button
android:id="#+id/fourIndia"
style="#style/CircleButton"
android:text="Four"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<Button
android:id="#+id/singleIndia"
style="#style/CircleButton"
android:text="Single"/>
<Button
android:id="#+id/twoIndia"
style="#style/CircleButton"
android:text="Two"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<Button
android:id="#+id/noIndia"
style="#style/CircleButton"
android:text="No"/>
<Button
android:id="#+id/wideIndia"
style="#style/CircleButton"
android:text="Wide"/>
</LinearLayout>
<Button
android:id="#+id/wicketIndia"
style="#style/RoundedButtons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp"
android:layout_gravity="center_horizontal"
android:text="wicket" />
</LinearLayout>
<!-- PARTITION -->
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#33FFFFFF" />
<!--SOUTH AFRICA COLUMN -->
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:layout_marginTop="16dp"
android:src="#drawable/ic_south_africa" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SOUTH AFRICA"
android:textColor="#FFFFFF"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginBottom="32dp"
android:gravity="center_horizontal">
<TextView
android:id="#+id/scoreSAText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="40sp"
android:fontFamily="sans-serif-thin"
android:textColor="#FFFFFF"/>
<TextView
android:id="#+id/wicketsSAText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" / 0"
android:textSize="20sp"
android:fontFamily="sans-serif-thin"
android:textColor="#FFFFFF"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<Button
android:id="#+id/sixerSA"
style="#style/CircleButton"
android:text="Sixer"/>
<Button
android:id="#+id/fourSA"
style="#style/CircleButton"
android:text="Four"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<Button
android:id="#+id/singleSA"
style="#style/CircleButton"
android:text="Single"/>
<Button
android:id="#+id/twoSA"
style="#style/CircleButton"
android:text="Two"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<Button
android:id="#+id/noSA"
style="#style/CircleButton"
android:text="No"/>
<Button
android:id="#+id/wideSA"
style="#style/CircleButton"
android:text="Wide"/>
</LinearLayout>
<Button
android:id="#+id/wicketSA"
style="#style/RoundedButtons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp"
android:layout_gravity="center_horizontal"
android:text="wicket" />
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/resetScore"
style="?android:attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="reset"
android:textColor="#FFFFFF"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
</FrameLayout>
</RelativeLayout>
You are comparing int. So just use
if (wicketsIndia == 10) {
btnWicketIndia.setEnabled(false);
}
EDIT:
int wicketsSA = 0;
Button btnWicketIndia; // DECLARE IT HERE
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
btnWicketIndia = findViewById(R.id.wicketIndia); // ASSIGN HERE
...
}
I'd have a look at the pattern you have chosen.
Use a ViewModel to hold the scores and wickets of the "home team" and the "away team".
Make some observers of the data in your activity/widget and respond to the changes.
You will need to add Google's/Android dependency to your App Gradle file:
// ViewModel and LiveData
implementation "android.arch.lifecycle:extensions:1.1.1"
Here is an example showing a ViewModel and an Activity using an observer like pattern:
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.view.View;
//Extend FRAGMENT ACTIVITY
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get handle on the ViewModel:
final ViewModelMain viewModelMain = ViewModelProviders.of(this).get(ViewModelMain.class);
//Observe the data in the viewmodel class:
viewModelMain.homeWickets.observe(this, new Observer<Integer>() {
#Override
public void onChanged(#Nullable Integer integer) {
//MAKE CHANGES WHEN THE VALUE FOR THE HOME WICKETS CHANGE LIKE SET ON CLICK METHODS TO NULL?
}
});
viewModelMain.homeScore.observe(this, new Observer<Integer>() {
#Override
public void onChanged(#Nullable Integer integer) {
//MAKE CHANGES WHEN THE VALUE FOR THE HOME SCORE CHANGE LIKE SET ON CLICK METHODS TO NULL?
}
});
//HOW TO SET A VIEW MODEL VALUE LIKE AFTER CLICKING A BUTTON:
View v = new View(getApplicationContext());
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewModelMain.setHomeScore(viewModelMain.getHomeScore().getValue() + 1);
}
});
}
}
import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.MutableLiveData;
import android.support.annotation.NonNull;
public class ViewModelMain extends AndroidViewModel {
public ViewModelMain(#NonNull Application application) {
super(application);
// Set all values to 0 when constructed?
this.awayScore.postValue(0);
this.homeScore.postValue(0);
this.homeWickets.postValue(0);
this.awayWickets.postValue(0);
}
public MutableLiveData<Integer> awayScore = new MutableLiveData<>();
public MutableLiveData<Integer> homeScore = new MutableLiveData<>();
public MutableLiveData<Integer> homeWickets = new MutableLiveData<>();
public MutableLiveData<Integer> awayWickets = new MutableLiveData<>();
//SETTERS -> POST THE DATA TO THE MUTABLE FIELDS
public void setAwayScore(Integer awayScore) {
this.awayScore.postValue(awayScore);
}
public void setAwayWickets(Integer awayWickets) {
this.awayWickets.postValue(awayWickets);
}
public void setHomeScore(Integer homeScore) {
this.homeScore.postValue(homeScore);
}
public void setHomeWickets(Integer homeWickets) {
this.homeWickets.postValue(homeWickets);
}
//STANDARD JAVA GETTERS
public MutableLiveData<Integer> getAwayScore() {
return awayScore;
}
public MutableLiveData<Integer> getAwayWickets() {
return awayWickets;
}
public MutableLiveData<Integer> getHomeScore() {
return homeScore;
}
public MutableLiveData<Integer> getHomeWickets() {
return homeWickets;
}
}
\ is a special character. So if you get a text that contains \, you must add \ before.
if (wicketsIndiaText.getText().toString().equals(" \\ 10 ")) {
btnWicketIndia.setEnabled(false);
}

passing edittext values to another activity getting null values

here's my sample task app, I have six clases Employee, Department, EmployeeActivity , ViewEmployeeInfo, ViewDepartmentInfo,
When user click on add employee it must be navigate to EmployeeActivity, and the same thing when click on department it's navigate to Department class, I created an employee object on EmployeeActivity to send it to ViewEmployeeInfo activity and it must view it on the five EditText that I created it, the problem is that when I Click on Submit button to send data via Intent with putExtra method that takes Serializable object I see no values on EditTexts on anther activity, I tried to send it with regual putExtra method as int,String,String,double,String also got NullPointerException
Here's my code, first this the Employee class
package com.companyactivityexample.companyactivityexample;
import android.widget.Button;
import android.widget.EditText;
import java.io.Serializable;
/**
* Created by MML on 24/12/2017.
*/
public class Employee implements Serializable {
private int id;
private String name;
private String address;
private double salary;
private String job;
public Employee(int id, String name, String address, double salary, String job) {
this.id = id;
this.name = name;
this.address = address;
this.salary = salary;
this.job = job;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
this activity_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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.companyactivityexample.companyactivityexample.MainActivity"
android:orientation="vertical"
>
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_marginStart="40dp"
android:layout_marginEnd="40dp"
android:layout_marginBottom="10dp"
android:text="Add employee"
android:textSize="25sp"
android:textAllCaps="false"
/>
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="40dp"
android:layout_marginEnd="40dp"
android:text="Add department"
android:textSize="25sp"
android:textAllCaps="false"
/>
</LinearLayout>
and this Main Class
`package com.companyactivityexample.companyactivityexample;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button addEmployee;
private Button addDepartment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addEmployee = (Button) findViewById(R.id.button1);
addDepartment = (Button) findViewById(R.id.button2);
addEmployee.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,EmployeeActivity.class);
startActivity(i);
}
});
addDepartment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,Department.class);
startActivity(i);
}
});
}
}
the employee_activity xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
>
<EditText
android:id="#+id/empID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:gravity="center"
android:hint="ID"
android:textSize="25sp"
android:textColorHint="#color/black"
android:inputType="number"
/>
<EditText
android:id="#+id/empName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:gravity="center"
android:hint="Name"
android:textSize="25sp"
android:textColorHint="#color/black"
android:inputType="text"
/>
<EditText
android:id="#+id/empAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:gravity="center"
android:hint="Address"
android:textSize="25sp"
android:textColorHint="#color/black"
android:inputType="text"
/>
<EditText
android:id="#+id/empSalary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:gravity="center"
android:hint="Salary"
android:textSize="25sp"
android:textColorHint="#color/black"
android:inputType="numberDecimal"
/>
<EditText
android:id="#+id/empJob"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:gravity="center"
android:hint="Job"
android:textSize="25sp"
android:textColorHint="#color/black"
android:inputType="text"
/>
<Button
android:id="#+id/submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="40dp"
android:layout_marginEnd="40dp"
android:text="Submit"
android:textSize="25sp"
android:textAllCaps="false"
/>
</LinearLayout>
</ScrollView>
the EmployeeActivity class
package com.companyactivityexample.companyactivityexample;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
/**
* Created by MML on 27/12/2017.
*/
public class EmployeeActivity extends AppCompatActivity {
private EditText editTextID;
private EditText editTextName;
private EditText editTextAddress;
private EditText editTextSalary;
private EditText editTextJob;
private Button submitButton;
private Employee employee1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.employee_activity);
editTextID = (EditText) findViewById(R.id.empID);
editTextName = (EditText) findViewById(R.id.empName);
editTextAddress = (EditText) findViewById(R.id.empAddress);
editTextSalary = (EditText) findViewById(R.id.empSalary);
editTextJob = (EditText) findViewById(R.id.empJob);
submitButton = (Button) findViewById(R.id.submit);
if(isEmpty(editTextID) || isEmpty(editTextSalary)){
editTextID.setText("0");
editTextSalary.setText("0");
}
employee1 = new Employee(Integer.parseInt(editTextID.getText().toString())
, editTextName.getText().toString(), editTextAddress.getText().toString()
, Double.parseDouble(editTextSalary.getText().toString())
, editTextJob.getText().toString());
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(EmployeeActivity.this, ViewEmployeeInfo.class);
i.putExtra("emp",employee1);
startActivity(i);
}
});
}
/*i.putExtra("id",id);
i.putExtra("name",name);
i.putExtra("address",address);
i.putExtra("salary",salary);
i.putExtra("job",job);*/
private static boolean isEmpty(EditText etText) {
if (etText.getText().toString().trim().length() > 0)
return false;
return true;
}
}
the view_employee_info activity xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:fillViewport="true"
tools:context=".ViewEmployeeInfo">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:gravity="center"
android:text="ID"
android:textColor="#color/black"
android:textSize="25sp"
/>
<EditText
android:id="#+id/editTextID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:inputType="number" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:gravity="center"
android:text="Name"
android:textColor="#color/black"
android:textSize="25sp"
/>
<EditText
android:id="#+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:gravity="center"
android:text="Address"
android:textColor="#color/black"
android:textSize="25sp"
/>
<EditText
android:id="#+id/editTextAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:gravity="center"
android:text="Salary"
android:textColor="#color/black"
android:textSize="25sp"
/>
<EditText
android:id="#+id/editTextSalary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:inputType="numberDecimal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:gravity="center"
android:text="Job"
android:textColor="#color/black"
android:textSize="25sp"
/>
<EditText
android:id="#+id/editTextJob"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp" />
</LinearLayout>
<Button
android:id="#+id/editButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="30dp"
android:layout_marginStart="30dp"
android:layout_marginTop="20dp"
android:text="Edit"
android:textAllCaps="false"
android:textSize="25sp" />
</LinearLayout>
</ScrollView>
the ViewEmployeeInfo class
package com.companyactivityexample.companyactivityexample;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* Created by MML on 24/12/2017.
*/
public class ViewEmployeeInfo extends AppCompatActivity {
private EditText editID;
private EditText editName;
private EditText editAddress;
private EditText editSalary;
private EditText editJob;
private Button editButton;
private Employee employee;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_employee_info);
Intent i = getIntent();
employee = (Employee) i.getSerializableExtra("emp");
editID = (EditText) findViewById(R.id.editTextID);
editID.setText(employee.getId() + "");
editName = (EditText) findViewById(R.id.editTextName);
editName.setText(employee.getName());
editAddress = (EditText) findViewById(R.id.editTextAddress);
editAddress.setText(employee.getAddress());
editSalary = (EditText) findViewById(R.id.editTextSalary);
editSalary.setText(employee.getSalary() + "");
editJob = (EditText) findViewById(R.id.editTextJob);
editJob.setText(employee.getJob());
editButton = (Button) findViewById(R.id.editButton);
/*Intent i = getIntent();
int getID = i.getIntExtra("id", 0);
String getName = i.getStringExtra("name");
String getAddress = i.getStringExtra("address");
double getSalary = i.getDoubleExtra("salary", 0.0);
String getJob = i.getStringExtra("job");
editID.setText(getID);
editName.setText(getName);
editAddress.setText(getAddress);
editSalary.setText(getSalary + "");
editJob.setText(getJob);*/
}
}
You put the extra in with key of "emp1" and are trying to retrieve it using a key of "emp" in getSerializableExtra("emp"). Simple typo.
Edit: Not a typo. Instead of putExtra("emp", employee1) , cast like putExtra("emp", (serializable) employee1)
Pass the serializable list using Bundle.Serializable
Intent i = new Intent(EmployeeActivity.this, ViewEmployeeInfo.class);
i.putSerializable("emp",employee1);
startActivity(i);
Instead
Intent i = new Intent(EmployeeActivity.this, ViewEmployeeInfo.class);
i.putExtra("emp",employee1);
startActivity(i);
Receive
Intent i = getIntent();
employee = (Employee) i.getSerializableExtra("emp");
The problem was resolved, it was supposed to put the new object of employee1
inside the action of submit button
employee1 = new Employee(Integer.parseInt(editTextID.getText().toString())
, editTextName.getText().toString(), editTextAddress.getText().toString()
, Double.parseDouble(editTextSalary.getText().toString())
, editTextJob.getText().toString());

onOptionsItemClick or onMenuItemClick not being called

(Very first thing i want to make clear is that i am COMPLETELY NEWBIE, very beginner in android, in fact in programming/coding!)
The menu is referred in onCreateOptionMenu and the calling method is also onOptionsItemSelected to open up menu but the method for each option/item is set as onMenuItemClick and onMenuItemLongClick which is ideal for context menu options/items!
The problem is onMenuItemClick have input parameters as (View v, int position) and I cannot change it to only (View v) or to (MenuItem item).
What I want is clicking on each item of menu should bring out new activity!
I also tried putting all my switch-case-break statements to onOptionsItemSelected method but it is still not working!
I also tried in fragment class, setHasOptionsMenu (true); but it did not work!
onMenuItemClick doesn't get called
(Deprecated) Fragment onOptionsItemSelected not being called
Below is the activity_main_menu.xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/menu_item_background">
<include layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Below is the fragment_main.xml layout
<ScrollView 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"
tools:context="com.example.android.coffeeshop.MainFragment">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#color/menu_item_background">
<EditText
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/EditTextHint"
android:inputType="textNoSuggestions" />
<EditText
android:id="#+id/usercontact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/usercontactHint"
android:inputType="textNoSuggestions" />
<EditText
android:id="#+id/useremail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/useremailHint"
android:inputType="textEmailAddress" />
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/Toppings" />
<CheckBox
android:id="#+id/whippedCreamcheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingEnd="24dp"
android:paddingLeft="24dp"
android:paddingStart="24dp"
android:text="#string/WhippedCream"
android:textSize="16sp" />
<CheckBox
android:id="#+id/Chocolatebox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingEnd="24dp"
android:paddingLeft="24dp"
android:paddingStart="24dp"
android:text="#string/Chocolate"
android:textSize="16sp" />
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/quantity" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginTop="16dp"
android:onClick="decrement"
android:text="#string/minus" />
<TextView
android:id="#+id/quantity_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="16dp"
android:text="#string/Zero"
android:textColor="#android:color/black"
android:textSize="20sp" />
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginTop="16dp"
android:onClick="increment"
android:text="#string/plus" />
</LinearLayout>
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/OrderSummary" />
<TextView
android:id="#+id/order_summary_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/Price"
android:textColor="#android:color/black"
android:textSize="20sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/orderButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="submitOrder"
android:text="#string/Order" />
<Button
android:id="#+id/placeOrder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:onClick="placeOrder"
android:text="#string/PlaceOrder" />
</LinearLayout>
</LinearLayout>
</ScrollView>
Below is the MainMenu.java class file from where i am trying to handle fragment menu!
package com.example.android.coffeeshop5profile;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.yalantis.contextmenu.lib.ContextMenuDialogFragment;
import com.yalantis.contextmenu.lib.MenuObject;
import com.yalantis.contextmenu.lib.MenuParams;
import com.yalantis.contextmenu.lib.interfaces.OnMenuItemLongClickListener;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* This app displays an order form to order coffee.
*/
public class MainMenu extends AppCompatActivity implements ActionMenuView.OnMenuItemClickListener, OnMenuItemLongClickListener {
private FragmentManager fragmentManager;
private ContextMenuDialogFragment mMenuDialogFragment;
int quantity = 1;
int price = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
fragmentManager = getSupportFragmentManager();
initToolbar();
initMenuFragment();
addFragment(new MainFragment(), true, R.id.container);
}
private void initMenuFragment() {
MenuParams menuParams = new MenuParams();
menuParams.setActionBarSize((int) getResources().getDimension(R.dimen.tool_bar_height));
menuParams.setMenuObjects(getMenuObjects());
menuParams.setClosableOutside(false);
mMenuDialogFragment = ContextMenuDialogFragment.newInstance(menuParams);
mMenuDialogFragment.setItemLongClickListener(this);
}
private List<MenuObject> getMenuObjects() {
List<MenuObject> menuObjects = new ArrayList<>();
MenuObject close = new MenuObject();
close.setResource(R.drawable.icn_close);
MenuObject send = new MenuObject("Send message");
send.setResource(R.drawable.icn_1);
MenuObject like = new MenuObject("Like profile");
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.icn_2);
like.setBitmap(b);
MenuObject addFr = new MenuObject("Add to friends");
BitmapDrawable bd = new BitmapDrawable(getResources(),
BitmapFactory.decodeResource(getResources(), R.drawable.icn_3));
addFr.setDrawable(bd);
MenuObject addFav = new MenuObject("Add to favorites");
addFav.setResource(R.drawable.icn_4);
MenuObject block = new MenuObject("Block user");
block.setResource(R.drawable.icn_5);
menuObjects.add(close);
menuObjects.add(send);
menuObjects.add(like);
menuObjects.add(addFr);
menuObjects.add(addFav);
menuObjects.add(block);
return menuObjects;
}
private void initToolbar() {
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
TextView mToolBarTextView = (TextView) findViewById(R.id.text_view_toolbar_title);
setSupportActionBar(mToolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mToolbar.setNavigationIcon(R.drawable.btn_back);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
mToolBarTextView.setText(R.string.title_text);
}
protected void addFragment(Fragment fragment, boolean addToBackStack, int containerId) {
invalidateOptionsMenu();
String backStackName = fragment.getClass().getName();
boolean fragmentPopped = fragmentManager.popBackStackImmediate(backStackName, 0);
if (!fragmentPopped) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(containerId, fragment, backStackName)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
if (addToBackStack)
transaction.addToBackStack(backStackName);
transaction.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.context_menu:
if (fragmentManager.findFragmentByTag(ContextMenuDialogFragment.TAG) == null) {
mMenuDialogFragment.show(fragmentManager, ContextMenuDialogFragment.TAG);
}
break;
case R.drawable.icn_3:
Intent userProfileIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(userProfileIntent);
break;
case R.drawable.icn_4:
Intent wishListIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(wishListIntent);
break;
}
return false; //Turning this true or to super.OnOptionsItemSelected did nothing!
}
#Override
public void onBackPressed() {
if (mMenuDialogFragment != null && mMenuDialogFragment.isAdded()) {
mMenuDialogFragment.dismiss();
} else {
finish();
}
}
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.drawable.icn_3:
Intent userProfileIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(userProfileIntent);
break;
case R.drawable.icn_4:
Intent wishListIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(wishListIntent);
break;
} return true;
}
#Override
public void onMenuItemLongClick(View clickedView, int position) {
Toast.makeText(this, "Long clicked on position: " + position, Toast.LENGTH_SHORT).show();
}
public void submitOrder(View view) {
String orderSummaryString = createOrderSummary(quantity);
displayMessage(orderSummaryString);
}
public void placeOrder(View view) {
TextView useremail = (TextView) findViewById(R.id.useremail);
String useremailString = useremail.getText().toString();
String orderSummaryString = createOrderSummary(quantity);
sendMail(useremailString, "Coffee Order By: " + useremailString, orderSummaryString);
}
private void sendMail(String email, String subject, String messageBody) {
Session session = createSessionObject();
try {
Message message = createMessage(email, subject, messageBody, session);
new SendMailTask().execute(message);
} catch (MessagingException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private Message createMessage(String email, String subject, String messageBody, Session session)
throws MessagingException, UnsupportedEncodingException {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("clientaddress#gmail.com", "Coffee Order By"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
message.setSubject(subject);
message.setText(messageBody);
return message;
}
private Session createSessionObject() {
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
return Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("clientaddress#gmail.com", "************");
}
});
}
public class SendMailTask extends AsyncTask<Message, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(MainMenu.this, "Please wait", "Sending mail", true, false);
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
#Override
public Void doInBackground(Message... messages) {
try {
Transport.send(messages[0]);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
/**
* This method is called when the plus button is clicked.
*/
public void increment(View view) {
if (quantity < 100) {
quantity = quantity + 1;
displayQuantity(quantity);
} else {
Toast.makeText(this, "You have reached maximum numbers of coffees to be allowed!", Toast.LENGTH_SHORT).show();
}
}
/**
* This method is called when the minus button is clicked.
*/
public void decrement(View view) {
if (quantity >= 2) {
quantity = quantity - 1;
displayQuantity(quantity);
} else {
Toast.makeText(this, "You can not place order in negative number!", Toast.LENGTH_SHORT).show();
}
}
public String createOrderSummary(int quantity) {
CheckBox whippedCreamCheckbox = (CheckBox) findViewById(R.id.whippedCreamcheckbox);
boolean hasWhippedCream = whippedCreamCheckbox.isChecked();
CheckBox chocolatebox = (CheckBox) findViewById(R.id.Chocolatebox);
boolean hasChocolate = chocolatebox.isChecked();
price = 5;
if (hasWhippedCream) {
price = price + 1;
}
if (hasChocolate) {
price = price + 2;
}
int finalPrice = quantity * price;
EditText usernameTextView = (EditText) findViewById(R.id.username);
String usernameString = usernameTextView.getText().toString();
EditText usercontact = (EditText) findViewById(R.id.usercontact);
String userContactString = usercontact.getText().toString();
EditText useremail = (EditText) findViewById(R.id.useremail);
String userEmailString = useremail.getText().toString();
String OrderSummary = getString(R.string.username) + ": " + usernameString;
OrderSummary += "\n" + getString(R.string.ContactNumber) + " " + userContactString;
OrderSummary += "\n" + getString(R.string.eAddress) + " " + userEmailString;
OrderSummary += "\n" + getString(R.string.AddedWhippedCream) + " " + hasWhippedCream;
OrderSummary += "\n" + getString(R.string.AddedChocolate) + " " + hasChocolate;
OrderSummary += "\n" + getString(R.string.quantity) + ": " + quantity;
OrderSummary += "\n" + getString(R.string.totalprice) + finalPrice;
OrderSummary += "\n" + getString(R.string.thankyou);
return OrderSummary;
}
/**
* This method displays the given quantity value on the screen.
*/
public void displayQuantity(int number) {
TextView quantityTextView = (TextView) findViewById(
R.id.quantity_text_view);
quantityTextView.setText(String.format("%d", number));
}
/**
* This method displays the given text on the screen.
*/
public void displayMessage(String message) {
TextView orderSummaryTextView = (TextView) findViewById(R.id.order_summary_text_view);
orderSummaryTextView.setText(message);
}
}
Below is the MainFragment.java class file
package com.example.android.coffeeshop5profile;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
setHasOptionsMenu(true);
setMenuVisibility(false);
return rootView;
}
}
Following is the Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue_grey_700"
android:orientation="vertical"
android:weightSum="4"
tools:context=".legacy.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3"
android:gravity="center_vertical"
android:orientation="vertical">
<ImageView
android:id="#+id/google_icon"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:contentDescription="#string/desc_google_icon"
android:src="#drawable/googleg_color" />
<TextView
android:id="#+id/title_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_gravity="center"
android:text="#string/title_text"
android:textColor="#android:color/white"
android:textSize="36sp" />
<TextView
android:id="#+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/signed_out"
android:textColor="#android:color/white"
android:textSize="14sp" />
<TextView
android:id="#+id/detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fadeScrollbars="true"
android:gravity="center"
android:maxLines="5"
android:padding="10dp"
android:scrollbars="vertical"
android:textColor="#android:color/white"
android:textSize="14sp" />
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/blue_grey_900">
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible"
tools:visibility="gone" />
<LinearLayout
android:id="#+id/sign_out_and_disconnect"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="horizontal"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:visibility="gone"
tools:visibility="visible">
<Button
android:id="#+id/sign_out_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/sign_out"
android:theme="#style/ThemeOverlay.MyDarkButton" />
<Button
android:id="#+id/disconnect_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/disconnect"
android:theme="#style/ThemeOverlay.MyDarkButton" />
<Button
android:id="#+id/secondpage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/secondpage"
android:theme="#style/ThemeOverlay.MyDarkButton" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
below is the res/menu/context_main_menu.xml file
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/context_menu"
android:title="#string/context_menu"
android:icon="#drawable/btn_add"
android:orderInCategory="100"
app:showAsAction="always" />
</menu>
...unfortunately, 30000 characters limit has been reached so i cant upload mainActivity.java file!
Kindly help!
Best regards,
sagar
try this code on
Change the following code
onMenuItemClick(MenuItem item)
to
onMenuItemClick(View clickedView, int position)
like this
`#override
public void onMenuItemClick(View clickedView, int position) {
switch (position) {
case 1:
startActivity(new Intent(MainActivity.this, UserProfile.class));
break;
case 2:
startActivity(new Intent(MainActivity.this, UserProfile.class));
break;
}
}`
i hope this help you
If onOptionsItemSelected() method is not called in fragment then just make sure you return false from the onOptionsItemSelected() method of Activity.

How to connect to a bluetooth device with android smartphone using only its Mac adress?

I'm making an android app that is supposed to send values of three
seekbars through bluetooth but I don't know how to programmatically connect it
to a paired bluetooth device by clicking on its name on the list that shows the paired devices
Any help would be much appreciated.
MainActivity.java
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends ActionBarActivity {
private BluetoothAdapter btadapter;
private Set<BluetoothDevice> pairedDevices;
private SeekBar redcontrol = null;
private SeekBar greencontrol = null;
private SeekBar bluecontrol = null;
private TextView redv;
private TextView greenv;
private TextView bluev;
private ListView lv;
public static String EXTRA_DEVICE_ADDRESS = "device_address";
LinearLayout linearLayout;
Button on, off, button;
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Insert bluetooth devices MAC address
private static String address = "00:14:02:13:08:21";
private BluetoothChatService mChatService = null;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
finish();
System.exit(10);
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btadapter = (BluetoothAdapter.getDefaultAdapter());
button = (Button)findViewById(R.id.button);
lv = (ListView)findViewById(R.id.listView1);
btadapter = BluetoothAdapter.getDefaultAdapter();
button = (Button) findViewById(R.id.button);
redv = (TextView) findViewById(R.id.redv);
greenv = (TextView) findViewById(R.id.greenv);
bluev = (TextView) findViewById(R.id.bluev);
redcontrol = (SeekBar) findViewById(R.id.seekBar);
greencontrol = (SeekBar) findViewById(R.id.seekBar2);
bluecontrol = (SeekBar) findViewById(R.id.seekBar3);
redcontrol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
redv.setText(String.valueOf(progress));
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
//Toast.makeText(MainActivity.this, "seek bar progress:" + progressChanged,
// Toast.LENGTH_SHORT).show();
}
});
greencontrol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
greenv.setText(String.valueOf(progress));
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
// Toast.makeText(MainActivity.this, "seek bar progress:" + progressChanged,
//Toast.LENGTH_SHORT).show();
}
});
bluecontrol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
bluev.setText(String.valueOf(progress));
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
//Toast.makeText(MainActivity.this, "seek bar progress:" + progressChanged,
// Toast.LENGTH_SHORT).show();
}
});
linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
on = (Button) findViewById(R.id.on);
off = (Button) findViewById(R.id.off);
on.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
on.setBackgroundColor(Color.parseColor("#57D3E8"));
off.setBackgroundColor(Color.parseColor("#EAEAEA"));
if (!btadapter.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(), "Bluetooth Turning On"
, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Already On",
Toast.LENGTH_SHORT).show();
}
}
});
off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
off.setBackgroundColor(Color.parseColor("#57D3E8"));
on.setBackgroundColor(Color.parseColor("#EAEAEA"));
if (btadapter.isEnabled()) {
btadapter.disable();
Toast.makeText(getApplicationContext(), "Bluetooth Off"
, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Already Off",
Toast.LENGTH_SHORT).show();
}
}
});
}
public void list(View view){
pairedDevices = btadapter.getBondedDevices();
ArrayList list = new ArrayList();
for(BluetoothDevice bt : pairedDevices)
list.add(bt.getName() +"\n" + bt.getAddress() );
Toast.makeText(getApplicationContext(),"Showing Paired Devices",
Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new ArrayAdapter
(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView) view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_SHORT).show();
for (BluetoothDevice device : pairedDevices) {
if ("00:14:02:13:08:21".equals(device.getAddress())) {
Toast.makeText(getBaseContext(), "That's the right one ", Toast.LENGTH_SHORT).show();
break;
}
}
view.setEnabled(false);
}
});
}
#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;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="460dp"
android:layout_marginTop="0dp"
android:id="#+id/id"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.arduinolight.app.MainActivity"
android:background="#9DC42C"
>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="750dp"
android:id="#+id/scrollView"
android:layout_below="#+id/linearLayout"
android:layout_marginTop="-30dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
>
<RelativeLayout
android:layout_width="310dp"
android:layout_height="800dp"
android:orientation="vertical"
android:layout_marginTop="20dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
<Button
android:layout_width="200dp"
android:layout_height="50dp"
android:text="Paired Devices"
android:onClick="list"
android:layout_marginLeft="50dp"
android:layout_marginTop="320dp"
android:id="#+id/button" />
<SeekBar
android:layout_width="170dp"
android:layout_height="wrap_content"
android:id="#+id/seekBar"
android:indeterminate="false"
android:max="255"
android:progress="0"
android:layout_above="#+id/seekBar2"
android:layout_alignLeft="#+id/seekBar2"
android:layout_alignStart="#+id/seekBar2"
android:layout_marginBottom="26dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="RED Light"
android:id="#+id/redlight"
android:textColor="#59126F"
android:textIsSelectable="false"
android:textStyle="bold"
android:textSize="16sp"
android:typeface="monospace"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="165dp" />
<SeekBar
android:layout_width="170dp"
android:layout_height="wrap_content"
android:id="#+id/seekBar2"
android:indeterminate="false"
android:max="255"
android:progress="0"
android:layout_alignTop="#+id/greenlight"
android:layout_toRightOf="#+id/bluetooth"
android:layout_marginTop="-5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="GREEN Light"
android:id="#+id/greenlight"
android:textColor="#59126F"
android:textIsSelectable="false"
android:textStyle="bold"
android:textSize="16sp"
android:typeface="monospace"
android:layout_alignBottom="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="134dp" />
<SeekBar
android:layout_width="170dp"
android:layout_height="wrap_content"
android:id="#+id/seekBar3"
android:indeterminate="false"
android:max="255"
android:progress="0"
android:layout_alignTop="#+id/bluelight"
android:layout_toRightOf="#+id/greenlight"
android:layout_marginTop="-5dp"
android:layout_marginLeft="4dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="BLUE Light"
android:id="#+id/bluelight"
android:textColor="#59126F"
android:textIsSelectable="false"
android:textStyle="bold"
android:textSize="16sp"
android:typeface="monospace"
android:layout_below="#+id/seekBar2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="23dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Red :"
android:id="#+id/red"
android:singleLine="false"
android:textColor="#F51E3E"
android:layout_marginTop="28dp"
android:layout_below="#+id/on"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Green :"
android:id="#+id/green"
android:textColor="#59126F"
android:layout_alignTop="#+id/red"
android:layout_toRightOf="#+id/redlight" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text=" 0"
android:id="#+id/redv"
android:textColor="#F51E3E"
android:layout_alignTop="#+id/red"
android:layout_toRightOf="#+id/red"
android:layout_marginLeft="2dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text=" 0"
android:id="#+id/greenv"
android:textColor="#04670F"
android:layout_alignTop="#+id/green"
android:layout_toRightOf="#+id/green" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Blue :"
android:id="#+id/blue"
android:textColor="#292EFF"
android:layout_alignTop="#+id/greenv"
android:layout_marginLeft="205dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text=" 0"
android:id="#+id/bluev"
android:textColor="#1850C6"
android:layout_alignTop="#+id/blue"
android:layout_marginLeft="250dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Bluetooth :"
android:textColor="#59126F"
android:textSize="24sp"
android:id="#+id/bluetooth"
android:layout_alignParentTop="false"
android:layout_alignStart="#+id/red"
android:layout_marginTop="40dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="70sp"
android:layout_height="40sp"
android:text="ON"
android:textSize="20sp"
android:id="#+id/on"
android:longClickable="false"
android:textColor="#000000"
android:layout_alignTop="#+id/bluetooth"
android:layout_toRightOf="#+id/bluetooth"
android:layout_marginLeft="7dp"
android:layout_marginTop="-7dp"
android:background="#EAEAEA" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="70dp"
android:layout_height="40sp"
android:text="OFF"
android:textSize="20sp"
android:id="#+id/off"
android:clickable="true"
android:textColor="#000"
android:layout_alignTop="#+id/on"
android:layout_alignLeft="#+id/blue"
android:layout_alignStart="#+id/blue"
android:layout_marginLeft="-5dp"
android:layout_marginTop="0dp"
android:background="#EAEAEA" />
<ListView
android:id="#+id/listView1"
android:layout_width="wrap_content"
android:layout_height="150dp"
android:cacheColorHint="#00000000"
android:visibility="visible"
android:layout_below="#+id/button"
android:layout_marginTop="30dp">
</ListView>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.arduinolightning.app"
>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="Arduino Lighting"
android:theme="#style/AppTheme" >
<activity
android:name="com.arduinolightning.app.MainActivity"
android:label="Arduino Lighting" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Categories

Resources