Why isn't the data showing up on my listview? - java

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.

Related

Add spinner to HashMap Android

I have a ListView, and the list view is populated with an HashMap. I can add text without in issue. I have an issue adding spinners.
How would I go about adding spinners to a HashMap in Android?
Here is the code for my HashMap:
final Spinner hashSpinner = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> array = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, array);
hashSpinner.setAdapter(hashSpinner);
mapTwo = new HashMap<String, String>();
mapTwo.put("zero", "OK");
mapTwo.put("one", " 2");
mapTwo.put("two", " 3");
listTwo.add(mapTwo);
try {
adapter = new SimpleAdapter(this, listOne, R.layout.row_two,
new String[] { "zero", "one", "two" }, new int[] {
R.id.spinner1, R.id.spinner2, R.id.spinner3 });
listViewOne.setAdapter(adapter);
} catch (Exception e) {
}
row_two already contains the spinners, the issue is, I can't get it to display. How will I go about adding the spinners to the ListView?

Why does my ListView not display the list of items?

I am trying to display my list of alarms in the ListActivity but it does not work. There rows appear but there is no text visible. I'm not sure if it's retrieving the data from the HashMap and inserting into the rows correctly.
Here is my code:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm_list);
List<Alarm> list;
Database db = new Database(AlarmListActivity.this);
list = db.getAllAlarms();
List<HashMap<String, String>> alarmMap = new ArrayList<HashMap<String, String>>();
for (Alarm alarm: list) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(Integer.toString(alarm.getID()), alarm.toString());
alarmMap.add(map);
}
if(!list.isEmpty() && list != null)
{
System.out.println("inside list");
System.out.println(list);
ListAdapter adapter = new SimpleAdapter(
AlarmListActivity.this,
alarmMap,
R.layout.list_item,
new String[] { "id", "hour"},
new int[] { R.id.id, R.id.time});
setListAdapter(adapter);
}
else
{
Toast.makeText(AlarmListActivity.this, "No Alarms Set",
Toast.LENGTH_SHORT).show();
}
}
This is what I get. You can vaguely see the lines of each row. But there is no text or anything. All the System.out.println() work as expected which print out the HashMap. It's just nothing is being displayed in the list. I've even added: android:text="Testing" to no avail

Android listview adapter get item id without setting it

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();
// ...
}

How to use intent to call the method of next activity in android

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

Fatal exception caused by android.os.NetworkOnMainThreadException

As I am a beginner to Android programming, I was trying to run some tutorials, but upon running the programs( the source code is available here: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ ) I got an error.
The program is supposed to read in data from a website and process it, but I think there is something wrong with the networking part.
I am fully aware there have been similar questions here on SO, yet I had no clue how to solve it, perhaps anyone could give solutions which I also can understand.
Strange NetworkOnMainThreadException in Android app?
This is a questions which was asked earlier and is identical to my problem, but I had no clue what they are trying to say there, i.e. "To fix you just need to move any thing that is touching the network to its own thread." makes no sense to me whatsoever..
Can anyone please shed some light on this?
Use an AsyncTask to move your network operation off of the main/ui thread and onto a background/worker thread.
Expanding on the example from the tutorial, wrap the JSON stuff inside of an anonymous AsyncTask:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new AsyncTask<Void, Void, JSONObject>() {
protected JSONObject doInBackground(Void... args) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
return jParser.getJSONFromUrl(url);
}
protected void onPostExecute(JSONObject json) {
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// 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_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
}
}.execute((Void) null);
}

Categories

Resources