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..,

Friday, 2 August 2013

Android E-Mail & Mobile Number Validation

Hi!


  Today i am going to show How to validate e-mail id & mobile number in android. Because some struggle with validation as specially for e-mail..,

   Validation of email id & Mobile number in android is similar to validation in java.


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

or


  •     create a bean class to  forward your input to validate


package ra_jEmail_Mob_Validation;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RValidation {
String r_email, r_mobil_no;
boolean is_mob_number = false, is_email = false;

        //this is the default format for email validation 

String regEx = "[a-zA-Z0-9+._%-+]{1,256}" + "@"
+ "[a-zA-Z0-9][a-zA-Z0-9-]{0,64}" + "(" + "."
+ "[a-zA-Z0-9][a-zA-Z0-9-]{0,25}" + ")+";

// empty constructor for call the object

public RValidation() {
super();
}

// create getter & setter for parameters 

public String getR_email() {
return r_email;
}

public void setR_email(String raj_email) {
this.r_email = raj_email;
}

public String getR_mobil_no() {
return r_mobil_no;
}

public void setR_mobil_no(String raj_mobil_no) {
this.r_mobil_no = raj_mobil_no;
}

//method to validate you mobile number, if it is valid it will return true
public boolean isIs_mob_number() {
// mobile number should be 10 digit
Pattern pattern = Pattern.compile("\\d{10}");
Matcher matchr = pattern.matcher(this.getR_mobil_no().trim());
if (matchr.matches()) {
is_mob_number = true;
}
return is_mob_number;
}

// method to validate you e-mail id, if it is valid it will return true
public boolean isIs_email() {
Matcher matcherObj = Pattern.compile(regEx).matcher(
this.getR_email().trim());
if (matcherObj.matches()) {
is_email = true;
}
return is_email;
}

}



  • Here Pass the value for validation from your Action class by on click listener
public class Register extends Activity {


EditText et_r_name,et_r_mob,et_r_email,r_pass;
//create reference for our class
RValidation r_valid;
boolean sucess_regist=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Button reg=(Button) findViewById(R.id.r_regist);
et_r_name=(EditText) findViewById(R.id.r_name);
et_r_mob=(EditText) findViewById(R.id.r_mob);
et_r_email=(EditText) findViewById(R.id.r_email);
r_pass=(EditText) findViewById(R.id.r_pass);

// create a new object for our reference

r_valid=new RValidation();

reg.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!et_r_name.getText().toString().equals(""))
{
// pass the mobile number to through our setter methid
r_valid.setR_mobil_no(et_r_mob.getText().toString());
// if it is true move to next step
if(r_valid.isIs_mob_number())
{
//pass the e-mile id to through our setter methid
r_valid.setR_email(et_r_email.getText().toString());
//if it is true move to next step
if(r_valid.isIs_email())
{
if(!r_pass.getText().toString().equals(""))
{
AlertDialog.Builder ad= new AlertDialog.Builder(new ContextThemeWrapper(Register.this, R.style.popup_theme));
ad.setTitle("Success");
ad.setMessage("You Have Login Successfully..,");
ad.setInverseBackgroundForced(false);
ad.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

}
});  
a ad.show();
}
else
{
r_pass.setError(Html.fromHtml("<font color='green'>Enter Your Password</font>"));
}
}
else
{
et_r_email.setError(Html.fromHtml("<font color='green'>Enter Your Valid E-mail address</font>"));
}
}
else
{
et_r_mob.setError(Html.fromHtml("<font color='green'>Mobile Number Should Be 10 Digit</font>"));
}
}
else
{
et_r_name.setError(Html.fromHtml("<font color='green'>Enter Your Name</font>"));
//
}
}
});
}
}


finally i have set some error messages and add some html tag for my customization..,

Thank You..,

Please Leave Your Comment..,



Have A Happy Day..,

Custom Horizontal(ListView) Dynamic TextView Without using Adopter & with On Click function

Hi!

   I was faced a problem to generate dynamic horizontal list view in fragment.I search the help with Google too. But their is no more help to fulfill my need.

The Problems are :

  • Their is no default horizontal list view in Android (the default list view is vertical),
  • Even though we implement the customize Horizontal list view, It is too heard to implementing with Fragment,
  • Implementing the "on click" Listener on the dynamic items too.
I try and found the solution for the problem and happy to share with developers.

ArrayList for my business class


ArrayList<CatagoryB> clist;

return the view for the list and execute the Async class

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_list_of_category,container);
clist = new ArrayList<CatagoryB>();
new CatagoryList().execute();

return view;
}

store the list item into the array list

clist.add(new CatagoryB(lcid, lcname));


initialize the dynamic text view 

final TextView myid[] = new TextView[clist.size()];
final TextView mynm[] = new TextView[clist.size()];

initialize the layout too

LinearLayout lout = (LinearLayout) getActivity().findViewById(
R.id.catlout);

create dynamic object for the textview

myid[i] = new TextView(getActivity());
mynm[i] = new TextView(getActivity());

set it on layout 

myid[i].setLayoutParams(new LayoutParams(0, 0));

assign the parameters

myid[i].setText(clist.get(i).getCid());
mynm[i].setText(clist.get(i).getCname());

assign the id

mynm[i].setId(i);
myid[i].setId(i);
set onclick listener

mynm[i].setOnClickListener(new OnClickListener()

can get the relevent item by id

int iid = v.getId();
String actual_id = clist.get(iid).getCid();

Here is over view of my code


//@SuppressLint("NewApi")
@SuppressLint("ResourceAsColor")
public class CategoryList extends Fragment {

private CategoryToSubCategory connecter;
String Cat_Url = "onsite link for your database query";
ArrayList<CatagoryB> clist;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_list_of_category,
container);
clist = new ArrayList<CatagoryB>();
new CatagoryList().execute();
return view;
}

public interface CategoryToSubCategory {
public void List_SubCategory(int item);
}

@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
if (activity instanceof CategoryToSubCategory) {
connecter = (CategoryToSubCategory) activity;
} else {
throw new ClassCastException();
}
}

class CatagoryList extends AsyncTask<String, String, String> {

@Override
protected String doInBackground(String... arg0) {
JSONParser jparse = new JSONParser();
List<NameValuePair> pair = new ArrayList<NameValuePair>();
String JSon = jparse.makeHttpRequest(Cat_Url, "GET", pair);
try {
JSONArray jaray = new JSONArray(JSon);
if (jaray != null) {
Log.d("JSon", JSon);
for (int i = 0; i < jaray.length(); i++) {
JSONObject j = jaray.getJSONObject(i);
String lcid = j.getString("categorykey");
String lcname = j.getString("stockcategoryname");
clist.add(new CatagoryB(lcid, lcname));
}
}

} catch (Exception e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
final TextView myid[] = new TextView[clist.size()];
final TextView mynm[] = new TextView[clist.size()];
LinearLayout lout = (LinearLayout) getActivity().findViewById(
R.id.catlout);
for (int i = 0; i < clist.size(); i++) {
myid[i] = new TextView(getActivity());
mynm[i] = new TextView(getActivity());
myid[i].setLayoutParams(new LayoutParams(0, 0));
mynm[i].setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
myid[i].setTextSize(30);
mynm[i].setTextSize(30);
mynm[i].setPadding(5, 1, 5, 1);
myid[i].setTextColor(Color.WHITE);
mynm[i].setBackgroundResource(R.drawable.b);
mynm[i].setTextColor(Color.WHITE);
myid[i].setText(clist.get(i).getCid());
mynm[i].setId(i);
myid[i].setId(i);
mynm[i].setText(clist.get(i).getCname());
lout.addView(myid[i]);
lout.addView(mynm[i]);
mynm[i].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int iid = v.getId();
String actual_id = clist.get(iid).getCid();
 connecter.List_SubCategory(Integer.valueOf(actual_id));
}
});
}
}

}
}


Layout xml file for the Layout


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:widget="http://schemas.android.com/apk/res-auto"
    android:id="@+id/LinearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <HorizontalScrollView
        android:id="@+id/horizontalScrollView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/hesdbg" >

        <LinearLayout
            android:id="@+id/catlout"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_gravity="center"
            android:orientation="horizontal" >
        </LinearLayout>
    </HorizontalScrollView>

</LinearLayout>



Please Leave Your Comment..,