im a beginner in android/java programming and im trying to retrieve the element from a listview and put them in a textview.I know you can set text to a textview using settext but I dont know how to retrieve element from my listview(they are all strings) and put them in my textview
thank you
StringBuffer allItems = new StringBuffer();
Adapter adapter = listView.getAdapter();
for (int i=0; i<adapter.getCount(); i++) {
Object item = adapter.getItem(i);
allItems.append(item.toString());
allItems.append(", ");
}
textView.setText(allItems.toString());
Related
I am trying to do a app with multiple EditText and is wondering if there is any easy way to do that.
For instance to add matrix of EditText from your java code to your activity_main.xml or maby do a for loop which adds them at your specified location.
EditText[][] edittext = new EditText[10][10];
gridView = (GridView) findViewById(R.id.gridview);
for (int i=0;i<9;i++){
for (int j=0;j<9;j++){
gridView.addView(edittext[i][j], column X, row Y);
}
}
Here is a working example..
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout root = (LinearLayout) findViewById(R.id.master);
EditText t[][] = new EditText[10][10];
LinearLayout.LayoutParams dim = new LinearLayout.LayoutParams(LinearLayout.LayoutParams
.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
for (int i=0;i<9;i++){
for (int j=0;j<9;j++){
t[i][j]=new EditText(this);
t[i][j].setLayoutParams(dim);
t[i][j].setHint("Hello World , EditText[" + i + "]" + "[" + j + "]");
root.addView(t[i][j]);
}
}
}
There is no easier way to make a "form". Each EditText is a different xml component with different id, with its own attributes.
What you can do is an adapter with listview/recyclerview with EditText the holder.
You can do smth like that:
ArrayList<EditText> editTexts = new ArrayList<>();
LinearLayout ll = (LinearLayout) findViewById(R.id.container);
EditText oneOfEditText;
for (int i = 0; i < 100; i++){
oneOfEditText = new EditText(this);
oneOfEditText.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
));
oneOfEditText.setHint("MyHint");
oneOfEditText.setId(i);
ll.addView(oneOfEditText);
editTexts.add(oneOfEditText);
}
And then you can access these EditTexts like that:
for (EditText editText : editTexts){
Log.d("myLog", editText.getText().toString());
}
But the best practice for such things is to create them statically in xml, and then you can access them either via static ids, or like that:
for (int i =0; i < ll.getChildCount(); i++){
editTexts.add((EditText) ll.getChildAt(i));
}
I think the proper way implement each item is to use an adapter. In your case, you can use SimpleAdapter or create a custom adapter that extends BaseAdapter and set it using setAdapter(ListAdapter).
You can check the documentation for GridView here:
http://developer.android.com/guide/topics/ui/layout/gridview.html
I try to add dinamically some TextViews in Java. I assume that when I want to use setText() method, I should earlier connect my Java's TextView object with XML's TextView - I use setId().
At the end, I got NullPointerException in the line where I use setId().
My code:
TextView[] tvQuestion = new TextView[numberOfQuestions];
TextView[] tvAnswer1 = new TextView[numberOfQuestions];
TextView[] tvAnswer2 = new TextView[numberOfQuestions];
TextView[] tvAnswer3 = new TextView[numberOfQuestions];
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
for (int i = 0; i < numberOfQuestions; i++) {
tvQuestion[i].setId(View.generateViewId()); // NullPointerException!
tvAnswer1[i].setId(View.generateViewId());
tvAnswer2[i].setId(View.generateViewId());
tvAnswer3[i].setId(View.generateViewId());
tvQuestion[i].setLayoutParams(params);
tvAnswer1[i].setLayoutParams(params);
tvAnswer2[i].setLayoutParams(params);
tvAnswer3[i].setLayoutParams(params);
tvQuestion[i].setText(question[i]);
tvAnswer1[i].setText(option1[i]);
tvAnswer2[i].setText(option2[i]);
tvAnswer3[i].setText(option3[i]);
layAll.addView(tvQuestion[i]);
layAll.addView(tvAnswer1[i]);
layAll.addView(tvAnswer2[i]);
layAll.addView(tvAnswer3[i]);
}
EDIT:
Solution: Philipp Jahoda's post.
You just created an Array for the TextViews. The TextViews inside the Array are null as long as they are not initialized.
So you need to call
tvQuestion[i] = new TextView(Context);
tvAnswer[i] = new TextView(Context);
// and so on ...
// and then later
tvQuestion[i].setId(View.generateViewId());
// and so on ...
before setting the ID and other stuff.
I wish to have a auto-complete text-box which comes up with the users contact names. My code is as follows.
private void getContactNames()
{
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
_contactAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line);
while (cursor.moveToNext())
{
int nameIdx = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
String tmp = cursor.getString(nameIdx);
_contactAdapter.add(tmp);
}
}
Setting the adapter:
AutoCompleteTextView contactName = (AutoCompleteTextView) findViewById(R.id.contactName);
contactName.setAdapter(_contactAdapter);
When I do this, the adapter has all the contact names in there (238 contacts). However, when I start typing into the text box, the auto complete does not show.
Funny, as when I test it out doing this:
String[] ab = new String[] {"aaaaa", "bbbbb"};
_contactAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,ab);
it will show "aaaaa" and "bbbbb" when typing in to the text box.
Any ideas?
Thanks,
Tom
*EDIT
Just thought I would follow up. It does seem to be the sheer amount of contacts that is preventing it from appearing. Any way to get around this?
while (cursor.moveToNext())
{
int nameIdx = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
String tmp = cursor.getString(nameIdx);
//_contactAdapter.add(tmp);
// get all names in a new arraylist and then assign it to
arrayList.add(tmp);
}
and then assign it to your adapter as
_contactAdapter = new ArrayAdapter<String> this,android.R.layout.simple_dropdown_item_1line, arrayList);
I am trying to build a simple TV-Guide for Android. To make that, I am using RSS from one site. I parse XML and now, I'd like to show it. The idea is a List that displays Station, Whats currently on the show and date, and when I press on some item in the list it will give me a new Activity that shows the full schedule of some TV station. I've managed to separate parts of Whole TV program in just separate Strings (like: 06:00 News; 07:15 Movie). And I even managed to separate it so it fills String[][] (like: |06|,|00|,|News| ; |07|,|15|,|Movie|). And my Idea was to check which one is closest to real time and to display it.
Well, currently my App displays TV Station, WHOLE program (schedule), and Date. And I want it to display just whats currently showed. Can anybody help me with this one?
Here is class in which I want to do it: (I also have Parser class and Main class with just buttons and URLs of XMLs)
public class Pomocna extends ListActivity {
// All static variables
static String url =null;
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_DATE = "pubDate";
static final String KEY_DESC = "encoded";
Calendar calendar = new GregorianCalendar();
int DSQ=calendar.get(Calendar.HOUR_OF_DAY);
int DMQ=calendar.get(Calendar.MINUTE);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent in = getIntent();
// Get XML values from previous intent
url = in.getStringExtra("A");
ArrayList<HashMap<String,String>> menuItems = new ArrayList<HashMap<String,String>>();
//ArrayList<String[][]> nekaj = new ArrayList<String[][]>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(url); //get XML
Document doc = parser.getDomElement(xml); // get DOM elem.
//doc.getDocumentElement().normalize();
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
//loop
for (int i=0; i< nl.getLength(); i++){
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
//add to map
map.put(KEY_TITLE, Vracanje1(parser.getValue(e, KEY_TITLE)));
map.put(KEY_DATE, Vracanje2(parser.getValue(e, KEY_DATE)));
map.put(KEY_DESC, parser.getValue3(e,KEY_DESC));
//NEKO FRCERANJE -=- POCETAK
String pvp = parser.getValue3(e,KEY_DESC);
char[] rast = pvp.toCharArray();
int brojac = 0;
for(int q=0; q<pvp.length(); q++){
if(rast[q]=='*') brojac++;
}
String[][] niz= new String[brojac][3];
int bf1=0;
int bf3=0;
int oo=0;
for(int q=0; q<pvp.length(); q++){
if(rast[q]=='*'){
bf3=bf1;
bf1=q;
String lol = pvp.substring(bf3, bf1);
// SEPARATE STRING: LOL
// IT MUST HAVE 3 PARTS: HOUR, MINUTE, AND DESCRIPTION
if(oo==0){
String ps=lol.substring(0,2);
String ds=lol.substring(3,5);
String ts=lol.substring(6,lol.length());
niz[oo][0]=ps;
niz[oo][1]=ds;
niz[oo][2]=ts;
}
if(oo>0){
String ps=lol.substring(1,3);
String ds=lol.substring(4,6);
String ts=lol.substring(7,lol.length());
niz[oo][0]=ps;
niz[oo][1]=ds;
niz[oo][2]=ts;
}
oo++;
}
}
//NEKO FRCERANJE -=- KRAJ
menuItems.add(map);
//nekaj.add(niz);
}
//DISPLAY WHAT's CURRENTLY ON PROGRAM
//USE TIME TO COMPARE AND SHOW
ListAdapter adapter = new SimpleAdapter(this, menuItems, R.layout.list_item,
new String[]{KEY_TITLE, KEY_DESC, KEY_DATE}, new int[]{
R.id.title, R.id.description, R.id.date
});
setListAdapter(adapter);
//singleView
ListView lv = getListView();
}
public String Vracanje1(String bq){
int p1=bq.length();
int p2=p1-10;
StringBuilder sbp= new StringBuilder(bq);
sbp.delete(p2, p1);
String ses=sbp.toString();
return ses;
}
public String Vracanje2(String bq){
int p1=bq.length();
int p2=p1-14;
StringBuilder sbp=new StringBuilder(bq);
sbp.delete(p2, p1);
String ses = sbp.toString();
return ses;
}
}
Per my understanding the way You're doing won't be acceptable to any TV-program application, because usually program has many channels with many programs and parsing and analysing the data in UI thread will (sooner or later) cause ANRs. I would suggest You to consider use of separate service and content provider to let UI thread do only UI-related stuff and leave data processing to corresponding components. It would be faster and easier to find/process data via sqlite in provider.
Regarding a question about finding closest data - You could sort arrays and when find closest one (e.g. just iterating from the beginning).
I agree with #sandstar, but I'm not sure if what you're asking is how to filter the data or how to show the data? In this case it is the matter of updating the ListAdapter. This means, when you want to show only the most recent program, you need to provide the adapter a list of maps containing only the map with the data for the latest show. This means you should filter the data before applying the adapter to the ListView. If you want to have more control over the adapter you might consider extending the ArrayAdapter which also allows you to add/clear the data of the existing adapter.
I have looked at Android - how to update ListView item that is currently displayed and http://commonsware.com/Android/excerpt.pdf and the Android documentation but I still don't understand.
My problem:
Using a handler, I am trying to update a Stock data multi-column listview which I have populated from a webservice which retrieves data from a MySQL database.
To update the listview, I am calling a servlet which returns an XML that I loop through using DOM.
I cannot find a working way to apply the new data (from the XML) into the Listview, though only the third column (Trade Column) has to be updated. Also when I try to cast a View from a ListView row, I get a NullPointerException and can't figure out why.
The code I have done so far is below.
java Code:
private void updateUI() throws Exception
{
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":" + minutes + ":"+ seconds;
refreshHandler.sleep(60000);
ListView listview = (ListView) findViewById(R.id.listview);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("http://10.0.0.29:8080/CI3500/FTSEXML");
//Filter and store ALL 'update' XML elements into node array
NodeList nodeList = doc.getElementsByTagName("update");
View v = null;
TextView t = null;
Adapter adapter = listview.getAdapter();
for (int i = 0; i < adapter.getCount(); i++)
{
v = listview.getChildAt(i);
t = (TextView)v.findViewById(R.id.item2);
String companyCode = t.getText().toString(); //Column 1
for(int j = 0; j < nodeList.getLength(); j++)
{
if(companyCode == nodeList.item(j).getFirstChild().getNodeValue())
{
//TODO Update Listview Code
}
}
}
txtStatus.setText(String.valueOf("Last Update: " + curTime));
}
The listview mapping is as follows:
// create the grid item mapping
String[] columns = new String[] {"col_1", "col_2", "col_3" };
int[] rows = new int[] { R.id.CodeColumn, R.id.NameColumn, R.id.TradeColumn };
You should implement you own ListView Adapter that will provide data to the list view. Calling notifyDataSetChanged() from adapter will force list view to fetch data from the adapter. Updating list view views directly looks strange.
You can call invalidate to let the listview redraw.