How to pass a variable from inner class to another class - java

I am very new in Android studio and Java, I tried to convert a variable sensor0 to double by using CO = new Double(sensor0).doubleValue(); , and I would like to pass the variable to another class to use it. But I cannot use the variable of sensor0 in another class. The value of the variable is always 0.
public class bt extends Activity {
public String sensor0, sensor1;
public double CO;
Button btnOn, btnOff, btnNext;
TextView txtArduino, txtString, txtStringLength, sensorView0, sensorView1, sensorView2, sensorView3;
Handler bluetoothIn;
final int handlerState = 0; //used to identify handler message
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder recDataString = new StringBuilder();
private ConnectedThread mConnectedThread;
// SPP UUID service - this should work for most devices
private static final UUID ID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// String for MAC address
private static String address;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bt);
//Link the buttons and textViews to respective views
btnOn = (Button) findViewById(R.id.buttonOn);
btnOff = (Button) findViewById(R.id.buttonOff);
btnNext = (Button) findViewById(R.id.buttonNext);
txtString = (TextView) findViewById(R.id.txtString);
txtStringLength = (TextView) findViewById(R.id.testView1);
sensorView0 = (TextView) findViewById(R.id.sensorView0);
sensorView1 = (TextView) findViewById(R.id.sensorView1);
sensorView2 = (TextView) findViewById(R.id.sensorView2);
sensorView3 = (TextView) findViewById(R.id.sensorView3);
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) { //if message is what we want
String readMessage = (String) msg.obj; // msg.arg1 = bytes from connect thread
recDataString.append(readMessage); //keep appending to string until ~
int endOfLineIndex = recDataString.indexOf("~"); // determine the end-of-line
if (endOfLineIndex > 0) { // make sure there data before ~
String dataInPrint = recDataString.substring(0, endOfLineIndex); // extract string
txtString.setText("Data Received = " + dataInPrint);
int dataLength = dataInPrint.length(); //get length of data received
txtStringLength.setText("String Length = " + String.valueOf(dataLength));
if (recDataString.charAt(0) == '#') //if it starts with # we know it is what we are looking for
{
sensor0 = recDataString.substring(1, 4); //get sensor value from string between indices 1-5
sensor1 = recDataString.substring(5, 8); //same again...
//String sensor2 = recDataString.substring(11, 15);
//String sensor3 = recDataString.substring(16, 20);
sensorView0.setText(" CO2 Value = " + sensor0 + ""); //update the textviews with sensor values
sensorView1.setText(" CO Value = " + sensor1 + "");
// sensorView2.setText(" Sensor 2 Voltage = " + sensor2 + "V");
// sensorView3.setText(" Sensor 3 Voltage = " + sensor3 + "V");
}
recDataString.delete(0, recDataString.length()); //clear all string data
// strIncom =" ";
dataInPrint = " ";
CO = new Double(sensor0).doubleValue();
}
}
}
};

you need to allow access to this variable.
the bast way to do this is to define a getter for this variable.
create a variable in the class and once your method runs populate the field
create a "public" method called getC0() which will return your value.
in the class you need this after you create an instance of your class and the logic that populates the variable runs, you can call the method to get the value.

I changed CO = new Double(sensor0).doubleValue(); to double CO = Double.parseDouble(sensor0);. Then I get 0 from another class by using the code
bt SensorCO = new bt();
double COValue = SensorCO.CO;,
and below is the code of another class
public void setBitmap( Bitmap bitmap ) {
oldTime = (System.currentTimeMillis()+500)/1000;
mBitmap = bitmap;
if (!detector.isOperational()) {
//Handle contingency
} else {
//Log.d("time1", SystemClock.currentThreadTimeMillis()+"");
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
mFaces = detector.detect(frame);
}
bt SensorCO = new bt();
double COValue = SensorCO.CO;
newTime = (System.currentTimeMillis()+500)/1000;
timeDifference = (newTime - oldTime);
accumulate = (accumulate + timeDifference);
CameraActivity.showScore(blinkCount, accumulate, COValue);
if(isEyeBlinked()){
accumulate = 0;
Log.d("isEyeBlinked","eye blink is observed");
blinkCount++;
}
if(accumulate > 6){
playSound playSound1 = new playSound();
playSound1.play(accumulate);
}
invalidate();
}

make sure that sensor0 have the right value and then
replace
CO = new Double(sensor0).doubleValue();
with
double CO = Double.parseDouble(sensor0);

Related

I add data into list from API server but size of the list is zero why?

I am adding data into the list from model class object still it is showing list size is zero:
apiService.getOrdersDateWise(dateFrom,dateTo).enqueue(new Callback<List<OrdersDateWiseModel>>() {
#Override public void onResponse(Call<List<OrdersDateWiseModel>> call, Response<List<OrdersDateWiseModel>> response) {
List<OrdersDateWiseModel> ordsList = response.body();
int ordsListSize = ordsList.size();
Log.i(TAG, "OrdersListSize 250 : " + ordsListSize);
if (ordsList.size() != 0) {
if (fromDateMillisecs <= toDateMillisecs) {
for (int i = 0;i<ordsList.size();i++){
String ordDate = ordsList.get(i).getOrder_date();
String ordNo = ordsList.get(i).getOrder_number();
String ordValue = ordsList.get(i).getOrder_value();
String retaId = ordsList.get(i).getRetailer_id();
String shopName1 = ordsList.get(i).getShop_name();
String retName1 = ordsList.get(i).getRetailer_name();
String area1 = ordsList.get(i).getArea();
String phone1 = ordsList.get(i).getPhone();
getOrdersList.add(
new OrdersDateWiseModel(
ordDate,
ordNo,
ordValue,
retaId,
shopName1,
retName1,
area1,
phone1
));
}
ordersDateWiseAdapter.notifyDataSetChanged();
I expected output is the size of the list:
I/OrdersDateWiseActivity: OrdersListSize 250 : 0

I need my counter to stop counting and display a toast when it reaches 510

This is the math part at the moment, i have one of these for each text view element, and it counts fine, all i need is for the numbers in all of the text views to stop counting when the total reaches 510 and all the others to stop counting when they reach 252 individually
when the total reaches 510 and/or when the individual values reach 252 i want a toast displaying "Highest number reached" or something like that
This is Java if anyone doesn't know, and it's in android studio
private View.OnClickListener hpListener = new View.OnClickListener() {
public void onClick(View view) {
// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.evval);
// TextView element
TextView HPtx = (TextView) findViewById(R.id.hpval);
TextView atttx = (TextView) findViewById(R.id.attval);
TextView deftx = (TextView) findViewById(R.id.defval);
TextView satx = (TextView) findViewById(R.id.saval);
TextView sdtx = (TextView) findViewById(R.id.sdval);
TextView spdtx = (TextView) findViewById(R.id.spdval);
TextView totaltx = (TextView) findViewById(R.id.totalval);
// Ev values
int add = Integer.parseInt(spinner.getSelectedItem().toString());
// Calculation
int HP = Integer.parseInt(HPtx.getText().toString());
int att = Integer.parseInt(atttx.getText().toString());
int def = Integer.parseInt(deftx.getText().toString());
int sa = Integer.parseInt(satx.getText().toString());
int sd = Integer.parseInt(sdtx.getText().toString());
int spd = Integer.parseInt(spdtx.getText().toString());
int hptotal = HP + add;
int total = hptotal + att + def + sa + sd + spd;
// Value calculations
DecimalFormat addHPFormat = new DecimalFormat("000");
DecimalFormat addtotalFormat = new DecimalFormat("000");
HPtx.setText(addHPFormat.format(hptotal));
totaltx.setText(addtotalFormat.format(total));
}
};
Just Place this in your code after total:
if(total >= 510 || hp >=252 || att >=252 || def >=252 || sa >=252 || sd >=252 || spd >=252)
Toast.makeText(this,"highest Number Reached",Toast.LENGTH_SHORT).show();
else {
DecimalFormat addHPFormat = new DecimalFormat("000");
DecimalFormat addtotalFormat = new DecimalFormat("000");
HPtx.setText(addHPFormat.format(hptotal));
totaltx.setText(addtotalFormat.format(total));
}
private View.OnClickListener hpListener = new View.OnClickListener() {
public void onClick(View view) {
// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.evval);
// TextView element
TextView HPtx = (TextView) findViewById(R.id.hpval);
TextView atttx = (TextView) findViewById(R.id.attval);
TextView deftx = (TextView) findViewById(R.id.defval);
TextView satx = (TextView) findViewById(R.id.saval);
TextView sdtx = (TextView) findViewById(R.id.sdval);
TextView spdtx = (TextView) findViewById(R.id.spdval);
TextView totaltx = (TextView) findViewById(R.id.totalval);
// Ev values
int add = Integer.parseInt(spinner.getSelectedItem().toString());
// Calculation
int HP = Integer.parseInt(HPtx.getText().toString());
int att = Integer.parseInt(atttx.getText().toString());
int def = Integer.parseInt(deftx.getText().toString());
int sa = Integer.parseInt(satx.getText().toString());
int sd = Integer.parseInt(sdtx.getText().toString());
int spd = Integer.parseInt(spdtx.getText().toString());
int hptotal = HP + add;
int total = hptotal + att + def + sa + sd + spd;
if (total >= 510 || add >= 253 || att >= 252 || def >= 252 || sa >= 252 || sf >= 252 || spd >= 252) {
// Replace MainActivity.this with your context
Toast.makeText(MainActivity.this, "Highest number reached", Toast.LENGTH_SHORT).show();
return;
}
// Value calculations
DecimalFormat addHPFormat = new DecimalFormat("000");
DecimalFormat addtotalFormat = new DecimalFormat("000");
HPtx.setText(addHPFormat.format(hptotal));
totaltx.setText(addtotalFormat.format(total));
}
};

Android ArrayList without first value

I have problem with ArrayList. I have the question files structure like:
Y aaaaaa.
Y bbbbbb.
N ccccccc.
N ddddddd.
and I want to put into textview3 the first letter like Y or N
public void value (){
Scanner answerScanner = new Scanner(getResources().openRawResource(R.raw.answer));
Scanner questionScanner = new Scanner(getResources().openRawResource(R.raw.question));
ArrayList<String> answerList = new ArrayList<String>();
ArrayList<String> questionList = new ArrayList<String>();
try {
while (answerScanner.hasNextLine() ) {
answerList.add(answerScanner.nextLine());
questionList.add(questionScanner.nextLine());
}
} finally {
answerScanner.close();
questionScanner.close();
}
int nextInt = random.nextInt(questionList.size());
String answerString = answerList.get(nextInt);
String questionString = questionList.get(nextInt);
yourAnswerString = answerString.substring(0);
yourQuestionString = questionString.substring(2);
shortform = questionString.substring(0,1);
TextView textGenerateNumber = (TextView)findViewById(R.id.textView1);
TextView textGenerateNumber2 = (TextView)findViewById(R.id.textView2);
TextView textGenerateNumber3 = (TextView)findViewById(R.id.textView3);
textGenerateNumber.setText(yourQuestionString);
textGenerateNumber2.setText(yourAnswerString);
textGenerateNumber3.setText(shortform);
}
then I add:
shortform = questionString.substring(0,1);
TextView textGenerateNumber3 = (TextView)findViewById(R.id.textView3);
textGenerateNumber3.setText(shortform);
I get good answers I all cases without first .... when radom get first line from text file I get empty value ( my textView3 are empty).

why i get null when intent double value

I need to intent a double value in order to insert in SQLite but when i print output it show NULL value.
This is code intent in first Activity
Intent intent = new Intent(Process.this,AddStudent.class);
intent.putExtra("Intent", result);
startActivity(intent);
and this is code get intent in another activity
String concentrate = getIntent().getStringExtra("Intent");
Here is full code.
FirstActivity;
public class Process extends Activity {
public static double a,b,r,std_err = 0.0;
public static double e;
public static int N;
#SuppressWarnings("static-access")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_process);
double[] x = { 10,30,50,60,90,55 };
double[] y = { 1, 10, 20, 30, 40, 50 };
Process model = new Process();
model.Regression(x, y);
double result = Math.pow(2.71828182845904,x[0]*b); // e^bx
Intent intent = new Intent(Process.this,AddStudent.class);
intent.putExtra("Intent", result);
startActivity(intent);
}
//-----------------------------------------------------------------------------------//
public static void Regression (double[] oat, double[] energy) {
N = oat.length;
// constant e:
Double e = Math.E;
Double sumX = 0.00;
Double sumX2 = 0.00;
Double sumY = 0.00;
Double sumYlin = 0.00;
Double sumY2 = 0.00;
Double sumY2lin = 0.00;
Double sumXY = 0.00;
Double sumXYlin = 0.00;
for(int i=0;i<N;i++)
{
sumX = sumX + oat[i];
sumX2 = sumX2 + Math.pow(oat[i], 2);
// exponential
sumY = sumY + Math.log(energy[i]);
sumY2 = sumY2 + Math.pow(Math.log(energy[i]), 2);
sumXY = sumXY + (oat[i]*(Math.log(energy[i])));
}
b = ((N*sumXY) - (sumX*sumY))/(N*sumX2 - (sumX*sumX));
a = Math.pow(e, (sumY - (b*sumX))/N);
Double c = 0.00; // numerator
Double d = 0.00; // denominator
c = (b)*(sumXY - sumX*sumY/N);
d = sumY2 - (sumY*sumY)/N;
r = c/d;
Double p = 0.00;
if(r > 0){
p = Math.sqrt(r);
} else {
p = 0.00;
}
std_err = Math.sqrt((d-c)/(N-2));
}
}
SecondActivity; the activity for add data in SQLite
public class AddStudent extends Activity {
DatabaseStudent mHelper;
SQLiteDatabase mDb;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
mHelper = new DatabaseStudent(this);
mDb = mHelper.getWritableDatabase();
final EditText editName = (EditText)findViewById(R.id.editName);
final EditText editLastName = (EditText)findViewById(R.id.editLastName);
final EditText editSchool = (EditText)findViewById(R.id.editSchool);
Button buttonAdd = (Button)findViewById(R.id.buttonAdd);
buttonAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String name = editName.getText().toString();
String lastname = editLastName.getText().toString();
String school = editSchool.getText().toString();
//concentrate
//String concentrate = getIntent().getStringExtra("Intent");
String concentrate = getIntent().getStringExtra("Intent");
//Date&Time
java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(dt);
if(name.length() != 0 && lastname.length() != 0
&& school.length() != 0 ) {
Cursor mCursor = mDb.rawQuery("SELECT * FROM "
+ DatabaseStudent.TABLE_NAME + " WHERE "
+ DatabaseStudent.COL_NAME + "='" + name + "'"
+ " AND " + DatabaseStudent.COL_LASTNAME + "='"
+ concentrate + "'" + " AND "
+ DatabaseStudent.COL_SCHOOL + "='" + currentTime //add COL_SCHOOL = currentTime
+ "'", null);
if(mCursor.getCount() == 0) {
mDb.execSQL("INSERT INTO " + DatabaseStudent.TABLE_NAME
+ " (" + DatabaseStudent.COL_NAME
+ ", " + DatabaseStudent.COL_LASTNAME
+ ", " + DatabaseStudent.COL_SCHOOL
+ ") VALUES ('" + name + "', '" + concentrate //result ไม่มา
+ "', '" + currentTime + "');");
editName.setText("");
editLastName.setText("");
editSchool.setText("");
}
});
}
public void onStop() {
super.onStop();
mHelper.close();
mDb.close();
}
}
You have
double result = Math.pow(2.71828182845904,x[0]*b);
and
intent.putExtra("Intent", result);
result is a double.
But when you retrieve you have
String concentrate = getIntent().getStringExtra("Intent");
Instead you should use
double concentrate = getIntent().getDoubleExtra("Intent", 0);
Reference :
http://developer.android.com/reference/android/content/Intent.html#getDoubleExtra(java.lang.String, double)
You're not actually placing your double value into your Intent. You need to use putDouble and getDouble methods.
Intent intent = new Intent(Process.this,AddStudent.class);
Bundle b = new Bundle();
b.putDouble("Intent", result);
intent.putExtras(b);
startActivity(intent);
Then, get it in your next Activity:
Bundle b = getIntent().getExtras();
double result = b.getDouble("Intent");
String concentrate = getIntent().getStringExtra("Intent");
Should be like this:
double concentrate = getIntent().getExtras().getDouble("Intent");
Wrap the passed bundle directly into double.
You are passing a Double value and trying to get a String value so you are getting null
Replace
getIntent().getStringExtra("Intent");
with
getIntent().getDoubleExtra("Intent", 0);
Try putting your double into a bundle, then passing like so
Intent intent = new Intent(Process.this,AddStudent.class);
Bundle extras = new Bundle();
intent.putExtras(b);
startActivity(intent);
Then, in your new activity
Bundle extras = Intent.getExtras();
Double result = extras.getDouble("Intent");

the postExecute method of AsyncTask not working properly

If I run above and below code in separate projects, it works. But when I try integrate them, the graph is not getting populated.
The reason I feel is in postExecute method because
One important thing to notice is when I run any other random project, make some change in it, and relaunch the app then for some moments Graph.java is visible as it is in background. At that moment, output is coming perfectly.
But if I run the Graph.java , it's showing blank graph.
EDIT
{{ 1st code is to fetch data from URL and store it in various arrays.
2nd code is to diaplay data on graph.
In below code the two arrays passed to graph contain static values, they should take the values from the 1st code. }}
PLEASE HELP
Graph.java
public class Graph extends Activity {
String arr[], arr1[], temp[], company[], current[], close[], time[];
int sub;
String s1;
String[] verlabels = new String[] { " y1 ", " y2 ", " y3 " };
String[] horlabels = new String[] { " x1 ", " x2 ", " x3 ", " x4 " };
private XYPlot mySimpleXYPlot;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://abc.com/stockcharts.aspx?id=Reliance" });
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
sub = result.lastIndexOf('#', result.length());
s1 = result.substring(0, sub + 2);
arr1 = s1.split("#");
arr = new String[arr1.length - 1];
company = new String[arr.length];
current = new String[arr.length];
close = new String[arr.length];
time = new String[arr.length];
for (int j = 0; j < arr.length; j++) {
arr[j] = arr1[j];
}
for (int i = 0; i < arr.length; i++) {
temp = arr[i].split(";");
company[i] = temp[0];
current[i] = temp[1];
close[i] = temp[2];
time[i] = temp[3];
}
.
mySimpleXYPlot = (XYPlot) findViewById(R.id.mySimpleXYPlot);
Number[] series1Numbers = { 1324266358000L, 1324266418000L,
1324266478000L, 1324266538000L, 1324266598000L,
1324266658000L, 1324266718000L, 1324266778000L,
1324266838000L, 1324266898000L, 1324266958000L };
Number[] series2Numbers = { 3, 1, 2, 9, 6, 5, 4, 3, 7, 3, 2 };
XYSeries series1 = new SimpleXYSeries(
Arrays.asList(series1Numbers),
Arrays.asList(series2Numbers),
"Company");
LineAndPointFormatter series1Format = new LineAndPointFormatter(
Color.rgb(0, 200, 0), // line color
Color.rgb(0, 100, 0), // point color
Color.rgb(150, 190, 150)); // fill color (optional)
mySimpleXYPlot.addSeries(series1, series1Format);
mySimpleXYPlot.setTicksPerRangeLabel(2);
mySimpleXYPlot.setRangeStep(XYStepMode.INCREMENT_BY_VAL, 1);
mySimpleXYPlot.setDomainValueFormat(new MyDateFormat());
mySimpleXYPlot.disableAllMarkup();
}
public class MyDateFormat extends Format {
private SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
#Override
public StringBuffer format(Object obj, StringBuffer toAppendTo,
FieldPosition pos) {
long timestamp = ((Number) obj).longValue();
Date date = new Date(timestamp);
return dateFormat.format(date, toAppendTo, pos);
}
#Override
public Object parseObject(String source, ParsePosition pos) {
return null;
}
}
}
}
I created another class for plotting graph.
Call that class from current class by using intent. Passed the two arrays to graph class by using intent property. plotted the graph in 2nd activity using two arrays.

Categories