i am building a listview with items from web server. I got all the items with JSON, i am able to load all the text values to the list view, but i can't assign the image to the list item. when i access a static image from drawable folder it works. Here is my code. I have the image with Base64 and direct file URL.
int[] listviewImage = new int[]{R.drawable.food};
JSONObject reader = new JSONObject(result);
JSONArray foods= reader.getJSONArray("foods");
List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
for(int i = 0;i<foods.length();i++)
{
JSONObject obj_foods = foods.getJSONObject(i);
HashMap<String, String> hm = new HashMap<String, String>();
byte[] decodedString = Base64.decode(obj_foods .getString("photo_hex"), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
hm.put("listview_image", Integer.toString(listviewImage[0]));
hm.put("food_name", obj_foods .getString("food_name"));
hm.put("food_description",obj_foods .getString("food_description"));
hm.put("price",obj_foods .getString("price"));
hm.put("restaurant",obj_foods .getString("restaurant"));
aList.add(hm);
}
String[] from = {"listview_image", "food_name", "food_description","price","restaurant"};
int[] to = {R.id.listview_image, R.id.listview_item_title, R.id.listview_item_short_description,R.id.price,R.id.restaurant};
SimpleAdapter simpleAdapter = new SimpleAdapter(getBaseContext(), aList, R.layout.food_list, from, to);
final ListView androidListView = (ListView) findViewById(R.id.listview);
androidListView.setAdapter(simpleAdapter);
Use Picasso to fetch images from online to your app
implementation 'com.squareup.picasso:picasso:2.71828'
Picasso.get().load("http://i.imgur.com/DvpvklR.png").into(imageView);
Related
I recently created a new ListView object for an Android application, but I am encountering some errors. When I try using a Simple Adapter to create an Item that includes a subitem on my list, The newest item created overlaps the other ones. I am using a List of Maps to create the items.
For example, If I add an item to my map list that displays "1" with a subitem that displays "A1", the item and subitems will be displayed. But if I add an new item to my map list named "2" with a subitem "B2", the "1" and "A1" will be replaced with "2" and "B2". There will still be 2 items on the ListView, but one of them is empty and the other one is "2" and "B2"
Here is my code:
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView)findViewById(R.id.listView1);
Map<String, String> datum = new HashMap<String, String>();
datum.put("RouterName", "Test1");
datum.put("RouterIP", "SubTest1");
data.add(datum);
Map<String, String> datum2 = new HashMap<String, String>();
datum.put("RouterName", "Test2");
datum.put("RouterIP", "SubTest2");
data.add(datum2);
SimpleAdapter adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[] {"RouterName", "RouterIP"}, new int[] {android.R.id.text1, android.R.id.text2});
lv.setAdapter(adapter);
}
Changing the list type will not work because the Simple Adapter specifically uses a Map List.
Hi I found some minor mistakes while storing in Hashmap. In that HashMap object is not creating. Previous instance is getting deleted.
Kindly use the below code. Hope it will help you.
ArrayList<HashMap<String, String>> data;
private String[] titleArray,subItemArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
ListView lv = (ListView)findViewById(R.id.listview);
data = new ArrayList<HashMap<String, String>>();
titleArray=new String[]{"Test1","Test2"};
subItemArray=new String[]{"SubTest1","SubTest2"};
for(int i=0;i<titleArray.length;i++){
HashMap<String,String> datum = new HashMap<String, String>();
datum.put("RouterName", titleArray[i]);
datum.put("RouterIP", subItemArray[i]);
data.add(datum);
}
SimpleAdapter adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[] {"RouterName", "RouterIP"}, new int[] {android.R.id.text1, android.R.id.text2});
lv.setAdapter(adapter);
}
I'm new to Android and I have Adapter - ListView model to display array.
I set it's value's so:
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.bank_list,
new String[] { TAG_NAME, TAG_central_office_address }, new int[] {
R.id.bank_name, R.id.central_office_address});
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, android.view.View view,
int position, long id) {
Intent in = new Intent(getApplicationContext(), BankExchangersListActivity.class);
in.putExtra("Bank_id", TAG_ID);
startActivity(in);
}
});
I get my values from JSON:
url = "http://192.168.1.4:3000/banks.json";
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
banks = json.getJSONArray(TAG_BANKS);
// looping through All Contacts
for(int i = 0; i < banks.length(); i++){
JSONObject c = banks.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String central_office_address = c.getString(TAG_central_office_address);
// Phone number is agin JSON Object
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_central_office_address, name);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
As you can see in JSON I have ID field, but i didn't set it in ListView. For next query I click on ListView element and go to other activity, but I need to get TAG_ID of this element. Maybe I did something wrong? How to get element's TAG_ID on which I click, without displaying it on ListView?
JUST send tag_id of clicked item!
The position parameter of the onItemClick method gives the index of the selected item in the adapted list. So you can find the TAG_ID of the original item at
((Map<String, String>) adapter.getItem(position)).get(TAG_ID)
make the adapter final so that you can reference it inside the listener:
final ListAdapter adapter = ...
Hope this helps you.
you can get Postion of ListSelectedItemId and passed it with Intentand get it in SecondActivity now Here get FirstActivity HashMap with define it static
now use foreachloop to get all values from HashMap like
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
}
}
now with specific position of ListSelectedItemId you can get values from currentList
or like
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// ...
}
What i am doing now is--> i'm getting data from the webservice in one activity and displaying the entire data in a listview. i added just a search functinality on the presented listview itself.
My requirement is --> i should have a search button in the first activity. When it is clicked, should show the related result in second activity, to do this added putExtras in the intent like this intent.putExtra("search", searchBox); that is the second activities search function keyword. but still m not getting the searched output.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
final EditText searchBox=(EditText) findViewById(R.id.search);
final ListView list=(ListView)findViewById(android.R.id.list);
//get the LayoutInflater for inflating the customomView
//this will be used in the custom adapter
inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
final JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
posts = json.getJSONArray(KEY_POSTS);
// looping through all song nodes <song>
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// to remove all <P> </p> and <br /> and replace with ""
content = content.replace("<br />", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
//authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
String url = null;
String slug = null;
try {
JSONArray atta = c.getJSONArray("attachments");
for(int j = 0; j < atta.length(); j++){
JSONObject d = atta.getJSONObject(j);
slug = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
url = thumbnail.getString(KEY_URL);
}
} catch (Exception e) {
e.printStackTrace();
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug);
map.put(KEY_URL, url);
// System.out.println("the map is title "+map.get("title"));
//title2.add(map.get("title"));
// adding HashList to ArrayList
songsList.add(map);
}
}catch (JSONException e) {
e.printStackTrace();
}
//searchResults=OriginalValues initially
searchResults=new ArrayList<HashMap<String, String>>(songsList);
// Getting adapter by passing json data ArrayList
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
//get the text in the EditText
searchString=searchBox.getText().toString();
textLength=searchString.length();
searchResults.clear();
for(int i=0;i<songsList.size();i++)
{
playerName=songsList.get(i).get("title").toString();
System.out.println("player name "+playerName);
if(textLength<=playerName.length()){
//compare the String in EditText with Names in the ArrayList
if(searchString.equalsIgnoreCase(playerName.substring(0,textLength))){
searchResults.add(songsList.get(i));
System.out.println("the array list is "+songsList.get(i));
adapter=new LazyAdapter(Home.this, searchResults);
list.setAdapter(adapter);
}
}
Intents are for activity and not methods inside them , So you cannot use it to call any specific method however you can use extras to figure out what you want to do \
like after when you get extras from Intent you can ,
if extras has "search" value
then do something about it
It's connecting and pulling the data from the json array. Its adding two listview items but not showing any text?
JSON array
{"tournaments":[{"Title":"my title","Contact":"my contact","Description":"my description","City":"my city","State":"Kansas","Category":"Roulette"},{"Title":"my title","Contact":"my contact","Description":"my description","City":"my city","State":"Connecticut","Category":"Three Card Poker"}]}
And some of my code in java...
JSONObject json = JSONfunctions.getJSONfromURL("http://kleinefrosch.com/retrieve.php");
try{
JSONArray tourneys = json.getJSONArray("tournaments");
for(int i=0;i<tourneys.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = tourneys.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("Title:" , e.getString("Title"));
map.put("Contact:" , e.getString("Contact"));
map.put("Description:" , e.getString("Description"));
map.put("City:" , e.getString("City"));
map.put("State:" , e.getString("State"));
map.put("Country:" , e.getString("Country"));
map.put("Category:" , e.getString("Category"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
new String[] { "Title","Contact","Description","City","State","Country","Category" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(JsonActivity.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
}
Try to remove map.put("id", String.valueOf(i));
Hope it runs then.
EDITED
Your Mistake is Here
map.put("Title:" , e.getString("Title"));
it should be
map.put("Title" , e.getString("Title"));
As it is Key which will be Matched in SimpleAdapter.
Like this remove : from each string value.
So please make sure that both the Keys match perfectly.
Assuming that JSON string parsing is completed without any exceptions, I think that you should use this construction:
setListAdapter(new ArrayAdapter<String>(Context context, int resource, int textViewResourceId, List<T> objects);
For more info about go to developers guide
Post your Xml code, are you using any Customized Listview? If it is means add some Dark color for Textview.
i need to show images from sqlite database into gridview or gallery view.
this is the code for displaying on a single view:
mMain = (ImageView) findViewById(R.id.ivMain);
byte[] blob = imgs.getBytes(); //there is a method that will return the bytes from the database
ByteArrayInputStream inputStream = new ByteArrayInputStream(blob);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
mMain.setImageBitmap(bitmap);
i have the android tutorial for grid view but it gets the image from file
// references to our images
private Integer[] mThumbIds = {
R.drawable.sample_2, R.drawable.sample_3
... }
is there a way to populate the gridview from the sqlite database?
UPDATE:
Im using the ImageAdapter provide in android tutorial:
http://developer.android.com/resources/tutorials/views/hello-gridview.html
my code becomes this:
ArrayList<byte[]> image_arr = new ArrayList<byte[]>();
//loop through all images on sqlite
for(int l = 0 ;l< db.getAllImages().size(); l++){
Image imgs = db.getAllImages().get(l);
byte[] blob = imgs.getBytes();
image_arr.add(blob);
ByteArrayInputStream inputStream = new ByteArrayInputStream(blob);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// mMain.setImageBitmap(bitmap);
}
//TODO; find way to make the bitmap get to the ImageView
Gallery gallery = (Gallery) findViewById(R.id.gallery);
gallery.setAdapter(new ImageAdapter(this));
This code is on main activity so i need to find way to pass the resources in ImageView which is in other file.
private void getDataAndPopulate() {
image = new ArrayList<byte[]>();
caption = new ArrayList<String>();
cursor=db.rawQuery("select * from NAME",null);
while (cursor.moveToNext()) {
byte[] temp_image = cursor.getBlob(2);
String temp_caption = cursor.getString(1);
String temp_id= cursor.getString(0);
image.add(temp_image);
caption.add(temp_caption);
id.add(temp_id);
}
String[] captionArray = (String[]) caption.toArray(
new String[caption.size()]);
ItemsAdapter itemsAdapter = new ItemsAdapter(Item_show_grid.this, R.layout.item_grid,captionArray);
gv.setAdapter(itemsAdapter);
}