I have a list view with a list of channels on them and when I press one of the channels, it starts to load a streaming URL to watch the channel. However, I can still navigate through the list and select another entry in the list which causes an Exception to occur. How can I disable controller input similar to how I can disable touch input once something has been pressed?
Here is the code for my onItemClickListener:
channel_list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
main_progressBar.setVisibility(View.VISIBLE);
//to disable touch input
//getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
final int channel = channelListAdapter.getItem(position);
final String switch_major = majorChannelNumberList.get(channel);
Log.d(TAG, "Switch Major :" + switch_major);
final String switch_minor = minorChannelNumberList.get(channel);
Log.d(TAG, "Switch Minor :" + switch_minor);
final String switch_name = channelNameList.get(channel);
Log.d(TAG, "Switch Name :" + switch_name);
final String tuner = tuneLink + "Major=" + switch_major + "&Minor=" + switch_minor + "&Resolution=" + "1280x720";
Log.d(TAG, "Tuner String :" + tuner);
new Thread(new Runnable() {
#Override
public void run() {
String playlive = "";
String tuneResponse = tuneConnection.get_response(tuner);
if(tuneResponse.contains("successful")){
long startTime = System.currentTimeMillis();
do {
String hlsStatusResponse = hlsConnection.get_response(HLSLink);
Log.d(TAG,"HLS Status Response :" + hlsStatusResponse);
Matcher matcher = Pattern.compile("<hls_link>(.+?)</hls_link>").matcher(hlsStatusResponse);
while(matcher.find()){
playlive = matcher.group(1);
}
playlink = "http://" + ip + "/" + playlive;
} while (Objects.equals(playlive, "none") && (System.currentTimeMillis()-startTime)<20000);
if(!playlink.contains("none")){
streamConnection.get_response(playlink);
} else {
//TODO: implement some sort of message here to show no channel, see tablet app
}
} else {
Toast.makeText(OfflineActivity.this, "Ch " + switch_major + "-" + switch_minor + " " + switch_name + " is not available now",
Toast.LENGTH_LONG).show();
}
}
}).start();
//start player activity
streamConnection.responseHandler = new Handler(){
#Override
public void handleMessage(Message message){
Toast.makeText(OfflineActivity.this, "Tune to Channel " + switch_major + "-" + switch_minor, Toast.LENGTH_LONG).show();
Intent intent = new Intent(OfflineActivity.this, OfflinePlaybackActivity.class);
intent.putExtra("stream",playlink);
intent.putExtra("channel_index", channel);
startActivity(intent);
main_progressBar.setVisibility(View.INVISIBLE);
}
};
}
});
I know I can use
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
to disable touch input, looking for something similar for Amazon Fire TV.
Decided to use channel_list_view.setClickable(false) to prevent user from clicking on it.
This is activityresult1
Button buttonorder;
TextView textviewcard;
private static final int REQUEST_CODE = 10;
int[] image ={R.drawable.friednoodle, R.drawable.friedrice, R.drawable.steamfish,R.drawable.tehice};
String[] item = {"Fried Noodle", "Fried Rice", "Steam Fish","Iced Tea"};
String[] description = {"Classic Chinese stir fried noodle with prawn and Pork", "Special sauce Fried Rice using indian rice", "HongKong Style Steamed Fish ","HongKong classical iced tea"};
String[] cost={"6","5","25","2"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activityresult1);
Bundle extras = getIntent().getExtras();
String strcardnumber = extras.getString("Card Number");
textviewcard = (TextView) findViewById(R.id.textviewcard);
textviewcard.setText("Welcome, " + strcardnumber + " !" + "\nPlease select the food you want ! : ");
itemList = new ArrayList<DataInfo>();
itemList.add(new DataInfo(item[0], image[0], description[0], cost[0]));
itemList.add(new DataInfo(item[1], image[1], description[1], cost[1]));
itemList.add(new DataInfo(item[2], image[2], description[2], cost[2]));
itemList.add(new DataInfo(item[3], image[3], description[3], cost[3]));
final MenuAdapter adapter = new MenuAdapter(this);
ListView listView = (ListView)findViewById(R.id.list);
LVAdapter lvAdapter = new LVAdapter(this, itemList);
//listView.setAdapter(lvAdapter);
listView.setAdapter(adapter);
for (int i = 0; i < item.length; i++) {
adapter.addData(String.valueOf(i), item[i], image[i], description[i], cost[i]);
}
buttonorder = (Button) findViewById(R.id.suborder);
buttonorder.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String[] a = adapter.getQuantity();
Toast.makeText(getApplicationContext(), "Noodle: " + a[0] + "\nRice: " + a[1] + "\nSteam fish: " + a[2] + "\nIced tea: " + a[3], Toast.LENGTH_LONG).show();
int sum = Integer.parseInt(adapter.getQuantity()[0])*Integer.parseInt(cost[0]) +
Integer.parseInt(adapter.getQuantity()[1])*Integer.parseInt(cost[1]) +
Integer.parseInt(adapter.getQuantity()[2])*Integer.parseInt(cost[2]) +
Integer.parseInt(adapter.getQuantity()[3])*Integer.parseInt(cost[3]);
Intent myIntent = new Intent(activityresult1.this, activityresult2.class);
myIntent.putExtra("sum",sum);
startActivity(myIntent);
Intent intent = new Intent(getApplicationContext(), activityresult2.class);
Bundle bundle = new Bundle();
bundle.putString("Noodle quantity", adapter.getQuantity()[0]);
bundle.putString("Rice quantity", adapter.getQuantity()[1]);
bundle.putString("Fish quantity", adapter.getQuantity()[2]);
bundle.putString("Iced tea", adapter.getQuantity()[3]);
bundle.putInt("sum", sum);
bundle.putBoolean("ANI", adapter.getItem(0).isAddInisCheck());//add noodle ingredients
bundle.putBoolean("ARI", adapter.getItem(1).isAddInisCheck()); // add rice ingredients
bundle.putBoolean("AFI", adapter.getItem(2).isAddInisCheck());// add fish ingredients
bundle.putBoolean("AIT", adapter.getItem(3).isAddInisCheck()); // add ice tea ingredients
intent.putExtras(bundle);
startActivityForResult(intent, REQUEST_CODE);
}
});
}
how do i sent the calculated sum from activityresult1 to activityresult2
static public String txtOrder ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activityresult2);
Bundle bundle = getIntent().getExtras();
String strfnq = bundle.getString("Noodle quantity");
String strfrq = bundle.getString("Rice quantity");
String strfsq = bundle.getString("Fish quantity");
String stricq = bundle.getString("Iced tea");
Integer strsum = bundle.getInt("sum");
boolean addNingc = bundle.getBoolean("ANI");
boolean addRingc = bundle.getBoolean("ARI");
boolean addFingc = bundle.getBoolean("AFI");
boolean addTingc = bundle.getBoolean("AIT");
// boolean addmoneyc = bundle.getBoolean("AMY");
Intent mIntent = getIntent();
int sum = mIntent.getIntExtra("sum",strsum);
TextView costtext = (TextView)findViewById(R.id.costtext);
costtext.setText(getIntent().getExtras().getString("sum"));
TextView foodorders = (TextView) findViewById(R.id.foodordershow);
foodorders.setText(getIntent().getExtras().getString("Quantity"));
String addNdlThing = "";
if (addNingc) {
addNdlThing = " with addition of ingredients";
}
String addRlThing = "";
if (addRingc) {
addRlThing = " with addition of ingredients";
}
String addSlThing = "";
if ( addFingc) {
addSlThing = " with addition of ingredients";
}
String addTeac = "";
if ( addTingc ) {
addTeac = " with addition of ingredients";
}
foodorders = (TextView) findViewById(R.id.foodordershow);
if(strfnq.equals("") && strfrq.equals("") && strfsq.equals("")&& stricq.equals("")){
txtOrder = "Sorry, You've not ordered any thing , please return to previous menu to order";
}else if (!strfnq.equals("") && !strfrq.equals("") && !strfsq.equals("")&& stricq.equals("")) {
txtOrder = "Thank you , You've ordered\n" + strfnq + " fried noodle" + addNdlThing +" and\n"+ strfrq
+ " fried rice" + addRlThing +" and\n" + strfsq + " Steam fish " + addSlThing + "and\n" + stricq + " Steam fish " + addTeac;
} else {
txtOrder = "Thank you , You've ordered\n";
if(!strfnq.equals("")){
txtOrder = txtOrder + strfnq + " fried noodle" + addNdlThing;
}
if(!strfrq.equals("")){
txtOrder = txtOrder + strfrq + " fried rice" + addRlThing;
}
if(!strfsq.equals("")){
txtOrder = txtOrder + strfsq + " Steam fish" + addSlThing;
}
if(!stricq.equals("")){
txtOrder = txtOrder + stricq + " Iced Tea"+ addTeac;
}
}
foodorders.setText(txtOrder);
}
i want to calculate the money spent in result1 and display it in result 2
i have tried using the method they written at the bottom but it dont work as i dont know what to fill in for some . please help me , i really need help on this , and i am typing alot to make the word count so i can post , as i have too much codes they say , and please stop disliking this post , dont be such persons , like this and it will be happy for both parties , asking question dont mean i am stupid
You can sent the value of the sum to the next activity and get it via Bundle in the other activity like this. Think that your are sending it to the activity B
Intent i= new Intent(this,B.class);
i.putExtra("sum",sum);
startActivity(i);
you can send the context to the activity B through either one of the following this,getActivity(),getApplicationContext()
Then inactivity B you can add these lines in onCreate() method, to get the passed content
Bundle MainActivityData= getIntent().getExtras();
int sum= MainActivityData.getString("sum");
This question already has answers here:
Round a double to 2 decimal places [duplicate]
(13 answers)
Closed 9 years ago.
For my simple calculator, I am showing the result in a TextView, but it is always showing decimals. How can I remove them ?
This is my code :
public class MainActivity extends Activity implements OnClickListener {
EditText etNum1;
EditText etNum2;
Button btnAdd;
Button btnSub;
Button btnMult;
Button btnDiv;
TextView tvResult;
String oper = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// find the elements
etNum1 = (EditText) findViewById(R.id.etNum1);
etNum2 = (EditText) findViewById(R.id.etNum2);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnSub = (Button) findViewById(R.id.btnSub);
btnMult = (Button) findViewById(R.id.btnMult);
btnDiv = (Button) findViewById(R.id.btnDiv);
tvResult = (TextView) findViewById(R.id.tvResult);
// set a listener
btnAdd.setOnClickListener((OnClickListener) this);
btnSub.setOnClickListener(this);
btnMult.setOnClickListener(this);
btnDiv.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
double num1=0;
double num2=0;
double result=0;
// check if the fields are empty
if (TextUtils.isEmpty(etNum1.getText().toString())
|| TextUtils.isEmpty(etNum2.getText().toString())) {
return;
}
// read EditText and fill variables with numbers
num1 = Double.parseDouble(etNum1.getText().toString());
num2 = Double.parseDouble(etNum2.getText().toString());
// defines the button that has been clicked and performs the corresponding operation
// write operation into oper, we will use it later for output
switch (v.getId()) {
case R.id.btnAdd:
oper = "+";
result = num1 + num2;
break;
case R.id.btnSub:
oper = "-";
result = num1 - num2;
break;
case R.id.btnMult:
oper = "*";
result = num1 * num2;
break;
case R.id.btnDiv:
oper = "/";
result = num1 / num2;
break;
default:
break;
}
// form the output line
tvResult.setText(num1 + " " + oper + " " + num2 + " = " + result);
}
}
A non mathematical way to do it:
A short and simple method is, convert the double to string:
String text = String.valueOf(result);
Now you have the result in the string. Given that your requirement is that you don't want decimals, so split your string based on "." as a delimiter:
String str[] = text.split(".");
Now in str[0] you will have only the number part. so set it to the text view:
tvResult.setText(num1 + " " + oper + " " + num2 + " = " + str[0]);
I'm sure this one works fine.
You can use DecimalFormat to format the result:
DecimalFormat df = new DecimalFormat("0.##########");
tvResult.setText(num1 + " " + oper + " " + num2 + " = " + df.format(result));
This will print with up to 10 decimal places.
Many ways to do that, i use:
public static double round(double value, int places) {
if (places < 0)
throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
And then call:
round(yourAnswer, 2)
For BigDecimal:
http://developer.android.com/reference/java/math/BigDecimal.html
Efficient BigDecimal round Up and down to two decimals
I'm trying to randomly pick a string from an array and spit it out to the user, but whenever I try to run it via AVD the app crashes. I'm very much a novice at this, and can't figure out what to do.
Here is my code:
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final LinearLayout rr = new LinearLayout (this);
// setting up the LinearLayout. I'll get to proper formatting one I get the code running.
Button b1 = new Button (this);
b1.setId(R.id.Button01);
b1.setText("Generate");
rr.addView(b1);
final TextView tv;
tv = new TextView(this);
tv.setId(R.id.Text1);
rr.addView(tv);
setContentView(rr);
final String [] columnA = { "artless", "bawdy", "beslubbering", "bootless", "churlish", "cockered", "clouted", "craven", "currish", "dankish", "dissembling", "droning", "errant", "fawning", "fobbing", "froward", "frothy", "gleeking", "goatish", "gorbellied", "impertinent", "infectious", "jarring", "loggerheaded", "lumpish", "mammering", "mangled", "mewling", "paunchy", "pribbling", "puking", "puny", "qualling", "rank", "reeky", "roguish", "ruttish", "saucy", "spleeny", "spongy", "surly", "tottering", "unmuzzled", "vain", "venomed", "villainous", "warped", "wayward", "weedy", "yeasty" };
final String [] columnB = { "base-court", "bat-fowling", "beef-witted", "beetle-headed", "boil-brained", "clapper-clawed", "clay-brained", "common-kissing", "crook-patted", "dismal-dreaming", "dizzy-eyed", "doghearted", "dread-boiled", "earth-vexing", "elf-skinned", "fat-kidneyed", "fen-sucked", "flap-mouthed", "fly-bitten", "folly-fallen", "fool-born", "full-gorged", "guts-gripping", "hasty-witted", "half-faced", "hell-hated", "idle-headed", "ill-breeding", "ill-nurtured", "knotty-pated", "milk-livered", "motley-minded", "onion-eyed", "plume-plucked", "pottle-deep", "pox-marked", "reeling-riped", "rough-hewn", "rude-growing", "rump-fed", "shard-borne", "sheep-biting", "spur-galled", "swag-bellied", "tardy-gaited", "tickle-brained", "toad-spotted", "unchin-snouted", "weather-bitten"};
final String [] columnC = { "apple-john", "baggage", "barnacle", "bladder", "boar-pig", "bugbear", "bum-bailey", "canker-blossom", "clack-dish", "clotpole", "coxcomb", "codpiece", "death-token", "dewberry", "flap-dragon", "flax-wench", "flirt-gill", "foot-licker", "fustilarian", "giglet", "gudgeon", "haggard", "harpy", "hedge-pig", "horn-beast", "hugger-mugger", "joithead", "lewdster", "lout", "maggot-pie", "malt-worm", "mammet", "measle", "minnow", "miscreant", "moldwarp", "mumble-news", "nut-hook", "pigeon-egg", "pignut", "puttock", "pumpion", "ratsbane", "scut", "skainsmate", "strumpet", "varlot", "vassal", "whey-face", "wagtail"};
//Attempts to pick one string from each array, add "thou art a" and spaces, and display it to the device.
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String outputA;
Random r;
r = new Random(columnA.length);
Random s;
s = new Random(columnB.length);
Random t;
t = new Random(columnC.length);
outputA = "Thou art a" + " " + columnA[r.nextInt() % columnA.length] + " " + columnB[s.nextInt() % columnB.length] + " " + columnC[t.nextInt() % columnC.length];
tv.setText(outputA);
}
});
}
#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;
}
I imagine you were getting an ArrayIndexOutOfBoundsException
To solve, remove all the Randoms and change your onClickListener to:
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String outputA = "Thou art a" + " " + columnA[(int) (Math.random() * columnA.length)] + " " + columnB[(int) (Math.random() * columnB.length)] + " " + columnC[(int) (Math.random() * columnC.length)];
tv.setText(outputA);
}
});
So currently I am making an educational application where users can view how to solve a given problem by pressing a button. While my code works fine initially, when I hit the back button and click my View Solution button, my default layout pops up and I cannot edit the last four TextViews. Here is my code:
public class AdditionTensSolutionActivity extends Activity {
public static ArrayList<TextView> explain = new ArrayList<TextView>(3);
public static Button nextstep;
public static int onesnum1 = TensAdditionExerciseActivity.n1display % 10;
public static int onesnum2 = TensAdditionExerciseActivity.n2display % 10;
public static int onesanswer = onesnum1 + onesnum2;
public static int onesanswermod = onesanswer % 10;
public static int tensnum1 = TensAdditionExerciseActivity.n1display / 10;
public static int tensnum2 = TensAdditionExerciseActivity.n2display / 10;
public static int tensanswer = tensnum1 + tensnum2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showsolutionlayout);
TextView numrow1 = (TextView) findViewById(R.id.solproblemrow1);
TextView numrow2 = (TextView) findViewById(R.id.solproblemrow2);
TextView solution = (TextView) findViewById(R.id.solutiontextview);
TextView carryover = (TextView) findViewById(R.id.carryovernumbers);
TextView exp1 = (TextView) findViewById(R.id.explain1);
TextView exp2 = (TextView) findViewById(R.id.explain2);
TextView exp3 = (TextView) findViewById(R.id.explain3);
TextView exp4 = (TextView) findViewById(R.id.explain4);
numrow1.setText(TensAdditionExerciseActivity.n1display + "");
numrow2.setText(" " + TensAdditionExerciseActivity.n2display + " +");
explain.add(exp1);
explain.add(exp2);
explain.add(exp3);
explain.add(exp4);
nextstep = (Button) findViewById(R.id.nextstep);
for (int i = 0; i < 4; i++) {
explain.get(i).setVisibility(View.GONE);
}
solution.setVisibility(View.GONE);
carryover.setVisibility(View.GONE);
explain.get(0).setText("test");
setTextViews();
nextButtonsetOnClickListener();
}
protected void nextButtonsetOnClickListener() {
nextstep.setOnClickListener(new View.OnClickListener() {
int i = 0;
public void onClick(View v) {
explain.get(i).setVisibility(View.VISIBLE);
i++;
if (i > 2 && onesanswer < 10) {
nextstep.setClickable(false);
}
if (i > 3 && onesanswer >= 10) {
nextstep.setClickable(false);
}
}
});
}
protected void setTextViews() {
explain.get(0).setText(
"Add " + (onesnum1) + " and " + (onesnum2) + " which equals "
+ (onesanswer) + ".");
if (onesanswer >= 10) {
explain.get(1).setText(
"Since the answer is 10 or greater, 1 must carry over to the tens place and "
+ onesanswermod + " is left in the ones place.");
explain.get(2).setText(
"Add the tens place digits, " + tensnum1 + " and "
+ tensnum2
+ ". Don't forget to add the carried over 1!");
explain.get(3).setText(
"1 + " + tensnum1 + " + " + tensnum2 + " = "
+ (tensanswer + 1));
} else {
explain.get(1).setText(
"Add the tens place digits: " + tensnum1 + " and "
+ tensnum2 + ".");
explain.get(2).setText(
tensnum1 + " + " + tensnum2 + " = " + tensanswer);
}
Ah, I figured it out. I had my ArrayList set to static rather than final, but I still do not completely the entirety of my error. Would someone be willing to tell me why it made such a big difference?
A static variable / method has only one instance for the entire class. That means, that in the case of your listview, only one exists for all instances of your activity in the entire app, which is why your getting your error. Final means that it can't be initialized anywhere other than the constructor or when the variable is defined. (Difference between Static and final?).