Showing posts with label actionbarcompact. Show all posts
Showing posts with label actionbarcompact. Show all posts

Android JSON Parsing Using Google gson-Part III


In the previous part of the Json series , we seen the complete basics of json.In this part we are going to actually parse a sample Json Object Using Google GSON.The Json will be not  passed as a String within the code , instead we will call the json object through  external URL through HTTP call.




--------------------------------------------------------------------------------------
Check for previous part :
Android Json Parsing basics tutorialAndroid Parsing Json tutorial part -2
----------------------------------------------------------------------------------------
Step 1:
Here is our Json Code that we are going to parse Using Gson in Android:

   "Os_version":[ {    "title":"Android 4.3 Jelly Bean (API level 18)"
      },
      { 
         "title":"Android 4.4 KitKat (API level 19)"
      },
      { 
         "title":"Android 5.0 Lollipop (API level 21)"
      }
   ],
   "author":"Venkatesh Pillai",
   "price":"Open Source",
   "subject":"Last Android Os release"
}



Step 2: 
The next step is to download the Gson jar file.

Step 3:
Right-click the project's top most folder and select PROPERTIES ->JAVA BUILD PATH and select the libraries tab.

 Click the Add JARs button and select the Gson jar we added to the /libs folder 


Step 4:
We need to create one model class Beansubject.java and BeanOs_version.java and annotate field names  with the SerializedName annotation. When we add serialized name to field must match with key name from JSON

Beansubject.java

import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
public class BeanSubject {

@SerializedName("subject")
    private String subject; 
@SerializedName("price")   
private String price;    
@SerializedName("author")    
private String author;    
@SerializedName("Os_version")    
private ArrayList<BeanOs_version> beanOs_version;

    public BeanSubject(ArrayList<BeanOs_version> beanOs_version, String subject, String price, String author)
{        this.beanOs_version = beanOs_version;      
this.subject = subject;        
this.price = price;        
this.author = author;    

}

public String getSubject() { 
return subject;   
}    
public void setSubject(String subject) { 
this.subject = subject;    
}   
public String getPrice() { 
return price;   
}    
public void setPrice(String price) {  
this.price = price;    
}    
public String getAuthor() {  
return author;    
}    
public void setAuthor(String author) {
this.author = author;    
}    
public ArrayList<BeanOs_version> getBeanOs_version() { 
return beanOs_version;    
}    
public void setBeanOs_version(ArrayList<BeanOs_version> beanOs_version) {
this.beanOs_version = beanOs_version;    
}

}


Step 5:

     BeanOs_version.java

import com.google.gson.annotations.SerializedName;
public class BeanOs_version {

    @SerializedName("title") 
private String title;

    public BeanOs_version(String title)
{   
this.title = title;    
}

    public String getTitle() {
return title;    
}   
public void setTitle(String title) 
{        
this.title = title;    
}
}

Step 6:
Here come the important task of creating HTTP request to the url to fetch the required data through Json. 
Create API.java class to perform an HTTP request and retrieve the resource as a stream.

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class API 
{                
private static Reader reader=null;                
public static Reader getData(String SERVER_URL) 
{        
                        try {                                              
DefaultHttpClient httpClient = new DefaultHttpClient();                                                
HttpPost httpPost = new HttpPost(SERVER_URL);                                                
HttpResponse response = httpClient.execute(httpPost);                                                
StatusLine statusLine = response.getStatusLine();                                                
if (statusLine.getStatusCode() == 200) {                                                               
 HttpEntity entity = response.getEntity();                                                               
 InputStream content = entity.getContent();                                                                
reader = new InputStreamReader(content);                                                
} else {  
}                               
} catch (ClientProtocolException e) {                                           
e.printStackTrace();                                
} catch (IllegalStateException e) {                                             
e.printStackTrace();                                
} catch (IOException e) {                                                
         e.printStackTrace();                     
}                              
return reader;                
}
}



Step 7:
Now change the code in MainActivity.java Activity class and 
create GSON instance get data in required way that can be shown in your activity_main.xml layout file .
We will use Asyn Task Since the required details need to be fetched in background.Its not the good way to fetch data in tha UI thread. The doInBackground() method will help to work in background. 

Main Activity.java

public class MainActivity extends Activity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {

-----
------
-------
new AsyncTask<Void,Void,Void>(){

@Override

protected void onPreExecute() {

super.onPreExecute();

progressDialog=new ProgressDialog(MyActivity.this);

progressDialog.setCancelable(false);

progressDialog.setMessage("Loading...");

progressDialog.show();

} @Override



protected Void doInBackground(Void... voids) {

Reader reader=API.getData("....url....");//enter the json url 

beanSubject = new GsonBuilder().create().fromJson(reader, BeanSubject.class);



//Printing in Log File

Log.e("Subject: ", beanSubject.getSubject()+"");

Log.e("Author: ", beanSubject.getAuthor()+"");

Log.e("Price: ", beanSubject.getPrice()+"");

Os_versionArrayList=beanSubject.getBeanOs_version();




Os_versionList=new StringBuffer();

for(BeanOs_version Os_version: Os_versionArrayList){

Log.e("Os_version title: ",Os_version.getTitle()+"");

Os_versionList.append("* "+Os_version.getTitle()+"\n");

} return null;

} @Override



protected void onPostExecute(Void aVoid) {

super.onPostExecute(aVoid);

progressDialog.dismiss();

txtSubject.setText("Subject: "+beanSubject.getSubject());

txtPrice.setText("price: "+beanSubject.getPrice());

txtAuthor.setText("Author: "+beanSubject.getAuthor());

txtOs_versionList.setText("Os_version: "+"\n"+Os_versionList);

}

}.execute();

Step 8:

Run the application to see the result.





Thats it .We are able to fetch the data from the URL using HTTP request through GSON in android app

Happy Coding!Happy Development.

How to apply Material Design to your app

Changes HDDMigration to be made from Holo to Material.

The Android 5.0 SDK was released(if you want know step by step guide to installing it) last Friday, featuring new UI widgets and material design, our visual language focused on good design. To enable you to bring your latest designs to older Android platforms we have expanded our support libraries, including a major update to AppCompat, as well as new RecyclerViewCardView and Palette libraries.
In this post we'll take a look at what’s new in AppCompat and how you can use it to support material design in your apps.

We will go Step by Step to make changes for Material Design:

From ActionbarCompact to AppCompactv21

AppCompat (aka ActionBarCompat) started out as a backport of the Android 4.0 ActionBar API for devices running on Gingerbread, providing a common API layer on top of the backported implementation and the framework implementation. AppCompat v21 delivers an API and feature-set that is up-to-date with Android 5.0.

Three things to lookout or there might be three situations we need to consider.

Setting up the things first to migrate to appcompact v21:

Migrating from holo to material.

If you have followed the guidelines correctly then you don't require to change lots of thing in your app for migration.

A)Open the values Folder that contains the Themes.xml file and change accordingly.
values/themes.xml:
<style name="Theme.MyTheme" parent="Theme.AppCompat.Light">
   
<!-- Set AppCompats actionBarStyle -->
   
<item name="actionBarStyle">@style/MyActionBarStyle</item>

    <!-- Set AppCompat’s color theming attrs -->
    <item name=”colorPrimary”>@color/
my_awesome_red</item>
    <item name=”colorPrimaryDark”>@color/
my_awesome_darker_red</item>
   
    <!-- The rest of your attributes -->
</
style>

Note:
B)If you are using gradle , add appcompat as a dependency in your build.gradle file:
just paste the below code in dependency
dependencies {
    compile
"com.android.support:appcompat-v7:21.0.+"
}
 C) Now you can remove all other actionbar styles.

2)Apply themes using new color palette attributes:
Checkout the new colors added in Android 5.0 Lollipop


D)Copy the code the themes,xml in values folder.
<!-- colorAccent is used as the default value for colorControlActivated,
         which is used to tint widgets -->
    <item name=”colorAccent”>@color/
accent</item>

    <!-- You can also set colorControlNormal, colorControlActivated
         colorControlHighlight, and colorSwitchThumbNormal. -->


In the next post we will look at how to create a Actionbar from scratch using the latest Material Design.

We would ask you to try this things and comments if you face with some problems,
Please like and share with other dev who are willings to try this out too!

Happy developing!Happy Coding!


Working with Android Actionbarcompact basics


I strongly believe that you should use ActionBarCompat for all new projects that want to support older devices. It also might make sense to migrate existing projects. So read on to learn why you should migrate or use ActionBarCompat right away and how to migrate existing projects.


http://androidgreeve.blogspot.in/p/blog-page.html
Why you should prefer ActionBarCompat over ActionBarSherlock?
There are many reasons why you should prefer ActionbarCompat over ActionbarSherlock.
A.First of all this project is by Google, is part of the Support Library and thus likely will support new Action Bar related stuff at the same time Google releases them with stock Android.

B.Another good reason is that it supports the Navigation Drawer pattern right out of the box, while ActionBarSherlock does not. Thus if you want to add this drawer to an existing project/app you should migrate.

C.The last and Important  is, that the creator of ActionBarSherlock, Jake Wharton, announced on Google+ that further development of ActionBarSherlock has been stopped. ActionBarSherlock 4.4 is the last release and might get bug fixes – but there won’t be any new features:
 So if new functionality is included in actionbar you may not keepup to it  with actionbarsherlock.
He’s not too sad either  

Here is a list for the difference between the actionbarsherlock and actionbarcompact

 ActionBarSherlock vs ActionBarCompat **strong text**

I originally developed this project using Eclipse – which is why I occasionally refer to Eclipse specific shortcuts or why I include an Eclipse dialog later on. But the core of this post is independent of the IDE you want to use.

How to proceed?
In the next post i will take you through all the steps needed to get the project deployable again.
I start with the resources and deal with code changes later on. Android’s Development Tools only generate a new R.java file when the resources are error-free. And without a correct R file your Java sources won’t compile properly. Thus I prefer to fix resources first.