Saturday, 28 December 2013

Android Load Image From URL Faster

Hi!

In Android we hale lot of method to load image from url like Bitmap,etc..,

But if you wants to load image as faster please do this simple way..,

You may have the experience using UniversalImageLoader, i do the like. But different in logic,

Download this jar and add into your project than create an object  for the ImageLoader class and finally call the display method..,


//default image if image is not exit
int dummy_image = R.drawable.default_image;

//ImageView
ImageView imv_content;
imv_content = (ImageView) findViewById(R.id.imv_content);

// class call from the jar file
ImageLoader iml = new ImageLoader(getApplicationContext());

//Image Path
String url_image_path= "your image full path";

//Method to display the image
iml.DisplayImage(url_image_path, dummy_image, imv_content);


It will take minimal amount of time only when compare with other loading process..,

Thank You!

Please Leave Your Comment..,


Have A Happy Day..,


Sunday, 8 December 2013

GIF Animation in Android

Hi!

 It is to hard for doing animation in android, because we can't call directly any animations including .gif.

But we can over come it by using the fallowing way

Step-1

decompress your gif file as screens

Step-2

write an xml file for animating the gif screens like



<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:drawable="@drawable/g_gm_zero"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_one"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_two"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_three"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_four"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_five"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_six"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_seven"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_eight"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_nine"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_ten"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_eleven"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_twelve"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_thirteen"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_fourteen"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_fifteen"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_sixteen"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_seventeen"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_eighteen"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_nineteen"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_twenty"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_twenty_one"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_twenty_two"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_twenty_three"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_twenty_four"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_twenty_five"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_twenty_six"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_twenty_seven"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_twenty_eight"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_twenty_nine"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_thirty"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_thirty_one"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_thirty_two"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_thirty_three"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_thirty_four"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_thirty_five"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_thirty_six"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_thirty_seven"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_thirty_eight"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_thirty_nine"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_forty"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_forty_one"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_forty_two"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_forty_three"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_forty_four"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_forty_five"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_forty_six"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_forty_seven"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_forty_eight"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_forty_nine"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_fifty"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_fifty_one"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_fifty_two"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_fifty_three"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_fifty_four"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_fifty_five"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_fifty_six"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_fifty_seven"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_fifty_eight"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_fifty_nine"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_sixty"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_sixty_one"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_sixty_two"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_sixty_three"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_sixty_four"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_sixty_five"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_sixty_six"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_sixty_seven"
        android:duration="100"/>
    <item
        android:drawable="@drawable/g_gm_sixty_eight"
        android:duration="100"/>

</animation-list>



Step-3

    write your activity class for load and run the animation,


  • crate an object for AnimationDrawable class,
  • Apply the animation on your components (here i am using ImageButton),
  • Start & stop the animation depends on windows focusing action (because if not on windowsfocus listener the animation will affect the processor speed)
Activity class

package dcs.raj.entertainment;

import dcs.raj.restaurant.R;
import android.os.Bundle;
import android.widget.ImageButton;
import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;

public class Entertainment extends Activity {

private ImageButton img_btn_game;

private AnimationDrawable frm_ani_game;



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entertainment);
initSelva();
}

public void initSelva() {

img_btn_game = (ImageButton) findViewById(R.id.entern_game);
img_btn_game.setBackgroundResource(R.drawable.a_game);
frm_ani_game = (AnimationDrawable) img_btn_game.getBackground();
}

@Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
frm_ani_game.start();

} else {
frm_ani_game.stop();
}
}

@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
}


Thank you!


Please Leave Your Comment..,


Have A Happy Day..,

Friday, 25 October 2013

Simple Spinner with Dynamic Data

Hi!


   Some time we may facing problem to load the dynamic data on android spinners.

I give you a very simple way to load the spinner with dynamic data by using normal ArrayAdapter<String>.

Create a Spinner on your xml file


  • For Static Data:



if you wants using static data you can use the  android:entries
and cal the array data from your string.xml like,


<string-array name="project">
Select
<item>Project_100</item>
<item>Project_101</item>
    </string-array>



<Spinner
            android:id="@+id/spinner1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:entries="@array/project" />


  • For Dynamic Data:



if you wants to load the data dynamically fallow the code below,

Call the spinner normally in your xml


<Spinner
            android:id="@+id/spinner2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />




  1. In your Activity class declare an ArrayAdapter<String> for custom spinner,
  2. Create a List<String> for keep your date as list,
  3. Set the List on your ArrayAdapter<String>,
  4. set the Adapter on your Spinner
package dcs.raj.timesheet;

import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.app.Activity;

public class EditTimeSheet extends Activity {

Spinner pjt_spnr;
ArrayAdapter<String> pjt_sp_adoptr;
List<String> pjt_sp_list;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_time_sheet);

pjt_sp_list = new ArrayList<String>();
pjt_sp_list.add("Project_1");
pjt_sp_list.add("Project_2");
pjt_sp_list.add("Project_3");
pjt_sp_list.add("Project_4");
pjt_sp_list.add("Project_5");
pjt_spnr = (Spinner) findViewById(R.id.spinner2);
pjt_sp_adoptr = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_item, pjt_sp_list);
pjt_sp_adoptr
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
pjt_spnr.setAdapter(pjt_sp_adoptr);
}

}

Thats All..,

Thank You!


Please Leave Your Comment..,




Custom Tab Background Image

Hi!



          Just i am going to show a simple task how to change the background of Tab in android.


Create Your normal xml file for TabHost


<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />
    </LinearLayout>

</TabHost>



  • create different images / background for on mouse over, click & normal and save it on drawable folder.
  • write selector for on click by using those images,




<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/tab_bl_cent" android:state_pressed="true"></item>
    <item android:drawable="@drawable/tab_wt_cntr" android:state_focused="true"></item>
    <item android:drawable="@drawable/tab_wt_cntr"></item>

</selector>




  • In your main activity class extend by using TabActivity, Then write your normal activity code 
  • Call the child position and set the background for it by using your selector of xml




package dcs.raj.timesheet;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

@SuppressWarnings("deprecation")
public class Main_Tab extends TabActivity {

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main__tab);
// Show the Up button in the action bar.
TabHost thst = getTabHost();

TabSpec ts_project = thst.newTabSpec("Project");
ts_project.setIndicator("Project",getResources().getDrawable(R.drawable.ic_launcher));
Intent i_project = new Intent(this, Project.class);
ts_project.setContent(i_project);

TabSpec ts_Edit_ts = thst.newTabSpec("Edit Time Sheet");
ts_Edit_ts.setIndicator("Edit Time Sheet",getResources().getDrawable(R.drawable.ic_launcher));
Intent i_Time_sheet = new Intent(this, EditTimeSheet.class);
ts_Edit_ts.setContent(i_Time_sheet);

TabSpec ts_Time_sheet = thst.newTabSpec("View Time Sheet");
ts_Time_sheet.setIndicator("View Time Sheet", getResources().getDrawable(R.drawable.ic_launcher));
Intent i_Edit_ts = new Intent(this, ViewTimeSheet.class);
ts_Time_sheet.setContent(i_Edit_ts);

thst.addTab(ts_project);
thst.addTab(ts_Edit_ts);
thst.addTab(ts_Time_sheet);

thst.getTabWidget().getChildAt(0)
.setBackgroundResource(R.drawable.tab_center_selector);
thst.getTabWidget().getChildAt(1)
.setBackgroundResource(R.drawable.tab_center_selector);
thst.getTabWidget().getChildAt(2)
.setBackgroundResource(R.drawable.tab_center_selector);
}

}


Now you can check with your device..,


Thank You!




Wednesday, 23 October 2013

WebView

Hi!

     We can write both Android Standalone & Web applications,in this blogger i am going to explain about the web application only especially by calling the URL directly.

There are two ways to create the web application in android

  1. Directly Call the URL By using WebView ,
  2. By using HTML5, PhoneGap we can create the Web Applications.


In android we are using WebView to make executable Android application for our websites.

It is very simple to do it.


  • Create an Object for WebView,
  • Assign setting for like JavaScript Enable,Zooming Controlling  ,etc..,
  • load your url to WebView object
  • keep to manage the history if their is any previous page,
  • in your XML create the WebView,

Java Code:

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class Pets extends Activity {
WebView webview;

@SuppressLint("SetJavaScriptEnabled")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
Window.PROGRESS_VISIBILITY_ON);
webview = new WebView(this);
setContentView(webview);
setProgressBarVisibility(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setBuiltInZoomControls(true);
webview.getSettings().setUseWideViewPort(true);
webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
final Activity activity = this;
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setProgress(progress * 100);
}
});

webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Toast.makeText(activity, "Oh no! " + description,
Toast.LENGTH_SHORT).show();
}
});
webview.loadUrl("http://petsfacebook.in/index.php");
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webview.canGoBack() == true) {
webview.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}


XML Code:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".Pets" >

    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

 In Your Android Manifest don't forget to give permission for Internet connection "android.permission.INTERNET"



Thank You!

Generate the Google Map API key for Release Too

Hi!


       Some of us facing problem to receive the Google map API key for accessing the Google map in Android.

I have explain below in step by step for Windows users!


  1. we have to generate the Google API Account,
  2. In "Services" have to switch on the Google Maps Android API v2
  3. Create a Client ID for installed applications 
  4. While try to create an Android Key for API Project it will ask SHA1 (Fingerprint),
    Do same as what i am going to do for receiving the Finger Print

Method - 1
  • Open Your Debug Key Store From Eclipse >> Windows >> Preferences >> Android >> Build >> (Copy Your) Default Debug Key Store
  • Open Your keytool path from "C:\Program Files\Java\jdk1.6.0_23\bin\keytool.exe"
  • Open Your Windows (Console) CMD.exe
  • Now place the below formate to get your Fingerprint 
C:\Users\Administrator>"Your keytool path" -list -v -alias androiddebugkey -keystore "Your Debug Key Store" -storepass android -keypass android

ex:

C:\Users\Administrator>"C:\Program Files\Java\jdk1.6.0_23\bin\keytool.exe" -list
 -v -alias androiddebugkey -keystore "C:\Users\Administrator\.android\debug.keys
tore" -storepass android -keypass android

now you will receive your Unique Fingerprint like

Certificate fingerprints:

MD5 : 00:00:0:00:00:00:00:00:00:00:00:00:00:00:00:00         SHA1: 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00
Signature algorithm name: SHA1withRSA

Method - 2

The another one method is

Step -1

open this java path in your console / cmd (should mention your java version correctly)
C:\Program Files\Java\jdk1.6.0_43\bin>
press enter
Step - 2

the andindir is your local dir / folder name , copy and past the below code and press enter

keytool -list -v -keystore C:\Users\andindir\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android

Process - II - (Release Key)

Step -1

open this java path in your console / cmd (should mention your java version correctly)
C:\Program Files\Java\jdk1.6.0_43\bin>
press enter
Step - 2

the andindir is your local xxxxx.jks located path name & xyxyxyxy is your alias, copy and past the below code and press enter

keytool -list -v -keystore C:\ andindir \xxxxx.jks -alias xyxyxyxy

eg: (C:\Program Files\Java\jdk1.8.0_40\bin>keytool -list -v -keystore D:\Android_Raj_
xxxx\SW\Raj_xxx\xxx_Xxxxxxx\xxxxxxx.jks -alias xyxyxyxy
Enter keystore password:
)


Now You can get your Unique API key by placing the Fingerprint..,


Thank You!





Thursday, 22 August 2013

How To Use startActivityForResult()

Hi!

     Today in this blog i have explain about the difference between startActivity & startActivityForResult()..,

Activity;


    in android activity means an action / screen, when we wants to move to next action / screen we are using startActivity() menthod.

The startActivity() is not only used for migration and it also can carry data within..,



Intent intent = new Intent(1stActivity.this, 2ndActivity.class);
//here putExtra() method is used for carry some data
intent.putExtra("data_name", actual_data);
startActivity(intent);


Now directly we can forward the data from one activity to another activity.


But if you wants to redirect to the 1st activity from the 2nd activity with data of 2nd activity we can use number of technology in Android like

  • Preference,
  • with the help of Bean,
  • startActivityForResult()
  • & etc..,



The Best & Simple way is to use startActivityForResult() method

Step-1 :

(In your 1st Activity class)
Use the syntax below When you want to move from the 1st Activity to the 2nd Activity

 use startActivityForResult() instead of using startActivity()


Intent intent= new Intent(1stActivity.this, 2ndActivity.class);
startActivityForResult(intent, 1);

//here we are passing two arguments the 1st one is Intent & the 2nd one is integer value for specification.


Step-2 :

(In your 2nd Activity class)

Use the Syntax below When you want to pass your data to the 1st Activity from the 2nd Activity


Intent i=new Intent();
i.putExtra("data_name",actual_data);
setResult(1, i);
//here we are passing two arguments the 1st one is Intent & the 2nd one is integer value for specification.
finish();

Step-3 :

(In your 1st Activity class)

// override the onActivityResult() method

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
super.onActivityResult(requestCode, resultCode, data);
//check with the int code specification 
//(in above activity we are using the integer value of "1")
if (requestCode == 1) 
{
if (null != data) 
  {
String lst_of_sr = data.getStringExtra("data_name");
Toast.makeText(getApplicationContext(), lst_of_sr  Toast.LENGTH_LONG).show();
  }
}
}


To Transfer Object Between Activities!



// Custom Been Class

public class List_Of_List_B implements Serializable {

    String food;

    public List_Of_List_B() {
    }

    public List_Of_List_B(String food) {
        this.food = food;
    }

    public String getFood() {
        return food;
    }

    public void setFood(String food) {
        this.food = food;
    }
}

// Array list for Custom Class

ArrayList<List_Of_List_B> sing_mod = new ArrayList<List_Of_List_B>();
sing_mod.add(new List_Of_List_B("Conversion van"));
sing_mod.add(new List_Of_List_B("Cutaway van chassis"));
sing_mod.add(new List_Of_List_B("Mail order"));
sing_mod.add(new List_Of_List_B("Multi-stop truck"));
sing_mod.add(new List_Of_List_B("Cargo"));

// From 1st Activity

Intent int_po_trkr = new Intent(PurchaseOrder.this, List_Of_List.class);
int_po_trkr.putExtra("commom_list", sing_mod);
startActivityForResult(int_po_trkr, 1);


// On Second Activity 

ArrayList<List_Of_List_B> temp_list= (ArrayList<List_Of_List_B>) getIntent().getSerializableExtra("commom_list");


Thats All..,

 now you can back to the 1st activity with the data of 2nd activity.

Thank you..,

Please Leave Your Comment..,


 Have A Happy Day..,




Saturday, 17 August 2013

JSONParser for Request & Response


Hi!

   I show you "How to handle the Request & Response for data transfer through JSON".


The JSON:

  • JSON is one of the Fastest way to transfer data, when compare with XML,
  • We can transfer even large amount of data through JSON.
  • Data type should be any one of the fallow double,boolean,Array,String,Object & null.
  • JSON mostly support for all languages.
I show you blow how to handle the Request & Response through JSON.


package dcs.raj.mylist;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;

public class JSONParser {

    // Declare InputStream for handle input & String for return the result
static InputStream ips = null;
static String jsn_rtn = "";

// empty constructor is necessary
public JSONParser() {

}
// create a method for input arguments "url & type & values"
public String GenrtHttpRequest(String url, String method,
List<NameValuePair> params) {
try {
// if the method is post
if (method == "POST") {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
ips = httpEntity.getContent();


// if the method is get

else if (method == "GET") {
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
ips = httpEntity.getContent();
}

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(ips, "iso-8859-1"), 8);
//use StringBuilder to concordinate the String values
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
ips.close();
jsn_rtn = sb.toString();
} catch (Exception e) {
e.getMessage();
}
// return the final result values
return jsn_rtn;
}
}


How To Handle It!


JSONParser jsonParser = new JSONParser();

This is the part of code for AsyncTask class


protected String doInBackground(String... args) {

List<NameValuePair> parameter = new ArrayList<NameValuePair>();

 parameter .add(new BasicNameValuePair("name", username));
 parameter .add(new BasicNameValuePair("id", user_id));

String json = jsonParser.GenrtHttpRequest(URL_User,"GET", parameter);

Log.d("Use_Info", json);

try {
JSONObject jObj = new JSONObject(json);
if(jObj != null){
UserName= jObj.getString(UserName);
}

} catch (JSONException e) {
e.printStackTrace();
}

return null;
}

Notes : 


On update of Android API 23 the Apache plugin was Deprecated, we should update the fallowing line into build.gradle file.

android {
             ....
             ....
             useLibrary 'org.apache.http.legacy'
             ... 
                }

   
You can download the ready made jar fie for the above class.

Thank You!

Please Leave Your Comment..,



Have A happy Day..,

Wednesday, 7 August 2013

How to Check Internet Connection in Android

How to Check Internet Connection in Android


Hi!


  Some of new android programmers facing the one of the problem to check the internet connectivity.

You can Download my jar at Here and can add into your project

or

 I have write the blow  class for to check the internet connection.




package ra_jEmail_Mob_Validation;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class RCheckInternet {

boolean is_Rconnected=true;
private int TYPE_WIFI=1,TYPE_MOBILE = 2,TYPE_NOT_CONNECTED = 0;

private int isInternetAvailabl(Context context) {
ConnectivityManager cm=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf=cm.getActiveNetworkInfo();
if (null != nf) {
            if(nf.getType() == ConnectivityManager.TYPE_WIFI)
                return TYPE_WIFI;
           
            if(nf.getType() == ConnectivityManager.TYPE_MOBILE)
                return TYPE_MOBILE;
        }
        return TYPE_NOT_CONNECTED;
}

public boolean is_Rconnected(Context context) {
int conn = isInternetAvailabl(context);
if (conn == TYPE_NOT_CONNECTED)
{
is_Rconnected=false;
        }
return is_Rconnected;
}
}




it is enough to pass the application context & you will receive the status of the current connection



public class Main extends Activity implements OnClickListener{

Button lin,regs;
Login_Emenu_Manager lgMan;
EditText un,pw;
boolean log_chk = false;
String url_lin="http:my link to pass the variables";//?Email,Password
public ProgressDialog pDialog;

// create reference for the class

RCheckInternet r_nw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
lgMan = new Login_Emenu_Manager(getApplicationContext());

// create an object for the class
r_nw=new RCheckInternet();
lin.setOnClickListener(this);
regs.setOnClickListener(this);
}
public void init()
{
lin=(Button) findViewById(R.id.bn_login);
regs=(Button) findViewById(R.id.bnreg);
un=(EditText) findViewById(R.id.r_email);
pw=(EditText) findViewById(R.id.r_pass);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.bn_login:
if(!un.getText().toString().equals(""))
{
if(!pw.getText().toString().equals(""))
{
//pass the context of the current class to check the internet status
if(r_nw.is_Rconnected(getApplicationContext()))
{
new MainAsy().execute();
}
else
{
Toast.makeText(getApplicationContext(), "Not connected to Internet", Toast.LENGTH_SHORT).show();
}

}
else
{
pw.setError(Html.fromHtml("<font color='green'>Enter Valid Password</font>"));
}
}
else
{
un.setError(Html.fromHtml("<font color='green'>Enter Valid UserName</font>"));
}
break;
case R.id.bnreg:
Intent ii=new Intent(this,Register.class);
startActivity(ii);
break;
}
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
finish();
super.onBackPressed();
}
class MainAsy extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(Main.this);
pDialog.setMessage("LOGIN..,");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}

@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
List<NameValuePair> sv_param = new ArrayList<NameValuePair>();
JSONParser sv_jparse = new JSONParser();
sv_param.add(new BasicNameValuePair("Email", un.getText().toString()));
Log.d("un.getText().toString()", un.getText().toString());
sv_param.add(new BasicNameValuePair("Password", pw.getText().toString()));
Log.d("pw.getText().toString()", pw.getText().toString());
String sv_json = sv_jparse.makeHttpRequest(url_lin, "GET", sv_param);
Log.d("sv_json", sv_json);
try {
JSONObject sv_jobj = new JSONObject(sv_json);
if (sv_jobj != null) {
String user_key=sv_jobj.getString("UserID");
log_chk=true;
lgMan.createSession(un.getText().toString(), pw.getText().toString(), user_key);
Intent i=new Intent(Main.this,HomeActivity.class);
startActivity(i);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pDialog.dismiss();
if(!log_chk)
{
AlertDialog.Builder ad= new AlertDialog.Builder(new ContextThemeWrapper(Main.this, R.style.popup_theme));
ad.setTitle("Login Failed");
ad.setMessage("Please Check Your Entry..,");
ad.setInverseBackgroundForced(false);
ad.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
un.setText("");
pw.setText("");
}
});
ad.show();
}
}
}




Now you can easily check the internet status by my above class..,


Thank You!

Please Leave Your Comment..,


Have A Happy Day..,