Using json with listview in Android - android

I have a dummy listview that I have setup in my app that uses the following code:
public class Roster extends Activity {
private ListView mainListView ;
private ArrayAdapter<String> listAdapter ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_roster);
// ListView resource.
mainListView = (ListView) findViewById( R.id.rosterListView );
// List of names.
String[] players = new String[] { "Dude1", "Guy2"};
ArrayList<String> playerlist = new ArrayList<String>();
playerlist.addAll( Arrays.asList(players) );
//ArrayAdapter using the list.
listAdapter = new ArrayAdapter<String>(this, R.layout.rosterrow, playerlist);
// Add more Players, If you passed a String[] instead of a List<String>
// into the ArrayAdapter constructor, you must not add more items.
// Otherwise an exception will occur.
listAdapter.add( "Person8" );
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );
getActionBar().setDisplayHomeAsUpEnabled(true);
}
which gives me a listview of three players.
I now want to use the json object to populate the list instead of using a string. How can I populate the list using my json object?

Try to get the value of Json by key and put it in to string array.
JsonObject myjsondata = new JsonObject(jsondata.toString());
String[] players = new String[] {myjsondata.getString("key") , myjsondata.getString("key1")};

Related

List of Text and Grid of Images on the same screen android

I'm following the following tutorial http://www.devexchanges.info/2015/03/combining-gridview-and-listview-in-one.html
I'm attempting to change the list view to use an array of strings, and display text rather than images for the bottom part of this application.
I'm not entirely sure what I should be using as my ListView ID here. It seems like I can only use a findViewbyID, but I'd rather just give it an array of strings to populate that list view. Am I missing something simple here?
ArrayAdapter<String> adapter =new ArrayAdapter<String>(this, R.layout.item_grid, CORPS);
ListView lv = (ListView)findViewById(????);
lv.setAdapter(adapter);
Here is the code
public class ListViewActivity extends Activity {
private ExpandableHeightGridView gridView;
private ListView listView;
//drawables array for listview
private static final int[] corpImage = { R.drawable.apple, R.drawable.blackberry_logo,
R.drawable.google, R.drawable.microsoft, R.drawable.mozilla, R.drawable.oracle };
static final String[] CORPS = new String[] { "Microsoft", "Google", "Apple" };
//drawables array for gridview
private static final int[] osImage = { R.drawable.bbos, R.drawable.firefox_os,
R.drawable.ic_launcher, R.drawable.ios, R.drawable.tizen, R.drawable.ubuntu_touch,
R.drawable.wpos, R.drawable.symbian };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
addGridViewAsListViewHeader();
setAdapters();
}
/**
* set header for listview (it's a gridview)
*/
#SuppressLint("InflateParams")
private void addGridViewAsListViewHeader() {
View header = (View) getLayoutInflater().inflate(R.layout.layout_gridview, null);
listView.addHeaderView(header);
gridView = (ExpandableHeightGridView) header.findViewById(R.id.gridview);
// set expand to show all gridview rows
gridView.setExpanded(true);
}
/**
* set adapters for list view and gridview
*/
private void setAdapters() {
// convert int array to Integer array by apache common lang library
Integer[] osImageList = ArrayUtils.toObject(osImage);
Integer[] corpImageList = ArrayUtils.toObject(corpImage);
//Added by me but not working correctly
//ArrayAdapter<String> adapter =new ArrayAdapter<String>(this, R.layout.item_grid, CORPS);
//ListView lv = (ListView)findViewById(R.id.image);
// lv.setAdapter(adapter);
// set listview and gridview adapters
CustomAdapter gridViewAdapter = new CustomAdapter(this, R.layout.item_grid, R.id.image, osImageList);
CustomAdapter listViewAdapter = new CustomAdapter(this, R.layout.item_grid, R.id.image, corpImageList);
gridView.setAdapter(gridViewAdapter);
listView.setAdapter(listViewAdapter);
}
}
If your goal is to only use one string in each line, and display it as a list of items you can simply do this by using array adapters as follows.
ArrayList<String> companies = new ArrayList<>();
companies.add("Google");
companies.add("Microsoft");
// Find a reference to the {#link ListView} in the layout
ListView companiesListView = (ListView) findViewById(R.id.list);
// Create a new {#link ArrayAdapter} of earthquakes
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, earthquakes);
// Set the adapter on the {#link ListView}
// so the list can be populated in the user interface
companiesListView.setAdapter(adapter);
In your layout file you should declare a list view where you want to display this list of items. In this case id of that list view would be "list"

Maintaining the previous items after the update listview

I have a problem with updating my ListView. I don't want to lose my ListView's data after the first initialization.
I searched on this site and some other sites and found different solutions. At last I used the below code, but I didn't get any result.
private void handelpost(List<Posts> posts,Page pages) {
ListView listView;
final CustomListAdapterForPostOrgan adapter;
if (pages.getCurrentPage() > 1) {
listView = (ListView) findViewById(R.id.lv_for_post_organ);
adapter = new CustomListAdapterForPostOrgan(this, posts);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
} else {
listView = (ListView) findViewById(R.id.lv_for_post_organ);
adapter = new CustomListAdapterForPostOrgan(this, posts);
listView.setAdapter(adapter);
}
}
You're creating new Adapter with new data every time. Which is not advisable when you're working with pagination. You need to do following changes.
Declare your adapter and list view and an ArrayList class level.
public class MyActivity extends Activity{
private ListView mListView;
private CustomListAdapterForPostOrgan mAdapter;
private List<Posts> mPosts;
}
Initialize your ArrayList, then Adapter and then set it as adapter to ListView once in onCreate() of Activity.
private void onCreate(Bundle savedInstanceState) {
super.onCreate();
//After you've called setContentView() etc etc.
mPosts = new ArrayList();
mListView = (ListView) findViewById(R.id.lv_for_post_organ);
mAdapter = new CustomListAdapterForPostOrgan(this, mPosts);
mListView.setAdapter(mAdapter);
}
When you receive new data, first add it to your class-level array and then call notifyDataSetChanged() like this:
private void handelpost(List<Posts> posts,Page pages) {
//add new posts to existing array..
mPosts.addAll(posts);
//since adapter already has your array, simply make it refresh.
mAdapter.notifyDataSetChanged();
}

How to assign value to each item in listView?

I am working on health related app. In ListView I want to assign value to each item. For example milk contains 21 calories so I want to assign 21 to ListView item milk.
Here is my activity code containing ListView.
public class FoodEntry extends AppCompatActivity {
// Array of strings...
String[] food = {"Naan","Pav bhaji","chole tikiya", "rice", "soybean", "milk", "curd"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_entry);
ArrayAdapter adapter = new ArrayAdapter<>(this, R.layout.activity_item, food);
ListView listViewFoodItems = (ListView)findViewById(R.id.listViewFood);
listViewFoodItems.setAdapter(adapter);
}
}
Instead of using a String[] to store your data like you're doing here:
// Array of strings...
String[] food = {"Naan","Pav bhaji","chole tikiya", "rice", "soybean", "milk", "curd"};
Use a new object, such as CalorieCount.
// Array of CalorieCount
CalorieCount[] food = { new CalorieCount("Naan", 20) ... };
You can use SimpleAdapter with Hashmap
foodItems= new ArrayList<HashMap<String, String>>();
//create first item object
HashMap<String, String> item1= new HashMap<String, String>();
item1.put("name", "Naan");
item1.put("calories", "21");
foodItems.add(item1)//add multiple items like this
String[] from = { "name"};
// view id's to which data to be binded
int[] to = { R.id.name};
//Creating Adapter
ListAdapter adapter = new SimpleAdapter(MainActivity.this, foodItems,
R.layout.activity_item, from, to);
//Setting Adapter to ListView
listViewFoodItems.setAdapter(adapter);
To know more visit How SimpleAdapter Binds Hashmap Data to items of ListView

Null Pointer exception error with spinners int array

So when I try to set dropdown3 as adapter1, I get a null pointer exception. However I do not get any issues with the String arrays. Why is this happening with the Integer array? What can I do to fix it??
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner dropdown1 = (Spinner)findViewById(R.id.spinnertext1);
Spinner dropdown2 = (Spinner)findViewById(R.id.spinnertext2);
Spinner dropdown3 = (Spinner)findViewById(R.id.spinnernumber1);
String[] items = new String[]{"ml", "oz", "L"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
Integer[] numbers = new Integer[]{1,2,3,4,5,6,7,8,9,10};
ArrayAdapter<Integer> adapter1 = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item, numbers);
//adapts the string "items" to be an adapter and fit into the spinner.
dropdown1.setAdapter(adapter);
dropdown2.setAdapter(adapter);
dropdown3.setAdapter(adapter1);
I don't think you can use the same adapter object for two different views.
Try instantiating three different adapters.

Android if-else code not working properly

The problem i am facing is that i have my code is executing "else" block even when the "if " condition is true.
public class MsgNewPackage extends Activity {
private DatabaseHandler dbhandler;
private SimpleCursorAdapter dataAdapter;
private ListView listView;
String PKG_NAME,PKG_DUR,PKG_PRICE,PKG_ITEMS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_msg_new_package);
dbhandler = new DatabaseHandler(this);
displayListView();
}
private void displayListView()
{
String check= "Mobilink";
Intent intent = getIntent();
String conn = intent.getStringExtra("NET_CONN");
// Toast.makeText(getApplicationContext(), conn, Toast.LENGTH_SHORT).show();
if(conn == check)
{
Cursor cursor = dbhandler.fetchAllMOBSMSPackages();
String[] columns = new String[]{DatabaseHandler.KEY_PKG_NAME,DatabaseHandler.KEY_NO_OF_FREE_ITEMS,DatabaseHandler.KEY_DURATION,DatabaseHandler.KEY_CHARGES};
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.title,R.id.no_of_item,R.id.duration,R.id.pkgcharges};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(this, R.layout.list_row2, cursor,columns,to);
listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
}
else
{
Cursor cursor = dbhandler.fetchAllSMSPackages();
String[] columns = new String[]{DatabaseHandler.KEY_PKG_NAME,DatabaseHandler.KEY_NO_OF_FREE_ITEMS,DatabaseHandler.KEY_DURATION,DatabaseHandler.KEY_CHARGES};
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.title,R.id.no_of_item,R.id.duration,R.id.pkgcharges};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(this, R.layout.list_row2, cursor,columns,to);
listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
}
The toast displays that conn has "Mobilink" but the listview gets populated with results of fetchAllSMSPackages() (i.e function called in else block ) which should not be the case. Pleas help.
Try using conn.equals(check) instead of conn == check.
Strings in Java are objects, and not primitives, so you cannot compare their value using ==. This will compare the object as a whole, and not the text.
You should use .equals() when comparing String values. Not ==.
Try using:
conn.equals(check);

Categories

Resources