Calculate total checkboxes ticked and perform calculation (Android Java) - java

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;

Related

Looping through an array of edittexts and getting the texts of each

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)));
}
}
});

[HELP]FATAL EXCEPTION: main java.lang.NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
ProductDatabase.ProductDatabaseHelper controller = new ProductDatabase.ProductDatabaseHelper(this);
EditText mBarcodeEdit;
EditText mFormatEdit;
EditText mTitleEdit;
EditText mPriceEdit;
private static final int ZBAR_SCANNER_REQUEST = 0;
private static final int ZBAR_QR_SCANNER_REQUEST = 1;
private static final ProductData mProductData = new ProductData();
Button mScanButton;
Button mAddButton;
Button mSelectButton;
Button mExportButton;
Button btnimport;
ProductDatabase mProductDb;
ListView ls;
TextView infotext;
File file = null;
// DatabaseHelper dbhelper = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ls = (ListView) findViewById(R.id.placeslist);
mBarcodeEdit = (EditText) findViewById(R.id.barcodeEdit);
mFormatEdit = (EditText) findViewById(R.id.codeFormatEdit);
mTitleEdit = (EditText) findViewById(R.id.titleEdit);
mPriceEdit = (EditText) findViewById(R.id.priceEdit);
mScanButton = (Button) findViewById(R.id.scan_btn);
mAddButton = (Button) findViewById(R.id.addButton);
mSelectButton = (Button) findViewById(R.id.selelctButton);
mProductDb = new ProductDatabase(this); // not yet shown
infotext = (TextView) findViewById(R.id.txtresulttext);
mExportButton = (Button) findViewById(R.id.exportbtn);
mSelectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, product_list.class);
startActivity(i);
}
});
mAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String barcode = mBarcodeEdit.getText().toString();
String format = mFormatEdit.getText().toString();
String title = mTitleEdit.getText().toString();
String price = mPriceEdit.getText().toString();
String errors = validateFields(barcode, format, title, price);
if (errors.length() > 0) {
showInfoDialog(MainActivity.this, "Please fix errors", errors);
} else {
mProductData.barcode = barcode;
mProductData.format = format;
mProductData.title = title;
mProductData.price = new BigDecimal(price);
mProductDb.insert(mProductData);
showInfoDialog(MainActivity.this, "Success", "Product saved successfully");
resetForm();
}
}
});
mExportButton.setOnClickListener(new View.OnClickListener() {
SQLiteDatabase sqldb = controller.getReadableDatabase(); //My Database class
Cursor c =null;
#Override
public void onClick(View view) { //main code begins here
try {
c = sqldb.rawQuery("select * from spot_pay.db", null);
int rowcount = 0;
int colcount = 0;
File sdCardDir = Environment.getExternalStorageDirectory();
String filename = "MyBackUp.csv";
// the name of the file to export with
File saveFile = new File(sdCardDir, filename);
FileWriter fw = new FileWriter(saveFile);
BufferedWriter bw = new BufferedWriter(fw);
rowcount = c.getCount();
colcount = c.getColumnCount();
if (rowcount > 0) {
c.moveToFirst();
for (int i = 0; i < colcount; i++) {
if (i != colcount - 1) {
bw.write(c.getColumnName(i) + ",");
} else {
bw.write(c.getColumnName(i));
}
}
bw.newLine();
for (int i = 0; i < rowcount; i++) {
c.moveToPosition(i);
for (int j = 0; j < colcount; j++) {
if (j != colcount - 1)
bw.write(c.getString(j) + ",");
else
bw.write(c.getString(j));
}
bw.newLine();
}
bw.flush();
infotext.setText("Exported Successfully.");
}
} catch (Exception ex) {
if (sqldb.isOpen()) {
sqldb.close();
infotext.setText(ex.getMessage().toString());
}
} finally {
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
private void showInfoDialog(Context context, String title, String information) {
new AlertDialog.Builder(context)
.setMessage(information)
.setTitle(title)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
private void resetForm() {
// TODO Auto-generated method stub
mBarcodeEdit.getText().clear();
mFormatEdit.getText().clear();
mTitleEdit.getText().clear();
mPriceEdit.getText().clear();
}
public void launchScanner(View v) {
if (isCameraAvailable()) {
Intent intent = new Intent(this, ZBarScannerActivity.class);
startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
} else {
Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
}
}
public void launchQRScanner(View v) {
if (isCameraAvailable()) {
Intent intent = new Intent(this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.QRCODE});
startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
} else {
Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
}
}
public boolean isCameraAvailable() {
PackageManager pm = getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ZBAR_SCANNER_REQUEST:
case ZBAR_QR_SCANNER_REQUEST:
if (resultCode == RESULT_OK) {
mBarcodeEdit.setText(data.getStringExtra(ZBarConstants.SCAN_RESULT));
// Toast.makeText(this, "Scan Result = " + data.getStringExtra(ZBarConstants.SCAN_RESULT), Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED && data != null) {
String error = data.getStringExtra(ZBarConstants.ERROR_INFO);
if (!TextUtils.isEmpty(error)) {
Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
}
}
break;
}
}
private static String validateFields(String barcode, String format,
String title, String price) {
StringBuilder errors = new StringBuilder();
if (barcode.matches("^\\s*$")) {
errors.append("Barcode required\n");
}
if (format.matches("^\\s*$")) {
errors.append("Format required\n");
}
if (title.matches("^\\s*$")) {
errors.append("Title required\n");
}
if (!price.matches("^-?\\d+(.\\d+)?$")) {
errors.append("Need numeric price\n");
}
return errors.toString();
}
}
I think string may be null somewhere. Please type something in textfield or check for null string.

Pointing to a looped textview and Button

I want to make a program where it will looped a text view and 2 button from database,
and I want to make when user click one of the button, certain textview and button will disappear,
I tried this code, but the one which disappear only the last inputted textview and button,
How can I make a pointer or something that refer to certain textview or button that I want to make it gone/disappear?
Here is my code :
private void doActionWithDatabase() {
// TODO Auto-generated method stub
myDatabase.open();
countInvitation = myDatabase.countHowManyInvitation(username);
String groupName[] = myDatabase.fetchGroupNameInvitation(username);
String groupId[] = myDatabase.fetchGroupIdInvitation(username);
/*
* String data = myDatabase.getDataFromInvitation();
* invGroupName.setText(data);
*/
for (int i = 0; i < countInvitation; i++) {
// invGroupName.setText("Invitation to join " + groupName[i]);
test1 = new TextView(this);
test1.setText("Invitation to join " + groupName[i]);
test1.setTag(i);
bAccept = new Button(this);
bAccept.setText("Accept yeh");
bAccept.setTag(groupId[i]);
bAccept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button clickedButton = (Button) v;
String tempForGroupId = (String) clickedButton.getTag();
Toast.makeText(getApplicationContext(),
tempForGroupId+" " +username, Toast.LENGTH_LONG).show();
test1.setVisibility(View.GONE);
bAccept.setVisibility(View.GONE);
bReject.setVisibility(View.GONE);
/* myDatabase.open();
myDatabase.addGroupMember(tempForGroupId, username);
myDatabase.deleteInvitation(tempForGroupId, username);
myDatabase.close();*/
}
});
bReject = new Button(this);
bReject.setText("Reject");
bReject.setTag(groupId[i]);
bReject.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button clickedButton = (Button) v;
String tempForGroupId = (String) clickedButton.getTag();
Toast.makeText(getApplicationContext(),
tempForGroupId+" " +username, Toast.LENGTH_LONG).show();
/* myDatabase.open();
myDatabase.deleteInvitation(tempForGroupId, username);
myDatabase.close();*/
}
});
layout.addView(test1);
layout.addView(bAccept);
layout.addView(bReject);
}
}
you should define your TextView and Button variable inside your for loop
something like
for (int i = 0; i < countInvitation; i++) {
final TextView test1 = new TextView(this);
final Button bAccept = new Button(this);
bAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
test1.setVisibility(View.GONE);
}
});
final Button bReject = new Button(this);
}

cannot be resolved or is not a field with some EditTexts

Ok so i have the following situation : I create some Editexts dynamically and i want to add another row of Editexts when one of the EditTexts from the last row is clicked.
I tried doing it the following way :
When the last row of EditTexts is created,i assign each of them an id
et.setId(997);
et.setId(998);
et.setId(999);
I declared each of them ;
public EditText camp1;
public EditText camp2;
public EditText camp3;
camp1 = (EditText) findViewById(997);
camp2 = (EditText) findViewById(998);
camp3 = (EditText) findViewById(999);
camp1.setOnClickListener(this);
camp2.setOnClickListener(this);
camp3.setOnClickListener(this);
And when i try to do this
case R.id.camp1:
inside a switch i get "camp1 cannot be resolved or is not a field"
What am i doing wrong ?
Is there a better way to detect when the last Edittext is clicked and create a new one ?
EDIT:
public class MainActivity extends Activity implements OnClickListener,
TextWatcher {
public Button paginanoua;
// public Button calculeaza;
public Button produsnou;
public EditText camp1;
public EditText camp2;
public EditText camp3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
produsnou();
paginanoua = (Button) findViewById(R.id.paginanoua);
// calculeaza = (Button) findViewById(R.id.calculeaza);
produsnou = (Button) findViewById(R.id.produsnou);
camp1 = (EditText) findViewById(997);
camp2 = (EditText) findViewById(998);
camp3 = (EditText) findViewById(999);
paginanoua.setOnClickListener(this);
// calculeaza.setOnClickListener(this);
produsnou.setOnClickListener(this);
camp1.setOnClickListener(this);
camp2.setOnClickListener(this);
camp3.setOnClickListener(this);
}
public void onClick(View view) {
switch(view.getId())
{
case R.id.paginanoua:
ShowDialog();
case R.id.produsnou:
produsnou();
case R.id.997:///error
produsnou();
}
}
private void ShowDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Pagina noua..");
dialogBuilder.setMessage("Sigur doriti o pagina noua?");
dialogBuilder.setPositiveButton("Da",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),
"Am inceput o lista noua", Toast.LENGTH_SHORT)
.show();
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
dialogBuilder.setNegativeButton("Nu",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),
"Ramanem la lista curenta", Toast.LENGTH_SHORT)
.show();
}
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
}
List<EditText> allpret = new ArrayList<EditText>();
List<EditText> allcant = new ArrayList<EditText>();
List<Float> alltotal = new ArrayList<Float>();
float totaltest = 0;
public void produsnou() {
LinearLayout l1 = (LinearLayout) findViewById(R.id.layout1);
EditText et = new EditText(this);
et.setHint("Produs");
l1.addView(et);
et.addTextChangedListener(this);
et.setId(997);
LinearLayout l2 = (LinearLayout) findViewById(R.id.layout2);
EditText et2 = new EditText(this);
et2.setHint("Cantitate");
et2.setInputType(InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_NUMBER_FLAG_DECIMAL);
et2.setId(998);
allcant.add(et2);
l2.addView(et2);
et2.addTextChangedListener(this);
LinearLayout l3 = (LinearLayout) findViewById(R.id.layout3);
EditText et3 = new EditText(this);
et3.setHint("Pret");
et3.setInputType(InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_NUMBER_FLAG_DECIMAL);
l3.addView(et3);
et3.setId(999);
allpret.add(et3);
et3.addTextChangedListener(this);
}
float temp = 0;
public void calculeaza() {
totaltest = 0;
String[] cant = new String[allcant.size()];
for (int j = 0; j < allcant.size(); j++) {
cant[j] = allcant.get(j).getText().toString();
if (cant[j].matches("")) {
Toast.makeText(this,
"Ati omis cantitatea de pe pozitia " + (j + 1),
Toast.LENGTH_SHORT).show();
cant[j] = Float.toString(0);
}
}
String[] pret = new String[allcant.size()];
for (int k = 0; k < allpret.size(); k++) {
pret[k] = allpret.get(k).getText().toString();
if (pret[k].matches("")) {
Toast.makeText(this,
"Ati omis pretul de pe pozitia " + (k + 1),
Toast.LENGTH_SHORT).show();
pret[k] = Float.toString(0);
}
}
for (int l = 0; l < allpret.size(); l++) {
Float temp = Float.parseFloat(cant[l]) * Float.parseFloat(pret[l]);
alltotal.add(temp);
totaltest = totaltest + temp;
// totaluri[l] = temp ; }
TextView totalf = (TextView) findViewById(R.id.total);
totalf.setText(String.format("Total: %.2f", totaltest));
}
}
// Float[] totaluri = new Float[allcant.size()];
public void reload(View v) {
Intent intent = getIntent();
finish();
startActivity(intent);
calculeaza();
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
calculeaza();
}
}
All you care about is the last editText, right? Just give the last editText an onClickListener that creates another editText. Then give the new editText the onClickListener and remove it from the the previous "last one".
like this:
camp1 = (EditText) findViewById(997);
camp2 = (EditText) findViewById(998);
camp3 = (EditText) findViewById(999);
camp1.setOnClickListener(this);
camp2.setOnClickListener(this);
camp3.setOnClickListener(new myListener());
...
//put this private class in the same activity as the stuff above
private class myListener implements View.OnClickListener {
#Override
public void onClick(View view) {
EditText editText = new EditText(YourActivityName.this);
editText.setOnClickListener(new myListener());
//TODO put it in your viewGroup
//Give the old EditText your standard onClickListener
view.setOnClickListener(YourActivityName.this);
//To change body of implemented methods use File | Settings | File Templates.
}
}
setId() does not add any variables to the R.id class because setId() executes at run-time, but R is generated at compile-time. Since you are creating dynamic views, you need to rethink your onClick() method. You might want to consider using a ListView to help you. You can also set up the three TextViews using a separate XML file, such as row.xml.

How to get onClickListener for Android array of buttons to work

I have created a dynamic array of buttons that come from sqllite database. For the life of me I cannot get a click listener set up to address each button individually. I have been searching for 3 hours with no success at all.
Any help would be appreciated. Don't worry about the database crap, it's just the listener.
imports...
public class CreatePlayList extends Activity {
ScrollView scrollleft, scrollright;
LinearLayout songsright, songsleft;
TextView testtext;
String[][] allsongs;
int numofsongs, i;
Button b1[];
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.createplaylist);
scrollleft = (ScrollView) findViewById(R.id.scrollleft);
scrollright = (ScrollView) findViewById(R.id.scrollright);
songsright = (LinearLayout) findViewById(R.id.layRight);
songsleft = (LinearLayout) findViewById(R.id.layLeft);
LyricDb connect = new LyricDb(CreatePlayList.this);
connect.open();
numofsongs = connect.getNumSongs();
b1 = new Button[(numofsongs)];
allsongs = new String[numofsongs][2];
allsongs = connect.getSongArray();
connect.close();
testtext = new TextView(this);
testtext.setText("Test");
songsleft.addView(testtext);
for (i = 0; i < allsongs.length; i++) {
b1[i] = new Button(this);
b1[i].setText(allsongs[i][1]);
songsright.addView(b1[i]);
}
b1[19].setText("test 123");
createClic();
}
public void createClic(){
for (i = 0; i < (allsongs.length - 1); i++) {
b1[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
testtext.setText(b1[i].getText());
}
});
}
}
}
Dump the 'i' declared at class level. Replace method with this (the "Button theButton" needs to stay 'final').
public void createClic()
{
for (int i = 0; i < (allsongs.length - 1); i++)
{
final Button theButton = b1[i];
theButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
testtext.setText(theButton.getText());
}
});
}
}
First implement OnClickListener in your Activity and call setOnClickListener() method to all of your buttons when you are creating it.
b[i].setOnClickListener(this);
and also set id with each button
b[i].setId(i);
//and override this method
#Override
public void onClick(View v)
{
//here check which button called
if(v.getId==1)
{
//its Button 1 do what ever u want
}
if(v.getId==2)
{
//its Button 2 do what ever u want its Button 2
}
......
}
Try it once...
b1[i] = new Button[allsongs.length];
for (i = 0; i < allsongs.length; i++) {
b1[i].setText(allsongs[i][1]);
songsright.addView(b1[i]);
}

Categories