"How to convert String Builder to Array ?" - android

What kind of mistake did I make in my code?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.update_activity);
etEname = findViewById(R.id.etEname);
etSalary = findViewById(R.id.etSalary);
rbMale = findViewById(R.id.rbMale);
rbFemale = findViewById(R.id.rbFemale);
cbWork = findViewById(R.id.cbWork);
spEno = findViewById(R.id.spEno);
//creation
helper = new DBHelper(this);
Cursor cursor = helper.readAll();
String arr [] = new String[0];
StringBuilder builder=new StringBuilder();
while(cursor.moveToNext()){
builder.append(cursor.getString(0)+" "+cursor.getString(1));
}
try {
for (int i = 0 ; i < cursor.getCount(); i++)
arr[i] = builder.toString();
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, R.layout.custom, R.id.textView2,arr );
// Add adapter to spinner
spEno.setAdapter(adapter);
}
Simply put, I want to add specific data from the database name and id to spinner, what way?

Change this Line :
String arr [] = new String[cursor.getCount()];
builder.append(cursor.getString(0)+" "+cursor.getString(1));
to
int i =0;
arr[i] = cursor.getString(0)+" "+cursor.getString(1);
i++;
And Remove this things :
try {
for (int i = 0 ; i < cursor.getCount(); i++)
arr[i] = builder.toString();

You don't need a StringBuilder:
int i = 0;
while(cursor.moveToNext()){
arr[i++] = String.format("%s %s", cursor.getString(0), cursor.getString(1));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, R.layout.custom, R.id.textView2,arr);
spEno.setAdapter(adapter);

Related

Got String Data from Internal Storage When i set it to listview only last item is displayed

Got String Data from Internal Storage.When i tried to display that data on listview only last item is displayed.
Here is my code.
listView=(ListView)findViewById(R.id.listview);
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("/storage/sdcard0/client_new.txt")));
while (s.hasNext()) {
String str = s.next();
char[] myChar = str.toCharArray();
System.out.println(myChar);
String str_new = String.valueOf(myChar);
String[] items={str_new};
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < items.length; ++i)
{
list.add(items[i]);
}
Toast.makeText(ExistingContacts.this,str_new,Toast.LENGTH_LONG).show();
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,list);
listView.setAdapter(adapter);
}
}catch (Exception e)
{
e.printStackTrace();;
}
use final ArrayList list = new ArrayList(); before while loop
listView=(ListView)findViewById(R.id.listview);
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("/storage/sdcard0/client_new.txt")));
final ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()) {
String str = s.next();
char[] myChar = str.toCharArray();
System.out.println(myChar);
String str_new = String.valueOf(myChar);
String[] items={str_new};
for (int i = 0; i < items.length; ++i)
{
list.add(items[i]);
}
Toast.makeText(ExistingContacts.this,str_new,Toast.LENGTH_LONG).show();
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,list);
listView.setAdapter(adapter);
}
}catch (Exception e)
{
e.printStackTrace();;
}

why I'm getting error when I want rewrite String[ ] with duplicate to String[ ] without duplicate

Hi I have String[] array with repeating data.
I want to rewrite this array to new String[] array2, without duplicate.
Cursor c;
c= myDbHelper.getReadableDatabase().rawQuery("SELECT * FROM BusPlan", null);
c.moveToFirst();
int columnCnt = c.getCount();
String[] stringArray = new String[columnCnt]; //deklaracja tablicy stringArray
String[] stringArray2 = new String[columnCnt];
for(int i = 0; i < columnCnt ; i++){
String variable= new String();
variable=c.getString(c.getColumnIndex("Bushaltestelle"));
stringArray2[i] = c.getString(c.getColumnIndex("Bushaltestelle"));
c.moveToNext();
for (int j=0;j< columnCnt;j++){
if(!variable.equals(stringArray2[j].toString())){
stringArray[j]= c.getString(c.getColumnIndex("Bushaltestelle"));
}
}
}
what I'm doing wrong?
How to make it working?
I solved problem using Hashset, but I'm not happy from that.
Spinner spinner= (Spinner) findViewById(R.id.spinner);
Cursor c;
c= myDbHelper.getReadableDatabase().rawQuery("SELECT * FROM BusPlan", null);
c.moveToFirst();
int columnCnt = c.getCount();
String[] stringArray = new String[columnCnt]; //deklaracja tablicy stringArray
String[] stringArray2 = new String[columnCnt];
for(int i = 0; i < columnCnt ; i++){
stringArray[i] = c.getString(c.getColumnIndex("Bushaltestelle"));
c.moveToNext();}
stringArray2 = new HashSet<String>(Arrays.asList(stringArray)).toArray(new String[0]);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(Bodo.this, android.R.layout.simple_spinner_item,stringArray2); //selected item will look like a spinner set from XML
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(stringArray[16]);
If someone know how to make it working using arrays I'll be glad for info
In your for (int j loop your overwriting all data thats not equal to the new data. Try this:
Cursor c;
c= myDbHelper.getReadableDatabase().rawQuery("SELECT * FROM BusPlan", null);
c.moveToFirst();
int columnCnt = c.getCount();
String[] stringArray = new String[columnCnt]; //deklaracja tablicy stringArray
String[] stringArray2 = new String[columnCnt];
for(int i = 0; i < columnCnt ; i++){
String variable = c.getString(c.getColumnIndex("Bushaltestelle"));
stringArray[i] = variable;
c.moveToNext();
if (variable == null)
continue;
for (int j=0;j< columnCnt;j++){
if (stringArray2[j] != null && variable.equals(stringArray2[j].toString())) {
break; // duplicate so ignore
}
if (stringArray2[j] == null) {
stringArray2[j]= variable; // new empty slot, all already added data has already been passed by the loop
break;
}
}
}

how to get all values of particular TextView of listView? -Android

i have made ListView with three columns 'item','qty','rate' i get this entries from the user and i have made the listview work perfectly but i want to get all the values of the 'rate' column and add them for the net amount.
Here is my android code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
populateList();
adapter = new listviewAdapter(List.this, list);
lview.setAdapter(adapter);
}
private void populateList() {
HashMap temp = new HashMap();
list = new ArrayList<HashMap>();
item = etItem.getText().toString();
qty = etQty.getText().toString();
rate = etRate.getText().toString();
temp.put(FIRST_COLUMN, "1");
temp.put(SECOND_COLUMN, item);
temp.put(THIRD_COLUMN, qty);
temp.put(FOURTH_COLUMN, rate);
list.add(temp);
}
I tried out this method below but it only toast the first value.But i want to get all the values under the rate column and add them up for the net-amount.
public void get() {
StringBuilder sb = new StringBuilder();
for(int i=0; i<adapter.getCount(); i++) {
String a = ((TextView) findViewById(R.id.FourthText)).getText().toString();
adapter.getItem(i).toString();
sb.append(a);
sb.append("\n");
}
text = sb.toString();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
I think this might help you.
private int GrandTotal(ListView list) {
int sum=0;
for (int i = 0; i < list.getCount(); i++) {
View v = list.getChildAt(i);
TextView rate = (TextView) v.findViewById(R.id.rate);
sum = sum + Integer.parseInt(rate.getText().toString() )
}
return sum;
}
:)
public void getTotalRate() {
int totalRate = 0;
for (int i = 0; i < list.size(); i++) {
HashMap temp = list.get(i);
/// here fourth column is rate
int rate = (int) temp.get(FOURTH_COLUMN);
totalRate = totalRate + rate;
}
Toast.makeText(getApplicationContext(), "total rate=" + totalRate, Toast.LENGTH_LONG).show();
}

How to add data in array on button click?

int size = mcq.size();
String arr[] = null;
int i;
{
for (i = 0; i < size; i++) {
if (op1.isPressed()) {
arr[i] = tv1.getText().toString();
// Log.e("Array",arr[i]);
} else if (op2.isPressed()) {
arr[i] = tv2.getText().toString();
//Log.e("Array",arr[i]);
} else if (op3.isPressed()) {
arr[i] = tv3.getText().toString();
// Log.e("Array",arr[i]);
} else if (op4.isPressed()) {
arr[i] = tv4.getText().toString();
//Log.e("Array",arr[i]);
}
I am trying to store the data in an array when the button is pressed,but it always shows null.And when the for loop is over I want to display my array.
here , Arrays in Java have a size so u cannot do like this. Instead of this
use list,
ArrayList<String> arr = new ArrayList<String>();
Inorder to do using String array :
String[] arr = new String[SIZEDEFNE HERE];
For ur answer :
ArrayList<String> arr = new ArrayList<String>();
int i;
{
for (i = 0; i < size; i++) {
if (op1.isPressed()) {
arr.add(tv1.getText().toString());
} else if (op2.isPressed()) {
arr.add(tv2.getText().toString());
} else if (op3.isPressed()) {
arr.add(tv3.getText().toString());
} else if (op4.isPressed()) {
arr.add(tv4.getText().toString());
}
Retrive value using
String s = arr.get(0);
This is because your string array is null. Declare it with the size as
String[] arr = new String[size];
Try Array List. use the following code in your main java
final ArrayList<String> list = new ArrayList<String>();
Button button= (Button) findViewById(R.id.buttonId);
final EditText editText = (EditText) findViewById(R.id.editTextId)
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list.add(editText.getText().toString());
}
});
To avoid duplication in arraylist .You can use arraylist for faster then String array
ArrayList<String> list = new ArrayList<String>();
list.add("Krishna");
list.add("Krishna");
list.add("Kishan");
list.add("Krishn");
list.add("Aryan");
list.add("Harm");
System.out.println("List"+list);
HashSet hs = new HashSet();
hs.addAll(list);
list.clear();
list.addAll(hs);

I want to delete a null column from a 2d array in android?

i have problem in data binding in expandable list view. here i use
ArrayList<ExpandListGroup> list = new ArrayList<ExpandListGroup>();
ExpandListGroup for data binding. but in sum 2d array there is null value.Data is coming dynamically .
eg:
String [] [] array1 = [[one,two,three,null],[seven,six,null]] ;
I want to remove the null column from this two dimensional array
You need to take a intermediate arraylist and result array and follows the below steps.
First copy the source array(containing null) into arraylist.
Then remove null from arraylist
Then create new array and copy data from arraylist to array.
private void remove_nulls()
{
String [] [] array1 = {{"one","two","three",null},{"seven","six",null}} ;
ArrayList<ArrayList<String>> contact = new ArrayList<ArrayList<String>>();
for(int i=0;i<array1.length;i++)
{
ArrayList<String> con = new ArrayList<String>();
for(int j=0;j<array1[i].length;j++)
{
if(array1[i][j]!=null)
con.add(array1[i][j]);
}
if(con.size()>0)
contact.add(con);
}
String [] [] array2 = new String[array1.length][];
for(int i=0;i<contact.size();i++)
{
array2[i]=new String[contact.get(i).size()];
for(int j=0;j<contact.get(i).size();j++)
{
array2[i][j]=contact.get(i).get(j);
}
}
}
Unless there is some trick to the question...
String[][] array1 = {{"one", "two", "three", null}, {"seven", "six", null}};
List<String[]> newList = new ArrayList<>();
for (int i = 0; i < array1.length; ++i) {
List<String> currentLine = new ArrayList<>();
for (int j = 0; j < array1[i].length; ++j) {
if (array1[i][j] != null) {
currentLine.add(array1[i][j]);
}
}
//create the array in place
newList.add(currentLine.toArray(new String[currentLine.size()]));
}
//no need to use an intermediate array
String[][] array2 = newList.toArray(new String [newList.size()][]);
//And a test for array2
for (int i = 0; i < array2.length; ++i) {
for (int j = 0; j < array2[i].length; ++j) {
System.out.print(array2[i][j] + " ");
}
System.out.println();
}
System.out.println("Compared to...");
//Compared to the original array1
for (int i = 0; i < array1.length; ++i) {
for (int j = 0; j < array1[i].length; ++j) {
System.out.print(array1[i][j] + " ");
}
System.out.println();
}

Categories

Resources