Thursday, 11 July 2013

imgldr


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Stack;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

public class ImageLoader {
   
    //the simplest in-memory cache implementation. This should be replaced with something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
    private HashMap<String, Bitmap> cache=new HashMap<String, Bitmap>();
   
    private File cacheDir;
   
    public ImageLoader(Context context){
    System.gc();
        //Make the background thead low priority. This way it will not affect the UI performance
        photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);
       
        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
          //  cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),".cusines");
        cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),".businessdirectory");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
        else{
        System.out.println("Reached inside clearing file");
        cacheDir.delete();
        System.gc();
        cacheDir.mkdirs();
        }
       
    }
   
    final int stub_id=com.reubro.businessdirectory.R.drawable.noimage;
    public void DisplayImage(String url, Activity activity, ImageView imageView)
    {
        if(cache.containsKey(url))
            imageView.setImageBitmap(cache.get(url));
        else
        {
            queuePhoto(url, activity, imageView);
            imageView.setImageResource(stub_id);
        }  
    }
       
    private void queuePhoto(String url, Activity activity, ImageView imageView)
    {
        //This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them.
        photosQueue.Clean(imageView);
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        synchronized(photosQueue.photosToLoad){
            photosQueue.photosToLoad.push(p);
            photosQueue.photosToLoad.notifyAll();
        }
       
        //start thread if it's not started yet
        if(photoLoaderThread.getState()==Thread.State.NEW)
            photoLoaderThread.start();
    }
   
    public Bitmap getBitmap(String url)
    {
        //I identify images by hashcode. Not a perfect solution, good for the demo.
        String filename=String.valueOf(url.hashCode());
        File f=new File(cacheDir, filename);
       
        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
            return b;
       
        //from web
        try {
            Bitmap bitmap=null;
         
            InputStream is=new URL(url).openStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap.recycle();
            System.gc();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
           ex.printStackTrace();
         
           return null;
        }
    }

    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);
           
            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=1;
            }
           
            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
          //  BitmapFactory.decodeStream
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }
   
    //Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i){
            url=u;
            imageView=i;
        }
    }
   
    PhotosQueue photosQueue=new PhotosQueue();
   
    public void stopThread()
    {
        photoLoaderThread.interrupt();
    }
   
    //stores list of photos to download
    class PhotosQueue
    {
        private Stack<PhotoToLoad> photosToLoad=new Stack<PhotoToLoad>();
       
        //removes all instances of this ImageView
        public void Clean(ImageView image)
        {
            for(int j=0 ;j<photosToLoad.size();){
                if(photosToLoad.get(j).imageView==image)
                    photosToLoad.remove(j);
                else
                    ++j;
            }
        }
    }
   
    class PhotosLoader extends Thread {
        public void run() {
            try {
                while(true)
                {
                    //thread waits until there are any images to load in the queue
                    if(photosQueue.photosToLoad.size()==0)
                        synchronized(photosQueue.photosToLoad){
                            photosQueue.photosToLoad.wait();
                        }
                    if(photosQueue.photosToLoad.size()!=0)
                    {
                        PhotoToLoad photoToLoad;
                        synchronized(photosQueue.photosToLoad){
                            photoToLoad=photosQueue.photosToLoad.pop();
                        }
                        Bitmap bmp=getBitmap(photoToLoad.url);
                        cache.put(photoToLoad.url, bmp);
                        Object tag=photoToLoad.imageView.getTag();
                        if(tag!=null && ((String)tag).equals(photoToLoad.url)){
                            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad.imageView);
                            Activity a=(Activity)photoToLoad.imageView.getContext();
                            a.runOnUiThread(bd);
                        }
                    }
                    if(Thread.interrupted())
                        break;
                }
            } catch (InterruptedException e) {
                //allow thread to exit
            }
        }
    }
   
    PhotosLoader photoLoaderThread=new PhotosLoader();
   
    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        ImageView imageView;
        public BitmapDisplayer(Bitmap b, ImageView i){bitmap=b;imageView=i;}
        public void run()
        {
            if(bitmap!=null)
                imageView.setImageBitmap(bitmap);
            else
                imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        //clear memory cache
        cache.clear();
       
        //clear SD cache
        File[] files=cacheDir.listFiles();
        for(File f:files)
            f.delete();
    }

}

Wednesday, 3 July 2013

listallclick

public class Recipelist extends Activity implements OnItemClickListener{

list.setOnItemClickListener(Recipelist.this);

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
System.out.println("pos clicked in recipe details===="+arg2);
Intent i=new Intent(Recipelist.this,Ingredient.class);
Bundle success=new Bundle();
success.putString("RECID",recId[arg2]);
success.putString("CATID",catId);
success.putString("RECTITLE",recTitle[arg2]);
success.putString("CATTITLE",catTitle);
i.putExtras(success);
startActivity(i);
}

public void goback(View v)
{

Intent i=new Intent(Recipelist.this,Rezepte.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}

public static class Utility {
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}

int totalHeight = 0;
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}

ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
}
public void onBackPressed(){

Intent i=new Intent(Recipelist.this,Rezepte.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}


bizadpt


package com.Adapter;


import com.reubro.businessdirectory.R;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CompanyListAdapter extends BaseAdapter {

private Activity activity;
private String[] data;
private String[] name;
private String[] number;
public ImageLoader imageLoader;

private static LayoutInflater inflater=null;

public CompanyListAdapter(Activity a, String[] d, String[] nameArray, String[] numberArray) {
activity = a;
data=d;
name=nameArray;
number=numberArray;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
        System.gc();
}
public int getCount() {
System.out.println();
return name.length;

}

public Object getItem(int position) {
return position;
}

public long getItemId(int position) {
return position;
}

public static class ViewHolder{
public TextView text1;
public TextView text2;
public ImageView image;
}  

public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.companylistdetails, null);
holder=new ViewHolder();
holder.text1 =(TextView)vi.findViewById(R.id.text1);
holder.text2 =(TextView)vi.findViewById(R.id.text2);
holder.image=(ImageView)vi.findViewById(R.id.image);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text1.setText(name[position]);
holder.text2.setText(number[position]);


holder.image.setTag(data[position]);

imageLoader.DisplayImage(data[position],activity, holder.image);
return vi;
}
}

util


package com.Adapter;

import java.io.InputStream;
import java.io.OutputStream;

public class Utils {
    public static void CopyStream(InputStream is, OutputStream os)
    {
        final int buffer_size=1024;
        try
        {
            byte[] bytes=new byte[buffer_size];
            for(;;)
            {
              int count=is.read(bytes, 0, buffer_size);
              if(count==-1)
                  break;
              os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }
}

imgldr


package com.Adapter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Stack;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

public class ImageLoader {
   
    //the simplest in-memory cache implementation. This should be replaced with something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
    private HashMap<String, Bitmap> cache=new HashMap<String, Bitmap>();
   
    private File cacheDir;
   
    public ImageLoader(Context context){
    System.gc();
        //Make the background thead low priority. This way it will not affect the UI performance
        photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);
       
        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
          //  cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),".cusines");
        cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),".businessdirectory");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
        else{
        System.out.println("Reached inside clearing file");
        cacheDir.delete();
        System.gc();
        cacheDir.mkdirs();
        }
       
    }
   
    final int stub_id=com.reubro.businessdirectory.R.drawable.noimage;
    public void DisplayImage(String url, Activity activity, ImageView imageView)
    {
        if(cache.containsKey(url))
            imageView.setImageBitmap(cache.get(url));
        else
        {
            queuePhoto(url, activity, imageView);
            imageView.setImageResource(stub_id);
        }  
    }
       
    private void queuePhoto(String url, Activity activity, ImageView imageView)
    {
        //This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them.
        photosQueue.Clean(imageView);
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        synchronized(photosQueue.photosToLoad){
            photosQueue.photosToLoad.push(p);
            photosQueue.photosToLoad.notifyAll();
        }
       
        //start thread if it's not started yet
        if(photoLoaderThread.getState()==Thread.State.NEW)
            photoLoaderThread.start();
    }
   
    public Bitmap getBitmap(String url)
    {
        //I identify images by hashcode. Not a perfect solution, good for the demo.
        String filename=String.valueOf(url.hashCode());
        File f=new File(cacheDir, filename);
       
        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
            return b;
       
        //from web
        try {
            Bitmap bitmap=null;
         
            InputStream is=new URL(url).openStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap.recycle();
            System.gc();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
           ex.printStackTrace();
         
           return null;
        }
    }

    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);
           
            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=1;
            }
           
            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
          //  BitmapFactory.decodeStream
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }
   
    //Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i){
            url=u;
            imageView=i;
        }
    }
   
    PhotosQueue photosQueue=new PhotosQueue();
   
    public void stopThread()
    {
        photoLoaderThread.interrupt();
    }
   
    //stores list of photos to download
    class PhotosQueue
    {
        private Stack<PhotoToLoad> photosToLoad=new Stack<PhotoToLoad>();
       
        //removes all instances of this ImageView
        public void Clean(ImageView image)
        {
            for(int j=0 ;j<photosToLoad.size();){
                if(photosToLoad.get(j).imageView==image)
                    photosToLoad.remove(j);
                else
                    ++j;
            }
        }
    }
   
    class PhotosLoader extends Thread {
        public void run() {
            try {
                while(true)
                {
                    //thread waits until there are any images to load in the queue
                    if(photosQueue.photosToLoad.size()==0)
                        synchronized(photosQueue.photosToLoad){
                            photosQueue.photosToLoad.wait();
                        }
                    if(photosQueue.photosToLoad.size()!=0)
                    {
                        PhotoToLoad photoToLoad;
                        synchronized(photosQueue.photosToLoad){
                            photoToLoad=photosQueue.photosToLoad.pop();
                        }
                        Bitmap bmp=getBitmap(photoToLoad.url);
                        cache.put(photoToLoad.url, bmp);
                        Object tag=photoToLoad.imageView.getTag();
                        if(tag!=null && ((String)tag).equals(photoToLoad.url)){
                            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad.imageView);
                            Activity a=(Activity)photoToLoad.imageView.getContext();
                            a.runOnUiThread(bd);
                        }
                    }
                    if(Thread.interrupted())
                        break;
                }
            } catch (InterruptedException e) {
                //allow thread to exit
            }
        }
    }
   
    PhotosLoader photoLoaderThread=new PhotosLoader();
   
    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        ImageView imageView;
        public BitmapDisplayer(Bitmap b, ImageView i){bitmap=b;imageView=i;}
        public void run()
        {
            if(bitmap!=null)
                imageView.setImageBitmap(bitmap);
            else
                imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        //clear memory cache
        cache.clear();
       
        //clear SD cache
        File[] files=cacheDir.listFiles();
        for(File f:files)
            f.delete();
    }

}

normal red2


public static String RecipeList(String catId) {
try {

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(postURL+"Recipelist/");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("category_id",catId));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
response = EntityUtils.toString(resEntity);
response = response.trim();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Recipe Response return back to calling ()" + response);
return response;
}


reddatabae 2

    public static String home(String udid) throws IllegalStateException, ClientProtocolException, IOException {

try{
HttpClient client = new DefaultHttpClient();
    //   String postURL = "http://192.168.0.43/portafare/apis/apps/v1.2/";
// String postURL = "http://50.56.207.251/portafare/apis/apps/v1.2/";
       HttpPost post = new HttpPost(postURL);
       post.setHeader("USER_UDID", udid);      
           List<NameValuePair> params = new ArrayList<NameValuePair>();
           str=jsonEncodinghome().toString();          
           //System.out.println("json="+str);
           params.add(new BasicNameValuePair("Data",str));    
           UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
           post.setEntity(ent);
           HttpResponse responsePOST = client.execute(post);            
           HttpEntity resEntity = responsePOST.getEntity();
           str=EntityUtils.toString(resEntity);
           str=str.trim();
           System.out.println("PARAM= " + params);
}
catch (Exception e) {
e.printStackTrace();
}
//System.out.println("json ================="+str);
System.out.println("home RESPONSE = " + str);
return str;
}
       public static JSONObject jsonEncodinghome(){

   /** Called when the activity is first created. */
JSONObject hobj=new JSONObject();  
       try{
       
             JSONArray argsArray = new JSONArray();
       
         hobj.put("argsArray", "");
         hobj.put("methodName","getAllContent");
         hobj.put("className","Recipe");
            }
           catch(Exception e){
         
           }
return(hobj);
}

Tuesday, 2 July 2013

complex web


public static String LogoutWebservice(String logid,String latitude,String longitude,String logmode,String reason) throws IllegalStateException, ClientProtocolException, IOException {

try{

HttpClient client = new DefaultHttpClient();  
HttpPost post = new HttpPost(postURL);

System.out.println("reached in webservice class for login");      
List<NameValuePair> params = new ArrayList<NameValuePair>();
 
str=jsonEncodinggetLogout(logid,latitude,longitude,logmode,reason).toString();
System.out.println("json="+str);
params.add(new BasicNameValuePair("Data",str));
params.add(new BasicNameValuePair("reubro_debug","1"));    
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
System.out.println("rrrrrrrr= ==" +postURL+ params);
System.out.println("PARAM= " + params);
HttpResponse responsePOST = client.execute(post);
  HttpEntity resEntity = responsePOST.getEntity();
str=EntityUtils.toString(resEntity);
str=str.trim();
int res = responsePOST.getStatusLine().getStatusCode();
System.out.println("res in LogoutWebservice webservice====="+res);

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

System.out.println("RESPONSE in LogoutWebservice webservice = ===" + str);
return str;
}
public static JSONObject jsonEncodinggetLogout(String logid,String latitude,String longitude,String logmode,String reason){

/** Called when the activity is first created. */
JSONObject obj=new JSONObject();  
try{
int v=Integer.parseInt(logid);
JSONArray argsArray = new JSONArray();
JSONObject objnew=new JSONObject();  
objnew.put("login_id",v);
objnew.put("lat",latitude);
objnew.put("lon",longitude);
objnew.put("login_mode",1);
objnew.put("clk_out_note",reason);
argsArray.put(0,objnew);
obj.put("argsArray",argsArray);
obj.put("methodName","userLogout");

}
catch(Exception e){

}


return(obj);
}