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);
Related
I want add newly added listitems from the index 0. like if one items is present already then if i insert another item so i want it display at top.
ListView lst1 = (ListView) findViewById(R.id.list2);
List<Map<String, String>> MyDataList = null;
reuestitems myData = new reuestitems();
MyDataList = myData.getlist10();
String[] from = {"bloodgrp", "date", "time", "name", "Username"};
int[] to = {R.id.listt, R.id.date, R.id.time1, R.id.name3, R.id.user};
ad = new SimpleAdapter(request.this, MyDataList, R.layout.listrequest, from, to);
lst1.setAdapter(ad);
lst1.setBackgroundColor(getColor(R.color.colorPrimary));
if(ad.getCount()==0){
Toast.makeText(getApplicationContext(), "No requests are currently visible", Toast.LENGTH_SHORT).show();
}
i strongly suggest to use RecyclerView instead of ListView.
the function you are looking for is adapter.notifyItemInserted or if you want to remove an item adapter.notifyItemRemoved.
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 an odd problem, (see shorter version at the bottom first please)
When my activity starts for the first time, the listview shows the dataset fine. The adapter is a custom adapter which shows 2 rows of text and an image. I call an asynctask upon a click event to the listview, the dataset updates in accordance with whatever was clicked on in the listview - more specifically the arrays which are associated with the adapter become rewritten with the parsings of some xml, and then notifyachapterdatasetchanged method is called to update the listview in the onPostExecute function. However I always get NullPointerException when I am iterating through some xml (which is very well formed and validates). ALso its worth mentioing that the algorithm that parses the desired values is good, because as mentioned above, if i write to just 1 element of the array then I dont get the error I just get the last node value so its looping in the correct places. i.e If I simple try to copy the current node value I am parsing during the loop into, say, producyTypes[0] then the last value from within the loop actually makes it to the listview as it constantly overwrites this elemet of the array
Here is my code.`
public class main extends Activity implements OnItemClickListener
{
String selectedType="";
ListView lview3;
ImageView iv;
ListViewCustomAdapter adapter;
String test = "";
List<String> ls;
String productTypes[] = {"Monitor","Components","Systems","Laptops","Flash / Usb Memory",
"Networking","Cables","Peripherals","Sound and Vision", "Software"};
String productsIncluded[] = {"Sizes (inches) 17, 19, 20",
"Motherboards, PSU, Cases, Fans/Heatsinks/Coolers, Barebones Systems, Blue-Ray/DVD. Card Readers, Controller Cards, Drive Enclosures, Sound Cards",
"Bundles, Switches and Hubs, Print Servers, Accessories/Modules",
"Cables for: Drives, Networking, HDMI/Monitor, Audio/Video, USB/Firewire, Power, Miscellaneous",
"Mice, Connectors, Bluetooth Devices",
"Mp3/Mp4 Solar Panel",
"Anti-Virus, Internet Security, Operating Systems, Office,,
"",
""};
private static int images[] = {R.drawable.monitor, R.drawable.components, R.drawable.systems,
R.drawable.laptops, R.drawable.flashusb, R.drawable.networking, R.drawable.cables, R.drawable.
peripherals, R.drawable.soundandvision, R.drawable.software};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iv = (ImageView)findViewById(R.id.ImageView01);
iv.setImageResource(R.drawable.logo);
iv.setVisibility(View.VISIBLE);
lview3 = (ListView) findViewById(R.id.listView3);
adapter = new ListViewCustomAdapter(main.this, productTypes, productsIncluded, images);
lview3.setAdapter(adapter);
lview3.setOnItemClickListener(main.this);
}
#Override
public void onItemClick(AdapterView arg0, View arg1, int position, long id) {
selectedType = "";
if(position == 0)
{
selectedType= "Monitors";
}
if(position == 1)
{
selectedType= "Hard Drives";
}
Toast.makeText(this, Integer.toString(position), Toast.LENGTH_SHORT).show();
new async().execute();
/*
Intent intent = new Intent(getApplicationContext(),activitywo.class);
Bundle bundle =new Bundle();
bundle.putString("selectedType",selectedType);
intent.putExtras(bundle);
startActivity(intent);
//Toast.makeText(this, "Title => "+productTypes[position]+" \n Description => "+productsIncluded[position], Toast.LENGTH_SHORT).show();
*/
}
private class async extends AsyncTask<String, Void, Void> {
// UI Thread
protected void onPreExecute() {
}
// automatically done on worker thread (separate from UI thread)
protected Void doInBackground(final String... args) {
try{
Resources res = getResources();
InputStream in;
in = res.openRawResource(R.raw.core);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(in);
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("entry");
count=0;
for(int i =0;i<items.getLength();i++){
Node item = items.item(i);
NodeList properties = item.getChildNodes();
//productsDefinedByTypeArray = new String[properties.getLength()];
for(int j = 0;j<properties.getLength();j++){
Node property = properties.item(j);
String name = property.getNodeName();
if(name.equalsIgnoreCase("g:product_type")){//everytime we hit g:product_type grab the value
String strText = property.getFirstChild().getNodeValue();
if(strText.contains(selectedType)){
//
for(int k = 0;k<properties.getLength();k++){
Node propertysecond = properties.item(k);
String namesecond = propertysecond.getNodeName();
if(namesecond.equalsIgnoreCase("title")){//everytime we hit title grab the value
String strTextsecond = propertysecond.getFirstChild().getNodeValue();
productTypes[0] = strTextsecond;
yo = strTextsecond;
count++;
}
}
}
}
}
}
The code crashes at the point where I am trying to copy the value of a "title" node that I parse out of my xml file into the list-String-. I am using a list-string- to show that even if you try and copy the value into the array itself (the array that is associated with the adapter), even if you comment out the notifydatasetchanged () line the program still crashes. The xml is well formed and very consistent. I know this because (aecept the fact its really small and I have read it all) ! Why can I not copy every node value into my array/list whilst the loop is in progress?
Any help is massively appreciated. Thank you.
Shorter version:
I cannot write to the List
if(strText.contains(selectedType)){
//
for(int k = 0;k<properties.getLength();k++){
property = properties.item(k);
name = property.getNodeName();
if(name.equalsIgnoreCase("title")){//everytime we hit title grab the value
String strTextsecond = property.getFirstChild().getNodeValue().toString();
ls.add(strTextsecond.toString());
//test = strTextsecond;
}
}
}
Maybe you forget initialize ls? I don't find in your code something like:
ls = new List<String>();
my code here is horribly wrong, and i'm not sure how you would properly do this. i have a Spinner which is populated from a SQLite database query through a CursorAdapter. i need to get the text (value) of the currently selected item. i tried this garbage:
((Cursor)prdSpn.getItemAtPosition(prdSpn.getSelectedItemPosition())).getString(prdSpn.getSelectedItemPosition())
to get the text, but it crashes every time. what's the proper way to do this? here's some additional code that may be relevant:
/// qc defined above as a SimpleCursorAdapter
/////////setup product selection spinner from db
prdSpn = (Spinner)findViewById(R.id.prd_spn);
Cursor prdCur = null;
try {
prdCur = mDb.query(smsDbSchema.ProductSchema.TABLE_NAME, null, null, null, null, null, null);
} catch(Exception e) {
Log.e("smsdb", e.toString());
}
prdCur.moveToFirst();
startManagingCursor(prdCur);
qc = new SimpleCursorAdapter(
this,
android.R.layout.simple_spinner_item,
prdCur,
new String[] {smsDbSchema.ProductSchema.COLUMN_NAME},
new int[] {android.R.id.text1}
);
qc.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
prdSpn.setAdapter(qc);
Code similar to the following works for me...
Cursor theCursor = qc.getCursor();
String theString = theCursor.getString(theCursor.getColumnIndex(<your column name here>));
EDIT by moonlightcheese:
implementation:
Cursor theCursor = (Cursor)prdSpn.getSelectedItem();
Log.e("spnERRtest", "Item: " + theCursor.getString(theCursor.getColumnIndex(smsDbSchema.ProductSchema.COLUMN_NAME)));
//theCursor.getString(theCursor.getColumnIndex(smsDbSchema.ProductSchema.COLUMN_NAME)).contains("CAR")
((Cursor)prdSpn.getItemAtPosition(prdSpn.getSelectedItemPosition())).getString(prdSpn.getSelectedItemPosition())
I'm unclear why you are passing getSelectedItemPosition() to getString(). Shouldn't you pass the column number of the column that has the data you want? Isn't this column unrelated to the row that was selected in the spinner?
I'm new to java and I'm trying to run a method once a button is clicked and I am unsure if I'm on the right track. I am selecting 10 questions from a Sqlite database and would like to cycle through each question 0-9 everytime the button is clicked. Once all 10 questions are asked I will move to another activity. I have the app displaying the first question fine but I am having trouble calling the showQuestions method and increasing the questionNum int by one when the button is clicked and passing this onto the method. Any help would be appreciated!
This is the showQuestions method which I am trying to call.
public void showQuestions(Cursor cursor) {
cursor.moveToPosition(questionNum);
while (cursor.moveToNext()) {
// Collect String Values from Query
StringBuilder questiontxt = new StringBuilder("");
StringBuilder answertxt1 = new StringBuilder("");
StringBuilder answertxt2 = new StringBuilder("");
StringBuilder answertxt3 = new StringBuilder("");
StringBuilder answertxt4 = new StringBuilder("");
String question = cursor.getString(2);
String answer = cursor.getString(3);
String option1 = cursor.getString(4);
String option2 = cursor.getString(5);
String option3 = cursor.getString(6);
questiontxt.append(question).append("");
answertxt1.append(answer).append("");
answertxt2.append(option1).append("");
answertxt3.append(option2).append("");
answertxt4.append(option3).append("");
}
}
This is the code for the button which I am working on. There are 4 buttons.
public void onClick(View v) {
switch (v.getId()) {
case R.id.option1_button:
if (questionNum<9) {
questionNum ++;
}
Questions.this.showQuestions(null);
break;
}
And this is the XML code for the buttons.
<Button
android:id="#+id/option1_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/option3_button"/>
OnClick Listener for the button
View option1_button = findViewById(R.id.option1_button);
option1_button.setOnClickListener(this);
Database Query and Allocation to Cursor
//Get the questions and allocate them to the Cursor
public Cursor getQuestions() {
//Select Query
String loadQuestions = "SELECT * FROM questionlist ORDER BY QID LIMIT 10";
SQLiteDatabase db = questions.getReadableDatabase();
Cursor cursor = db.rawQuery(loadQuestions, null);
startManagingCursor(cursor);
return cursor;
}
Thanks in advance.
Questions.this.showQuestions(null);
Why you pass null to the showQuestions method?
Let me guess - it crashes with NullPointerException.
Did you tried
showQuestions(getQuestions())
EDIT:
Some general suggestions:
don't load the question every time when the button is clicked.
make some Question class containing all needed information for a question
when onCreate is invoked, open the database and load all needed questions in some Collection, like ArrayList<Question>
Every time when the user clicks a button, get the next Question element from the Collection and show it