list results from mysql on a listview in android - android

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.

Related

Display images dynamically into list view items

i develop android apps since one year so i'm not able to solve this kind of problem. I searched many times on our friend google but 0 real result. This is a very precise question, i try to display images dynamically into listview items, i mean :
1- I receive an array of int from my database (ex : 5, 6, 7, 7)
2- I want the adpater to display differents images depending of this numbers
for exemple i receive : "result" = {"1", "2", "3"} i want the app to associate images to this numbers (Images come from drawable folder)
if (int number = 1) {
imageview into item layout.setImageRessource(R.id.blabla)
}else ...
I really don't know how do that, i tried building a custom adapter but it doesn't display the listview...
I'll be the happiest developper if somebody can tell me what the good way to do that.
protected void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON2);
Poeple2 = jsonObj.getJSONArray(TAG_RESULTS);
for (int i = 0; i < Poeple2.length(); i++) {
JSONObject c = Poeple2.getJSONObject(i);
String username = c.getString(TAG_USERNAME);
int mood = c.getInt(TAG_MOOD);
HashMap<String, String> persons = new HashMap<String, String>();
persons.put(TAG_USERNAME, username);
persons.put(TAG_MOOD, String.valueOf(mood));
personList2.add(persons);
}
// i used a simple adapter but i know it's a wrong way
adapter = new SimpleAdapter(getActivity(), personList2, R.layout.modeluser4, new String[]{TAG_USERNAME, TAG_MOOD}, new int[]{R.id.tvHypo2, R.id.tvId});
list3.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
create a switch like
public void runTheSwitch(int num){
int number = num;
switch(number){
case 1:
//add image to listview
case 2:
//add image to listview
case 3:
//add image to listview
....and so on...
}
}
When you recieve the Array of numbers from database (lets call it ArrayNum), run a loop through those num.
For(int num : ArrayNum){
runTheSwitch(num);
}
Put this into a method and run the method before you set your adapter. So basically in this method you add items to your Arraylist like arraylist.add(); then after this you define an Object of your custom adapter and pass the Arraylist in your adapter.
Hope it helps

android search array from csv

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.

Show ListView header even when ListView has no items

Since my ListView is in a ScrollView and there is a complex layout above the ListView I had to set that layout to be the header of the ListView. This made things work wonderfully, except one thing: When the ListView has no items, the header does not show up. This header is basically the base of the whole layout, the ListView includes only comments written by users.
I checked solutions like this and this and this and others but I still don't know what to do.
This is how I set the header for the ListView:
lv = (ListView) findViewById(R.id.bucket_profile_lv);
LayoutInflater inflater=getLayoutInflater();
header = inflater.inflate(R.layout.bucket_profile_header,null,false);
lv.addHeaderView(header);
When I am downloading the data for the header, it has nothing to do with the adapter of the ListView. I refer to them as
num_added = response.getString("NUM_ADDED");
tv_num_added.setText(String.valueOf(num_added));
where
tv_num_added = (TextView) header.findViewById(R.id.bucket_profile_bucket_no_added);
When I am downloading the comments, I put the result (username, photo, comment etc.) in arrays and link them to an adapter:
if (response.length() > 10) {
try {
jArray = new JSONArray(response);
for(int i=0;i<jArray.length();i++){
JSONArray innerJsonArray = jArray.getJSONArray(i);
for(int j=0;j<innerJsonArray.length();j++){
JSONObject jsonObject = innerJsonArray.getJSONObject(j);
arr_tips_id.add(jsonObject.getString("COMMENTID"));
arr_tips_userid.add(jsonObject.getString("ID"));
arr_tips_username.add(jsonObject.getString("USERNAME"));
arr_tips_userphoto.add(jsonObject.getString("PHOTO"));
arr_tips_fbuserid.add(jsonObject.getString("FB_USERID"));
arr_tips_imagetype.add(jsonObject.getString("IMAGE_TYPE"));
arr_tips_twuserid.add(jsonObject.getString("TW_USERID"));
arr_tips_twphoto.add(jsonObject.getString("TW_PHOTO"));
arr_tips_tips.add(jsonObject.getString("COMMENT"));
arr_tips_date.add(jsonObject.getString("TIMEDIFF"));
myadapter = new MyAdapter(BucketProfileActivity.this, arr_tips_id, arr_tips_userid, arr_tips_username, arr_tips_userphoto, arr_tips_fbuserid, arr_tips_imagetype, arr_tips_twuserid, arr_tips_twphoto, arr_tips_tips, arr_tips_date);
lv.setAdapter(myadapter);
lv.setVisibility(View.VISIBLE);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
/*Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SSS");
String strDate = sdf.format(c.getTime());
Toast.makeText(BucketProfileActivity.this, "3 -- " + strDate + "", Toast.LENGTH_LONG).show();*/
} else {
Toast.makeText(BucketProfileActivity.this, "No comments, how to show header?", Toast.LENGTH_SHORT).show();
lv.setVisibility(View.VISIBLE);
}
In my adapter I have overriden isEmpty() but it didn't help:
#Override
public boolean isEmpty() {
return false;
}
Please help.
Don't use addHeaderView. Instead make the header as a separate item
<LinearLayout
...
android:orientation="vertical">
<include layout="#layout/bucket_profile_header" />
<ListView
.....
/>
</LinearLayout>
Initialize your adapter once, for example when you inflate your views in onCreate() or onCreateView() and also set your adapter to your listview (after you added your headerView).
In your JSON iteration loop do something like this:
myadapter.addItem(arr_tips_date);
In your adapter you have to create this method, which adds your data item to its internal adapter collection and call notifyDataSetChanged().
Then it should work just fine.

ListView refresh items

I have a ListView with some items, but after I update a Database I'd like to "refresh" the ListView. Anyone can help me?
EDIT: populateListView add items to ListView
public void populateListView()
{
String URL = config.getUrl_For_Query() + ",&nameq=Select&tipo=select"; // my URL
String jsonString = reading.execute_query(URL); // jsonString is formatted well
try
{
JSONObject jsonResponse = new JSONObject(jsonString);
JSONArray array = jsonResponse.getJSONArray("elenco");
for (int i=0; i<array.length(); i++) // I scan all array
{
JSONObject nameObj = (JSONObject)array.get(i);
// I retrieve all information
allNames.add(nameObj.getString("name")); // Name
allLng.add(nameObj.getString("lng")); // Another information
}
}
catch (Exception e)
{ e.printStackTrace(); }
List<String> Array = new ArrayList<String>();
for(int i=0;i<allNames.size();i++) // I add all values
{
String value = allNames.get(i).toString() + ", \n\t" + allLng.get(i).toString();
Array.add(value); // here I populate my Array
}
final ListView listView = (ListView) getActivity().findViewById(R.id.List);
listView.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, Array));
//
// Click
//
}
saveChanges
public void saveChanges()
{
// I update a Database
// And then I'd like to refresh ListView's items
populateListView(); // Update ListView
}
Use a Comparator. There you define what to compare and how, in the compare() method you define what should be returned from two of your instances. Here's an example for a String Comparator.
Comparator myComparator = new Comparator<String>() {
public int compare(final String user1, final String user2) {
// This would return the ASCII representation of the first character of each string
return (int) user2.charAt(0) - (int) user1.charAt(0);
};
};
adapter.sort(myComparator);
This way, when you add an item, you don't have to recreate the whole Adapter but it will be sorted instead. But don't forget to call .notifyDataSetChanged() on your adapter, this will make (amongs other things) to refresh your layout.
Try using ArrayAdapter.insert method to insert objects in specific index.
At first take a look at this tutorial about SQlite database in Android.
So, your problem is that new items are added at the end of the list. Huh? This is because you have not notified Adapter from the changes of the Array.
ArrayAdapter<String> Adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, Array);
Your first solution is to clear Adapter before updating Database. Sth like:
Adapter.clear(); can do that. This way your Adapter is empty before updating database and new items are inserted. You can use Adapter.notifyDataSetChanched(); for awaring Adapter about the changes.
In above tutorial there is a custom Adapter. It uses this code:
List<String> Array = new ArrayList<String>();
Array = (ArrayList<String>) db.getAllContacts();
Adapter = new MyCustomAdapter(getActivity() [in fragment case or getApplicationContext() in Activity case], R.layout.simple_list_item_1, Array);
This way there is no need for clearing Adapter because it automatically does that. Wherever you use this method, updated adapter is used for showing the list.

How to dynamically add suggestions to autocompletetextview with preserving character status

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.

Categories

Resources