Putting LinearLayout to LinearLayout Array - java

i wanna create button 1 to 9 and i want to do that in loop. But in each 3 count, i want to create a new LinearLayout.
final LinearLayout[] ll2 = new LinearLayout[10]; // create an empty array;
for(int i=1; i<=9;i++)
{
Button btnNums = new Button(this);
final LinearLayout[] ll2 = new LinearLayout[10]; // create an empty array;
for(int i=1; i<=9;i++)
{
Button btnNums = new Button(this);
btnNums.setText(i+"");
ll.addView(btnNums);
if(i%3==0){
ll2[i] = ll;
ll = null;
}
}
layout.addView(ll2[0]);
btnNums.setText(i+"");
ll.addView(btnNums);
if(i%3==0){
ll2[i] = ll;
ll = null;
}
}
layout.addView(ll2[0]);
This does not work. I get no error but when o run the app, it is stopped to work. What's the problem?

I used it in my Project and it worked for me, i used it like this. Hope it helps
Declare empty array at class level:
LinearLayout[] imageLayoutContainers = new LinearLayout[10];
And then in on onCreate methord :
for (int i = 0; i < imageLayoutContainers.length; i++) {
imageLayoutContainers[i] = new LinearLayout(this);
imageLayoutContainers[i].setOrientation(LinearLayout.VERTICAL);
imageLayoutContainers[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
imageLayoutContainers[i].setBackgroundResource(imagesIds[i]);
}
It worked, thanks

Related

how to count filled edit text from multiple edittext

In my app have twenty edit text,but I want to count filled edit text and that data goes in anther activity through an array. Like when I filled 3 edit text from twenty, that 3 edit text data goes next page and that 3 count goes to next page as an int.
this is my 1st java class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select);
mspin=(Spinner) findViewById(R.id.spinner1);
submit = (Button) findViewById(R.id.btn1);
layout = (LinearLayout) findViewById(R.id.linear);
lay = (LinearLayout) findViewById(R.id.li);
edt=(EditText) findViewById(R.id.ed2);
sc = (ScrollView) findViewById(R.id.sc1);
int no = 20;
allEds = new ArrayList<EditText>();
for (int i=1;i<=no;i++){
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
edtAdd = new EditText(SelectActivity.this);
layout.setLayoutParams(params);
allEds.add(edtAdd);
edtAdd.setHint("Enter Name" + i);
edtAdd.setId(i);
layout.addView(edtAdd);
}
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (allEds.size()<=9) {
Intent data = new Intent(SelectActivity.this, HalfPieChartActivity.class);
String[] items = new String[allEds.size()];
String str = String.valueOf(allEds.size());
data.putExtra("size", str); //you don't need to keep this in loop as its same.
data.putExtra("edt", edt.getText().toString());
for (int j = 0; j < allEds.size(); j++) {
items[j] = allEds.get(j).getText().toString();
data.putExtra("edData" + j, items[j]);
}
startActivity(data);
}
else {
Intent data = new Intent(SelectActivity.this, FullPieChartActivity.class);
String[] items = new String[allEds.size()];
String str = String.valueOf(allEds.size());
data.putExtra("size", str);// this is the line where I sent that count
data.putExtra("edt", edt.getText().toString());
for (int j = 0; j < allEds.size(); j++) {
items[j] = allEds.get(j).getText().toString();
data.putExtra("edData" + j, items[j]);//here is filled data send line
}
startActivity(data);
}
}
});
}
}
When I click submit 20 show in next page as an int.I want to sent that 3data and 3 as an int.
Please help me
As you have asked for sample in comment, i am posting my answer with sample.
In onclicklistener of your submit button you can add following code.
myNoneEmptyEdittextCounter = 0;
for (int i=1;i<=no;i++)
{
myEt = (EditText) findViewById(i);
if(!TextUtils.isEmpty(myEt.getText().toString()))
{
myNoneEmptyEdittextCounter +=1;
}
}
//myNoneEmptyEdittextCounter is count of your filled edittexts
This method will return list of data and its size will give you the int you are looking for which is number of filled items.
In submit button click
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(edittextValues().isEmpty()) {
//nothing has been filled
} else {
//items in edittextValues() are your data.
edittextValues().size();//this is your int which is number of edit text filled.
}
}
}
I have mentioned in comments what each step does. Hope this helps.
Method edittextValues()
ArrayList<String> edittextValues() {
ArrayList<String> filledData = new ArrayList<>(); //initialise empty string array.
for (int i=1; i<=20; i++){ //loop through ids from 1 to 20
for (int j = 0; j< layout.getChildCount(); j++) { //loop through all the children of root layout
if(layout.getChildAt(j) instanceof EditText) { //filter EditText
EditText editText = (EditText) layout.getChildAt(j);
if(editText.getId() == i) { // filter the one which u programmatically added
if(!editText.getText().toString().isEmpty()) { // check if its not empty, that's the one you are looking
filledData.add(editText.getText().toString()); //add it to the list
}
}
}
}
}
return filledData; //return string list
}

Setting the context of a textview array

How do i apply a context to a textview array?
TextView[] textView = new TextView[3];
for (int cell = 0; cell < 3; cell++){
textView[cell].setText("-");
}
Apparently, this error gets thrown:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
If this was not a textview array, adding the activity context as a parameter when calling the constructor would render the object not null, solving my issue:
for (int cell = 0; cell < 3; cell++){
TextView textView = new TextView(context);
textView.setText("-");
}
Where, context = getActivity().getApplicationContext()
How do i set the context parameter for the textview array? What i want is dynamic variable names for each textview so i can call the individual textviews respectively.
You should create object before calling method.
Try this:
TextView[] textView = new TextView[3];
for (int cell = 0; cell < 3; cell++) {
textView[cell] = new TextView(context);
textView[cell].setText("-");
}
I hope below code would help you out regarding context for array of views. First you will just create array but before using it you will have to create object using new keyword.
LinearLayout rootview = (LinearLayout) findViewById(R.id.rootview);
ArrayList<String> words= new ArrayList<>();
words.add("One"); words.add("two"); words.add("three"); words.add("four"); words.add("five"); words.add("six"); words.add("seven"); words.add("eight"); words.add("nine"); words.add("ten");
int index=0;
while(index<words.size()){
TextView [] textViews = new TextView[words.size()];
textViews[index] = new TextView(this);
textViews[index].setText(words.get(index));
rootview.addView(textViews[index]);
index++;
}

MPAndroidChart Label inside Bar

I am using an HorizontalBarChart I want to draw a Label (the name of the vendor) inside or in the middle of the Bar, in the BarDaset there is something called setLabel but it's not working.
Here is my code:
private BarDataSet createLineChart(String storeName, List<String> listofcompanies){
ArrayList<BarEntry> entries= new ArrayList<BarEntry>();
for (int j = 0; j < listofcompanies.size(); j++) {
entries.add(new BarEntry(Float.parseFloat(listofcompanies.get(j)),j));
}
Random rd = new Random();
setComp1 = new BarDataSet(entries,storeName);
setComp1.setColor(Color.argb(255,rd.nextInt(256),rd.nextInt(256),rd.nextInt(256)));
setComp1.setDrawValues(true);
setComp1.setLabel(storeName);
setComp1.setHighlightEnabled(true);
setComp1.setDrawValues(true);
// LineData data =new LineData(labels,dataset);
return setComp1;
}
Try to use:
chart.getXAxis().setPosition(XAxisPosition.BOTTOM_INSIDE);
Or
chart.getXAxis().setPosition(XAxisPosition.TOP_INSIDE);
This will solve your problem.

Make Button Array Invisible(Make an hint)

I want to make a Hint button, so when I click on it, I want to delete two buttons from the list (answers list). Now I don't know how to do it,ho w to make the for loop on the button array, so I can make this buttons invisible.
public class ClassicMode extends Activity {//מהמשחק עצמו
String pic;//תמונה של הדגל
Button answer1;//תשובות
Button answer2;
Button answer3;
Button answer4;
Button hint;
TextView guess;
TextView numOfGuess;
TextView score;
TextView scorenum;
DatabaseHandler db = new DatabaseHandler(this);
String fn;
Guesses G;
Bitmap bm;
Score s;
Button [] b = new Button[4];
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
score =(TextView)findViewById(R.id.score);
scorenum =(TextView)findViewById(R.id.scorenum);
scorenum.setText(String.valueOf(s.score));
guess =(TextView)findViewById(R.id.guesses);
numOfGuess=(TextView)findViewById(R.id.numOfGuesses);
numOfGuess.setText(String.valueOf(Guesses.numOfGuesses));
hint =(Button)findViewById(R.id.hint);
Flags f = new Flags();
Random r = new Random();//הדגל שיבחר לשאלה
int num = r.nextInt(160);//Up
f = db.getFlag(num);//הצגת הדגל הרנדומלי שיצא
fn = f.getName().toString();
pic = f.getImage().toString();
pic_view(pic);//מעבר לפונקציה להשמת התמונה של הדגל במשחק
//מערך ארבע כפתורים כנגד ארבע תשובות
b[0] = (Button)findViewById(R.id.button1);
b[1] = (Button)findViewById(R.id.button2);
b[2] = (Button)findViewById(R.id.button3);
b[3] = (Button)findViewById(R.id.button4);
List<String>Answers=new ArrayList<String>();//מערך תשובות
Answers.add(f.getName().toString());//הוספת התשובה הנכונה
for(int i=1;i<4;i++)
{
num = r.nextInt(200);
String valToAdd1 = db.getFlag(num).getName().toString();
if(!Answers.contains(valToAdd1)){
Answers.add(valToAdd1);
}
}
/*num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());//הוספת 3 תשובות רנדומליות
num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());
num = r.nextInt(30);
Answers.add(db.getFlag(num).getName().toString());*/
Collections.shuffle(Answers);//ערבוב התשובות
for(int i=0;i<Answers.size();i++)
{
b[i].setText(Answers.get(i));//השמת התשובות מהמהערך למערך הכפתורים
}
}//end of OnCreat
Now what I've done (there is the function check, which check if you answered correctly and the hint which I don't know how to make):
public void check(View v)
{
Log.d("yes", fn);
Button b = (Button)v;
String text = b.getText().toString();
if(text.equals(fn))
{
s.score+=5;
resetQuiz();
}
else
{
s.score-=5;
if(Guesses.numOfGuesses==1)
{
G.setNumOfGuesses(3);
finish();//כאשר מספר הניחושים
return;
}
Guesses.numOfGuesses--;
numOfGuess.setText(String.valueOf(Guesses.numOfGuesses));
}
}
public void hint(View v)
{
G.numOfGuesses--;
for(int i=0;i<2;i++)
for(int j=0;j<4;j++)
{
if()
}
}
Note: this is {mostly} pseudocode
I suggest keeping two separate lists of your answers. Your Flag object already holds the correct answer. You need a list to keep track of the wrong answers (so we don't have to loop and check against each item every time). You also need a list of all of them together that you can shuffle and display.
I took a little bit of liberty making your variable names longer so they are more clear.
onCreate() {
...
btnHint.setOnClickListener(hintOnClickListener);
...
Flag f = db.getFlag(randomNum); // This is the real question & answer
List<String> wrongAnswers = new ArrayList<String>(3);
List<String> allAnswers = new ArrayList<String>(4);
// Loop 3 times for 3 random wrong answers
for (int i=0; i<=3; i++) {
randNum = r.nextInt(200);
String randWrongAnswer = db.getFlag(randNum).getName().toString();
if (! wrongAnswers.contains(randWrongAnswer)) {
wrongAnswers.add(randWrongAnswer);
}
}
allAnswers.add(f.getName().toString());
allAnswers.addAll(wrongAnswers);
Collection.shuffle(allAnswers);
...
}
I like to declare all my listeners separately further down in the code, to keep the OnCreate method clean and legible.
private OnClickListener hintOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
G.numOfGuesses--;
// Since you shuffled the 'allAnswers' before displaying to the screen,
// we can just pick the first 2 answers from wrongAnswers list
// and it will appear to be random to the user.
for (int i=0; i < buttons.length; i++) {
String buttonText = buttons[i].getText().toString();
if (buttonText.equals(wrongAnswers.get(0))
|| buttonText.equals(wrongAnswers.get(1))) {
buttons[i].setVisibility(View.INVISIBLE);
}
}
}
};
Edit: to add hint logic based on OP's comment.

How to set Checkbox value into a array android

I got an ArrayList:
ArrayList<CheckBox> swmsInfo = new ArrayList<CheckBox>();
and some checkboxes:
checkBoxCompany = createCheckBox(R.id.checkBoxCompany);
checkBoxName = createCheckBox(R.id.checkBoxName);
checkBoxPhone = createCheckBox(R.id.checkBoxPhone);
checkBoxAdress = createCheckBox(R.id.checkBoxAdress);
I want to get their values 0 or 1 if some of the checkboxes are checked or not , and when i got their values i want to put them into a array. My checkboxes are inside a array
ArrayList<CheckBox> boxes = new ArrayList<CheckBox>();
You can loop through the arraylist and get the value. Something like
for (int i = 0; i<boxes.size(); i++){
CheckBox cb = boxes.get(i);
if (cb.isChecked()){
System.out.println("checked");
//from here you can populate you array
}else{
System.out.println("not checked");
//from here you can populate you array
}
}
======= Edit after the comment =======
public class CheckBoxStatus{
CheckBox cb;
boolean blnIsChecked;
public CheckBoxStatus(CheckBox cb, boolean blnIsChecked){
this.cb = cb;
this.blnIsChecked = blnIsChecked;
}
public CheckBox getCheckbox(){
return this.cb;
}
public boolean getStatus(){
return this.blnIsChecked;
}
public boolean setStatus(boolean blnIsChecked){
this.blnIsChecked = blnIsChecked;
}
}
//Now in your code instead of ArrayList<CheckBox>, use ArrayList<CheckBoxStatus>
ArrayList<CheckBoxStatus> alCBS = new ArrayList<CheckBoxStatus>();
CheckBoxStatus cbs = new CheckBoxStatus(<checkbox instance>, false); //pass false as default value;
alCBS.add(cbs);
//Modified loop
for (int i = 0; i<boxes.size(); i++){
CheckBox cb = boxes.get(i);
CheckBoxStatus cbs = new CheckBoxStatus(cb, cb.isChecked());
boxes.set(i, cbs);
}

Categories