Friday, 10 April 2015

Android AsyncTask

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask's generic types


The three types used by an asynchronous task are the following:
  1. Params, the type of the parameters sent to the task upon execution.(Which we passing into  doInBackground(Object[])
  2. Progress, the type of the progress units published during the background computation.
  3. Result, the type of the result of the background computation.


package com.example.mysmpleappforasync;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.util.Log;

public class MyAsync extends AsyncTask<String, Void, Object>{

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

@Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.e("onCancelled obj", "onCancelled"+result);

}

@Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}

@SuppressLint("NewApi") @Override
protected void onCancelled(Object result) {
// TODO Auto-generated method stub
super.onCancelled(result);
Log.e("onCancelled obj", "onCancelled"+result);
}

@Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
Log.e("onCancelled", "onCancelled");

}

@Override
protected Object doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient hc=new DefaultHttpClient();
HttpPost request=new HttpPost("http://www.mena-properties.com/mena_app/mobilemanager/getRows");
String json="";
JSONObject jobj=new JSONObject();
try {
jobj.accumulate("param","photos");
jobj.accumulate("start", 0);
jobj.accumulate("noofrows", 10);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
json=jobj.toString();
try {
StringEntity se=new StringEntity(json);
request.setEntity(se);
request.setHeader("Accept", "json/application");
request.setHeader("Content-type", "json/application");
try {
HttpResponse res=hc.execute(request);
String jsonResponse = EntityUtils.toString(res.getEntity());
           JSONObject jsobj=new JSONObject(jsonResponse);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

}

Sunday, 7 December 2014

Json Parsing in android


Here I am trying to implement jsonParsing in a Simple way using AsynTask


package com.technomobs.backdoing;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.technomobs.Interfacez.NewsLoadingCompleteInterface;
import com.technomobs.Interfacez.PhotoLoadingCompleteInterface;
import com.technomobs.Interfacez.VideoLoadingComplateInterface;
import com.technomobs.Models.HomePageModel;
import com.technomobs.Utils.Constantz;
import com.technomobs.menaproperties.R;

public class TestimonilLoading extends AsyncTask<String, Void, Object> {
ProgressDialog dialog;
ArrayList<HomePageModel> ArrhomePageModel;
ArrayList<HomePageModel> ArrhomePageModelsnd;
ArrayList<HomePageModel> ArrhomePageModelFinal;

private String errorMessage=null;
private Context context;
JSONArray jsonArraydata; String result;
JSONArray jsonArrayres;
VideoLoadingComplateInterface callback;
HomePageModel homePageModel;
JSONObject jsobj;
JSONObject jsonObject ;
boolean needloading;
public TestimonilLoading(Context context, VideoLoadingComplateInterface promo) {
this.callback=promo;
this.context=context;

Log.e("inside","gallery");
// TODO Auto-generated constructor stub
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
this.dialog=ProgressDialog.show(context, "", "");
this.dialog.setContentView(R.layout.custom_progressbarlayout);
// this.dialog.setMessage("Please wait..");
    this.dialog.show();
 
    this.dialog.setCancelable(false);


}
@Override
protected Object doInBackground(String... params) {

ArrhomePageModelFinal=new ArrayList<HomePageModel>();


    //First time start 0 else:10


 
    Log.e("inside", "First");
//    
try{

HttpClient clientTech = new DefaultHttpClient();
HttpPost request = new HttpPost(Constantz.getRows);




   String json = "";
  // Log.e("inside", "json"+params[0]+params[1]+params[2]+params[3]);
   // 3. build jsonObject
   if(params[0].equalsIgnoreCase("First")){
    Log.e("1nd", "1nd");
    jsonObject = new JSONObject();
   jsonObject.accumulate("param", params[1]);
   jsonObject.accumulate("start", 0);
   jsonObject.accumulate("noofrows", 10);



   }//first
   
   else{
    Log.e("2nd", "2nd");
    //2nd time start: from saved data, else:10
    jsonObject = new JSONObject();
    jsonObject.accumulate("param", params[1]);
   jsonObject.accumulate("start",  params[2]);
   jsonObject.accumulate("noofrows", 10);
 
   }
   // 4. convert JSONObject to JSON to String
   json = jsonObject.toString();
 
   Log.e("inside", "json"+json);
 
// 5. set json to StringEntity
   StringEntity se = new StringEntity(json);
   Log.e("inside", "se"+se);
// 6. set httpPost Entity
   request.setEntity(se);
   // 7. Set some headers to inform server about the type of the content
   request.setHeader("Accept", "application/json");
   request.setHeader("Content-type", "application/json");
 
// request.setEntity(new StringEntity(toPass) );
HttpResponse responseTech = clientTech.execute(request);

Log.e("test","Login:"+responseTech);
String jsonResponse = EntityUtils.toString(responseTech.getEntity());

Log.e("jsonResponse","jsonResponse:"+jsonResponse);
JSONObject reader = new JSONObject(jsonResponse);
Log.e("reader","reader:"+reader);
JSONObject sys  = reader.getJSONObject("response");
Log.e("response","response:"+sys);
jsonArraydata=sys.getJSONArray("data");

ArrhomePageModel=new ArrayList<HomePageModel>();
   if(params[0].equalsIgnoreCase("First")){
   
    Log.e("First", "First");
    needloading=true;
for(int i=0;i<jsonArraydata.length();i++)
{
jsobj=jsonArraydata.getJSONObject(i);
homePageModel=new HomePageModel();
homePageModel.id=jsobj.optString("id");
homePageModel.date_added=jsobj.optString("date_added");
homePageModel.agent=jsobj.optString("agent");
homePageModel.testi=jsobj.optString("testi");
homePageModel.name=jsobj.optString("name");
homePageModel.company=jsobj.optString("company");



ArrhomePageModel.add(homePageModel);


}//for
//
//jsonArrayres reading
   }
   //2nd time
   else{
Log.e("2nd","2nd:");

    ArrhomePageModelsnd=new ArrayList<HomePageModel>();

for(int i=0;i<jsonArraydata.length();i++)
{
jsobj=jsonArraydata.getJSONObject(i);
homePageModel=new HomePageModel();
homePageModel.id=jsobj.optString("id");
homePageModel.date_added=jsobj.optString("date_added");
homePageModel.agent=jsobj.optString("agent");
homePageModel.testi=jsobj.optString("testi");
homePageModel.name=jsobj.optString("name");
homePageModel.company=jsobj.optString("company");



ArrhomePageModelsnd.add(homePageModel);

}//for
//
if(jsonArraydata.length()==0)
{
needloading=false;
Log.e("3needloading", "needloading"+needloading);
}
else{
needloading=true;
}
FileInputStream fis;
try {
fis = context.openFileInput(Constantz.MENA_DATA_OFF+params[1]);
ObjectInputStream is = new ObjectInputStream(fis);

ArrhomePageModel = (ArrayList<HomePageModel>) is.readObject();
Log.e("2nd","2nd:"+ArrhomePageModel.size());

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrhomePageModel.addAll(ArrhomePageModelsnd);
Log.e("2nd","2nd: 2nd"+ArrhomePageModel.size());

   }//else

 

   }//try
 catch (UnsupportedEncodingException exception) {
errorMessage = exception.getMessage();
} catch (ClientProtocolException e) {
errorMessage = e.getMessage();
// e.printStackTrace();
} catch (ConnectTimeoutException e) {
errorMessage = "Time Out!";
//e.printStackTrace();
} catch (UnknownHostException e) {
errorMessage = "No Connection Available!";
//e.printStackTrace();
} catch (Exception e) {
errorMessage = "No Connection Available!";
//e.printStackTrace();
}

if (errorMessage == null) {
Log.e("errorMessage", "errorMessage 7"+errorMessage);
try {
FileOutputStream fos;
fos = context.openFileOutput(Constantz.MENA_DATA_OFF+params[1], Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(ArrhomePageModel);
os.close();
} catch (FileNotFoundException e) {
errorMessage = e.getMessage();
} catch (IOException e) {
errorMessage = e.getMessage();
}
}
else
{
Log.e("param", "param 8");
FileInputStream fis;
try {
fis = context.openFileInput(Constantz.MENA_DATA_OFF+params[1]);
ObjectInputStream is = new ObjectInputStream(fis);

ArrhomePageModel = (ArrayList<HomePageModel>) is.readObject();
Log.e("ArrhomePageModel","ArrhomePageModel final:"+ArrhomePageModel.size());

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
return ArrhomePageModel;

}
@Override
protected void onPostExecute(Object result) {
if (dialog.isShowing()) {
          dialog.dismiss();
      }

callback.onVideoLoadingComplete(errorMessage, result,needloading);

}
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

package com.technomobs.backdoing;

import java.util.HashMap;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.technomobs.Interfacez.RegistrationCompleteInterface;
import com.technomobs.Interfacez.TestimonilCompleteInterface;
import com.technomobs.Utils.Constantz;

public class TestimonilFormSendingLoading extends AsyncTask<String, Void, String> {
ProgressDialog dialog;

//ArrayList<QuestModel> questions;
HashMap<String, String> promoHash;
private String errorMessage=null;
private Context context;
static JSONArray jsonArray; String result;
TestimonilCompleteInterface callback;
String MobileUserID;
public TestimonilFormSendingLoading(Context context, TestimonilCompleteInterface promo) {
this.callback=promo;
this.context=context;

Log.e("inside","gallery");
// TODO Auto-generated constructor stub
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog= new ProgressDialog(context);
this.dialog.setMessage("Please wait..");
    this.dialog.show();
    this.dialog.setCancelable(false);
    Log.e("inside", "gallery");


}
@Override
protected String doInBackground(String... params) {

http://www.mena-properties.com/mena_app/mobilemanager/uploadData/


try{

HttpClient httpclient  = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constantz.UpLoadData);

    String json = "";
   // Log.e("inside", "json"+params[0]+params[1]+params[2]+params[3]);
    // 3. build jsonObject
    JSONObject jsonObject = new JSONObject();
    jsonObject.accumulate("p", "addtestimonial");
    jsonObject.accumulate("TestimonialUserName", ""+params[0]);
    jsonObject.accumulate("TestimonialPlace", ""+params[1]);
    jsonObject.accumulate("TestimonialComments", ""+params[2]);
    // 4. convert JSONObject to JSON to String
    json = jsonObject.toString();
    StringEntity se = new StringEntity(json);
    httppost.setEntity(se);
    httppost.setHeader("Accept", "application/json");
    httppost.setHeader("Content-type", "application/json");
HttpResponse responseTech = httpclient.execute(httppost);
//    
String jsonResponse = EntityUtils.toString(responseTech.getEntity());

Log.e("test","Login:"+jsonResponse);
JSONObject jobj=new JSONObject(jsonResponse);

JSONObject jsonArray=jobj.getJSONObject("response");

result=jsonArray.optString("status");

       if(result.equalsIgnoreCase("success"))
       {
      result="Testimonials added successfully";
           errorMessage="" ;

       }
       else{
      result="No connection available";
      errorMessage="No connection available" ;
       }

}
catch(Exception e)
{
            errorMessage="No connection available" ;
        result="No connection available";

}







return result;

}
@Override
protected void onPostExecute(String result) {
if (dialog.isShowing()) {
          dialog.dismiss();
      }


callback.onTestimonilCompleteInterface(errorMessage, result);

}
}


Wednesday, 24 September 2014

How to Make Android Map Scrollable Inside a ScrollView Layout

package com.technomobs.Utils;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.google.android.gms.maps.SupportMapFragment;

public class MyMapFragment extends SupportMapFragment {
private OnTouchListener mListener;

    @Override
    public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle savedInstance) {
        View layout = super.onCreateView(layoutInflater, viewGroup, savedInstance);

        TouchableWrapper frameLayout = new TouchableWrapper(getActivity());

        frameLayout.setBackgroundColor(getResources().getColor(android.R.color.transparent));

        ((ViewGroup) layout).addView(frameLayout,
                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        return layout;
    }

    public void setListener(OnTouchListener listener) {
    mListener = listener;
    }

    public interface OnTouchListener {
    public abstract void onTouch();
    }

    public class TouchableWrapper extends FrameLayout {

      public TouchableWrapper(Context context) {
        super(context);
      }

      @Override
      public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
          case MotionEvent.ACTION_DOWN:
         mListener.onTouch();
                break;
          case MotionEvent.ACTION_UP:
         mListener.onTouch();
                break;
        }
        return super.dispatchTouchEvent(event);
      }
    }
}

...............................................

Then  create layout using following code


<?xml version="1.0" encoding="UTF-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/sv_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!-- other child views //-->
     <fragment
        android:tag="fragment_map"
       android:id="@+id/fragment_map"
       android:layout_width="match_parent"
       android:layout_height="175dp"
       android:layout_marginTop="@dimen/activity_horizontal_margin"
       class="com.technomobs.Utils.MyMapFragment"/>
</ScrollView>

.................................


Inside map activity that uses the map,



package com.technomobs.main;
import com.technomobs.Utils.MyMapFragment ;
import com.google.android.gms.maps.GoogleMap;
import android.widget.ScrollView;

public class MyMapActivty extends MapActivity {
    private ScrollView mScrollView;
    private GoogleMap mMap;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.fragment_my_map);

        mMap = ((MyMapFragment ) getSupportFragmentManager().findFragmentById(R.id.fragment_map)).getMap();
        mScrollView = (ScrollView) findViewById(R.id.sv_container);

       ((MyMapFragment ) getSupportFragmentManager().findFragmentById(R.id.fragment_map)).setListener(new WorkaroundMapFragment.OnTouchListener() {
          @Override
          public void onTouch() {
              mScrollView.requestDisallowInterceptTouchEvent(true);
          }
     });
   }
}

Sunday, 21 September 2014

Check EditText View Empty or Not in Android

public class Util
{


public static boolean isEmpty(EditText etText) {
   if (etText.getText().toString().trim().length() > 0) {
       return false;
   } else {
       return true;
   }
}


}


..........................


public class MainActivity
  extends Activity
{

EditText sample;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_createaccount);
sample=(EditText)findViewById(R.id.sample);
if(Util.emailValidator(sample)){
                                                // edittext box empty
                                                      }
                                                        else{



                                                         }

Hide Keyboard in android

public class Util
{


public static void onHideKeyboard(Activity context)
{
try{
InputMethodManager imm = (InputMethodManager) context
           .getSystemService(Context.INPUT_METHOD_SERVICE);

   if (imm.isAcceptingText()) {
     
    imm.hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(), 0);
   } else {
       //Log.e("Software Keyboard was not shown","no");
   }
}catch(Exception e)
{

}
}

}


..........................


Call in Activity

String name="abcd@gmail.com";

public class MainActivity
  extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_createaccount);


//Hide Keyboard in android
Util.onHideKeyboard(MainActivity.this);


}

}

email Validation in Android

public class Util
{


public static boolean emailValidator(String email)
{
   Pattern pattern;
   Matcher matcher;
   final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
   pattern = Pattern.compile(EMAIL_PATTERN);
   matcher = pattern.matcher(email);
   return matcher.matches();
}


}


..........................


Call in Activity

public class MainActivity
  extends Activity
{

String emailSample="abcd@gmail.com"
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
if(Util.emailValidator(emailSample)){
                                                // email format is correct
                                                      }
                                                        else{

                                                         }


}

}


Set Font in android

publi class Util{
public static void setFont(TextView textview, String font) {

Typeface myTypeface = Typeface.createFromAsset(textview.getContext().getAssets(), font);
textview.setTypeface(myTypeface);

}

}
........................................................

In side Activity Class the following code

put HelveticaNeue-Medium.ttf font type into assets

assets->create folder fonts ->HelveticaNeue-Medium.ttf


TextView name=(TextView)findViewById(R.id.name);
//set font
Util.setFont(name, "fonts/HelveticaNeue-Medium.ttf");