Rabu, 31 Oktober 2018

SQLLite Android like %%


Akan salah jika :
android.database.sqlite.SQLiteException: near "%": 
syntax error: , while compiling: 
SELECT ... FROM ... 
WHERE ((display_name like %?%)) 
ORDER BY display_name ASC
SOLUSINYA:
Cursor contactsContractContacts = resolver.query(
    ContactsContract.Contacts.CONTENT_URI, projection,
    ContactsContract.Contacts.DISPLAY_NAME + " like ?",
    new String[]{"%" + filterStr + "%"},
    ContactsContract.Contacts.DISPLAY_NAME + " ASC");

Membuat Album dari JSON

package com.example.lp2maray;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class Galeri extends AppCompatActivity {
    private GridView gridView;
    private GridViewAdapter gridAdapter;

    private ProgressDialog pDialog;
    JSONParser jParser = new JSONParser();
    JSONArray myJSON = null;
    private static final String TAG_SUKSES = "sukses";
    private static final String TAG_record = "record";

    int jd=0;

    String ip="";
    String[]arId_galeri;
    String[]arJudul;
    String[]arTgl;
    String[]arJam;
    String[]arKeterangan;
    String[]arKode_anggota;
    String[]arGambar;
    Bitmap []arBitmap;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ip=jParser.getIP();
        new load().execute();

    }

    private ArrayList<ImageItem> getData() {
        final ArrayList<ImageItem> imageItems = new ArrayList<>();
        //TypedArray imgs = getResources().obtainTypedArray(R.array.image_ids);        for (int i = 0; i < jd; i++) {//jd/imgs.length()            //Bitmap bitmap = BitmapFactory.decodeResource(getResources(),arBitmap[i]);// imgs.getResourceId(i, -1)            imageItems.add(new ImageItem(arBitmap[i], arJudul[i]));
        }
        return imageItems;
    }

    class load extends AsyncTask<String, String, String> {
        @Override        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Galeri.this);
            pDialog.setMessage("Load data. Silahkan Tunggu...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
        protected String doInBackground(String... args) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            JSONObject json = jParser.makeHttpRequest(ip+"galeri/galeri_show.php", "GET", params);
           // Log.d("show: ", json.toString());            try {
                int sukses = json.getInt(TAG_SUKSES);
                if (sukses == 1) {
                    myJSON = json.getJSONArray(TAG_record);
                    jd=myJSON.length();
                    arId_galeri=new String[jd];
                    arJudul=new String[jd];
                    arTgl=new String[jd];
                    arJam=new String[jd];
                    arKeterangan=new String[jd];
                    arKode_anggota=new String[jd];
                    arGambar=new String[jd];
                    arBitmap=new Bitmap[jd];

                    for (int i = 0; i < myJSON.length(); i++) {
                        JSONObject c = myJSON.getJSONObject(i);
                        arId_galeri[i]= c.getString("id_galeri");
                        arJudul[i]= c.getString("judul");
                        arTgl[i]= c.getString("tgl");
                        arJam[i]= c.getString("jam");
                        arKeterangan[i]= c.getString("keterangan");
                        arKode_anggota[i]= c.getString("nama_anggota");
                        arGambar[i]= c.getString("gambar");
                        String gb=ip+"ypathfile/"+ arGambar[i];
                        Log.v("URL",gb);
                        arBitmap[i]=getBitmapFromURL(gb);
                    }
                }
            }
            catch (JSONException e) {e.printStackTrace();}
            return null;
        }

        protected void onPostExecute(String file_url) {
            pDialog.dismiss();
            runOnUiThread(new Runnable() {
                public void run() {
                    gridView = (GridView) findViewById(R.id.gridView);
                    gridAdapter = new GridViewAdapter(Galeri.this, R.layout.grid_item_layout, getData());
                    gridView.setAdapter(gridAdapter);

                    gridView.setOnItemClickListener(new OnItemClickListener() {
                        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                            ImageItem item = (ImageItem) parent.getItemAtPosition(position);
                            Intent intent = new Intent(Galeri.this, DetailGaleri.class);
                            intent.putExtra("title", arJudul[position]);//item.getTitle()                            intent.putExtra("title2", arTgl[position]);
                            intent.putExtra("title3", arKeterangan[position]);
                            intent.putExtra("title4", arKode_anggota[position]);
                            intent.putExtra("gambar", arGambar[position]);

                            //intent.putExtra("image", item.getImage());                            startActivity(intent);
                        }
                    });
                }
            });}
    }

    public static Bitmap getBitmapFromURL(String src) {
        try {
            URL url = new URL(src);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            // Log exception            return null;
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 1, 0, "Upload foto");//.setIcon(R.drawable.add);        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 1:
                Intent i = new Intent(getApplicationContext(), UploadToServer.class);
                startActivityForResult(i, 100);
                return true;
        }
        return false;
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
++++++++++++++++++
GridViewAdapter.java


package com.example.lp2maray;

import java.util.ArrayList;

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

public class GridViewAdapter extends ArrayAdapter<ImageItem> {

    private Context context;
    private int layoutResourceId;
    private ArrayList<ImageItem> data = new ArrayList<ImageItem>();

    public GridViewAdapter(Context context, int layoutResourceId, ArrayList<ImageItem> data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
    }

    @Override    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        ViewHolder holder;

        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);
            holder = new ViewHolder();
            holder.imageTitle = (TextView) row.findViewById(R.id.text);
            holder.image = (ImageView) row.findViewById(R.id.image);
            row.setTag(holder);
        } else {
            holder = (ViewHolder) row.getTag();
        }


        ImageItem item = data.get(position);
        holder.imageTitle.setText(item.getTitle());
        holder.image.setImageBitmap(item.getImage());
        return row;
    }

    static class ViewHolder {
        TextView imageTitle;
        ImageView image;
    }
}
+++++++++++++++++
ImageItem.java

package com.example.komunitas;

import android.graphics.Bitmap;

public class ImageItem {
    private Bitmap image;
    private String title;

    public ImageItem(Bitmap image, String title) {
        super();
        this.image = image;
        this.title = title;
    }

    public Bitmap getImage() {
        return image;
    }

    public void setImage(Bitmap image) {
        this.image = image;
    }

    public String getTitle() {
        return title;
    }

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










++++++++++++++
activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="#f0f0f0">

    <GridView        android:id="@+id/gridView"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_margin="5dp"        android:columnWidth="100dp"        android:drawSelectorOnTop="true"        android:gravity="center"        android:numColumns="2"        android:stretchMode="columnWidth"        android:verticalSpacing="5dp"        android:focusable="true"        android:clickable="true"/>
</RelativeLayout>



grid_item_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_marginTop="5dp"    android:background="@drawable/grid_color_selector"    android:orientation="vertical"    android:padding="5dp">

    <ImageView        android:id="@+id/image"        android:layout_width="160dp"        android:layout_height="150dp" />

    <TextView        android:id="@+id/text"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_marginTop="5dp"        android:gravity="center"        android:textSize="12sp" />

</LinearLayout>



RadioButton Group Checked

RadioGroup rg;


rg = (RadioGroup) findViewById(R.id.radiogroup);


if(JK.equalsIgnoreCase("Perempuan")){
   ((RadioButton)rg.getChildAt(1)).setChecked(true);
}
else{//Laki-laki
   ((RadioButton)rg.getChildAt(0)).setChecked(true);
}


===========================

<TextView    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:text="Jenis Kelamin"    android:textColor="#000000"    android:textSize="20sp"    android:textStyle="bold"/>

<RadioGroup    android:id="@+id/radio"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:orientation="vertical">
    <RadioButton android:id="@+id/radPa"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Laki-laki"        android:checked="true" />
    <RadioButton android:id="@+id/radPi"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Perempuan" />
</RadioGroup>



Selasa, 30 Oktober 2018

List cari

listviewcolorcari.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent">

<Button android:text="Search"android:id="@+id/btnCari"android:layout_alignParentTop="true"android:layout_alignParentRight="true"android:layout_width="wrap_content"android:layout_height="wrap_content">
</Button>

<EditText android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="" android:id="@+id/edCari"android:layout_toLeftOf="@+id/btnCari">
</EditText>

<ListView android:layout_height="wrap_content"android:layout_below="@+id/edCari"android:layout_width="wrap_content"android:id="@+id/listCari">
</ListView>
                               
</RelativeLayout>


listviewcolordetail.xml

<?xml version="1.0" encoding="utf-8"?><AbsoluteLayout    android:id="@+id/widget0"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    xmlns:android="http://schemas.android.com/apk/res/android">
    <ImageView        android:src="@drawable/member"        android:id="@+id/widget32"        android:layout_width="50dp"        android:layout_height="50dp"        android:layout_x="2dp"        android:layout_y="5dp" />
    <TextView        android:id="@+id/txtnama"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Riadi Marta Dinata"        android:textSize="20sp"        android:textColor="@color/red"        android:layout_x="62dp"        android:layout_y="8dp" />
    <TextView        android:id="@+id/txtdata"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="FMIPA / BIMA"        android:layout_x="62dp"        android:layout_y="37dp" />
</AbsoluteLayout>

cari.java
package com.example.komunitas;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Cari extends Activity{
   String skodelogin="",snamalogin="",smaillogin="";
   String myLati="-6.352953";
   String myLongi="106.831389";
   String myPosisi="UI";

EditText edCari;
ListView listview;
Button btnCari;

String ip="";

private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
JSONArray myJSON = null;

ArrayList<HashMap<String, String>> arrayList;
private static final String TAG_SUKSES = "sukses";
private static final String TAG_record = "record";
   


private static final String TAG_kode_anggota= "kode_anggota";
private static final String TAG_nama_anggota = "nama_anggota";
private static final String TAG_jenis_kelamin= "jenis_kelamin";
private static final String TAG_tgl_lahir= "tgl_lahir";
private static final String TAG_alamat = "alamat";
private static final String TAG_email= "email";
private static final String TAG_telepon= "telepon";
private static final String TAG_status= "status";
private static final String TAG_keterangan= "keterangan";

//String   myLati="-6.192748";//String   myLongi="106.849069";//String myPosisi="Kampus YAI Salemba";
int jd;
String[]arr_kode_anggota;
String[]arr_nama_anggota;
String[]arr_tgl_lahir;
String[]arr_alamat;
String[]arr_email;//..String[]arr_keterangan;//..String[]arr_telepon;
String[]arr_status;
int[]arr_gbr;

String[]arr_kode_anggota2;
String[]arr_nama_anggota2;
String[]arr_tgl_lahir2;
String[]arr_alamat2;
String[]arr_keterangan2;
String[]arr_email2;
String[]arr_telepon2;
String[]arr_status2;
int[]arr_gbr2;

String[]arr_kode_anggota3;
String[]arr_nama_anggota3;
String[]arr_tgl_lahir3;
String[]arr_alamat3;
String[]arr_keterangan3;//String[]arr_email3;
String[]arr_telepon3;
String[]arr_status3;
int[]arr_gbr3;

//double[]arr_jarak;//String[]arr_sjarak;//double[]arr_jarak2;//String[]arr_sjarak2;//double[]arr_jarak3;//String[]arr_sjarak3;
int textlength = 0;
ArrayList<String> text_sort = new ArrayList<String>();
ArrayList<String> text_sort2 = new ArrayList<String>();
ArrayList<Integer> image_sort = new ArrayList<Integer>();

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.listviewcolorcari);

ip=jParser.getIP();
   Intent i = getIntent();
   myLati= i.getStringExtra("myLati");
   myLongi= i.getStringExtra("myLongi");
   myPosisi= i.getStringExtra("myPosisi");

   skodelogin= i.getStringExtra("skodelogin");
   snamalogin= i.getStringExtra("snamalogin");
   smaillogin= i.getStringExtra("smaillogin");

new loads().execute();

btnCari = (Button) findViewById(R.id.btnCari);
edCari = (EditText) findViewById(R.id.edCari);

}


void lanjut(){
   listview = (ListView) findViewById(R.id.listCari);
   listview.setAdapter(new MyCustomAdapter(arr_nama_anggota,arr_status, arr_gbr));
   listview.setOnItemClickListener(new OnItemClickListener()
      {
         @Override
         public void onItemClick(AdapterView<?> a, View v, int p, long id)
         { 
            
            Intent i = new Intent(Cari.this, Detail_anggota.class);
             i.putExtra("pk", arr_kode_anggota[p]);

            i.putExtra("myLati", myLati);
            i.putExtra("myLongi", myLongi);
            i.putExtra("myPosisi", myPosisi);

            i.putExtra("skodelogin", skodelogin);
            i.putExtra("snamalogin", snamalogin);
            i.putExtra("smaillogin", smaillogin);

            startActivity(i);
             
Toast.makeText(getBaseContext(), "Anda memilih "+ arr_nama_anggota[p], Toast.LENGTH_LONG).show();
                    }  
              });

   btnCari.setOnClickListener(new OnClickListener()
   {
      public void onClick(View v){textlength = edCari.getText().length();
      text_sort.clear();
      text_sort2.clear();
      image_sort.clear();
      String scari=edCari.getText().toString().toLowerCase();

      int ada=0;
      for (int i = 0; i < jd; i++){
         String snama=arr_nama_anggota[i].toLowerCase();
         String skode=arr_kode_anggota[i].toLowerCase();
         String salamat=arr_alamat[i].toLowerCase();
         String sangkatan=arr_status[i].toLowerCase();
         String stelepon=arr_telepon[i].toLowerCase();

      if (snama.indexOf(scari)>=0 || skode.indexOf(scari)>=0 || salamat.indexOf(scari)>=0 || sangkatan.indexOf(scari)>=0 || stelepon.indexOf(scari)>=0 ){    //huruf yg awalannya sama         text_sort.add(arr_nama_anggota[i]);
         text_sort2.add(arr_status[i]);

         image_sort.add(arr_gbr[i]);
         arr_kode_anggota2[ada]=arr_kode_anggota[i];
         arr_nama_anggota2[ada]=arr_nama_anggota[i];
         arr_tgl_lahir2[ada]=arr_tgl_lahir[i];
         arr_alamat2[ada]=arr_alamat[i];
         arr_email2[ada]=arr_email[i];//--//         arr_keterangan2[ada]=arr_keterangan[i];//--//         arr_gbr2[ada]=arr_gbr[i];
         arr_telepon2[ada]=arr_telepon[i];
             arr_status2[ada]=arr_status[i];

         
            ada=ada+1;
      }

   }

   arr_kode_anggota3=new String[ada];
   arr_nama_anggota3=new String[ada];
   arr_tgl_lahir3=new String[ada];
   arr_alamat3=new String[ada];
   arr_email3=new String[ada];//--//   arr_keterangan3=new String[ada];//--//   arr_gbr3=new int[ada];
   arr_telepon3=new String[ada];
   arr_status3=new String[ada];

   for (int i = 0; i < ada; i++)
   {
      arr_kode_anggota3[i]=arr_kode_anggota2[i];
      arr_nama_anggota3[i]=arr_nama_anggota2[i];
      arr_tgl_lahir3[i]=arr_tgl_lahir2[i];
      arr_alamat3[i]=arr_alamat2[i];
      arr_email3[i]=arr_email2[i];//--//      arr_keterangan3[i]=arr_keterangan2[i];//--//      arr_gbr3[i]=arr_gbr2[i];
      arr_telepon3[i]=arr_telepon2[i];
          arr_status3[i]=arr_status2[i];
   }

      listview.setAdapter(new MyCustomAdapter(text_sort,text_sort2, image_sort));
      listview.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> a, View v, int p, long id) { 
               
                   Intent i = new Intent(Cari.this, Detail_anggota.class);
                   i.putExtra("pk", arr_kode_anggota3[p]);

               i.putExtra("myLati", myLati);
               i.putExtra("myLongi", myLongi);
               i.putExtra("myPosisi", myPosisi);

               i.putExtra("skodelogin", skodelogin);
               i.putExtra("snamalogin", snamalogin);
               i.putExtra("smaillogin", smaillogin);

               startActivity(i);
               
               
                       Toast.makeText(getBaseContext(), "Anda memilih "+ arr_nama_anggota3[p], Toast.LENGTH_LONG).show();
                    }  
                 });
      }});
   
}

class MyCustomAdapter extends BaseAdapter{
         String[] data_text;
         String[] data_text2;
         int[] data_image;
      MyCustomAdapter(){}
      
      MyCustomAdapter(String[] text, String[] text2, int[] image){
         data_text = text;
         data_text2 = text2;
         data_image = image;
      }
      
      MyCustomAdapter(ArrayList<String> text,ArrayList<String> text2, ArrayList<Integer> image){
         data_text = new String[text.size()];
         data_text2 = new String[text2.size()];
         data_image = new int[image.size()];
            for (int i = 0; i < text.size(); i++) {
               data_text[i] = text.get(i);
               data_text2[i] = text2.get(i);
               data_image[i] = image.get(i);
            }
      }
      
      public int getCount(){return data_text.length;}
      public String getItem(int position){return null;}
      public long getItemId(int position){return position;}

      public View getView(int p, View convertView, ViewGroup parent){
         LayoutInflater inflater = getLayoutInflater();
         View row;
         row = inflater.inflate(R.layout.listviewcolordetail, parent, false);
         TextView textview = (TextView) row.findViewById(R.id.txtnama);//txtCari         TextView txtdata = (TextView) row.findViewById(R.id.txtdata);//txtCari         ImageView imageview = (ImageView) row.findViewById(R.id.widget32);//imgCari         textview.setText(data_text[p]);
         txtdata.setText(data_text2[p]);
         imageview.setImageResource(data_image[p]);
         return (row);
         }
      
   }



class loads extends AsyncTask<String, String, String> {
   @Override
   protected void onPreExecute() {
      super.onPreExecute();
      pDialog = new ProgressDialog(Cari.this);
      pDialog.setMessage("Load data. Silahkan Tunggu...");
      pDialog.setIndeterminate(false);
      pDialog.setCancelable(false);
      pDialog.show();
   }
   protected String doInBackground(String... args) {
      List<NameValuePair> params = new ArrayList<NameValuePair>();
      JSONObject json = jParser.makeHttpRequest(ip+"anggota/anggota_show.php", "GET", params);
      Log.d("show: ", json.toString());
      try {
         int sukses = json.getInt(TAG_SUKSES);
         if (sukses == 1) {
            myJSON = json.getJSONArray(TAG_record);
            
            jd=myJSON.length();
            arr_kode_anggota=new String[jd];
            arr_nama_anggota=new String[jd];
            arr_tgl_lahir=new String[jd];
            arr_alamat=new String[jd];
            arr_email=new String[jd];
            arr_keterangan=new String[jd];
            arr_telepon=new String[jd];
            arr_status=new String[jd];
            arr_gbr=new int[jd];


            arr_kode_anggota2=new String[jd];
            arr_nama_anggota2=new String[jd];
            arr_tgl_lahir2=new String[jd];
            arr_alamat2=new String[jd];
            arr_email2=new String[jd];
            arr_keterangan2=new String[jd];
            arr_telepon2=new String[jd];
            arr_status2=new String[jd];
            arr_gbr2=new int[jd];

            
            for (int i = 0; i < jd; i++) {
               JSONObject c = myJSON.getJSONObject(i);
               String kode_anggota= c.getString(TAG_kode_anggota);
               String nama_anggota = c.getString(TAG_nama_anggota);
               String jenis_kelamin = c.getString(TAG_jenis_kelamin );
               String tgl_lahir= c.getString(TAG_tgl_lahir);
               String alamat= c.getString(TAG_alamat);
               String email= c.getString(TAG_email);
               String telepon= c.getString(TAG_telepon);
               String status= c.getString("visible");
               String fakultas= c.getString("fakultas");
               String angkatan= c.getString("angkatan");

               arr_kode_anggota[i]=kode_anggota;
               arr_nama_anggota[i]=nama_anggota;
               arr_tgl_lahir[i]=tgl_lahir;
               arr_alamat[i]=alamat;
               arr_email[i]=email;
               arr_keterangan[i]=jenis_kelamin;
               arr_telepon[i]=telepon;
               arr_status[i]=fakultas+" - "+angkatan+" /"+status+"";
               arr_gbr[i]=R.drawable.profil;

               

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

   protected void onPostExecute(String file_url) {
      pDialog.dismiss();
      runOnUiThread(new Runnable() {
         public void run() {
            lanjut();
         }
      });}
}



}


Share and Download Image

Button    btnShare=(Button)findViewById(R.id.btnShare);
btnShare.setOnClickListener(new View.OnClickListener() {
    public void onClick(View arg0) {

        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        sharingIntent.putExtra(Intent.EXTRA_TEXT, "Produk :"+title+"\n\nKet :"+title2+"\n\nHarga :"+title3+"\n\nStatus :"+title4);
        sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
        startActivity(Intent.createChooser(sharingIntent, "Share using"));

    }});


Button    btnsave=(Button)findViewById(R.id.btnsave);btnsave.setText("Download");
btnsave.setVisibility(View.VISIBLE);
btnsave.setOnClickListener(new View.OnClickListener() {
    public void onClick(View arg0) {
        savepicture();
    }});





    public void savepicture() {
        AlertDialog.Builder ad = new AlertDialog.Builder(DetailGaleri.this);
        ad.setTitle("Save Picture");
        ad.setMessage(title+" \n"+title3+"\n"+title4);

        ad.setPositiveButton("Save", new DialogInterface.OnClickListener() {
            @Override            public void onClick(DialogInterface dialog, int which) {

                View content = findViewById(R.id.myGambar);
                Bitmap bitmap = getScreenShot(content);
//                currentImage = "image" + System.currentTimeMillis() + ".jpg";                currentImage = title+" \n"+title3+"\n"+title4+".jpg";
                store(bitmap, currentImage);
//                b_share.setEnabled(true);               // finish();            }
        });
        ad.setNegativeButton("Cancle", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
            }
        });
        ad.show();
    }

    private static Bitmap getScreenShot(View view) {
        view.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);
        return bitmap;
    }

    private void store(Bitmap bm, String fileName) {
        String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/FILEPROJEK";
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dirPath, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            Toast.makeText(this, "Saved to "+dirPath +"..!", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

Upload to Server

package com.example.komunitas;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;


public class UploadToServer extends Activity {
    String myip="";
    JSONParser jsonParser = new JSONParser();
    EditText txtjudul;

    private static final int PICK_IMAGE = 1;
    private static final int PICK_Camera_IMAGE = 2;
    private ImageView imgView;
    private Button upload,cancel;
    private Bitmap bitmap;
    Uri imageUri;
    MediaPlayer mp=new MediaPlayer();

    String kode_anggota,nama_anggota,email;

    String URL="";
    TextView messageText;
    Button uploadButton,btnpilih,btncamera;
    int serverResponseCode = 0;
    ProgressDialog dialog = null;

    String upLoadServerUri = null;

    /**********  File Path *************/    final String uploadFilePath = "/mnt/sdcard/";
    final String uploadFileName = "service_lifecycle.png";

    @Override    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.uploadserver);

        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(UploadToServer.this);
        Boolean Registered = sharedPref.getBoolean("Registered", false);
        if (!Registered) {
            finish();
        } else {
            kode_anggota = sharedPref.getString("kode_anggota", "");
            nama_anggota = sharedPref.getString("nama_anggota", "");
            email = sharedPref.getString("email", "");
        }


        txtjudul= (EditText) findViewById(R.id.txtjudul);
        imgView = (ImageView) findViewById(R.id.imageView);
        uploadButton = (Button)findViewById(R.id.uploadButton);
        messageText  = (TextView)findViewById(R.id.messageText);

        btnpilih = (Button)findViewById(R.id.btnpilih);btnpilih.setVisibility(View.GONE);
        btncamera = (Button)findViewById(R.id.btncamera);

        messageText.setText(uploadFilePath+"/"+uploadFileName+"'");

        URL=jsonParser.getIP()+"uploadserver.php";
        upLoadServerUri =   URL;
        uploadButton.setOnClickListener(new OnClickListener() {
            @Override            public void onClick(View v) {

                String judul=txtjudul.getText().toString();
                if(judul.length()>0) {
                    dialog = ProgressDialog.show(UploadToServer.this, "", "Uploading file...", true);
                    new Thread(new Runnable() {
                        public void run() {
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    messageText.setText("Uploading Started.....");
                                }
                            });
                            String AL = messageText.getText().toString();
                            uploadFiles(AL);

                        }
                    }).start();
                }
                else{
                    lengkapi();
                }
            }
        });

        btnpilih.setVisibility(View.GONE);
        btnpilih.setOnClickListener(new OnClickListener() {
            @Override            public void onClick(View v) {
                try {
                    Intent gintent = new Intent();
                    gintent.setType("image/*");
                    gintent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(gintent, "Select Picture"),PICK_IMAGE);
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(),
                            e.getMessage(),
                            Toast.LENGTH_LONG).show();
                    Log.e(e.getClass().getName(), e.getMessage(), e);
                }
            }
        });


        btncamera.setOnClickListener(new OnClickListener() {
            @Override            public void onClick(View v) {
                //define the file-name to save photo taken by Camera activity                String fileName = "uploadFile.jpg";
                //create parameters for Intent with filename                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.TITLE, fileName);
                values.put(MediaStore.Images.Media.DESCRIPTION,"Image captured by camera");
                //imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)                imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                //create new Intent                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                startActivityForResult(intent, PICK_Camera_IMAGE);
            }
        });
    }
    public void lengkapi() {
        new AlertDialog.Builder(this)
                .setTitle("Lengkapi Judul")
                .setMessage("Yth "+nama_anggota+", Silakan lengkapi Judul Galeri Anda")
                .setNeutralButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dlg, int sumthin) {
                    }
                })
                .show();
    }
    public int uploadFiles(String sourceFileUri) {
        String fileName = sourceFileUri;

        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File sourceFile = new File(sourceFileUri);

        if (!sourceFile.isFile()) {

            dialog.dismiss();

            Log.e("uploadFile", "Source File not exist :"  +uploadFilePath + "" + uploadFileName);

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText.setText("File not exist :"+uploadFilePath + "" + uploadFileName);
                }
            });

            return 0;

        }
        else        {
            try {
                String judul=txtjudul.getText().toString();
                FileInputStream fileInputStream = new FileInputStream(sourceFile);
                URL url = new URL(upLoadServerUri);

                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs                conn.setDoOutput(true); // Allow Outputs                conn.setUseCaches(false); // Don't use a Cached Copy                conn.setRequestMethod("POST");
//==============
//                List<NameValuePair> params = new ArrayList<NameValuePair>();//                params.add(new BasicNameValuePair("kode_anggota", kode_anggota));//                params.add(new BasicNameValuePair("judul", judul));////                OutputStream os = conn.getOutputStream();//                BufferedWriter writer = new BufferedWriter(  new OutputStreamWriter(os, "UTF-8"));//                writer.write(getQuery(params));//                writer.write(getQuery(params));//                writer.flush();//                writer.close();//                os.close();//                conn.connect();//=============                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("uploaded_file", fileName);
                conn.setRequestProperty("kode_anggota", kode_anggota);
                conn.setRequestProperty("judul", judul);

//                Log.v("HAHAHA",fileName);//                Log.v("HEHE",kode_anggota);

                dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""                        + fileName + "\"" + lineEnd);

                dos.writeBytes(lineEnd);

                // create a buffer of  maximum size                bytesAvailable = fileInputStream.available();

                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                // read file and write it into form...                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0) {

                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                }

                // send multipart form data necesssary after file data...                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // Responses from the server (code and message)                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();

                Log.i("uploadFile", "HTTP Response is : "                        + serverResponseMessage + ": " + serverResponseCode);

                if(serverResponseCode == 200){

                    runOnUiThread(new Runnable() {
                        public void run() {

                            String msg = "File Upload Completed :"+uploadFileName;

                            messageText.setText(msg);
                            Toast.makeText(UploadToServer.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                //close the streams //                fileInputStream.close();
                dos.flush();
                dos.close();

            } catch (MalformedURLException ex) {

                dialog.dismiss();
                ex.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {
                        messageText.setText("Fail Upload");
                        Toast.makeText(UploadToServer.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {

                dialog.dismiss();
                e.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {
                        messageText.setText("Fail Uploaded.. ");
                        Toast.makeText(UploadToServer.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                    }
                });

            }
            dialog.dismiss();
            return serverResponseCode;

        } // End else block    }


    private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
    {
        StringBuilder result = new StringBuilder();
        boolean first = true;

        for (NameValuePair pair : params)
        {
            if (first)
                first = false;
            else                result.append("&");

            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        }

        return result.toString();
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Uri selectedImageUri = null;
        String filePath = null;
        switch (requestCode) {
            case PICK_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    selectedImageUri = data.getData();
                }
                break;
            case PICK_Camera_IMAGE:
                if (resultCode == RESULT_OK) {
                    //use imageUri here to access the image                    selectedImageUri = imageUri;
          /*Bitmap mPic = (Bitmap) data.getExtras().get("data");      selectedImageUri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), mPic, getResources().getString(R.string.app_name), Long.toString(System.currentTimeMillis())));*/                } else if (resultCode == RESULT_CANCELED) {
                    Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
                }
                break;
        }

        if(selectedImageUri != null){
            btnpilih.setVisibility(View.VISIBLE);

            try {
                // OI FILE Manager                String filemanagerstring = selectedImageUri.getPath();

                // MEDIA GALLERY                String selectedImagePath = getPath(selectedImageUri);


                messageText.setText(selectedImagePath);


                if (selectedImagePath != null) {
                    filePath = selectedImagePath;
                } else if (filemanagerstring != null) {
                    filePath = filemanagerstring;
                } else {
                    Toast.makeText(getApplicationContext(), "Unknown path",  Toast.LENGTH_LONG).show();
                    Log.e("Bitmap", "Unknown path");
                }

                if (filePath != null) {
                    decodeFile(filePath);
                } else {
                    bitmap = null;
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "Internal error",  Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
            }
        }

    }



    class ImageGalleryTask extends AsyncTask<Void, Void, String> {
        @SuppressWarnings("unused")
        @Override        protected String doInBackground(Void... unsued) {
            InputStream is;
            BitmapFactory.Options bfo;
            Bitmap bitmapOrg;
            ByteArrayOutputStream bao ;

            bfo = new BitmapFactory.Options();
            bfo.inSampleSize = 2;
            //bitmapOrg = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + customImage, bfo);
            bao = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
            byte [] ba = bao.toByteArray();
//            String ba1 = Base64.encodeBytes(ba);
            String ba1 = Base64.encodeToString(ba,1);
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("image",ba1));
            nameValuePairs.add(new BasicNameValuePair("cmd","image_android"));
            Log.v("log_tag", System.currentTimeMillis()+".jpg");
            try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new                        //  Here you need to put your server file address

                        HttpPost(URL);//"http://www.picsily.com/upload_photo.php");                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
                Log.v("log_tag", "In the try Loop" );
            }catch(Exception e){
                Log.v("log_tag", "Error in http connection "+e.toString());
            }
            return "Success";
            // (null);        }

        @Override        protected void onProgressUpdate(Void... unsued) {

        }

        @Override        protected void onPostExecute(String sResponse) {
            try {
                if (dialog.isShowing())
                    dialog.dismiss();
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(),
                        e.getMessage(),
                        Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
            }
        }

    }

    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if (cursor != null) {
            // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL            // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA            int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } else            return null;
    }

    public void decodeFile(String filePath) {
        // Decode image size        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, o);

        // The new size we want to scale to        final int REQUIRED_SIZE = 1024;

        // Find the correct scale value. It should be the power of 2.        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        // Decode with inSampleSize        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        bitmap = BitmapFactory.decodeFile(filePath, o2);

        imgView.setImageBitmap(bitmap);

    }

}

//+++++++++++++++++++++++

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    >

    <ImageView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_weight="1"        android:id="@+id/imageView" />

    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="Judul Foto"        android:textColor="#000000"        android:textSize="20sp"        android:textStyle="bold"/>

    <!--  telepon TextField -->    <EditText        android:id="@+id/txtjudul"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:textColor="#000000" />

    <Button        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="Click To Upload File"        android:id="@+id/uploadButton"        />

    <Button        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="Choose File"        android:id="@+id/btnpilih"        />


    <Button        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="Camera"        android:id="@+id/btncamera"        />



    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text=""        android:id="@+id/messageText"        android:textColor="#000000"        android:textStyle="bold"        />
</LinearLayout>

//++++++++++++++++++++++++++


<?php


  require_once"konmysqli.php";
    $file_path = "ypathfile/";
    
 $IMG=$_FILES['uploaded_file']['name'];
 $file_path = $file_path . basename( $IMG);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
    echo "success";
  
  $actualpath = "http://192.168.1.14/Web_Komunitas/ypathfile/$IMG";
  $tgl=date("Y-m-d");
  $jam=date("H:i:s");
  
  $sql = "INSERT INTO tb_temp (path,nama) VALUES ('$actualpath','$IMG')";
  mysqli_query($conn,$sql);
      

    } else{
        echo "fail";
    }
 
 function resize_image($file, $w, $h, $crop=FALSE) {
    list($width, $height) = getimagesize($file);
    $r = $width / $height;
    if ($crop) {
        if ($width > $height) {
            $width = ceil($width-($width*abs($r-$w/$h)));
        } else {
            $height = ceil($height-($height*abs($r-$w/$h)));
        }
        $newwidth = $w;
        $newheight = $h;
    } else {
        if ($w/$h > $r) {
            $newwidth = $h*$r;
            $newheight = $h;
        } else {
            $newheight = $w/$r;
            $newwidth = $w;
        }
    }
    $src = imagecreatefromjpeg($file);
    $dst = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    return $dst;
}

 
 ?>
 
<?php
if(isset($_POST["submit"])) {
if(is_array($_FILES)) {
/*$file = $_FILES['myImage']['tmp_name']; 
$source_properties = getimagesize($file);
$image_type = $source_properties[2]; 
*/
@copy($_FILES["myImage"]["tmp_name"],"ypathfile/".$_FILES["myImage"]["name"]);
 $file="ypathfile/".$_FILES["myImage"]["name"];
 $source_properties = getimagesize($file);
 $image_type = $source_properties[2]; 
 

if( $image_type == IMAGETYPE_JPEG ) {   
 $image_resource_id = imagecreatefromjpeg($file);  
 $target_layer = fn_resize($image_resource_id,$source_properties[0],$source_properties[1]);
 imagejpeg($target_layer,"ypathfile/".$_FILES['myImage']['name']);
}
elseif( $image_type == IMAGETYPE_GIF )  {  
 $image_resource_id = imagecreatefromgif($file);
 $target_layer = fn_resize($image_resource_id,$source_properties[0],$source_properties[1]);
 imagegif($target_layer,$_FILES['myImage']['name']);
}
elseif( $image_type == IMAGETYPE_PNG ) {
 $image_resource_id = imagecreatefrompng($file); 
 $target_layer = fn_resize($image_resource_id,$source_properties[0],$source_properties[1]);
 imagepng($target_layer,"ypathfile/".$_FILES['myImage']['name'] );
}
}
}


function fn_resize($image_resource_id,$width,$height) {
$target_width =200;
$target_height =200;
$target_layer=imagecreatetruecolor($target_width,$target_height);
imagecopyresampled($target_layer,$image_resource_id,0,0,0,0,$target_width,$target_height, $width,$height);
return $target_layer;
}
?>