Multidimensional array to ListView.. how? - java

I have a query result set which I like to edit first and then put it to my ListView. Without editing my data first, I could use SimpleCursorAdapter like that:
ListAdapter adapter = new SimpleCursorAdapter(
this,
R.layout.list_item,
mCursor,
new String[] { "address", "city" },
new int[] { R.id.address, R.id.zip_city });
this.setListAdapter(adapter);
But now, I put everything in a multidimensional array like that:
if(mCursor.isFirst()) {
//create a new array
String[][] listData = new String[mCursor.getCount()][3];
int i = 0;
do {
listData[i] = new String[] {
mCursor.getString(mCursor.getColumnIndex("address")),
mCursor.getString(mCursor.getColumnIndex("zip")) + " " + mCursor.getString(mCursor.getColumnIndex("city")),
calculateDistance(Double.parseDouble(mCursor.getString(mCursor.getColumnIndex("diff"))))
};
i++;
} while(mCursor.moveToNext());
}
So my problem is now, I have no idea how to put this to my ListView. Could someone help me here? Sorry for my bad english and Java knowledge. :)

Either write your own adapter class, extending BaseAdapter, that works with your array, or switch to a different data structure, such as a MatrixCursor.

HOW TO USE A LISTVIEW WITH A MULTI-DIMENSION ARRAY
Guys, the simplest way is as follows -
In the calling activity, let us call it FirstActivity, you declare the multiple dimension array as public static
public static MyArray[][];
In the second activity you refer to this array using -
FirstActivity.MyArray
Now create a single dimension array that reads just one column from the multi dimension array using a loop eg
for(int i = 0; i < FirstActivity.MyArray.length; i++){
SingleArray[i] = FirstActivity.MyArray[i][0];}
Then use an adapter to bind the list to the SingleArray
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, SingleArray));
Just remember to clear the arrays each time, so they do not retain values from before.
Regards
Craig Paardekooper

Related

Reverse AutoCompleteTextView suggestions order

I am using AutoCompleteTextView to suggest items to user when typing.
Because there is no space under the textView, it shows the suggestions above the textView. That's fine and I want to keep it that way.
However, the top suggestion is still on top of the suggestion list and I would like to reverse it so it's closer to the textView.
There is an image so you can understand better what I mean.
I would like to reverse the suggestions so "Item 1" is at the bottom etc.
With implementing the AutoCompleteTextSuggestion, I followed this tutorial.
This is the code I am using right now:
int layoutItemId = android.R.layout.simple_dropdown_item_1line;
String[] arr = getResources().getStringArray(R.array.items);
ArrayAdapter<String> adpt = new ArrayAdapter<>(this,layoutItemId,arr);
AutoCompleteTextView autoCompleteView = (AutoCompleteTextView) findViewById(R.id.autoCompleteText);
autoCompleteView.setAdapter(adpt);
I keep the suggestions in string array in res/values/strings.
Any help would be really appreciated. Thank you!
Perhaps you could reverse the data array itself before creating the adapter.
You can achieve that by using the Collections.reverse(List<T>) method. Something like the example below:
// Use the Collections.reverse() to reverse your list.
ArrayList<String> myList = new ArrayList<>(Arrays.asList(arr));
Collections.reverse(myList);
// Now, create the array back again from the ArrayList.
arr = myList.toArray(new String[0]);
// Create the adapter.
ArrayAdapter<String> adpt = new ArrayAdapter<>(this,layoutItemId,arr);
Or... Since you're reading from a resource file to begin with... you could also write the info in reverse order.

adding multiple data to Object array at run time

How to set values for two dimension array of objects in java.
following is my for loop :
Object[][] hexgenSecurityInferenceData = null;
for (String methodName: knowGoodMap.keySet()) {
hexgenSecurityInferenceData = new Object[][] {
{
(KnownGoodInfoRO) knowGoodMap.get(methodName), new Object[] {
(MethodPropertiesRO) methodPropertiesMap.get(methodName), (List) methodParametersMap.get(methodName)
}
},
};
}
this prints only one row of data. I am sure that i make mistake when adding values to Array of Object but really don't know how to fix.
Kindly help me to fix this
You can't add elements to an array - you can only set elements in an array.
I suggest you have a List<Object[]> instead:
List<Object[]> hexgenSecurityInferenceData = new ArrayList<Object[]>();
for (String methodName:knowGoodMap.keySet()) {
hexgenSecurityInferenceData.add(new Object[] {
knowGoodMap.get(methodName),
new Object[] {
methodPropertiesMap.get(methodName),
methodParametersMap.get(methodName)
}
});
}
(I've removed the casts as they were pointless... you're storing the values in an Object[] anyway. The only benefit of the casts would be to cause an exception if the objects were of an unexpected type.)
You could still use an array if you really wanted, but you'd need to create it with the right size to start with, and then keep the "current index". It's then generally harder to use arrays than lists anyway.
If you really need an array, you can create one from the list:
Object[][] array = hexgenSecurityInferenceData.toArray(new Object[0][]);
Doing it in two stages this way will be simpler than directly populating an array up-front.
I'd actually suggest two further changes:
Don't just use Object[] for this... create a type to encapsulate this data. With your current approach, you've even got a nested Object[] within the Object[]... any code reading this data will be horrible.
Use entrySet() instead of keySet(), then you don't need to fetch the value by key
You have a matrix of objects Object[][] so if you want to populate this 2-d array you have to do something like:
Object[][] hexgenSecurityInferenceData=new Object[10][10];
for(int i=0; i<10;i++){
for(int j=0; j<10;j++){
hexgenSecurityInferenceData[i][j] = new Object();
}
}
But as well pointed by Jon its better to have your own implementation/encapsulation instead of using Object
Using List is the best way to resolve this. However still you can do using object[] by initializing array.
Object[][] hexgenSecurityInferenceData = new Object[knowGoodMap.keySet().size()][];
int i = 0;
for (String methodName : knowGoodMap.keySet())
{
hexgenSecurityInferenceData[i][0] = new Object[][]
{
{(KnownGoodInfoRO) knowGoodMap.get(methodName),
new Object[]{(MethodPropertiesRO) methodPropertiesMap.get(methodName), (List) methodParametersMap.get(methodName)}
}
};
i++;
}

How to add new Strings to a certain array

I got 4 arrays in my code and everytime a user writes something into the edittext I want to store that string in one of the array, I tried to use the toCharArray method but I don't know how to define the array where the string should be put in :S
String [] array7 = {"Hey","Was Up","Yeahh"};
TextView txtV1,txtV2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layouttry);
txtV1=(TextView)findViewById(R.id.textView1);
txtV2=(TextView)findViewById(R.id.textView2);
Bundle extras = getIntent().getExtras();
String value = extras.getString("Key"); // this value I want to add to the stringarray
If you need to add new elements I would suggest replacing your arrays with ArrayLists. This will let you use the add method to insert new elements. An example of this:
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("Text here");
In your code I can only see one array on Strings, so I'm not sure about what you actually need. I'll try my best though.
Your String array is hard-coded to have only three cells in it, and they are all full. If you want to put the string into any of these places, do this:
array7[0] = value; //or:
array7[1] = value; //or:
array7[1] = value;
If you want to add value to the array without deleting the existing values, you can do something like this:
//Create a new array, larger than the original.
String[] newArray7 = new String[array7.length + 1 /*1 is the minimum you are going to need, but it is better to add more. Two times the current length would be a good idea*/];
//Copy the contents of the old array into the new one.
for (int i = 0; i < array7.length; i++){
newArray7[i] = array7[i];
}
//Set the old array's name to point to the new array object.
array7 = newArray7;
You can do this in a separate method, so whenever you need to re-size your array you can use it. You should know that the classes ArrayList and Vector already implement this mechanism for you, and you can arrayList.add(string) as much as you want.

error in this line :"private String[][] variable=new String[][] {var1,var2,var n}"

my question is im getting d jtable but i want to display the data from the database into the the jtable.
if i pass data directly its being displayed in the jtable but i wont data from the database..
please help
the problem is in this line:
private String[][] row1=new String[][]{jono,jdate,prname};
jono,jdate and prname are the variables that contain the data from database.
i need to display it in jtable.
Of course, you declare a two dimensional array but the initialization is just one dimension.
Try this:
private String[][] row1=new String[][]{{jono,jdate,prname}};
You're creating a matrix (2-dimensional array) but are only instantiating single-dimensional objects.
The declaration should look something like this:
String[][] row1 = new String[][] {
new String[] { jono },
new String[] { jdate },
new String[] { prname }
};
Without knowing much else about what you are doing, I can't be certain if this would be what you would need, but it's a start.
Most likely jono, jdate, and prname are not instances of String[]. Post the error and the declaration of those variables for more help.

Passing array into constructor to use on JList

I know the title sound confusing and thats because it is. its a bit long so try too stay with me.
this is the layout i have my code designed
variables
constructor
methods.
im trying too fill a Jlist full on names. i want too get those names using a method. so here goes.
in my variables i have my JList. its called contactNames;
i also have an array which stores 5 strings which are the contacts names;
heres the code for that anyway
String contact1;
String contact2;
String contact3;
String contact4;
String contact5;
String[] contactListNames;
JList contactList;
simple enough. then in my constructor i have the Jlist defined to fill itself with the contents of the array
String[] contactListNames = new String[5];
JList contactList = new JList(contactListNames);
fillContactList();
that method fillContactList() is coming up shortly.
now heres where stuff gets balls up.
ive created three different methods all of which havent worked. basically im trying to fill the array with all of them.
this is the simplest one. it doesnt set the Jlist, it doesnt do anything compilicated. all it trys too do is fill the array one bit at a time
public void fillContactList()
{
for(int i = 0;i<3;i++)
{
try
{
String contact;
System.out.println(" please fill the list at index "+ i);
Scanner in = new Scanner(System.in);
contact = in.next();
contactListNames[i] = contact;
in.nextLine();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
unfortunately this doesnt qwork. i get the print out to fill it at index 0; i input something and i get a nice big stack trace starting at
contactListNames[i] = contact;
so my question in short is
why cant i fill the array from that method.
***********************************************888 ***********************************************888
stack trace by request
please fill the list at index 0
overtone
please fill the list at index 1
java.lang.NullPointerException
at project.AdminMessages.fillContactList(AdminMessages.java:410)
at project.AdminMessages.<init>(AdminMessages.java:91)
at project.AdminUser.createAdminMessages(AdminUser.java:32)
at project.AdminUser.<init>(AdminUser.java:18)
at project.AdminUser.main(AdminUser.java:47)
To define an array in a constructor you can do something along these lines,
// if values are predefined, you can explicitly fill the array
String[] contacts = {"Bill Gates", "Steve Jobs", "Jon Skeet"};
// or this way, both will work.
String[] contacts = new String[2];
Looking at JList from the Java Doc's you can most certainly pass in an array to JList
String[] data = {"one", "two", "three", "four"};
JList dataList = new JList(data);
You are getting NullPointerException because the array, contactListNames is not initialized, you would need to initialize it.
You define an array in a constructor just like you would any other variable. So, it would look something like:
// define an array of size 3
String[] contactListNames = new String[3];
The reason you are getting exceptions is because you don't actually initialize the array. You declare it but you never set it to a value (or give it a size). You should post the stack trace of the error but I suspect it's a NullPointerException.
Then in my constructor i have the
Jlist defined to fill itself with the
contents of the array
String[] contactListNames = new String[5];
JList contactList = new JList(contactListNames);
fillContactList();
What you're doing here is creating new local variables that are shadowing the ones defined in your class.
Change it to:
contactListNames = new String[5];
contactList = new JList(contactListNames);
fillContactList();

Categories