Greetings fellow programmers!
I am building a mobile app where I fetch JSON data from an API then transfer it using bundle to next activity (all of that works perfectly). In the second activity the JSON data transferred (in the form of a string) is supposed to be used to dynamically populate fields.
Now what I am trying to do is that I am trying to extract names of the companies from my JSON data, populate them into buttons dynamically and use the rest of JSON data (such as phone numbers, emails etc) to display information only when the button (with the name of the company on it) is clicked on.
Ideally I would want to use an accordion button but after doing some research apparently it cannot be easily implemented in Android. So I was thinking of using a dialog box (with the rest of the info) that would pop up after pressing a button with the company name on it.
I am not sure where to begin to be honest with dynamical population of buttons and then dialog boxes from JSON data, so I would hoping that maybe someone from this amazing community could give me some pointers?
I would be extremely grateful for any help!!
Thank you
First you would need to parse JSON - convert it to java object.
You could either use GSON library, or do it yourself using JSONObject class.
Its quite simple, and if you are using Retrofit library for networking, there's a good chance that it does it for you.
Once you got your java models - objects created based on your JSON, just assign the values to controls. By the way, if you are using list of buttons, it is a good idea to use RecyclerView to create list.
You can find details here:
GSON library
Retrofit
Create an class for Company with members like name,address,phone-number,email etc .....
Create list of objects of Company class from json data ..
Eg :
List<Company> companies = new ArrayList<>();
jsonArray = new JsonArray(jsonInstring);
for(int i=0;i<jsonArray.length();i++){
jsonObject = jsonArray.getJsonObject(i);
company = new Company(jsonObject.getString("name"),......);
companies.add(company);
}
Now populate those data to list view or recyclerview and on click of item pass that object company and create a dialog... and inside that dialogView set value from that object to views.
Create Comapny Bean with id, name, number and other fields
Parse your json and create list of Company Bean as List<Company> companyList
In activity_main.xml file create a containerLayout for adding dynamic views
<LinearLayout
android:id="#+id/containerLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"/>
Create button_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
5.In your activity call addButton method
private void addButton(){
containerLayout = (LinearLayout)findViewById(R.id.containerLayout);
for(int i=0; i<companyList.size(); i++){
containerLayout.addView(generateButton(companyList.get(i)));
}
}
private Button generateButton(Company company) {
Button companyButton = (Button)getLayoutInflater().inflate(R.layout.button_layout, null);
companyButton.setText(company.getName());
companyButton.setTag(company);
companyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPopup((Company)v.getTag()); //other details popup
}
});
return companyButton;
}
If you want to convert JSON response to your Java class object, then In that case JAKSON API will be perfect for your task.
you can convert JSON to any java object in this way.
ObjectMapper mapper = new ObjectMapper();
//Object to JSON in file
User user = mapper.readValue(new File("c:\\user.json"), User.class);
Please follow referral URL for more information.
Hope this will help you.
Related
I am trying to learn about developing android TV apps and looking at sample code on github and on some tutorial links. I have grasped some basics around android TV development.
My problem is non of the tutorials properly explain how the browse fragment is populated with data from an online json source and how it is updated.
Can anyone please direct me to a link or source that can be used as a decent tutorial for a beginner?
I don't think there are any tutorials specifically for LeanBack, but you can probably find plenty of general android tutorials on how to use Retrofit to fetch json formatted data from a public API.
As for populating your BrowseFragment, something like this should do it:
//Create a rows adapter for your fragment
ArrayObjectAdapter mRowsAdapter = new ArrayObjectAdapter(new ListRowPresenter());
setAdapter(mRowsAdapter);
//Create a row and populate it
ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(someItemPresenter);
listRowAdapter.setItems(someItems, someDiffCallback);
ListRow row = new ListRow(listRowAdapter);
//Add row
mRowsAdapter.add(row);
someItems should be a List of your fetched items. someItemPresenter should be a class that extends Presenter and handles items of the type contained in the someItems list. someDiffCallback should be a DiffCallback.
I'm making a to-do list app and after user presses the button I create a new GridLayout(and all the data about time and name of the task inside of it) and add it into my RelativeLayout. How do I save those GridLayouts in UI so after the activity is destroyed and launched again those layouts are there.
After pressing the button I trigger the Create Activity method
public void CreateActivity(String name,int hours, int minutes,int i)
{
RelativeLayout.LayoutParams relparams= new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
relparams.addRule(RelativeLayout.BELOW,i);
relparams.setMargins(0,50,0,100);
Glayouts.add(new GridLayout(this));
Glayouts.get(i+1).setBackgroundColor(Color.GRAY);
Glayouts.get(i+1).setMinimumWidth(relative.getWidth());
Glayouts.get(i+1).setId(i+1);
Glayouts.get(i+1).setPadding(10,0,0,0);
GridLayout.LayoutParams namee = new GridLayout.LayoutParams();
namee.columnSpec = GridLayout.spec(0);
namee.rowSpec = GridLayout.spec(0);
namee.setGravity(Gravity.LEFT);
final TextView Actname = new TextView(this);
Actname.setText(name);
GridLayout.LayoutParams checkbox = new GridLayout.LayoutParams();
checkbox.columnSpec = GridLayout.spec(1);
checkbox.rowSpec = GridLayout.spec(0);
checkbox.setGravity(Gravity.RIGHT);
CheckBox check = new CheckBox(this);
// ADDING TO LAYOUT
Glayouts.get(i+1).addView(Actname,namee);
Glayouts.get(i+1).addView(check,checkbox);
relative.addView(Glayouts.get(i+1),relparams);
Theoretically when you extends View, then you can also override onSaveInstanceState and onRestoreInstanceState methods, where you must provide your own SavedState class that typically extends BaseSavedState. You can find info on that here
In your case, your layout is dynamic, therefore this doesn't really work. To tell you the truth, your layout probably shouldn't be constructed this way, you should be rendering the grid using a RecyclerView based on a "model" that describes this layout, render the items of the grid via the RecyclerView.Adapter, and you should persist either the "model", or the data you use to construct this model along with the user-inputted state so that you can re-construct the model that will be rendered via your RecyclerView.
You can read more about RecyclerView here.
You can read more about data persistence here.
You can read about using onSaveInstanceState to save data in Activities/Fragments across config change and process death (but not finishing then restarting the app) here.
You can’t. The best way to save state is to use some persistence mechanism, for example database (I’d recommend Room as it is officially supported by Google).
After clicking a button, you should put all the needed information (name, hours, minutes) in the database and when Activity is created, you can read all persisted data and - basing on it - create all needed layouts again.
Another option is storing data in SharedPreferences - it is much easier to setup, so you can also start with this solution. Please note, I'm suggesting it as a first step in the world of persistency in Android, not as a preferred solution for storing data.
i have a lot of recycler views, they all use the same adapter, i used to update them with arraylists of objects that id make as i went like this
ADAPTER
private List<CardWriter> cardMakerList;
public CardAdapter(List<CardWriter> cardMakerList){
this.cardMakerList = cardMakerList;
// this.mContext = context;
}
ACTIVITY
public List<CardWriter> cardMakerList = new ArrayList<>();
public CardAdapter cardAdapter;
recyclerView.setAdapter(cardAdapter);
CardWriter cardWriter = new
CardWriter(getResources().getDrawable(R.drawable.happy),"HAPPY","happy ");
cardMakerList.add(cardWriter);
THE PROBLEM
Ive now switched to using databases for each recycler view (using greenDao see this question) so my adapter now uses the below code (addNewCard refers to the generated java class made by greendao)
public List<addNewCard> leaseList = new ArrayList<>();
but now to get my second database(2) its the exact same properties but greendao makes a different file so i should use this in my adapter
public List<addSimpleCard> leaseList = new ArrayList<>();
but this would mean a new adapter for every database and im going to need a lot of them. All the databases im making are just lots of the same object with different properties (an image and 2 strings) but each database needs to be managed individually.
my last question (in the link above) asks how i can make all the same databases with a different title which i think would also solve my problem.
WHAT IVE TRIED
I've tried just creating an static reference to the array list and passing it the new one eg:
public static CardAdapterDB cardAdapterDB;
cardAdapterDB = new CardAdapterDB(leaseList);
this works but trying to change it for a new database
cardAdapterDB = new CardAdapterDB(simpleleaseList);
gives me an error
CardAdapterDB(java.util.List<greendao.addNewCard>) in CardAdapterDB cannot be applied to (java.util.List<greendao.addSimpleCard>)
addSimpleCard is the name of my other java file generated by greendao so this makes perfect sense but how can i get around this without creating loads of new adapters and switching them all the time?
since asking this ive tried multiple ways to get this to work but have yet to find something suitable
I am developing an android project in which I have to load from group of String arrays(say title,description,id) to the listview item TextView.
I did something similar with a database using a cursor like this
String[] from = new String[]{"medicine","healthsystem"};
int[] to = new int[] {R.id.textlist1,R.id.textlist2};
// Now creating an array adapter and set it to display using my row
SimpleCursorAdapter notes =new SimpleCursorAdapter(this,R.layout.notes_row, c, from, to);
I listed all the targets in "from" and all the origin in "to".
Now my problem is I don't have a database so cant use a cursor.
I have 3 arrays of strings which i want to load into textviews(title,description,id) of each item
How to do this
Please kindly help me out
thank you :)
If you don't have a cursor, why are you using a SimpleCursorAdapter?
Read this article about creating a SimpleListView using SimpleAdapter for alternate ideas.
There are lots of examples of populating lists from various data sources in the ApiDemos project that comes with the Android SDK - browse through those, and you should find one that fits what you're trying to do.
First of all you need to create a Class that holds that information, something like:
public class StringHolder{
String titte;
String description;
int id;
}
Then you create the layout of your row that says where you want your title, your description and your image.
Then you create an Adapter. The adapter will hold your data and will say for each position in the list what information should be loaded.
At last you need to use your adapter in an activity.
For more information you can see a tutorial here: http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/
I have to create a form in Android which may contain spinner or may not, based on data we have to create spinner. So I am trying to create a dynamic spinner in the form.
But it is not working. I am able to create the spinner but when I click on the spinner it show error message.
Code that I wrote:
dynamicSpinner = new Spinner(getApplicationContext());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, option);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
dynamicSpinner.setAdapter(adapter);
option is a ArrayList<String>, which content the list of the options.
If anyone have solution please share with me.
try this
Spinner s=new Spinner(yourActivity.this);
ParentLayout.addView(s);
I dont see you adding your spinner to parent layout.
I am more interested in what error are you getting exactly
Include a spinner in your xml with an id..
and then in code , use:
dynamicSpinner = (Spinner)findViewById(R.id.mydynamicspinner);
instead of
dynamicSpinner = new Spinner(getApplicationContext());
rest all looks fine...
Have a spinner in your xml, then in activity, use following:
dynamicSpinner = (Spinner)findViewbyID(spinner ID);
if(data available)
populate the spinner;
else
dynamicSpinner.setVisibility(View.Gone);
Hope it helps.
EDIT :
Incase you want to add spinner progarammatically, still you would be having a layout in xml which you are using in setContentView(layout id).. so get the layout in which all the childs are present in xml throught its id and then add spinner to that layout.
Have you tried viewflipper?
http://developer.android.com/reference/android/widget/ViewFlipper.html
Its effective especially for those in need in multiple views/widgets.
The thing is just that, the widgets/views that will be viewed/added is defined in xml.
Hope it helps :D