I have an autogenerated list of edittexts gotten from the user input. What i want to do is shuffle the edittexts when the shuffle button is clicked or get the texts and set them to different edittexts. What i tried doing is to get the texts of each edittext adding it to an arraylist and shuffling it and then recreating the layout with the shuffled list. But that in itself is giving me errors. When the shuffle button is clicked it gives me this error
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
Thanks For the help
`
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnForCreate = (Button) findViewById(R.id.btnCreateTxt);
editTextForInputToCreate = (EditText) findViewById(R.id.textForInputToCreate);
listLayout = (LinearLayout) findViewById(R.id.listLayout);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnShuffleTxt = (Button) findViewById(R.id.btnShuffleTxt);
editTextForInputToCreate.animate().translationX(-1000f);
btnForCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bringTextInputBackOnScreen();
}
});
btnDisplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (editTextForInputToCreate.getText().toString().length() >= 0) {
try {
listLayout.removeAllViews();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
length = Integer.parseInt(editTextForInputToCreate.getText().toString());
for (i = 0; i < length; i++) {
editTextCollection = new EditText[length];
editText = new EditText(MainActivity.this);
editText.setId(i + 1);
editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
editText.setHint("Input" + " " + (i + 1));
listLayout.addView(editText);
editTextCollection[i] = editText;
}
}
});
btnShuffleTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listLayout.removeAllViews();
for (EditText gottenEditText:editTextCollection)
{
String gottenTexts = gottenEditText.getText().toString();
list.add(gottenTexts);
}
Collections.shuffle(list);
}
});
}
private void bringTextInputBackOnScreen()
{
editTextForInputToCreate.animate().translationXBy(1000f).setDuration(2000);
}
`
Please make some corrections in your EditTextCollection.
editTextCollection = new EditText[length];// initialization outside the loop
for (i = 0; i < length; i++) {
editText = new EditText(MainActivity.this);
editText.setId(i + 1);
editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
editText.setHint("Input" + " " + (i + 1));
listLayout.addView(editText);
editTextCollection[i] = editText;
}
btnShuffleTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listLayout.removeAllViews();
for (EditText gottenEditText:editTextCollection)
{
String gottenTexts = gottenEditText.getText().toString();
list.add(gottenTexts);
}
Collections.shuffle(list);
for (EditText gottenEditText:editTextCollection)
{
gottenEditText.setText(list.get(editTextCollection.indexOf(gottenEditText)));
}
}
});
Related
Im making a cgpa calculator in android studio but app crash on following line always.gpa=Double.parseDouble(marks_et.getText().toString());
complete code is here.
public class CgpaActivity extends AppCompatActivity {
GridLayout DynamicEditTextHolder;
EditText edtNoCreate,marks_et,cr_et,cgpa_ET;
Button btnCreate,CalculateGPA;
TextView course;
double cgpa = 0,gpa,sumgpa = 0;
int i,length;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cgpa);
DynamicEditTextHolder = findViewById(R.id.DynamicEditTextHolder);
edtNoCreate = (EditText) findViewById(R.id.edtNoCreate);
cgpa_ET=findViewById(R.id.cgpa_ET);
btnCreate = (Button) findViewById(R.id.btnCreate);
CalculateGPA=findViewById(R.id.CalculateGPA);
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(edtNoCreate.getText().toString().length()>0) {
try {
DynamicEditTextHolder.removeAllViews();
} catch (Throwable e) {
e.printStackTrace();
}
length = Integer.parseInt(edtNoCreate.getText().toString());
for ( i=1;i<=length;i++){
course=new TextView(CgpaActivity.this);
course.setId(i);
course.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
course.setX(10);
// course.setX(ALIGN_BOUNDS);
// course.setRowOrderPreserved(false);
course.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
course.setText("Course"+(i));
DynamicEditTextHolder.addView(course,new GridLayout.LayoutParams());
marks_et = new EditText(CgpaActivity.this);
marks_et.setId(i);
marks_et.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
marks_et.setHint("marks ");
marks_et.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
DynamicEditTextHolder.addView(marks_et,new GridLayout.LayoutParams());
gpa=Double.parseDouble(marks_et.getText().toString());
sumgpa += gpa;
}
}
}
});
CalculateGPA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
{
cgpa = sumgpa / length;
cgpa_ET.setText(String.valueOf(cgpa));
}
}
});
}
}
One Linearlayout I have created and dynamically I am adding RadioGroup and textView in it. When next time I am calling the method, Textview is getting removed but old radio buttons are not getting removed.
Here is the code:
public void setShippingMethods() {
shippingChargesLayout.removeAllViews();
final RadioGroup radioGroup = new RadioGroup(getActivity());
radioGroup.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(getActivity());
textView.setText("Select Shipping Options:");
shippingChargesLayout.addView(textView);
for (int i = 0; i < shippingDetailsList.size(); i++) {
RadioButton radioButton = new RadioButton(getActivity());
radioButton.setText("" + shippingDetailsList.get(i).getMethodTitle() + "-" + (new SessionManager(getActivity()).getCurrency()) + df.format(shippingDetailsList.get(i).getAmount()));
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
radioGroup.addView(radioButton, params);
radioButton.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
shippingChargesLayout.addView(radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
shipmentCode = shippingDetailsList.get(i - 1).getCarrierCode();
Log.v("carrierCode", "" + shipmentCode);
}
});
checkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(getActivity(),"Select shipping options.",Toast.LENGTH_LONG).show();
} else {
completeOrder();
}
}
});
}
Here is the image:
I have made some changes in your code.
public void setShippingMethods() {
shippingChargesLayout.removeAllViews();
final RadioGroup radioGroup = new RadioGroup(getActivity());
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
radioGroup.setLayoutParams(params);
radioGroup.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(getActivity());
textView.setText("Select Shipping Options:");
shippingChargesLayout.addView(textView);
for (int i = 0; i < shippingDetailsList.size(); i++) {
RadioButton radioButton = new RadioButton(getActivity());
radioButton.setText("" + shippingDetailsList.get(i).getMethodTitle() + "-" + (new SessionManager(getActivity()).getCurrency()) + df.format(shippingDetailsList.get(i).getAmount()));
radioGroup.addView(radioButton);
}
shippingChargesLayout.addView(radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
shipmentCode = shippingDetailsList.get(i - 1).getCarrierCode();
Log.v("carrierCode", "" + shipmentCode);
}
});
checkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(getActivity(),"Select shipping options.",Toast.LENGTH_LONG).show();
} else {
completeOrder();
}
}
});
}
I have 5 choices in a test. I have a csv database which I read the headers and answers from. When I press on one of the buttons, I want the Text on the button to change to the next header. I want to use a "for" loop for that. How will I keep the same layout, but change the text on the buttons in this for loop?
public class MainActivity extends AppCompatActivity {
int say,may=0;
Button a,b,c,d,e;
private List<WeatherSample> weatherSamples=new ArrayList<>();
String[][] deneme=new String[20][7];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button asikki = (Button) findViewById(R.id.asikki);
final Button bsikki = (Button) findViewById(R.id.bsikki);
final Button csikki = (Button) findViewById(R.id.csikki);
final Button dsikki = (Button) findViewById(R.id.dsikki);
final Button esikki = (Button) findViewById(R.id.esikki);
String line = "";
a = (Button) findViewById(R.id.asikki);
b = (Button) findViewById(R.id.bsikki);
c = (Button) findViewById(R.id.csikki);
d = (Button) findViewById(R.id.dsikki);
e = (Button) findViewById(R.id.esikki);
InputStream is = getResources().openRawResource(R.raw.data);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8"))
);
try {
// step over header line
reader.readLine();
while ((line = reader.readLine()) != null) {
may++;
String sira = Integer.toString(may);
String[] tokens = line.split(",");
WeatherSample sample = new WeatherSample();
deneme[may][0] = tokens[0];
deneme[may][1] = tokens[1];
deneme[may][2] = tokens[2];
deneme[may][3] = tokens[3];
deneme[may][4] = tokens[4];
deneme[may][5] = tokens[5];
deneme[may][6] = tokens[6];
}
} catch (IOException e) {
e.printStackTrace();
}
for (int say=0;say<10;say++){
a.setText("A) " + deneme[1][0]);
b.setText("B) " + deneme[1][1]);
c.setText("C) " + deneme[1][2]);
d.setText("D) " + deneme[1][3]);
e.setText("E) " + deneme[1][4]);
asikki.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
asikki.setText("bilgin");
asikki.setBackgroundColor(Color.BLACK);
asikki.setTextColor(Color.WHITE);
}
});
bsikki.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bsikki.setText("bilgin");
bsikki.setBackgroundColor(Color.BLACK);
bsikki.setTextColor(Color.WHITE);
}
});
csikki.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
csikki.setText("bilgin");
csikki.setBackgroundColor(Color.BLACK);
csikki.setTextColor(Color.WHITE);
}
});
dsikki.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dsikki.setText("bilgin");
dsikki.setBackgroundColor(Color.BLACK);
dsikki.setTextColor(Color.WHITE);
}
});
esikki.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
esikki.setText("bilgin");
esikki.setBackgroundColor(Color.BLACK);
esikki.setTextColor(Color.WHITE);
}
});
}
}
for loop is something to be executed immediately, it doesn't wait, you only need the listener
asikki.setText(deneme[0][0]);
asikki.setBackgroundColor(Color.BLACK);
asikki.setTextColor(Color.WHITE);
asikki.setOnClickListener(new View.OnClickListener() {
int say = 1;
public void onClick(View v) {
// TODO check say isn't out of bound
asikki.setText("A) " +deneme[say++][0]);
}
});
Thanks to #Happy, Now I have the following lines in my code:
int say = 1;
asikki.setText(deneme[0][0]);
asikki.setBackgroundColor(Color.BLACK);
asikki.setTextColor(Color.WHITE);
asikki.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
say++;
asikki.setText("A) " +deneme[say][1]);
bsikki.setText("B) " +deneme[say][2]);
csikki.setText("C) " +deneme[say][3]);
dsikki.setText("D) " +deneme[say][4]);
esikki.setText("E) " +deneme[say][5]);
}
});
I have checkboxes created dynamically using shared preferences. The label for each checkbox is stored in array.xml. How can I calculate the total number of checkboxes that are ticked and store the total in a variable and further use it for another calculation -- (total/totalCheckboxes)*100?
Here's a snippet of the Java class:-
public class CheckBoxSharedPreferences extends Activity {
ListView myList;
Button getChoice, clearAll, button1;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyUserChoice";
ArrayList<String> selectedItems = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myList = (ListView) findViewById(R.id.list);
getChoice = (Button) findViewById(R.id.getchoice);
clearAll = (Button) findViewById(R.id.clearall);
button1 = (Button) findViewById(R.id.button1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice,
// code snippet to retrieve array values in ArrayAdapter
getResources().getStringArray(R.array.Questionnaire));
myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
myList.setAdapter(adapter);
sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(MyPREFERENCES)) {
LoadSelections();
}
getChoice.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
String selected = "";
int cntChoice = myList.getCount();
SparseBooleanArray sparseBooleanArray = myList
.getCheckedItemPositions();
for (int i = 0; i < cntChoice; i++) {
if (sparseBooleanArray.get(i)) {
selected += myList.getItemAtPosition(i).toString()
+ "\n";
System.out.println("Checking list while adding:"
+ myList.getItemAtPosition(i).toString());
SaveSelections();
}
}
Toast.makeText(CheckBoxSharedPreferences.this, selected,
Toast.LENGTH_LONG).show();
}
});
//listener for clear all button
clearAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ClearSelections();
}
});
//listener for button1 (that transfers the activity to another intent
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(CheckBoxSharedPreferences.this,
result.class);
startActivity(intent);
}
});
}
private void SaveSelections() {
// save the selections in the shared preference in private mode for the
// user
SharedPreferences.Editor prefEditor = sharedpreferences.edit();
String savedItems = getSavedItems();
prefEditor.putString(MyPREFERENCES.toString(), savedItems);
prefEditor.commit();
}
private String getSavedItems() {
String savedItems = "";
int count = this.myList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
if (this.myList.isItemChecked(i)) {
if (savedItems.length() > 0) {
savedItems += "," + this.myList.getItemAtPosition(i);
} else {
savedItems += this.myList.getItemAtPosition(i);
}
}
}
return savedItems;
}
private void LoadSelections() {
// if the selections were previously saved load them
if (sharedpreferences.contains(MyPREFERENCES.toString())) {
String savedItems = sharedpreferences.getString(
MyPREFERENCES.toString(), "");
selectedItems.addAll(Arrays.asList(savedItems.split(",")));
int count = this.myList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
String currentItem = (String) myList.getAdapter().getItem(i);
if (selectedItems.contains(currentItem)) {
myList.setItemChecked(i, true);
Toast.makeText(getApplicationContext(),
"Current Item: " + currentItem, Toast.LENGTH_LONG)
.show();
} else {
myList.setItemChecked(i, false);
}
}
}
}
and the array.xml:-
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="Questionnaire">
<item>abc</item>
<item>jkm</item>
<item>xyz</item>
<item>abc2</item>
<item>jkm2</item>
<item>xyz2</item>
<item>abc3</item>
<item>jkm3</item>
<item>xyz3</item>
</resources>
Thanks in advance!
Use this code where you want to get the total number of checked items and perform the calculation
int checkedCount = myList.getCheckedItemCount();
int totalCount = myList.getAdapter().getCount();
int calculatedValue = (totalCount/checkedCount) * 100;
I have an app here which adds the number. I have 4 edittexts here. What I want to happen is that when i entered none in one of the edittexts, it will assume that I entered 0. How can it be done? Here is my code:
public class Order extends Activity {
Button GoBackHome;
private Button button1;
private EditText txtbox1,txtbox2,txtbox3,txtbox4;
private TextView tv;
Button PayNow;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order);
GoBackHome = (Button) findViewById(R.id.gohomebutton);
PayNow = (Button) findViewById(R.id.button2);
txtbox1= (EditText) findViewById(R.id.editText1);
button1 = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.editText5);
txtbox2= (EditText) findViewById(R.id.editText2);
txtbox3= (EditText) findViewById(R.id.editText3);
txtbox4= (EditText) findViewById(R.id.editText4);
button1.setOnClickListener(new clicker());
GoBackHome.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent i = new Intent(Order.this, MainActivity.class);
startActivity(i);
}
});
PayNow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent i = new Intent(Order.this, Payment.class);
startActivity(i);
}
});
}
class clicker implements Button.OnClickListener
{
public void onClick(View v)
{
String a,b,c,d;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
c = txtbox3.getText().toString();
d = txtbox4.getText().toString();
vis = Integer.parseInt(a)*2+Integer.parseInt(b)*3+Integer.parseInt(c)*4+Integer.parseInt(d)*5;
tv.setText(vis.toString());
}
}
}
You can do as Tushar said or you can initialize the value in the XML. Something like
<EditText
android:name="#+id/editText1"
android:text="0"/>
FYI you might also find it cleaner to handle your button clicks on xml like:
<Button
android:name="#+id/btn1"
android:onClick="handleClicks"/>
and then in java you'd have a public void method:
public void handleClicks(View clickedView){
if(clickedView.getId() == btn1.getId(){
...
} else if (...){}
}
initialize as :
txtbox1.setText("0");
Check the EditText length when you get it
String value = null;
if(ed.getText().length()){
value = textBox.getText().toString();
} else
value = 0+"";
You can set android:hint="0" in your XML file, then, in your code, you can check if it's empty (maybe using TextUtils.isEmpty()) and setting some variable to 0.
android:hint="0" will make a "0" appear in your EditTexts, but the "0" will disappear when anything is inputted.
Then you can change the onClick() to this:
class clicker implements Button.OnClickListener {
public void onClick(View v) {
String a,b,c,d;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
c = txtbox3.getText().toString();
d = txtbox4.getText().toString();
try {
vis = Integer.parseInt(a)*2+Integer.parseInt(b)*3+Integer.parseInt(c)*4+Integer.parseInt(d)*5;
tv.setText(vis.toString());
} catch (NumberFormatException e) {
vis = "0";
}
// Do something with "vis"
}
}
Or you can create a method to check a value, try to parse to an int or return a default value.
public int getInt(String edtValue, int defaultValue) {
int value = defaultValue;
if (edtValue != null) {
try {
value = Integer.parseInt(edtValue);
} catch (NumberFormatException e) {
value = defaultValue;
}
}
return value;
}
Then you change your call to
vis = this.getInt(a, 0) * 2 + this.getInt(b, 0) * 3 + this.getInt(c, 0) * 4 + this.getInt(d, 0) * 5;