Use result from ParseQuery in android - android

Want to understand how to use / take result from ParseQuery into a String[] not inside the query.
Here is the code:
public class OptionDialogFragment extends DialogFragment implements
AdapterView.OnItemClickListener {
String[] listitems = {here is where i want the result from the query};
ListView mylist;
TextView chosenProperty;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.option_dialog_content, null, false);
mylist = (ListView) view.findViewById(R.id.list);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ParseQuery<PropertyTypes> pt = new ParseQuery<PropertyTypes>(PropertyTypes.class);
pt.whereExists("propertyType");
pt.orderByAscending("propertyType");
pt.findInBackground(new FindCallback<PropertyTypes>() {
#Override
public void done(List<PropertyTypes> pList, ParseException e) {
if (e == null) {
for(int i = 0; i < pList.size(); i++){
// Want to take the result from here and put it in the String array above
// String array "listitems"
}
} else {
e.printStackTrace();
}
}
});
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, listitems);
mylist.setAdapter(adapter);
mylist.setOnItemClickListener(this);
}
}

There would be a direct method to do it if your List was of String, However, in your case it will depend on what the PropertyType class contains. Here's an example of what the code may looks like:
listItems = new String[pList.size()];
for(int i = 0; i < pList.size(); i++){
listItems[i]=pList.get(i).getStringObject();
}
So pList.get(i) will get you your PropertyTypes class object, you should replace getStringObject() with a getter method within PropertyTypes that return a String
Above when you declare your member variable listItems, don't initialize it
String[] listItems;

chose a JSON lib used to parse response from ParseDB. ( std JSON or Jackson are both good libs )
{"results":[{"ACL":{"_User.objectId"
Change existing 'for' iteration inside of 'done()' to handle the JSON ARRAY that is a child of 'results' you see above
ArrayNode array = (ArrayNode) root.path("results");
int i = 0;
for (JsonNode node : array) {
i++;
Foreach element of the array get the string value of the columns that you want from 'PropertyTypes'
YourCollection
myCollection.add(node.path("PTyp.property1").getTextValue());
finally...
myCollection.toArray()
above uses 'jackson' lib for Json parse
gradle depencies
compile files('libs/jackson-core-lgpl-1.9.2.jar')
compile files('libs/jackson-mapper-lgpl-1.9.2.jar')

Related

Populate spinner based on selection in other spinner

I am trying to get data from server into spinner, my json object is
{"result":{"AndhrPradesh":["Jayamahal","ABC","JP nagar"],"Mumbai":["XYZ","PQR"],"Pune":["123","Hi"]}}
I am able to get the values AndhraPradesh,Mumbai and Pune in one spinner. now my problem is after selecting city i want to display corresponding data in that city.
for example, if select Mumbai from one spinner i want to display XYZ,PQR in another spinner, Please help me.
First of all parse the json data like
JSONObject jsonObject = response.getJSONObject("data");
JSONArray cityName= jsonObject.getJSONArray("AndhrPradesh")
for(i=0;i<cityName.length();i++){
//your inner string of the Array
}
Then
citynameSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//here set the values to another spinner
}
});
Please use this code snippet
public class SpinnerFilterActivity extends AppCompatActivity {
private ArrayAdapter<String> mArrayAdapter;
private Spinner mMainSPN;
private ArrayList<String> mSpinnerArray;
private Map<String,ArrayList<String>> innterDataMap;
private Spinner mInnerSPN;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSpinnerArray = new ArrayList<String>();
innterDataMap = new HashMap<String, ArrayList<String>>();
mMainSPN = (Spinner) findViewById(R.id.spn_main);
mInnerSPN = (Spinner) findViewById(R.id.spn_inner);
mMainSPN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String key = mSpinnerArray.get(position);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(SpinnerFilterActivity.this,android.R.layout.simple_spinner_item,innterDataMap.get(key));
mInnerSPN.setAdapter(arrayAdapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
parseJson();
}
private void parseJson() {
String s= "{\"result\":{\"AndhrPradesh\":[\"Jayamahal\",\"ABC\",\"JP nagar\"],\"Mumbai\":[\"XYZ\",\"PQR\"],\"Pune\":[\"123\",\"Hi\"]}}\n";
try {
JSONObject jsonObject = new JSONObject(s);
JSONObject obj= jsonObject.getJSONObject("result");
Iterator<String> stringIterator = obj.keys();
while (stringIterator.hasNext()){
String key = stringIterator.next();
mSpinnerArray.add(key);
JSONArray jsonArray = obj.getJSONArray(key);
ArrayList<String> innerList = new ArrayList<>();
for (int i=0;i<jsonArray.length();i++){
innerList.add(String.valueOf(jsonArray.get(i)));
}
innterDataMap.put(key,innerList);
}
populateDataInSpinner();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void populateDataInSpinner() {
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,mSpinnerArray);
mMainSPN.setAdapter(arrayAdapter);
}
}
In this code I have kept a data in 2 fields one i mSpinnerArray to display the aster list and other is map in which inner list is kept on behalf of the key as parent value. Whenever onOptionItemSelected method gets called I fetch the list of inner data from map on behalf of the seleted item from the master list as it is working as a key in innerMap data. I hope I am clear. Let me know if there is any problem.

how to create columns dynamically in android?

I am trying to make list view in android .I am able to make simple list view using static data .Now I take json file in asset folder . Then I read contend from json file and display on list view .It is working fine.
I do like this
public class MainActivity extends Activity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_view);
Log.d("==", loadJSONFromAsset());
String arr[];
try {
JSONArray js = new JSONArray(loadJSONFromAsset());
arr = new String[js.length()];
for (int i = 0; i < js.length(); i++) {
JSONObject obj = js.getJSONObject(i);
arr[i] = obj.getString("name");
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arr);
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
It is working fine
But I need to do different task .I need to read json file from asset folder . and create as same number of column as in json array
This is new json file
{"coulmns":[
{
"name": "Test_1"
},
{
"name": "Test_2"
},
{
"name": "Test_3"
},
{
"name": "Test_4"
}
]}
I need to create four column of equal width (because there is four object).If it is three than it show three column of equal width .can we do in android ?
any idea..?
how to do with grid view ?
A GridView is a specific type of ListView that is designed to put your list into multiple columns, or a grid. It's just as easy to use as a ListView, except that you need to specify the number of columns you have. Try this:
Replace the instance of ListView in your XML file with GridView
Replace the ListView in your activity with GridView
Set the number of columns you want. You can make this dynamic by changing it depending on your data.
public class MainActivity extends Activity {
GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (ListView) findViewById(R.id.grid_view);
Log.d("==", loadJSONFromAsset());
String arr[];
try {
JSONArray js = new JSONArray(loadJSONFromAsset());
arr = new String[js.length()];
for (int i = 0; i < js.length(); i++) {
JSONObject obj = js.getJSONObject(i);
arr[i] = obj.getString("name");
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arr);
gridView.setAdapter(adapter);
gridview.setNumColumns(4);
//You can replace 4 with a formula if you want it to be variable
} catch (JSONException e) {
e.printStackTrace();
}
}
Also see: http://developer.android.com/reference/android/widget/GridView.html
Straight out of the box, the ArrayAdapter<MyObject> is going to populate only a TextView with values as defined by myObject.toString(). If you need a mode complex list item view you have to create your own adapter that extends ArrayAdapter and override getView(...).
For example, your adapter creation would be:
MyArrayAdapter adapter = new MyArrayAdapter(this,R.layout.my_list_item,arr);
I defined MyObject inside the adapter, but it could anywhere. The idea is that MyObject will consist of the texts from one "row" (all the column values)
A very raw version of your adapter could be:
public class MyArrayAdapter extends ArrayAdapter<MyArrayAdapter.MyObject> {
public MyArrayAdapter(Context context, int resource, ArrayList<MyObject> objects) {
super(context, resource, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);
viewHolder = new ViewHolder();
for (int i= 0; i < MyObject.MAX_COLUMNS; i++)
viewHolder.mTextViews[i] = (TextView)((ViewGroup)convertView).getChildAt(i);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder)convertView.getTag();
}
MyObject myObject = getItem(position);
for (int i = 0; i < myObject.myTexts.length; i++)
{
viewHolder.mTextViews[i].setVisibility(View.VISIBLE);
viewHolder.mTextViews[i].setText(myObject.myTexts[i]);
}
for (int i = myObject.myTexts.length; i < MyObject.MAX_COLUMNS; i++)
viewHolder.mTextViews[i].setVisibility(View.GONE);
return convertView;
}
private static class ViewHolder {
public TextView[] mTextViews = new TextView[MyObject.MAX_COLUMNS];
}
public static class MyObject {
public static int MAX_COLUMNS = 4;
public MyObject(String[] texts) {
myTexts = texts;
}
public String[] myTexts;
}
}
And your item layout (with four TextViews, but add/remove if your max columns is different):
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
</LinearLayout>
In case you don't have a way to know the max number of your columns, you have to construct the item layout dynamically instead of inflating it from a resource and more importantly the ViewHolder pattern is pretty much useless.

Android add items to arraylist using custom class

I'm trying to add items to an arraylist using this class template:
public class Template {
public String username;
public String email;
}
Here's the whole code:
public void JsonToArrayList(JSONArray myJsonArray) throws JSONException
{
ArrayList<Template> listItems = new ArrayList<Template>();
JSONObject jo = new JSONObject();
Template tem = new Template();
ListView lv = (ListView) findViewById(R.id.listView1);
for(int i = 0; i<myJsonArray.length(); i++)
{
jo = myJsonArray.getJSONObject(i);
tem.username = jo.getString("username");
tem.email = jo.getString("user_email");
listItems.add(tem);
Log.e("Ninja Archives", tem.username);
}
// This is the array adapter, it takes the context of the activity as a first // parameter, the type of list view as a second parameter and your array as a third parameter
ArrayAdapter<Template> arrayAdapter = new ArrayAdapter<Template>(this,android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
}
The problem is, instead of filling my listview with nice username and email strings, it's filling up with items like this:
com.android.ninjaarchives.
Template#40585690
I think somewhere along the line I have become lost, but I've been trying all sorts for ages now and getting nowhere. Can anyone point me in the right direction?
Thanks for any help.
Note: not really sure what's going on with the code; it doesn't appear to be pasting correctly.
Use below code, it can be a solution for you
public void JsonToArrayList(JSONArray myJsonArray) throws JSONException
{
ArrayList<Template> listItems = new ArrayList<Template>();
JSONObject jo = new JSONObject();
Template tem = new Template();
ListView lv = (ListView) findViewById(R.id.listView1);
String listItemString[] = new String[myJsonArray.length];
for(int i = 0; i<myJsonArray.length(); i++)
{
jo = myJsonArray.getJSONObject(i);
tem.username = jo.getString("username");
tem.email = jo.getString("user_email");
listItemString[i] = tem.username +" - " + tem.email; // u can change it according to ur need.
listItems.add(tem);
Log.e("Ninja Archives", tem.username);
}
// This is the array adapter, it takes the context of the activity as a first // parameter, the type of list view as a second parameter and your array as a third parameter
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItemString);
lv.setAdapter(arrayAdapter);
}
But better to write Custom adapter by extending BaseAdapter, and do listItem handling in getView method here is one simple tutorial
Take a class extending Base
private class CustomAdapter extends BaseAdapter
{
LayoutInflater inflater;
public CustomAdapter(Context context)
{
inflater = LayoutInflater.from(context);
}
public int getCount()
{
return listItems.size();
}
public Object getItem(int position)
{
return listItems.get(position);
}
public long getItemId(int position)
{
return position;
}
public View getView(final int position, View convertView,ViewGroup parent)
{
//if(convertView==null)
//convertView = inflater.inflate(R.layout.listlayout, parent, false);
Template data = (Template) getItem(position);
TextView v=new TextView(context);
v.setText(data.name);
return v;
}
}
and set adapter to your listview
lv.setAdapter(new CustomAdapter(this));
In this case you have to use a custom adapter (that extends from ArrayAdapter) and override the getView method to display in a custom layout the username and the email.

How to use notifyDataSetChanged

My project simplify as below:
First, I use application method Data.java to save data.
It contain the data:
private ArrayList<String> data = new ArrayList<String>();
public int getsize() {
return this.data.size();
}
public String getdata(int i) {
return this.data.get(i);
}
public void adddata(String s) {
return this.data.add(s);
}
My AActivity class onCreate as below:
Data d = (Data)this.getApplication();
String test = new String[d.getsize()];
for(i = 0; i < d.getsize(); i++) {
test[i] = d.getdata(i);
}
//to show in list
DataAdapter = new DataAdapter (this, test);
setListAdapter(DataAdapter);
And when button is click, startActivity the BActivity class.
In BActivity class, the code as below:
Data d = (Data)this.getApplication();
d.adddata("newdata");
finish();
And AActivity class onResume() as below:
#Override
public void onResume(){
super.onResume();
this.DataAdapter.notifyDataSetChanged();
}
But why the list is not update?
I confirm the data has be save.
My DataAdapter:
public DataAdapter(Context ctxt, String[] d) {
this.data = new String[d.length];
myInflater = LayoutInflater.from(ctxt);
int i;
for(i = 0; i < d.length; i++) {
data[i] = d[i];
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewTag viewTag;
if(convertView == null) {
convertView = myInflater.inflate(R.layout.row_bookmark_list, null);
viewTag = new ViewTag((TextView)convertView.findViewById(R.id.tv));
convertView.setTag(viewTag);
}
else {
viewTag = (ViewTag) convertView.getTag();
}
viewTag.tv.setText(data[position]);
}
class ViewTag {
TextView tv;
public ViewTag(TextView t) {
this.tv = t;
}
}
Add your new data directly to the adapter not to 'd'. The adapter keeps its own internal data which means that whatever changes you apply to your 'd' has no impact on the adapter.
For example:
List<String> itemsList = new ArrayList<String>();
ArrayAdapter aa = new ArrayAdapter(..., itemsList);
...
itemsList.add("new item"); --> wrong!
aa.notifyDataSetChanged(); --> nothing changes, you wrongly added the item to itemsList
you have to deal directly with the adapter:
aa.add("new item"); --> correct
aa.notifyDataSetChanged(); --> the adapter will reflect the change
You can't access the notifyDataSetChanged as a static method
( thats what you are doing in your example ).
If you have a ListActivity: you have access to the method getListAdapter().
Thats the right reference to your dataset.
So in short:
getListAdapter().notifyDataSetChanged();
will do the trick. If you don't have a ListActivity then you will have to find your listview thru View.findViewById([id of listview]) and get the Adapter there.
Hope this helps a bit :-)
I think your problem is that your DataAdapter is referenced to the array test, but test never changes. Referencing data to the DataAdapter instead of test should work.
OK, after looking at the Adapter code it will not work. Why are you copying your data? The adapter will never notice a change in the data element, because it is only working with a copy of that element at construction time. If copying the data is necessary, you should make sure the adapter updates its content, too.

How to load these elements to populate a list in android?

I am using this to get a list of elements from a webpage.
http://www.gamespy.com/index/release.html
// Get all the game elements
Elements games = doc.select("div.FP_Up_TextWrap b");
// Create new ArrayList
ArrayList<String> gameList = new ArrayList<String>();
// Iterator over those elements
ListIterator<Element> postIt = games.listIterator();
while (postIt.hasNext()) {
// Add the game text to the ArrayList
gameList.add(postIt.next().text());
}
This returns all the tags with which is what I want. But it returns the full tag with the title I just want the title the release date and a Img sr.
I would like to return it to a list view.
How would I go about doing this? I maybe doing it totally wrong so you guys may want to check out the HTML page source.
EDIT - Gives me NullPointer error
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
outputTextView = (TextView)findViewById(R.id.outputTextView);
ListView list = (ListView)findViewById(R.id.list);
ArrayList<String> gameList = new ArrayList<String>();
Document doc = null;
try {
doc = Jsoup.connect("http://www.gamespy.com/index/release.html").get();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Get all td's that are a child of a row - each game has 4 of these
Elements games = doc.select("tr > td.indexList1, tr > td.indexList2");
// Iterator over those elements
ListIterator<Element> postIt = games.listIterator();
while (postIt.hasNext()) {
// Add the game text to the ArrayList
gameList.add(postIt.next().text());
}
String[] items = new String[gameList.size()];
gameList.toArray(items);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
// error points here
list.setAdapter(adapter);
}
}
EDIT - Layout for the list
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/outputTextView"
/>
<ListView android:layout_height="wrap_content" android:id="#+id/list" android:layout_width="match_parent"></ListView>
</LinearLayout>
You won't be able to "return a list view" using this code, but you could create your own list view sub class which you could then return, following the same techniques:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView1 = (ListView) findViewById(R.id.listView1);
ArrayList<String> gameList = new ArrayList<String>();
// Iterator over those elements
ListIterator<Element> postIt = games.listIterator();
while (postIt.hasNext()) {
// Add the game text to the ArrayList
gameList.add(postIt.next().text());
}
String[] items = new String[gameList.size()];
gameList.toArray(items);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.some_list_item_view, items);
listView1.setAdapter(adapter);
}
Ultimately what it comes down to is setting the list adapter for the list. If you need to create your own list adapter you can subclass and implement ListAdapter to databind other object types, but there's already a predefined adapter (ArrayAdapter) for handling simple string sets for ListView/ListActivity databinding.
UPDATE - Poster requested additional implementation details:
Given:
public class GameMeta {
private String m_title;
private java.util.Date m_releaseDate;
public GameMeta() {
}
public String getTitle(){
return m_title;
}
public void setTitle(String value) {
m_title = value;
}
public java.util.Date getReleaseDate(){
return m_releaseDate;
}
public void setReleaseDate(java.util.Date releaseDate){
m_releaseDate = releaseDate;
}
}
You might create the adapter:
public class GamesMetaAdapter implements Adapter extends ListAdapter {
private ArrayList<GameMeta> m_list = new ArrayList<GameMeta>();
private Context m_context = null;
public GamesMetaAdapter(Context context) {
m_context = context;
}
#Override
public int getCount(){
return m_list.size();
}
#Override
public Object getItem(int position){
if(position < m_list.size()){
return m_list.getAt(position);
}
return null;
}
#Override
public long getItemId(int position) {
return (long)position;
}
#Override
public int getItemViewType(int position) {
return IGNORE_ITEM_VIEW_TYPE;
}
#Override
public View getView (int position, View convertView, ViewGroup parent) {
TextView simpleView = new TextView(this.m_context);
String viewText = this.m_items[position].getTitle() + ", Released " + this.m_items[position].getReleaseDate().toString();
simpleView.setText(this.m_items[position].getTitle());
if(TextView.class.isInstance(convertView)) {
convertView = simpleView;
}
return simpleView;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public boolean hasStableIds(){
return false;
}
#Override
public boolean isEmpty() {
return m_list.size() == 0;
}
#Override
public void registerDataSetObserver (DataSetObserver observer) {
}
#Override
public void unregisterDataSetObserver (DataSetObserver observer) {
}
/* LIST ADAPTER MEMBERS */
#Override
public boolean areAllItemsEnabled() {
return true;
}
#Override
public boolean isEnabled(int position) {
return true;
}
}
I don't have a Java compiler here, so please don't ding me if this doesn't just copy/paste right into your project, but it should be well north of 90% there.
Happy coding.
B
This should gather the titles and release dates. Which image did you also want?
// Get all td's that are a child of a row - each game has 4 of these
Elements games = doc.select("tr > td.indexList1, tr > td.indexList2");
// Iterator over those elements
ListIterator<Element> gameIt = games.listIterator();
while (gameIt.hasNext()) {
// Get the title of the game
Element title = gameIt.next();
System.out.println(title.text());
// Unneeded elements
Element platform = gameIt.next();
Element genre = gameIt.next();
// Get the release date of the game
Element release = gameIt.next();
System.out.println(release.text() + "\n######");
}

Categories

Resources