I am using this -> http://www.ezzylearning.com/tutorial.aspx?tid=1763429 to create my own custom listview.
For my project, I am using while loop to get data and getting data back.
The original code is :
DownloadClass data[] = new DownloadClass[] {
new DownloadClass("test", "test"),
new DownloadClass("test", "Sunny")
};
However for my case..
DownloadClass data[] = new DownloadClass[] {};
SQLFunctions entry = new SQLFunctions(this);
entry.open();
highestID = entry.getHighestId();
for (int l = 1; l < highestID; l++) {
Long longVal = Long.valueOf(l);
new DownloadClass(entry.getName(longVal).toString(), entry.getURL(longVal).toString());
}
The listview appears to be empty because I know the data is not inserted. Any help is appreciated. Thanks.
EDIT :
my DownloadClass :
public class DownloadClass {
public String name;
public String url;
public DownloadClass(){
super();
}
public DownloadClass(String name, String url) {
super();
this.name = name;
this.url = url;
}
}
My new Activity
DownloadClass data[] = new DownloadClass[]; // need to work on this
SQLFunctions entry = new SQLFunctions(this);
entry.open();
highestID = entry.getHighestId();
Log.e("HIGHEST ID", highestID.toString());
if (highestID > 1) {
for (int l = 0; l < highestID; l++) {
Long longVal = Long.valueOf(l);
//String name = entry.getName(longVal);
//String id = entry.getURL(longVal);
//Log.e("NAME", name + " - " + id);
data[l] = new DownloadClass(entry.getName(longVal).toString(),entry.getURL(longVal).toString());
}
}
entry.close();
You're not ever adding your new DownloadClass object to your array. You also need to allocate size if you're going to use an array instead of an ArrayList (which to be honest is probably what you want).
As you iterate through the loop you need to assign the new object to a position in the array.
data[i] = new DownloadClass(...);
Try this and let me know what happen..
DownloadClass data[];
SQLFunctions entry = new SQLFunctions(this);
entry.open();
highestID = entry.getHighestId();
data[] = new DownloadClass[highestID];
for (int l = 0; l < highestID; l++) {
Long longVal = Long.valueOf(l);
data[i] = new DownloadClass(entry.getName(longVal).toString(), entry.getURL(longVal).toString());
}
Also start your loop with 0 index.. instead of 1..
Update:
First of all you are dynamically creating array of object. SO you have to know the size of array.
Second your loop is start with index 1, it should be 0.
Related
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'm tried to sort the database from a web service by using the bubble sort.
itemLists[i] = new ItemList(
a.getString(id),
a.getString(nama),
a.getString(latitude),
a.getString(longitude),
a.getString(alamat));
double terendah = Double.valueOf(a.getString("TAG_TERENDAH")).doubleValue();
//double terendah = a.getDouble(terenda);
harga[i] = terendah;
//bubble sort
double tHarga;
ItemList tItemList;
for (int k = 0; k < tempatrental.length(); k++) {
for (int l = 0; l < tempatrental.length() - (k + 1); l++) {
if (harga[l] > harga[l + 1]) {
tHarga = harga[l];
tItemList = itemLists[l];
harga[l] = harga[l + 1];
itemLists[l] = itemLists[l + 1];
harga[l + 1] = tHarga;
itemLists[l + 1] = tItemList;
}
}
Anyways, database from the web service is array type, so I store it in the array from another class.
public class ItemList{
public String label1, label2, label3, label4, label5;
public ItemList(String label1, String label2, String label3, String label4, String label5) {
super();
// TODO Auto-generated constructor stub
//this.icon = icon;
this.label1 = label1;
this.label2 = label2;
this.label3 = label3;
this.label3 = label4;
this.label3 = label5;
}
The problem came when I tried to show the results of sorting in the list view.
this.setListAdapter (new ArrayAdapter<String>(TermurahActivity.this, android.R.layout.simple_list_item_1, itemLists));
Eclipse says : The Constructor ArrayAdapter(TermurahActivity, int, ItemList[]) is undefined. Please help fix to fix this...
Once you defined ArrayAdapter<String> the adapter expects a list of String.
ItemLists is a list of ItemList so you should use:
new ArrayAdapter<ItemList>(TermurahActivity.this,
android.R.layout.simple_list_item_1, itemLists);`
I have a variable called current which holds the last clicked listview item data. The id of this data is to be used to query the db again for movies taht are similar.
The problem that current = id=17985, title=the matrix, year=1999 when all i need is the actual id-number. I have tried to use substring to only use the correct places of the string. This works for the matrix since its id is exactly 5 digits long, but as soon as i try to click movie with higher/lower amount of digits in its id of course it trips up.
String id = current.substring(4,9).trim().toString(); does not work for all movies.
Heres some code:
// search method: this is necessary cause this is the method thats first used and where the variable current is set. This is also the only method using three lines for getting data - id, title and year.
protected void search() {
data = new ArrayList<Map<String, String>>();
list = new ArrayList<String>();
EditText searchstring = (EditText) findViewById(R.id.searchstring);
String query = searchstring.getText().toString().replace(' ', '+');
String text;
text = searchquery(query);
try {
JSONObject res = new JSONObject(text);
JSONArray jsonArray = res.getJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item = new HashMap<String, String>(2);
item.put("id",jsonObject.getString("id"));
item.put("title",jsonObject.getString("title"));
item.put("year", jsonObject.getString("year"));
data.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
aa = new SimpleAdapter(SearchTab.this, data,
R.layout.mylistview,
new String[] {"title", "year"},
new int[] {R.id.text1,
R.id.text2});
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(aa);
lv.setDividerHeight(5);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
Map<String, String> s = data.get((int) id);
current = s.toString();
}});
}
// similar method: this tries to build a list from the fetched data from "current"-string. As you can see i try to use 4,9 to only get right numbers, but this fails with others. Best would be to only to be ble to get the ID which I cant seem to do. The toast is just to see what is beeing fetched, much like a system out print.
protected void similar() {
data = new ArrayList<Map<String, String>>();
list = new ArrayList<String>();
String id = current.substring(4,9).trim().toString();
Toast.makeText(getApplicationContext(), id, Toast.LENGTH_SHORT).show();
String text;
text = similarquery(id);
try {
JSONObject res = new JSONObject(text);
JSONArray jsonArray = res.getJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item = new HashMap<String, String>(2);
item.put("title",jsonObject.getString("title"));
item.put("year", jsonObject.getString("year"));
data.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
aa = new SimpleAdapter(SearchTab.this, data,
R.layout.mylistview2,
new String[] {"title", "year"},
new int[] {R.id.text1,
R.id.text2});
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(aa);
lv.setDividerHeight(5);
}
Use current.split(",")[0].split("=")[1]
edit - assuming of course that id is always the first in the comma separated list and will always be a name value pair delimited by '='
If you want to solve it via substring then you shouldn't use a predefined .substring(4,9). Use something like that:
String item = "id=17985, title=the matrix, year=1999";
String id = item.substring(item.indexOf("id=") + 3, item.indexOf(" ", item.indexOf("id=") + 3) - 1);
System.out.println("Your ID is: " + id);
// Works also for "test=asdf, id=17985, title=the matrix, year=1999"
It gets the String between "id=" and the next " " (space).
Hi can some one suggest me a sample example of how i can sort the textviews based on the numbers in textviews. I am able to get the text from the TextViews need to sort and place the lowest number first.
Thank you.
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
for (int i = 0; i < intValues.length; i++) {
Integer intValue = intValues[i];
//here I want to assign sorted numberes to the TextViews
}
}
So I have followed Jeffrey's advice. Here is the code which still doesn't work properly. What could be wrong?
Created an array of TextViews:
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
tvs[2] = textView43;
tvs[3] = textView53;
tvs[4] = textView63;
tvs[5] = textView73;
tvs[6] = textView83;
Sorted the array and assinged new values to the TextViews:
Arrays.sort(tvs, new TVTextComparator());
textView23.setText(tvs[0].getText().toString());
textView33.setText(tvs[1].getText().toString());
textView43.setText(tvs[2].getText().toString());
textView53.setText(tvs[3].getText().toString());
textView63.setText(tvs[4].getText().toString());
textView73.setText(tvs[5].getText().toString());
textView83.setText(tvs[6].getText().toString());
And here is the Comporator class:
public class TVTextComparator implements Comparator<TextView> {
public int compare(TextView lhs, TextView rhs) {
Integer oneInt = Integer.parseInt(lhs.getText().toString());
Integer twoInt = Integer.parseInt(rhs.getText().toString());
return oneInt.compareTo(twoInt);
}
}
to sort your textViews, first put them in an array,
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
// and so on
note that if you have handle to the parent container, you could easily build the array by using ViewGroup.getChildCount() and getChildAt().
now write a comparator for a text view,
class TVTextComparator implements Comparator<TextView> {
#Override
public int compare(TextView lhs, TextView rhs) {
return lhs.getText().toString().compareTo(rhs.getText().toString());
// should check for nulls here, this is NOT a robust impl of compare()
}
}
now use the comparator to sort the array,
Arrays.sort(tvs, 0, tvs.length, new TVTextComparator());
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
textView23.setText(intValues[0]);
textView33.setText(intValues[1]);
textView43.setText(intValues[2]);
textView53.setText(intValues[3]);
textView63.setText(intValues[4]);
textView73.setText(intValues[5]);
textView83.setText(intValues[6]);
}
This code is giving an error saying "error receiving broadcast intent in activity"
I cant find any eroors though...........any ideas ?
i've added the loop condition as seven as i only want the first seven scan results
class WifiReceiver extends BroadcastReceiver {
public void onReceive(Context con, Intent intent) {
sb = new StringBuilder();
wifiList = mainWifi.getScanResults();
for(int i = 0; i < wifiList.size(); i++)
{
sb.append((wifiList.get(i)).SSID.toString());
sb.append(' ');
sb.append('!');
sb.append("\n\n");
}
String net = sb.toString();
if(wifiList.size() > 0)
{
char excl = '!';
int excl1 = excl;
String[] aray = null;
for(int j = 0; j<7; j++)
{
int index = net.indexOf(excl1);
String a = net.substring(0, index);
aray[j] = a;
String temp = net.substring(index+1);
net = temp;
}
String one = aray[0];
String two = aray[1];
String three = aray[2];
String four = aray[3];
String five = aray[4];
String six = aray[5];
String seven = aray[7];
tv1.setText(one);
}
else
{
tv1.setText("No Networks Detected");
}
}
}
PS : I've only added into one TextView as this is a test module
The "aray" array is not being intialized correctly. You need to initialize "aray" before accessing it:
String[] aray = new String[7];
You are also going outside the dimensions of the array. this:
String seven = aray[7];
should be:
String seven = aray[6];
An even better solution would be to use an ArrayList.
ArrayList al = new ArrayList();
al.add(yourString);