TextViews become uneditable after reactivating activity? - android

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?).

Related

android textview settext is not displayed

Im facing a problem. After running app , the textview I set is not displayed. This is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView rangeLabel = (TextView) findViewById(R.id.range_label);
final TextView beaconMacAddressLabel = (TextView) findViewById(R.id.beacon_mac_address_label);
final TextView beaconUuidLabel = (TextView) findViewById(R.id.beacon_uuid_label);
final TextView beaconVersionLabel = (TextView) findViewById(R.id.beacon_major_minor_label);
final TextView beaconStatsLabel = (TextView) findViewById(R.id.beacon_stats_label);
rangeLabel.setTextColor(Color.BLACK);
rangeLabel.setText(R.string.question_mark);
region = new Region("regionid", null, null, null);
beaconManager = new BeaconManager(this);
beaconManager.setRangingListener(new RangingListener() {
#Override
public void onBeaconsDiscovered(Region region, final List<Beacon> beacons) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!beacons.isEmpty()) {
Beacon closestBeacon = beacons.get(0);
beaconMacAddressLabel.setText(getString(R.string.mac_address) + " : " + closestBeacon.getMacAddress());
beaconUuidLabel.setText(closestBeacon.getProximityUUID());
beaconVersionLabel.setText(getString(R.string.major) + ": "+closestBeacon.getMajor() +
" " + getString(R.string.minor) + ": " + closestBeacon.getMinor());
beaconStatsLabel.setText(getString(R.string.power) + ": " +
closestBeacon.getMeasuredPower() +
" " +
getString(R.string.dbm) +
" | " +
getString(R.string.rssi) +
": " + closestBeacon.getRssi());
double accuracy = Utils.computeAccuracy(closestBeacon);
switch (Utils.proximityFromAccuracy(accuracy)) {
case FAR:
rangeLabel.setText(R.string.cold);
rangeLabel.setTextColor(getResources().getColor(R.color.cold_colour));
rangeLabel.setBackgroundResource(R.drawable.cold_indicator_background);
break;
case NEAR:
rangeLabel.setText(R.string.warm);
rangeLabel.setTextColor(getResources().getColor(R.color.warm_colour));
rangeLabel.setBackgroundResource(R.drawable.warm_indicator_background);
break;
case IMMEDIATE:
rangeLabel.setText(R.string.hot);
rangeLabel.setTextColor(getResources().getColor(R.color.hot_colour));
rangeLabel.setBackgroundResource(R.drawable.hot_indicator_background);
break;
case UNKNOWN:
rangeLabel.setText(R.string.question_mark);
rangeLabel.setTextColor(Color.BLACK);
rangeLabel.setBackgroundResource(R.drawable.indicator_background);
break;
is there anything wrong in mycode? only the title(set in XML) and rangelable(set at line 10) are displayed. None of other. anyone know why?
Ive tried to change color but no help. Guess there something wrong with my code
in case needed, this is my XML:
https://github.com/KarlNosworthy/hotwarmcold/blob/master/HotWarmColdApp/src/main/res/layout/activity_main.xml
looks like Range label is centered in the middle of the screen.
it's probably covering the other labels
try hiding it to see if you you see the other labels.
and I'm not sure what you are trying to accomplish. but you might want to user LinearLayout instead of relative...

display multiplication table in TextView

I am trying to generate a multiplication table,where the 1st EditText takes the actual number while 2nd EditText takes the actual range of multiplication table. When I run the project , the result is only number * range..
can anyone help me in the loop or code below mentioned Or,any alternatives to display the table in GridLayout or TableLayout rather than TextView.
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multiplication_table);
number = (EditText)findViewById(R.id.numberTable);
range = (EditText)findViewById(R.id.numberRange);
click = (Button)findViewById(R.id.click);
result = (TextView)findViewById(R.id.display);
final String x = range.getText().toString();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
for(int i = 1 ; i <= 10; i++)
{
for(int j = 1 ; j <= 10; j++)
{
int res = a * b;
result. setText(a +" * " + b + " = " + res);
}
}
return;
}
});
}
}
you are calling setText() for every row, but setText() will reset the text of the TextView, you might want to use append() instead
result.setText("");
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
for(int i = 1 ; i <= b; i++){
int res = a * i;
result.append(a +" * " + i + " = " + res + "\n");
}
or maybe use StringBuilder
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
StringBuilder builder = new StringBuilder();
for(int i = 1 ; i <= b; i++){
int res = a * i;
builder.append(a +" * " + i + " = " + res + "\n");
}
result.setText(builder.toString())

Check Scores in Android Studio

This is my Code. When the user enters their answer and press the Submit Button which is the AnswerCheck Method, i would like the score to be shown in a TextView for example - if they input the right answer, the TextView would state 1 correct out of 1. I would like some help, Thanks
public class Perimeter extends AppCompatActivity {
private int number;
private int number2;
private String myString;
private String myString2;
private int perimeter;
private Random rand;
private Random rand2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_perimeter);
rand = new Random();
rand2 = new Random();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void PerimeterGame(View view) {
number = rand.nextInt(12) + 1;
TextView myText = (TextView) findViewById(R.id.rand1);
myString = String.valueOf(number);
myText.setText(myString);
number2 = rand2.nextInt(12) + 1;
TextView myText2 = (TextView) findViewById(R.id.rand2);
myString2 = String.valueOf(number2);
myText2.setText(myString2);
((TextView) findViewById(R.id.question)).setText
("Find the perimeter of a rectange with a width of " + myString + "cm" + " and " + "length of " + myString2 + "cm" + ".");
}
public void AnswerCheck(View view) {
EditText num = (EditText) findViewById(R.id.answertext);
int val = Integer.parseInt(num.getText().toString());
perimeter = (number + number2 + number + number2);
if (val == perimeter) {
Toast.makeText(this, "The answer is correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "The answer is incorrect ", Toast.LENGTH_SHORT).show();
}
findViewById(R.id.showsolbutton).setEnabled(true);
}
}
Set two global int variables
private int totalQuestion = 0;
and private int correctQuestions = 0;
Inside public void PerimeterGame(View view) increment totalQuestion by one.
When the answer is correct, inside public void AnswerCheck(View view) increment correctQuestion by one.
Finally, display the text
youTextView.setText(String.valueOf(correctQuestions) + " correct out of " + String.valueOf(totalQuestion));
Hope it helps.
public class Perimeter extends AppCompatActivity {
// Code ommitted
private int totalQuestion = 0 ;
private int correctQuestions = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Code ommitted
}
public void PerimeterGame(View view) {
// Increment totalQuestion
totalQuestion++;
number = rand.nextInt(12) + 1;
TextView myText = (TextView) findViewById(R.id.rand1);
myString = String.valueOf(number);
myText.setText(myString);
number2 = rand2.nextInt(12) + 1;
TextView myText2 = (TextView) findViewById(R.id.rand2);
myString2 = String.valueOf(number2);
myText2.setText(myString2);
((TextView) findViewById(R.id.question)).setText
("Find the perimeter of a rectange with a width of " + myString + "cm" + " and " + "length of " + myString2 + "cm" + ".");
}
public void AnswerCheck(View view) {
EditText num = (EditText) findViewById(R.id.answertext);
int val = Integer.parseInt(num.getText().toString());
perimeter = (number + number2 + number + number2);
if (val == perimeter) {
correctQuestions++;
Toast.makeText(this, "The answer is correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "The answer is incorrect ", Toast.LENGTH_SHORT).show();
}
findViewById(R.id.showsolbutton).setEnabled(true);
// Display text
youTextView.setText(String.valueOf(correctQuestions) + " correct out of " + String.valueOf(totalQuestion));
}
}

Passing data from one activity to another causes force close

I'm new to Android Programming world and this is driving me crazy. Any help would be appreciated !
Everything works fine except the intent putextra , getextra code part. Since when I added this part to the project, whenever I click on a button which would teorically start a new activity, force closes.
Below is MainActivity.java
public class MainActivity extends Activity {
EditText inputA, inputB, inputC;
TextView nrRoots, root1, root2, roots;
Button bStepByStep, calculate;
Double a, b, c, D, x1, x2, x, dRootNr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputA = (EditText) findViewById(R.id.etParamA);
inputB = (EditText) findViewById(R.id.etParamB);
inputC = (EditText) findViewById(R.id.etParamC);
nrRoots = (TextView) findViewById(R.id.tvNrRoots);
root1 = (TextView) findViewById(R.id.tvRoot1);
roots = (TextView) findViewById(R.id.tvRoots);
root2 = (TextView) findViewById(R.id.tvRoot2);
calculate = (Button) findViewById(R.id.bCalculate);
bStepByStep = (Button) findViewById(R.id.bStepByStep);
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
a = Double.parseDouble(inputA.getText().toString());
b = Double.parseDouble(inputB.getText().toString());
c = Double.parseDouble(inputC.getText().toString());
double D = Math.sqrt((b * b) - (4 * a * c));
if (D == 0) {
nrRoots.setText("The equation " + a + "x^2+" + b + "x+" + c
+ "=0 has 1 distinct root.");
x = ((-1) * b) / (2 * a);
root1.setText("x=" + x);
root2.setText("");
roots.setText("");
} else if (D > 0) {
nrRoots.setText("The equation " + a + "x^2+" + b + "x+" + c
+ "=0 has 2 distinct roots.");
x1 = (((-1) * b) + D) / (2 * a);
x2 = (((-1) * b) - D) / (2 * a);
root1.setText("x1= " + x1);
root2.setText("x2= " + x2);
} else {
nrRoots.setText("The equation " + a + "x^2+" + b + "x+" + c
+ "=0 has no distinct roots.");
root1.setText("");
root2.setText("");
}
}
});
bStepByStep.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(MainActivity.this, NewActivity.class);
i.putExtra("a", a);
i.putExtra("b", b);
i.putExtra("c", c);
i.putExtra("D", D);
i.putExtra("x1", x1);
i.putExtra("x2", x2);
startActivity(i);
finish();
}
});
}
}
here is NewActivity.java
public class NewActivity extends Activity {
Intent i = getIntent();
Double a = i.getExtras().getDouble("a");
Double b = i.getExtras().getDouble("b");
Double c = i.getExtras().getDouble("c");
Double D = i.getExtras().getDouble("D");
Double x1 = i.getExtras().getDouble("x1");
Double x2 = i.getExtras().getDouble("x2");
TextView bb;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.new_activity);
bb = (TextView) findViewById(R.id.tvArbli);
bb.setText("a=" + a + " " + b + " " + c + " " + D + " " + x1 + " " + x2);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
What am I doing wrong ?
You can't retrieve the intent during class instansiation.
Change your code to something like this...
public class NewActivity extends Activity {
Intent i;
TextView bb;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.new_activity);
i = getIntent();
Double a = i.getExtras().getDouble("a");
Double b = i.getExtras().getDouble("b");
Double c = i.getExtras().getDouble("c");
Double D = i.getExtras().getDouble("D");
Double x1 = i.getExtras().getDouble("x1");
Double x2 = i.getExtras().getDouble("x2");
bb = (TextView) findViewById(R.id.tvArbli);
bb.setText("a=" + a + " " + b + " " + c + " " + D + " " + x1 + " " + x2);
}
PS You need to do a lot of validation!
Also, always include you logcat (stack trace) for any sort of crash.

Show number of Notifications on the side navigation menu

I am using Horizontal ScrollView to get facebook like side navigation
Like this:
But how to show that "2" beside the Event item in the menu?
In my application i am using a ViewUtil class to get this menu:
public class ViewUtils {
private ViewUtils() {
}
public static void setViewWidths(View view, View[] views) {
int w = view.getWidth();
int h = view.getHeight();
for (int i = 0; i < views.length; i++) {
View v = views[i];
v.layout((i + 1) * w, 0, (i + 2) * w, h);
printView("view[" + i + "]", v);
}
}
public static void printView(String msg, View v) {
System.out.println(msg + "=" + v);
if (null == v) {
return;
}
System.out.print("[" + v.getLeft());
System.out.print(", " + v.getTop());
System.out.print(", w=" + v.getWidth());
System.out.println(", h=" + v.getHeight() + "]");
System.out.println("mw=" + v.getMeasuredWidth() + ", mh="
+ v.getMeasuredHeight());
System.out.println("scroll [" + v.getScrollX() + "," + v.getScrollY()
+ "]");
}
public static void initListView(Context context, ListView listView,
String prefix, int numItems, int layout) {
// By using setAdpater method in listview we an add string array in
// list.
String[] arr = new String[numItems];
arr[0] = "Feed";
arr[1] = "Friends";
arr[2] = "Notifications";
arr[3] = "Feedback";
arr[4] = "Logout";
listView.setAdapter(new ArrayAdapter<String>(context, layout, arr));
}
}
and set the adapter like this in the Activity:
ViewUtils.initListView(this, myListView, "Menu ", 5,
android.R.layout.simple_list_item_1);
I what my "Notifications" Text to be something like "Notification n" where n is like the "2" in the above pic. I tried to use Spannable String but i cannot set the Spannable String to the String Array "arr"
Thank You
I'm assuming those categories (News Feed, Messages,...) are items of a ListView.
Also, for displaying that "2" I'm assuming you will need a custom adapter.
In this case you just need to add a TextView to your row XML file and set the appropriate value in the getView() method of your custom Adapter, or, if you are create the TextView programaticaly in the getView() method.

Categories

Resources