This is a common problem and with a variety of solutions. In the solution I'll show you in a little while we check in our Activity if there is an id for the 2nd Fragment ( the one that will play the role of the DetailFragment ).
One common tactic is having two different versions of the xml layout we are wokring on. One in the layout folder and another one in the layout-sw600dp or whatever we define for the dual mode.
The 2nd file contains one more FrameLayout so what we basically have to do is check if the view is there. If its true then we are on a dual mode, if not then we are on a single mode.
First we define a Boolean isDualMode with false as an initial value.
Then on onCreate we check for the details id :
View aView = findViewById(R.id.details);
if (aView != null) {
isDualPane = true;
}
If thats true we add and commit the DetailsFragment also.
Full code for onCreate() :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View aView = findViewById(R.id.details);
if (aView != null) {
isDualPane = true;
}
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
mainFragment = new MainFragment();
if (isDualPane) {
detailsFragment = new DetailsFragment();
fragmentManager.beginTransaction().add(R.id.details, detailsFragment).commit();
}
fragmentManager.beginTransaction().add(R.id.main, mainFragment).commit();
fragmentTransaction.commit();
}
Thursday, May 28, 2015
Thursday, May 21, 2015
Set text size for Toolbar
Since Toolbar doesnt provide a textSize attribute to set the text size of the Title you have to add a TextView and pass the title text to it.
Ofcourse you can instead use setTitleTextAppearance where you can set color, size, style etc.
For the first solution the steps you got to follow are :
1) remove default title :
2) Add TextView in Toolbar :
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:minHeight="?android:attr/actionBarSize"
android:layout_width="match_parent"
android:layout_height="@dimen/toolbar_height"
android:background="@color/colorPrimary"
android:theme="@style/ActionBarThemeOverlay"
android:popupTheme="@style/ActionBarPopupThemeOverlay">
<TextView
android:id="@+id/tv_toolbar"
android:textSize="@dimen/toolbar_textSize"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</android.support.v7.widget.Toolbar>
3) Set toolbar_textSize on dimens.xml :
<dimen name="toolbar_textSize">16sp</dimen>
Now toolbar's title size is the one you specify on the dimens.xml file. That's it 16sp in our code.
We prefer sp units (instead of dp) so the size can scale when user changes the font size on her/his device.
Ofcourse you can instead use setTitleTextAppearance where you can set color, size, style etc.
For the first solution the steps you got to follow are :
1) remove default title :
getSupportActionBar().setDisplayShowTitleEnabled(false);
2) Add TextView in Toolbar :
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:minHeight="?android:attr/actionBarSize"
android:layout_width="match_parent"
android:layout_height="@dimen/toolbar_height"
android:background="@color/colorPrimary"
android:theme="@style/ActionBarThemeOverlay"
android:popupTheme="@style/ActionBarPopupThemeOverlay">
<TextView
android:id="@+id/tv_toolbar"
android:textSize="@dimen/toolbar_textSize"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</android.support.v7.widget.Toolbar>
3) Set toolbar_textSize on dimens.xml :
<dimen name="toolbar_textSize">16sp</dimen>
Now toolbar's title size is the one you specify on the dimens.xml file. That's it 16sp in our code.
We prefer sp units (instead of dp) so the size can scale when user changes the font size on her/his device.
Thursday, May 15, 2014
ActionBar dissapears although I'm using a scrollView
ActionBar dissapears when I click EditText although I'm using a ScrollView. This behavior appears after an orienation change when I click the EditText view.
Solution :
Seems that I need to add also adjustResize on my manifest :
android:windowSoftInputMode="adjustResize"
Solution :
Seems that I need to add also adjustResize on my manifest :
android:windowSoftInputMode="adjustResize"
//TODO
further investigate that behavior
Sunday, February 23, 2014
ToDo List example
Since repetition is the mother of all
learning and the following example is one of the most distinct
examples of how to start android
development I wrote it down as well
to try to explain it as best as I can.
What we are going to do is a ToDo
List app.
Bearing the design in mind will help us
better understand what components will be needed ( plus I prefer a
more visualized approach
to such kind of problems ).
As we can see from the mockup sketch
two fragments are needed. One will just display an EditText widget
and when the user clicks
'Send' on the software keyboard we will
pass the text to the list bellow. That gets us to the second fragment
which is a ListFragment.
Both of them are in the MainActivity.
Since we are using a ListFragment we
have to use an Adapter to bind the data to the list.
Also we will need a data model for our
todo items. Lets name it DataItem class.
Last but not least we will create a
custom view from each list item.
Let me summarize things a little bit : We have one MainActivity class with its layout, composed of two
fragments ( one is a ListFragment ). The ListFragment also needs an
Adapter class. Our data model will only need a String variable and a
Custom View for each ListFragment's item for the time.
So let's start from our model. We only
need one getter and one setter method since our only variable will be
a String. You can check the code here .
Now its time to create the TopFragment.
As you can see
the layout is just an EditText. We inflate that layout in onCreateView method ( like we do with every fragment ). The “tricky” part here is adding an OnEditorActionListener so we can listen for the 'SEND' action, get the user input and clear the text in EditText. An Interface is also necessary so we can implement it on the MainActivity and get the user's text input. All of these data will be stored on an ArrayList in the MainActivity and passed to the Adapter to bind them to the view.
The
TaskListAdapter gets each item from the ArrayList as we said above,
creates a new list item and sets the data.
ListFragment
just inflates the layout which consists of a ListView with the
android:divider
atrribute
set to null so we don't have to deal with the default divider line
from the ListView widget.
Since
each item is just a TextView our custom view needs to extend a
TextView. We saw on a previous post how to
create a custom view so I will not go into details.
The
XML layout file for the custom view, used by the TaskListAdapter is:
That input along with the id resource of the XML file that represents the list
item are passed to the Adapter.
The code is below :
public class MainActivity extends Activity implements TopFragment.OnItemAddedListener {
private ArrayList todoItems;
private TaskListAdapter aa;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get references to the Fragments
FragmentManager fm = getFragmentManager();
TaskListFragment todoListFragment =
(TaskListFragment)fm.findFragmentById(R.id.TaskListFragment);
// Create the array list of to do items
todoItems = new ArrayList();
// Create the array adapter to bind the array to the ListView
int resID = R.layout.tasklist_fragment;
aa = new TaskListAdapter(this, resID, todoItems);
// Bind the array adapter to the ListView.
todoListFragment.setListAdapter(aa);
}
public void onNewItemAdded(String newItem) {
DataItem newTodoItem = new DataItem(newItem);
todoItems.add(0, newTodoItem);
aa.notifyDataSetChanged();
}
}
The method onNewItemAdded() adds the DataItem before every other ArrayList item and also notify the data set has changed.
You can find the code of the project in the github repo here and you can import it and run it on your eclipse.
This example is based on Reto Meier's example on chapter four of his book "Professional Android 4 Application Development" you can find in this link
Sunday, December 29, 2013
Custom Views
We
get Custom Views by extending an existing Widget ( Button, EditText,
TextView, etc ), something that fits better to the functionality we
want to achieve and by defining attributes for that view.
1.
By extending a View we now have a Class, whose fully qualified name
can be used as an XML tag, to add to the layout file. If the package
is com.androidexamples.customviews and my Custom View's Class name is
MyEditText then the XML code we are going to add is :
<com.androidexamples.customviews.MyEditText
android:id=”@+id/myview”
android:layout_width="match_parent"
android:layout_height="wrap_content"
…
/>
2.
Into res/values/attrs.xml inside a <declare-styleable> tag we
add the attributes for our view. A valid example could be :
<resources>
<declare-styleable>
<attr
name=”attr_color” format=”color” />
<attr
name=”attr_firstname” format=”string” />
</declare-styleable>
</resources>
From now on we can use these attributes
either in our layout file as part of our custom View XML tag, or
through code.
In order to use them in the layout file
we have to first define a custom namespace similar to what android
does with its own attributes. The android default namespace is :
xmlns:android="http://schemas.android.com/apk/res/android”
and it's defined into the
parent element of the layout file.
Respectively our attributes' namespace uses the same format but instead of android we can use whatever name we want ( like “app” or “custom” ) and the schema is defined with our package name instead of the android. So a valid example could be :
Respectively our attributes' namespace uses the same format but instead of android we can use whatever name we want ( like “app” or “custom” ) and the schema is defined with our package name instead of the android. So a valid example could be :
xmlns:app="http://schemas.android.com/apk/res/com.androidexamples.customviews"
Now
we can add the “attr_firstname” to the XML in the form :
app:attr_firstname=”Some
Random Text”
Through
the code we have access to an array that stores each attribute. It is
a special container named TypedArray
and it can get referenced to the attributes with
obtainStyledAttributes().
3. In our Class code it is a
common practise to use an init() method to get the attributes and
assign initial values to them. This method is then passed to our
View's constructor.
4. Then all it's left to do is
to override the onDraw() and onMeasure() methods.
By
overriding onDraw()
we have access to the Canvas object. You can now create your UI for
your View. The styling of the elements is done through a Paint
object.
OnMeasure()
is called with the width and height specifications from the parent
layout element. Those values should be treated as requirements for
the restrictions on width and height measurements we will produce.
Some key points you should keep in mind
( otherwise it leads you to hard ) :
- call recycle() after you get the attributes from TypedArray.
- Don't create Paint objects inside onDraw() method. Views are redrawn frequently and creating objects inside onDraw() its expensive waste of resources.
- After every change on our attributes' values we have to call invalidate() so the system will know there might be a change in its appearance and needs to be redrawn.
The code below gives as a custom EditText which uses Paint to underline each line with a light green color.
public class MyEditText extends EditText {
private Rect mRect;
private Paint mPaint;
private int attrColor;
public MyEditText(Context context) {
super(context);
}
public MyEditText(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyEditText);
attrColor = ta.getInteger(R.styleable.MyEditText_attr_color, 0xff00ff00);
ta.recycle();
init();
}
public void init() {
mRect = new Rect();
mPaint = new Paint();
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(attrColor); //get value from attr
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int count = getLineCount();
Rect r = mRect;
Paint p = mPaint;
for(int i=0; i< count; i++) {
int baseline = getLineBounds(i, r);
canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, p);
}
}
}
Monday, December 9, 2013
Add Views programmatically
Example of adding two Buttons in a RelativeLayout :
1) Instantiate the RelativeLayout
2) Instantiate the Buttons.
3) Create the LayoutParams for each Buttons.
4) Add Views to their parent. That's the RelativeLayout.
One key point here. The LayoutParams for the child Views must the same type as that of their parent. So in our case both Buttons LayoutParams have to be RelativeLayout.LayoutParams.
Let's see how this applies to code :
RelativeLayout layout = new RelativeLayout(this); // Instantiate the parent
b3 = new Button(this); b3.setId(1);
b3.setText("Relative Button 3");
b4 = new Button(this); b4.setId(2);
b4.setText("Relative Button 4");
RelativeLayout.LayoutParams b3_lp = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams b4_lp = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
b4_lp.addRule(RelativeLayout.RIGHT_OF, b3.getId());
layout.addView(b3, b3_lp);
layout.addView(b4, b4_lp);
setContentView(layout);
The result is :
Notice the addRule() which sets the Button b4 to the right of the b3.
To achieve that we have to set Id's for our Buttons so we can refer to the view that acts as an anchor.
1) Instantiate the RelativeLayout
2) Instantiate the Buttons.
3) Create the LayoutParams for each Buttons.
4) Add Views to their parent. That's the RelativeLayout.
One key point here. The LayoutParams for the child Views must the same type as that of their parent. So in our case both Buttons LayoutParams have to be RelativeLayout.LayoutParams.
Let's see how this applies to code :
RelativeLayout layout = new RelativeLayout(this); // Instantiate the parent
b3 = new Button(this); b3.setId(1);
b3.setText("Relative Button 3");
b4 = new Button(this); b4.setId(2);
b4.setText("Relative Button 4");
RelativeLayout.LayoutParams b3_lp = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams b4_lp = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
b4_lp.addRule(RelativeLayout.RIGHT_OF, b3.getId());
layout.addView(b3, b3_lp);
layout.addView(b4, b4_lp);
setContentView(layout);
The result is :
Notice the addRule() which sets the Button b4 to the right of the b3.
To achieve that we have to set Id's for our Buttons so we can refer to the view that acts as an anchor.
Sunday, November 24, 2013
Send JSON unicode data to server with POST request
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url); // Address ( url )
HttpResponse response;
JSONObject json = new JSONObject();
json.put("passwd", param1);
json.put("comment", param2);
// String Entity to UTF-8
StringEntity se = new StringEntity(json.toString(), "UTF-8");
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.getParams().setParameter("json", json);
httppost.setEntity(se);
response = httpclient.execute(httppost);
HttpPost httppost = new HttpPost(url); // Address ( url )
HttpResponse response;
JSONObject json = new JSONObject();
json.put("passwd", param1);
json.put("comment", param2);
// String Entity to UTF-8
StringEntity se = new StringEntity(json.toString(), "UTF-8");
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.getParams().setParameter("json", json);
httppost.setEntity(se);
response = httpclient.execute(httppost);
Friday, November 1, 2013
Android Studio and Gradle Basics - part 1
With Android Studio there's a new build system called Gradle. In fact Gradle is much more than just a build system but we will focus on the basics here.
First of all lets see the Project Structure :
The root folder contains two Project folders and two gradle files.
For now build.gradle is empty while settings.gradle :
Between MyDemo and MyLibProject Project there are some differences :
1. Library Projects do not generate APK. Instead they generate an .aar package.
2. build.gradle of MyDemo contains a line
we have
Let's have a look at MyDemo build.gradle file :
repositories {
defaultConfig {
and MyLibProject build.gradle file :
repositories {
defaultConfig {
We can take the first block code of each file ( which is the same ) and move it to the external build.gradle :
Android Projects have source folders ( MyDemo ) , Library Projects ( MyLibProject ) and jar file dependencies.
There are three kinds of dependencies :
1. Maven
2. jar file
3. Module
If we choose to add a dependency like ActionBarSherlock to our project from the maven repositories we go to http://search.maven.org/ , write actionbarsherlock to the input area and click search button.
What we see is :
We can use it in our build.gradle code :
dependencies {
compile 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar'
}
Instead of the above way we can also download the rar file, add it to the /libs folder and
dependencies {
compile file ('libs/actionbarsherlock.jar')
}
Or if we had downloaded the source code and add it like a Library Project ( File > Project Structure > Modules ) and add it to the project. Then we had to add to the build.gradle
dependencies {
compile project (':ActionBarSherlock')
}
Just keep in mind that if we add an artifact as a .jar file to a libs folder and we have the same jar file in another library folder then we are going to have a conflict. We just need to have only one copy of the jar file.
That's a good reason for you to start using the maven repository and don't just add jar files. In that case if we have added the same artifact more than once there will be no conflict.
From the Command Line. Go to the root dir of your project. Gradle works with tasks.
First of all lets see the Project Structure :
The root folder contains two Project folders and two gradle files.
For now build.gradle is empty while settings.gradle :
include ':MyDemo', ':MyLibProject'Between MyDemo and MyLibProject Project there are some differences :
1. Library Projects do not generate APK. Instead they generate an .aar package.
2. build.gradle of MyDemo contains a line
apply plugin: 'android' where for Library Projectwe have
apply plugin : 'android-plugin'Let's have a look at MyDemo build.gradle file :
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.6.+'
}
}
apply plugin: 'android'
repositories {
mavenCentral()
}
android {
compileSdkVersion 18
buildToolsVersion "18.1.1"
defaultConfig {
minSdkVersion 8
targetSdkVersion 18
}
}
and MyLibProject build.gradle file :
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.6.+'
}
}
apply plugin: 'android-library'
repositories {
mavenCentral()
}
android {
compileSdkVersion 18
buildToolsVersion "18.1.1"
defaultConfig {
minSdkVersion 8
targetSdkVersion 18
}
}
We can take the first block code of each file ( which is the same ) and move it to the external build.gradle :
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.6.+'
}
}
Android Projects have source folders ( MyDemo ) , Library Projects ( MyLibProject ) and jar file dependencies.
There are three kinds of dependencies :
1. Maven
2. jar file
3. Module
If we choose to add a dependency like ActionBarSherlock to our project from the maven repositories we go to http://search.maven.org/ , write actionbarsherlock to the input area and click search button.
What we see is :
We can use it in our build.gradle code :
dependencies {
compile 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar'
}
Instead of the above way we can also download the rar file, add it to the /libs folder and
dependencies {
compile file ('libs/actionbarsherlock.jar')
}
Or if we had downloaded the source code and add it like a Library Project ( File > Project Structure > Modules ) and add it to the project. Then we had to add to the build.gradle
dependencies {
compile project (':ActionBarSherlock')
}
Just keep in mind that if we add an artifact as a .jar file to a libs folder and we have the same jar file in another library folder then we are going to have a conflict. We just need to have only one copy of the jar file.
That's a good reason for you to start using the maven repository and don't just add jar files. In that case if we have added the same artifact more than once there will be no conflict.
From the Command Line. Go to the root dir of your project. Gradle works with tasks.
gradlew tasks to see all available tasks. gradlew assemble to build the project andgradlew installDebug to install it to the connected devices.Wednesday, September 11, 2013
Check if Google's location Service is enabled
Check if Google's location Service is enabled by the user, else open Settings > Location so the user enables them.
First get the
String locationProviders = Settings.Secure.getString(getContentResolver(),Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
contains "network" or "gps" or both values separated by comma.
If the string is empty => Google Location Service is closed and you have to prompt the user to open it. Wifi might or not be open.
If the string equals "network" => WiFi and Google Location Service are enabled.
If the string equals "network,gps" => WiFi and GPS and Location Service are enabled.
We need to create a Dialog and ask the user to take the action he wants. In our case we want the user when she clicks Yes to open the Settings > Location , so she can enable the Location Service.
We can achieve that with ACTION_LOCATION_SOURCE_SETTINGS.
The code is :
if (locationProviders == null || locationProviders.equals("")) {
new AlertDialog.Builder(this)
.setTitle("Enable Location Service")
.setMessage("This Application requires the use of Google Location's service. " +
"Do you wish to enable this feature")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// show system settings
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
Link : http://stackoverflow.com/questions/10311834/android-dev-how-to-check-if-location-services-are-enabled
First get the
String locationProviders = Settings.Secure.getString(getContentResolver(),Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
contains "network" or "gps" or both values separated by comma.
If the string is empty => Google Location Service is closed and you have to prompt the user to open it. Wifi might or not be open.
If the string equals "network" => WiFi and Google Location Service are enabled.
If the string equals "network,gps" => WiFi and GPS and Location Service are enabled.
We need to create a Dialog and ask the user to take the action he wants. In our case we want the user when she clicks Yes to open the Settings > Location , so she can enable the Location Service.
We can achieve that with ACTION_LOCATION_SOURCE_SETTINGS.
The code is :
if (locationProviders == null || locationProviders.equals("")) {
new AlertDialog.Builder(this)
.setTitle("Enable Location Service")
.setMessage("This Application requires the use of Google Location's service. " +
"Do you wish to enable this feature")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// show system settings
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
Link : http://stackoverflow.com/questions/10311834/android-dev-how-to-check-if-location-services-are-enabled
Sunday, July 14, 2013
Android Parsing JSON data
When we are dealing with Web Services often the response are in JSON format. That means we have to get the data and with the JSONArray and JSONObject classes parse through the response and extract the data we want.
The whole JSON schema uses the convention of name:value pair. The simplest example we can have here is the JSON Object { "foo":"bar" } where bar is value of foo.
We can easily imagine making a request to the server for a basketball player name and getting the answer in the above format.
Even better we can ask the server for the Personal Information of the player named "lebron james" and get data like position, nationality, weight, height, age, etc...
Then a valid response from the server could be like that :
{
"age":"28",
"position":"Forward",
"nationality":"American",
"weight":"113",
"height":"203"
}
Values can be String, number, true, false, null, or even Object and Array.
You can read more about json here.
Now in our application we are going to use the schema ( and the values ) you can see in the image below.
What we see is that we have an Object described by the String "users" and that Object's value is an Array.
Now we just need to think procedural and a) add the data to a JSONObject and from that data b) get the JSONArray described by the name "users".
So our code should look like :
JSONObject jObj = new JSONObject(data);
JSONArray sArr = new JSONArray();
sArr = jObj.getJSONArray("users"); //getting the "users"
Now all we need to do is to iterate through the items of the Array and get the values specified by each tag ( id, username and password in our case ).
Since we don't get any response from a web server I stored the answer into a String.
The code is below :
And the XML layout file :
The result in our Android emulator :
The whole JSON schema uses the convention of name:value pair. The simplest example we can have here is the JSON Object { "foo":"bar" } where bar is value of foo.
We can easily imagine making a request to the server for a basketball player name and getting the answer in the above format.
Even better we can ask the server for the Personal Information of the player named "lebron james" and get data like position, nationality, weight, height, age, etc...
Then a valid response from the server could be like that :
{
"age":"28",
"position":"Forward",
"nationality":"American",
"weight":"113",
"height":"203"
}
Values can be String, number, true, false, null, or even Object and Array.
You can read more about json here.
Now in our application we are going to use the schema ( and the values ) you can see in the image below.
![]() |
| click the image to enlarge |
Now we just need to think procedural and a) add the data to a JSONObject and from that data b) get the JSONArray described by the name "users".
So our code should look like :
JSONObject jObj = new JSONObject(data);
JSONArray sArr = new JSONArray();
sArr = jObj.getJSONArray("users"); //getting the "users"
Now all we need to do is to iterate through the items of the Array and get the values specified by each tag ( id, username and password in our case ).
Since we don't get any response from a web server I stored the answer into a String.
The code is below :
And the XML layout file :
The result in our Android emulator :
![]() |
| display JSON response from server |
Wednesday, June 12, 2013
Root access with ES File Explorer
Open ES File Explore, go to settings scroll down to Home Directory and change it to "/".
Now you have access to the entire file system.
You can read more here
Tuesday, June 11, 2013
Add/Remove Fragment - Simple Example
What we are going to do :
A View with a Button. When we click that Button a fragment is being added dynamically in our View. We click again and the fragment is being dynamically removed.
One Activity and one Fragment. In the Activity's layout we add two layout objects. That's a Button and a FrameLayout.
In Fragment's layout we have a TextView that contains just text in a color background
So the code for the Activity's and Fragment's layout is:
Fragment's Layout :
Note the android:id = "@+id/fragment_container_1" in the Activity's layout which is an identifier for our fragment. When we make Transactions like add we refer to a fragment by id.
Activity and Fragment :
Fragment Class : is a typical Fragment class as we have seen it beforeActivity Class : onClick() begins Transaction. If state is null then we add and commit the fragment else we need to remove and commit again.
So the code is :
Saturday, May 25, 2013
ActionBar/ActionBarSherlock Tabs
Navigation Tabs:
ActionBar supports built-in Tabs or drop-down lists that you can use to change the Fragment is currently visible. We are going to work with ActionBarSherlock library so we can have backwards compatibility.
Note 1 : Either Tabs or drop-down lists but not both in ActionBar.
Note 2 : Every Tab is associated with one Fragment. To change Fragments by using the Tabs, perform a FragmentTransaction each time a Tab is selected.
Display Tabs :
Add Tabs :
You can add Tabs with the addTab() method. The first Tab added is the selected one therefore the visible.
Code is like below :
Implement ActionBar.TabListener :
We 're going to split it into 3 parts :
1) Fragments
Fragment class is just a basic Fragment class in which we only inflate the layout :
You can add Tabs with the addTab() method. The first Tab added is the selected one therefore the visible.
Code is like below :
Implement ActionBar.TabListener :
We 're going to split it into 3 parts :
- First part the implementation of the Fragments.
- Second part the implementation of ActionBar.TabListener
- Third part is to add the Tabs using the TabListener we created before.
The result we expect is the screenshot below :
1) Fragments
Fragment class is just a basic Fragment class in which we only inflate the layout :
And the corresponding XML layout :
We repeat this process for Fragment_2.
2) TabListener
TabListener's implementation is the most difficult part of the work.
Our constructor is public TabListener(Activity activity, String tag, Class<T> clz) where activity is the host Activity, tag is the identifier Tag of the fragment and cls the Fragment's class so we can instantiate the fragment.
Callbacks in this Interface will handle the event. Specifically when a Tab is clicked then onTabSelected() will execute the Fragment transaction and add the fragment to the Activity.
In our case the Tab content will fill the activity's layout, so our activity doesn't needs a layout. Each fragment is placed in the default root ViewGroup, which we can refer to with the android.R.id.content ID.
3) MainActivity
Because we have to deal with Fragments our MainActivity will extend FragmentActivity ( or just Activity for Android 3.0 and up ) but in our case with ActionBarSherlock will extend the SherlockFragmentActivity.
All we are doing here is to get the ActionBar item, and add Tabs with the addTab() method.
We set a TabListener for each Tab by calling the setTabListener().
Also we set the tab's title and/or icon with
setText() and/or setIcon().That's all ! Check all the code and/or fork the project from github here so you can see by yourself how it works.
Tuesday, May 14, 2013
Simple Fragment Transactions
What we are going to do here is a simple Activity with a button. When we click that button a Fragment Transaction takes place and we add the Fragment's layout.
So our code is here :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/cool">
<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Fragment A" />
</LinearLayout>
The part where the Transaction takes place is inside the click listener :
Fragment_A Frag_A = new Fragment_A();
FragmentManager fm1 = getSupportFragmentManager();
FragmentTransaction transaction = fm1.beginTransaction();
transaction.add(R.id.fragment_container, Frag_A);
transaction.commit();
-> new Fragment -> get FragmentManager -> beginTransaction -> add new layout and commit.
One last thing is the Activity's layout. The activity's layout includes an empty
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/button_id"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/button_text" />
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
1. You start a new Project and you are using support library if you target API less than 11. So first add the support lib to the project.
2. In my case I'm extending FragmentActivity ( i'm using minimum sdk version 8 ) or for API 11 and above you can use just Activity.
3. First we are going to create the Fragment.
We extend Fragment class, inflate Fragment's layout at onCreateView() method and declare an Interface for future communication between Fragment and Activity.So our code is here :
public class Fragment_A extends Fragment {
protected static final String TAG = "FRAGMENTS_A";
private CallbackInterface listener;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_a_layout, container, false);
return view; //returns view
}
// ********** declare INTERFACE ***************** //
public interface CallbackInterface {
public void onSomethingSelected(int position);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented the callback interface. If not, it throws an exception
try {
listener = (CallbackInterface) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement CallbackInterface");
}
}
}
4. Fragment's layout
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/cool">
<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Fragment A" />
</LinearLayout>
5. Now we are going to create our Activity :
public class MainActivity extends FragmentActivity implements CallbackInterface {
private static final String TAG = "passNumberTAG";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Fragment_A Frag_A = new Fragment_A();
FragmentManager fm1 = getSupportFragmentManager();
FragmentTransaction transaction = fm1.beginTransaction();
transaction.add(R.id.fragment_container, Frag_A);
transaction.commit();
}
});
}
@Override
public void onSomethingSelected(int position) {
Log.d(TAG, "Give me the result " + position );
position = position +1;
Log.d(TAG, "Give me the result " + position );
}
}
The part where the Transaction takes place is inside the click listener :
Fragment_A Frag_A = new Fragment_A();
FragmentManager fm1 = getSupportFragmentManager();
FragmentTransaction transaction = fm1.beginTransaction();
transaction.add(R.id.fragment_container, Frag_A);
transaction.commit();
-> new Fragment -> get FragmentManager -> beginTransaction -> add new layout and commit.
One last thing is the Activity's layout. The activity's layout includes an empty
FrameLayoutthat acts as the fragment container. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/button_id"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/button_text" />
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Monday, May 6, 2013
ActionBarSherlock configuration
1.
I'm creating a custom Theme, let's call it TestABS with parent the HOLO Theme ( in our case Sherlock ).
So now in my styles.xml I add the line :
<style name="Theme.TestABS" parent="@style/Theme.Sherlock"></style>
2.
Later I'll edit Manifest file like this :
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/Theme.TestABS"
android:logo="@drawable/ad_logo">
3.
When Activity starts, the system adds ActionBar and the overflow menu by calling onCreateOptionsMenu().
This method inflates an XML resource which defines the menu items. This files is in the folder
So a simple item should be like :
<item
android:id="@+id/menu_settings"
android:orderInCategory="100"
android:showAsAction="ifRoom"
android:title="Text Here" />
This works as long as I have an ActionBar in my Activity( When do I have an ActionBar ? When I add android:theme="@style/Theme.HOLO" in my manifest file for android 3.0 and greater. For lower versions I need Theme.Sherlock . In both cases I can declare mine custom theme like I did above with TestABS ).
Links :
1) Adding ActionBarSherlock to your Project
2) Adding Items to the ActionBar
3) The Overflow menu ( As a rule of thumb you should always use
I'm creating a custom Theme, let's call it TestABS with parent the HOLO Theme ( in our case Sherlock ).
So now in my styles.xml I add the line :
<style name="Theme.TestABS" parent="@style/Theme.Sherlock"></style>
2.
Later I'll edit Manifest file like this :
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/Theme.TestABS"
android:logo="@drawable/ad_logo">
3.
When Activity starts, the system adds ActionBar and the overflow menu by calling onCreateOptionsMenu().
This method inflates an XML resource which defines the menu items. This files is in the folder
/res/menu. In those items on the XML file I have to add the android:showAsAction keyword, so now the items will appear as Action Items in my ActionBar and not Options Menu.So a simple item should be like :
<item
android:id="@+id/menu_settings"
android:orderInCategory="100"
android:showAsAction="ifRoom"
android:title="Text Here" />
This works as long as I have an ActionBar in my Activity( When do I have an ActionBar ? When I add android:theme="@style/Theme.HOLO" in my manifest file for android 3.0 and greater. For lower versions I need Theme.Sherlock . In both cases I can declare mine custom theme like I did above with TestABS ).
Links :
1) Adding ActionBarSherlock to your Project
2) Adding Items to the ActionBar
3) The Overflow menu ( As a rule of thumb you should always use
ifRoom, if you want the icon to be part of your action bar and you should use never if you want the item to always be part of the overflow menu. )Wednesday, April 10, 2013
Add Marker to Google Map
To detect a long map click by the user, so add a new Marker, we need to implement OnMapLongClickListener Interface.
Then we set our map to listen for any calls when its long pressed : mMap.setOnMapLongClickListener(this);
And now in our code we can add a new Marker every time the user long clicks the map :
Then we set our map to listen for any calls when its long pressed : mMap.setOnMapLongClickListener(this);
And now in our code we can add a new Marker every time the user long clicks the map :
mMap.addMarker(new MarkerOptions().position(point));
Monday, April 8, 2013
Detect user click on Map
To detect click on GoogleMap we implement OnMapClickListener Interface.
We add to our GoogleMap setOnMapClickListener . This sets a callback to the Interface when the map is clicked
Then we need to override the onMapClick(LatLng point)
We are using CameraUpdateFactory to get a new CameraUpdate Object ( an object to modify a map's camera ) and animate to the new point with animateCamera.
We add to our GoogleMap setOnMapClickListener . This sets a callback to the Interface when the map is clicked
Then we need to override the onMapClick(LatLng point)
@Override
public void onMapClick(LatLng point) {
mMap.animateCamera(CameraUpdateFactory.newLatLng(point));
}
We are using CameraUpdateFactory to get a new CameraUpdate Object ( an object to modify a map's camera ) and animate to the new point with animateCamera.
Sunday, April 7, 2013
Display my Location - Google maps API V2
All we need to do is to use the method setMyLocationEnabled(boolean enabled) which enables the my-Location layer.
Like that :
private GoogleMap mMap;
mMap.setMyLocationEnabled(true);
Sunday, February 17, 2013
Fragments Tutorial - Simple 2 - Passing Data
Passing Data between Fragment and host Activity
To pass data from a Fragment to the host Activity we need to Define/declare an Interface and
Implement it on the Activity.
1. Declare an Interface on Fragment_A.
public interface OnSomethingSelectedListener {
public void passData(int position);
}
2. onAttach() : To be sure that Activity implements the Interface onAttach callback method of Fragment_A we instantiate an Instance of Ιnterface by casting the Activity passed into onAttach().The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in order to communicate with the Activity.
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented the callback interface. If not, it throws an exception
try {
listener = (OnSomethingSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
3. On Main Activity we implement the Interface like this :
public class MainActivity extends FragmentActivity implements OnSomethingSelectedListener
@Override
public void passData(int position) {
Log.d(TAG, "Give me the result " + position );
position = position +1;
Log.d(TAG, "Give me the result " + position );
}
We just take the integer value parameter from the Fragment and add one to it.
4. A button on Fragment's layout so we can add onClick event
<button
android:id="@+id/button_id"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="send Integer">
</button>
5. And on Fragment's onCreateView() we add the listener for the event:
Button button = (Button) view.findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v(TAG, "onClick 1");
listener.passData(5); //pass an Integer
}
});
We pass the value five to the method passData()
Now when we click on the Button we open LogCat View and we see that value one has been added to the value of the parameter:
Subscribe to:
Comments (Atom)



.png)





