I need some help. Im quite new to android and java.
Right now i have a csv code reader. The code will read the csv and then puts it into a Spinner. the csv file i have is example like this
1,"Easy"
2,"Medium"
3,"Hard"
4, "Very Hard
My Code
try{
InputStreamReader csvStreamReader = new InputStreamReader(MainActivity.this.getAssets().open("Category.csv"));
CSVReader reader = new CSVReader(csvStreamReader);
Log.d("test", "reading csv");
String [] nextLine;
List<String> list = new ArrayList<String>();
while ((nextLine = reader.readNext()) != null) {
list.add(nextLine[0] + "," + nextLine[1]);} spinner1 =(Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
spinner1.setAdapter(adapter);
} catch (IOException e) {
e.printStackTrace();
}
The code works well. It does appear in the spinner.
Now i want to go a little further, i want to create a for loop the check the array for a particular text example "Medium". When the word is found, it will be stored into another array. I really cant figure out the code. Try searching for ideas in this forum but fail. Can some one give me some pointers, preferred a sample code.
Related
I am new to android, am developing one application in which i have to get the data from the server need to store that data in sqlite, so every time i should not hit the server,when ever i want get from database,in this app i used fragment concept,when i enter the single character in multiautocomplete textview based on the names in json response it needs to show the email-ids which are matching to that character in drop down list. i have done the code am not getting errors but not getting the expected result in textview
when i debug the code the following block of code is not executing i don't know what is the problem in this can you please help me any one
new Handler().post(new Runnable() {
public void run() {
Cursor cursor = contactDataSource.getAllData();
if (BuildConfig.DEBUG)
Log.d(TAG, "total contcat count :" + cursor.getCount());
while (cursor.moveToNext()) {
if (BuildConfig.DEBUG)
Log.d(TAG,
"Contact from cursor:"
+ cursor.getString(cursor
.getColumnIndex(ExistingContactTable.COL_NAME)));
}
customAdapter = new CustomContactAdapter(getActivity(), cursor);
Log.i("Custom contact adapter", "" + customAdapter);
if (customAdapter != null)
editorIdSharableEmail.setAdapter(customAdapter);
}
});
First get your all data in array by json
and then use that array
String[] str={"Andoid","Jelly Bean","Froyo",
"Ginger Bread","Eclipse Indigo","Eclipse Juno"};
MultiAutoCompleteTextView mt=(MultiAutoCompleteTextView)
findViewById(R.id.multiAutoCompleteTextView1);
mt.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
ArrayAdapter<String> adp=new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line,str);
mt.setThreshold(1);
mt.setAdapter(adp);
if you dont know how to get data from json then check this and also check this
Problem Description:
I am facing some problem with AutoCompleteTextView where I have to show suggestions after each keypress.
Thing is that, list of suggestion is dynamic like google's suggestion feature.
It means the new suggestions should be added as user keeps typing in plus all matching old suggestions should be displayed.
For example
I write "te" and then it should display previous suggestions like "test1" & "test2" and the new suggestions that I will get from Web API. Suppose web api gives me word "tea"& "tension ".
Now the AutoCompleteTextView will have "te" as string with all four suggestions showing below it.
This is exactly what I am looking for.
looks simple but it is showing a strange behaviour.
I am using default ArrayAdapter class instance of which I am declaring globally.
arrayAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,suggestions);
word.setAdapter(arrayAdapter);
suggestions is ArrayList.
Upon getting new result from WebApi I simply call
arrayAdapter.notifyDataSetChanged();
to refresh the data observer and views attached with this (in our case AutoCompleteListView).
But it closes suggestions.
When I don't use notifyDataSetChanged(); it is showing all suggestions regardless of characters I have typed.
I tried it with custom filter as many suggested but none of them is helpful as I couldn't use notifyDataSetChanged().
I am posting an image to avoid confusions.
I have a confusion that why notifyDataSetChanged(); its not working. I haven't use any other reference of list with same arrayAdapter instance. I really doubt if it's a reference problem.
one of the easiest way of doing that (put the code in onCreate):
EDIT: addied wikipedia free opensearch (if https://en.wikipedia.org doesn't work try http://en.wikipedia.org)
AutoCompleteTextView actv = new AutoCompleteTextView(this);
actv.setThreshold(1);
String[] from = { "name", "description" };
int[] to = { android.R.id.text1, android.R.id.text2 };
SimpleCursorAdapter a = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, null, from, to, 0);
a.setStringConversionColumn(1);
FilterQueryProvider provider = new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence constraint) {
// run in the background thread
Log.d(TAG, "runQuery constraint: " + constraint);
if (constraint == null) {
return null;
}
String[] columnNames = { BaseColumns._ID, "name", "description" };
MatrixCursor c = new MatrixCursor(columnNames);
try {
String urlString = "https://en.wikipedia.org/w/api.php?" +
"action=opensearch&search=" + constraint +
"&limit=8&namespace=0&format=json";
URL url = new URL(urlString);
InputStream stream = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String jsonStr = reader.readLine();
// output ["query", ["n0", "n1", ..], ["d0", "d1", ..]]
JSONArray json = new JSONArray(jsonStr);
JSONArray names = json.getJSONArray(1);
JSONArray descriptions = json.getJSONArray(2);
for (int i = 0; i < names.length(); i++) {
c.newRow().add(i).add(names.getString(i)).add(descriptions.getString(i));
}
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
};
a.setFilterQueryProvider(provider);
actv.setAdapter(a);
setContentView(actv, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
You have impletent the custome filter in the child class of ArrayAdapter, there in perform filter method you have to do network call and get data from server. You can set this data in your main arraylist.
I want to add AutoCompleteTextView in my application. I have one txt file in that there are more than 2000 records are present. I want to use it for AutoCompleteTextView. Normally for small data we use array as:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_item,dataArray);
AutoCompleteTextView actv= (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
actv.setThreshold(1);
actv.setAdapter(adapter);
But now how to use txt file for AutoCompleteTextView. Any suggestion will be appreciated.
How are you separating elements in your text file? Assuming that you have a new elements on each line you can use this to convert the file to an array, the use the array adapter as you have mentioned above.
String[] arr= null;
List<String> items= new ArrayList<String>();
try
{
FileInputStream fstream = new FileInputStream("text1.txt");
DataInputStream data_input = new DataInputStream(fstream);
BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input));
String str_line;
while ((str_line = buffer.readLine()) != null)
{
str_line = str_line.trim();
if ((str_line.length()!=0))
{
items.add(str_line);
}
}
arr = (String[])items.toArray(new String[items.size()]);
}
create one string resource file like "string_autocompletearray" and define your array.
**res/values/string_autocompletearray.xml**
string-array name="autocomplete_array">
<item>AutoCompleteText 1 </item>
<item>AutoCompleteText 2 </item>
-------------------------------
-------------------------------
<item>AutoCompleteText N </item>
</string-array>
**Now find this array and set to adapter**
ArrayList<String> list = new ArrayList<String> (Arrays.asList(getResources().getStringArray(R.array.autocomplete_array)));
I am using data store in Assets folder like "reader.txt" this data get in using "InputStream" geting string value like this set to String value in textview. My question is how to store String in listview?
Here is my code:
try {
InputStream is = getAssets().open("reader.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
// Convert the buffer into a string.
String text = new String(buffer);
TextView tv = (TextView) findViewById(R.id.list);
tv.setText(text);
} catch (IOException e) {
// Should never happen!
throw new RuntimeException(e);
}
There are two ways by which you can store strings in listView. Either you can use android:entries which takes an array or object resource as an input, or u can use ArrayAdapter to set entries in listView.I will show you an example.
String[] values={""}//whatever values you have shown in the TextView
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
You can read text from file, then store it into String[] and then use ListAdapter for example ArrayAdapter<String> with ListView.
ListView list = (ListView) findViewById(R.id.someId);
your work with file ...
list.setAdapter(new ArrayAdapter<String>(Context, Layout, data));
// data is String[]
Here is similar example:
ArrayAdapter sample program in
Android
Difference with yours is that your String[] will be dynamically generated from file. So at first you will prepare data from file, store them into String[] and set them into Adapter.
I'm working on this tutorial, it's about querying the mysql database by using Json and a php script, and everything is just fine, but I'm working on listing these results you see here in a ListView and not as a TextView as you see below. Thats seems easy, but I can't make it work by replacing TextView with ListView.
image:
Here is the tutorial (code inside) :
http://blog.erlem.fr/fr/applications-mobiles/android/27-android-blog/applications-mobiles/android/59-android-connexion-a-mysql-a-laide-de-php.html
All of the below assumes you have already parsed the JSON out into an array. See this for parsing help.
ListViews use adapters to grab the elements to fill the list rows up with. You'll have to feed the JSON results into a SimpleListAdapter via a List or array (ArrayList, what have you.).
from this page about listviews:
SimpleAdapter nommes = new SimpleAdapter(
this,
list,
R.layout.main_item_two_line_row,
new String[] { "line1","line2" },
new int[] { R.id.text1, R.id.text2 } );
(in your case you could show/hide the id/name by using a one-line layout or a two-line layout like in this example)
Then apply the adapter
listView.setAdapter(nommes);
EDIT:
jObject = new JSONObject("<your JSON string from provider>");
// in my case:
res = jObject.getJSONObject("results");
**dataAdapter = new ArrayAdapter<String>(this, R.layout.item, R.id.itemName);**
try {
for (int r = 0; r < rslt.length(); r++){
JSONArray jA = rslt.getJSONArray(Integer.toString(r));
schoolLocString = jA.getString(0) +"|"+ jA.getString(1) +"[" + jA.optString(2);
**dataAdapter.add(schoolLocString);**
}
**myListView.setListAdapter(dataAdapter);**
} catch (JSONException e) {
Log.v(TAG, "Exception " + e);
} catch (NullPointerException e){
Log.v(TAG, "NPE, no rslt");
}
This is a really lazy way to do it and probably bad practice, but you can get the idea.