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).
Related
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);
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));
}
};
I have created dynamically edittext on my android application like below:
protected void onCreate(Bundle savedInstanceState) {
RelativeLayout layout = (RelativeLayout) findViewById(R.id.linearLayout1);
final EditText[] Et = new EditText[10];
int prevTextViewId = 0;
int add = 0;
int add1 = 0;
for (int a = 0; a < Arr.length; a++) {
Et[a] = new EditText(this);
RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(
(int) LayoutParams.WRAP_CONTENT,
(int) LayoutParams.WRAP_CONTENT);
param.leftMargin = 25;
param.topMargin = (a + 1) * (100 + add1);
Et[a].setPadding(5, 23, 5, 5);
Et[a].setLayoutParams(param);
Et[a].setSingleLine(false);
Et[a].setHorizontalScrollBarEnabled(false);
Et[a].setWidth(280);
Et[a].getText().toString();
layout.addView(Et[a]);
add = add + 25;
add1 = add1 + 15;
}
}
And I want to get text from dynamically created edittext into a button like below:
btn_doneAnswer = (Button) findViewById(R.id.btn_doneAnswer);
btn_doneAnswer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (int a = 0; a < Arr.length; a++) {
Et[a] = new EditText(this);
String text += Et[a].getText().toString();
}
Bundle bundle = new Bundle();
Intent i_backToAddItem = new Intent(
AnswerActivityMultiText.this,
QuestionActivityDynamic.class);
bundle.putString("text", text);
bundle.putString("MultiQues", MultiQues);
i_backToAddItem.putExtras(bundle);
startActivity(i_backToAddItem);
}
});
But I am getting error below in the button onclick method at this line Et[a] = new EditText(this);:
The constructor EditText(new View.OnClickListener(){}) is undefined
another below error at this line += in the button onclick method:
Syntax error on token "+=", = expected
Kindly suggest me how I am getting text from dynamically created edittext into a button.
Waiting for reply.
Thanks
you dont have to initialize the EditText again in the onClick. You should directly use the EditText object to get the text. So the line
Et[a] = new EditText(this);
is not required at all!
And for the error with '+=' operator, you are declaring the string and using the operator(+=) in one line. you have to split up the the declaration part out of the for loop and then use '+='. Here's the complete code :
btn_doneAnswer = (Button) findViewById(R.id.btn_doneAnswer);
btn_doneAnswer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String text;
for (int a = 0; a < Arr.length; a++) {
text += Et[a].getText().toString();
}
Bundle bundle = new Bundle();
Intent i_backToAddItem = new Intent(
AnswerActivityMultiText.this,
QuestionActivityDynamic.class);
bundle.putString("text", text);
bundle.putString("MultiQues", MultiQues);
i_backToAddItem.putExtras(bundle);
startActivity(i_backToAddItem);
}
});
Your problem is in this lines:
for (int a = 0; a < Arr.length; a++) {
Et[a] = new EditText(this);
String text += Et[a].getText().toString();
}
In this line:
Et[a] = new EditText(this);
this is the onClickListener object, you must have class.this (where class is the class name of file that this code is created).
In this other line:
String text += Et[a].getText().toString();
You always create a new String, and instead of created, you make an add. It is a Java concept fail.
You must do this:
String text = "";
for (int a = 0; a < Arr.length; a++) {
Et[a] = new EditText(class_name.this);
text += Et[a].getText().toString();
}
parsing json and i'm trying to setText a textview to do all elements in my array. Obviously I am doing something wrong here, would appreciate any help.
TextView tv1 = (TextView) findViewById(R.id.textView1);
TextView tv2 = (TextView) findViewById(R.id.textView2);
try {
String buildings = getJSON("http://iam.colum.edu/portfolio/api/course?json=True");
//JSONObject jsonObject = new JSONObject(buildings);
JSONArray queryArray = new JSONArray(buildings);
//queryArray = queryArray.getJSONArray(0);
List<String> list = new ArrayList<String>();
for (int i=0; i<queryArray.length(); i++) {
list.add( queryArray.getString(i) );
}
String text = list.get(0).toString();
String arr[] = text.split(" ");
arr[0] = arr[0].trim();
for(int i=0;i>queryArray.length();++i)
{
tv1.setText(list[i]);
}
you have an infinite loop here ;
for(int i=0;i>queryArray.length();++i)
{
tv1.setText(list[i]);
}
Also, the above snippet displays one line from your list on the textview each time the loop is running. It doesn't append the text on the textview. Try to optimize your code a bit, that you can do the task in one loop.
StringBuilder sb = new StringBuilder();
for (int i=0; i<queryArray.length(); i++) {
// chain each string, separated with a new line
sb.append(queryArray.getString(i) + "\n");
}
// display the content on textview
tv1.setText(sb.toString());
ref : StringBuilder - Android documentation
Use this dude :) u didnt concat all string just do with this
TextView tv1 = (TextView) findViewById(R.id.textView1);
TextView tv2 = (TextView) findViewById(R.id.textView2);
try {
String buildings = getJSON("http://iam.colum.edu/portfolio/api/course?json=True");
//JSONObject jsonObject = new JSONObject(buildings);
JSONArray queryArray = new JSONArray(buildings);
//queryArray = queryArray.getJSONArray(0);
List<String> list = new ArrayList<String>();
for (int i=0; i<queryArray.length(); i++) {
list.add( queryArray.getString(i) );
}
String finaltext="";
for(int i=0;i>list.size();i++)
{
finaltext.concat(list.get(i));
}
tv1.setText(finaltext.trim());
is there anyway where i can add the element inside both List 19 and List 20 together?
i have both of the element in integer form and by using List.get i can get the number. but i have trouble adding them in together as they are from different list and different if/else statement. is there anyway that i could add them up without changing the algorithm here?
List11.add(driver
.findElement(
By.xpath("html/body/table[2]/tbody/tr/td[4]/table/tbody/tr[3]/td/table/tbody/tr[2]/td[2]/div/span"))
.getAttribute("class"));
if (List11.get(0).equals(List10.get(0))) {
String c = "1";
ArrayList<String> List19 = null;
List19 = new ArrayList<String>();
List19.add(c);
System.out.println(List19.get(0));
System.out.println("Access Right add + 1point");
} else {
String c = "0";
ArrayList<String> List19 = null;
List19 = new ArrayList<String>();
List19.add(c);
System.out.println(List19.get(0));
System.out.println("Access Right no point will be added");
}
List12 = new ArrayList<String>();
System.out
.println("Edit profile: "
+ driver.findElement(
By.xpath("html/body/table[2]/tbody/tr/td[4]/table/tbody/tr[3]/td/table/tbody/tr[3]/td[2]/div/span"))
.getAttribute("class"));
List12.add(driver
.findElement(
By.xpath("html/body/table[2]/tbody/tr/td[4]/table/tbody/tr[3]/td/table/tbody/tr[3]/td[2]/div/span"))
.getAttribute("class"));
if (List12.get(0).equals(List10.get(0))) {
String d = "2";
ArrayList<String> List20 = null;
List20 = new ArrayList<String>();
List20.add(d);
System.out.println(List20.get(0));
System.out.println("Access Right add + 2point");
} else {
String d = "0";
ArrayList<String> List20 = null;
List20 = new ArrayList<String>();
List20.add(d);
System.out.println(List20.get(0));
System.out.println("Access Right no point will be added");
}