Difference between making an ArrayAdapter - android-studio

im learning Android programming with Android Studio. A few days ago we made a Spinner and filled it with a list of different countries, who were stored as an String-Array in the Strings.xml file.
To implement the ArrayAdapter we used the createFromRessource() method:
adapter = ArrayAdapter.createFromResource(this, R.array.countries, android.R.layout.simple_list_item_1);
Today i learned how to fill a ListView with items. But now, the teacher implemented the String array first, and then the Arrayadapter with new ArrayAdapter ....
public class ConstraintLayout extends AppCompatActivity {
ListView list;
ArrayAdapter <String> adapter;
String countries[];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_constraint_layout);
list = findViewById(R.id.list);
countries = getResources().getStringArray(R.array.countries);
adapter = new ArrayAdapter<String> (this, android.R.layout.simple_list_item_1, countries);
list.setAdapter(adapter);
I dont understand two things: The first example would work with the ListView too, and its less code than the second one. Why would someone use the second one for making the ArrayAdapter?
Why do i need Generics here? The ArrayAdapter can uses Strings anyway or not?
Tried to llok for an answer on Google.

Related

I am trying to display a list view in designer mode but I cannot see any list displayed

I am trying to run a project involving creating lists. I have just started and I already got the issue that if I drag and drop the listView from the palette in the designer mode, there is no list displayed in the app.
I only had one error, that the list is not constrained. Well, I have constrained it and still no list. Even if I start to code the elements of the list in the strings code, the code is running, but still nothing to be seen on the screen in the emulator (which is a nexus 5). Can anyone help me please?
This is the code in main activity where I call all the items of the list.
{
ListView myListView;
String [] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources res = getResources();
myListView = (ListView) findViewById(R.id.myListView);
items = res.getStringArray(R.array.items);
myListView.setAdapter(new ArrayAdapter<String>(this, R.layout.my_listview_detail, items));
}
}
}

Overlay toolbar with other toolbar when item is selected in RecyclerView which is inside a fragment

To illustrate what I mean with this, it is similar to WhatsApp, where various options are displayed in the toolbar when a chat is selected.
I have a similar layout, so a MainActivity with Fragments containing RecyclerViews. Now when an item in a RecyclerView is selected I would like to get a similar behaviour as in WhatsApp. The RecyclerViews have an Adapter that implements an OnClickListener.
However, from this Adapter I do not seem to have access to Views from the MainActivity. I tried the following (inside the OnClick method in the Adapter), but it did not work since the view could not be found.
View view = getActivity().findViewById(R.id.toolbar_main_activity);
if( view instanceof Toolbar) {
Toolbar toolbar = (Toolbar) view;
toolbar.setTitle("TestTitle");
}
Does anyone know how to get the intended behavior or have a reference to a tutorial?
UPDATE: for who is also stuck with this and this is still quite confusing, here is how I solved it in my own words
My Fragment contains the Interface by adding the following code to it;
OnItemsSelected mCallBack;
public interface OnItemsSelected {
void onToolbarOptions(String title);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mCallback = (OnItemsSelected) getActivity();
}
Also I passed 'mCallback' to the adapter like this;
MyAdapter adapter = new MyAdapter(myList, mCallback);
The RecyclerView adapter implements OnClickListener. In the OnClick method I called; 'mCallBack.onToolbarOptions("someTitle");'. And finally I made my MainActivity implement the method; 'implements myFragment.onItemsSelected' and I added the following code to it also;
#Override
public void onToolbarOptions(String title) {
toolbar.setTitle(title);
}
With this, only the title is changed, but from this it is quite easy to make other changes to the toolbar, such as changing the menu items.
Inside your Fragment you make an Interface and a global variable like this:
OnItemsSelected mCallBack;
public interface OnItemsSelected {
public void onToolbarOptions();
}
Then when in your RecyclerView items are selected or clicked you call:
mCallBack.onToolbarOptions();
In your Activity implement the Interface like this plus the method onToolbarOptions():
public static class YourActivityName extends AppCompatActivity
implements YourFragmentName.OnItemsSelected {
public void onToolbarOptions(){
// CHANGE YOUR TOOLBAR HERE
}
//.....OTHER STUFFS IN YOUR ACTIVITY
}

AndroidPlot FixedSizeEditableXYSeries How to use

Im new to android and very new to android plot. Can you point me to an example that uses FixedSizeEditableXYSeries?
My goal is to create a streaming plot that shows the latest sensor readings in an android app.
Thanks
===================Update - following discussion with #Nick====================
public class MainActivity extends AppCompatActivity {
// Create the redrawer so that the plot is updated
private Redrawer redrawer;
// create the message receiver - data is received via broadcasts
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("CurrentHR");
Log.d("ReceivedHR ",message);
// Now put the new data point at the end of the FixedSizeEditableXYSeries, move all data points by 1.
for (int index=0;index<9;index++){
if(index<9){
hrHistory.setY(hrHistory.getY(index+1),index);
}else{
hrHistory.setY(Float.parseFloat(message),9);
}
}
}
};
// create a few references
private XYPlot xyPlot;
private FixedSizeEditableXYSeries hrHistory;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_heart_rate);
// Now find the plot views
xyPlot = (XYPlot)findViewById(R.id.xyPlot);
// Declare the local broadcast manager
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter("hrUpdate"));
// now put in some data
hrHistory = new FixedSizeEditableXYSeries("HR",10);
xyPlot.addSeries(hrHistory, new LineAndPointFormatter(Color.GREEN,Color.RED,null,null));
xyPlot.setRangeBoundaries(40, 120, BoundaryMode.FIXED);
xyPlot.setDomainBoundaries(0, 20, BoundaryMode.FIXED);
}
#Override
protected void onResume(){
super.onResume();
// set a redraw rate of 1hz and start immediately:
redrawer = new Redrawer(xyPlot, 1, true);
}
}
This gives me a nice graph but no line. It doesnt look like the plot is being updates as new data is filling the FixedSizeEditableXYSeries.
If you want scrolling behavior then FixedSizeEditableXYSeries would be the wrong choice; as your data scrolls you're essentially enqueueing the newest value and dequeuing the oldest value; a linked list type structure would be a better choice.
You can either implement XYSeries and back it with any suitable data structure you prefer, or you can use SimpleXYSeries, which already supports queue operations a la removeFirst() and addLast(...). There's a great example of of a dynamic scrolling plot in the demo app: OrientationSensorExampleActivity. Lines 235-245 show the specific actions mentioned above.

Best way to create buttons dynamically

I want to create button dynamically in my application. The buttons need to be created based on items fetched from database. What is the best way to achieve this. Should I go for grid layout or Linear layout. My layout is simple with max 3 buttons per row. Once the first row is complete the buttons should be placed in second row.
I scanned lot of similar questions(some had grid layout other were using Linear layout) but unable to decide what is the optimum way to implement this.
I am complete newbie in android application, so any code snippets would be really helpful. Apologies if someone feels this is a duplicate question (I searched a lot before posting but didn't find appropriate answer to layout to be used.)
Thanks.
Please try to use gridView same as bellow code.
// in xml write this code
<GridView
android:id="#+id/calendar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="3" />
// grid adapter
public class GridAdapter extends BaseAdapter {
private final Context _context;
private final List<String> list;
public GridAdapter(Context context, ArrayList<String> list) {
super();
this._context = context;
this.list = list;
}
public String getItem(int position) {
return list.get(position);
}
#Override
public int getCount() {
return list.size();
}
public View getView(int position, View convertView, ViewGroup parent) {
Button button = new Button(_context);
button.setText("button" + list.get(position));
return button;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
/// in oncreate
gridView.setAdapter(new GridAdapter(getApplicationContext(),list);

Actionbarsherlock : How to "keep" it in 1 class

I'm completely new to Java and Android..
While using actionbarsherlock, I'm having a problem that I can't solve.
My app has around 8 Activities in total, and each of them has the SAME action bar,
using ABS.
So I was wondering if there is a way to keep the whole ABS part in 1 class,
and then call it in other activities when needed. Or else, I would have to write the same code in each activity to reach the same action bar, which really doesn't look correct.
I remember before using ABS, I had to use a separate row in XML then inflate it in other activities when needed. But this whole ABS project seems too vast for a newbie like me and I'm
really getting confused.. can any one help me clarify? Thanks in advance.
Use a base class which sets up the action bar.
public abstract class BaseActivity extends SherlockFragmentActivity {
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar ab = getSupportActionBar();
ab.whatever....
}
}
And then in your activities...
public class MySweetActivity extends BaseActivity {
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.whatever);
}
}

Resources