sjizl.com.FileUploadTest.java Source code

Java tutorial

Introduction

Here is the source code for sjizl.com.FileUploadTest.java

Source

/*******************************************************************************
 * Copyright 2011-2013 Sergey Tarasevich
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package sjizl.com;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import sjizl.com.ChatActivity.ItemAdapter;
import sjizl.com.ChatActivity.getPhotos;
import sjizl.com.Constants.Extra;
import sjizl.com.libary.UserFunctions;

import com.ipaulpro.afilechooser.utils.FileUtils;
import com.navdrawer.SimpleSideDrawer;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.nostra13.universalimageloader.utils.DiskCacheUtils;
import com.nostra13.universalimageloader.utils.MemoryCacheUtils;

import static sjizl.com.CommonUtilities.options;
import static sjizl.com.CommonUtilities.options_vierkant;

/**
 * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
 */
@SuppressLint("NewApi")
public class FileUploadTest extends AbsListViewBaseActivity {
    DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.ic_stub) // resource or drawable
            .showImageForEmptyUri(R.drawable.ic_empty) // resource or drawable
            .showImageOnFail(R.drawable.ic_error) // resource or drawable
            .resetViewBeforeLoading(false) // default
            .delayBeforeLoading(1000).cacheInMemory(false) // default
            .cacheOnDisk(false) // default

            .considerExifParams(false) // default
            .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
            .bitmapConfig(Bitmap.Config.ARGB_8888) // default

            .displayer(new SimpleBitmapDisplayer()) // default
            .handler(new Handler()) // default
            .build();
    ProgressDialog progressDialog;
    private static final int SELECT_FILE1 = 1;
    private static final int SELECT_FILE2 = 2;
    HttpEntity resEntity;
    String selectedPath1 = "NONE";
    String selectedPath2 = "NONE";
    ProgressBar progressBar_hole;
    String geslacht = "-";
    LinearLayout right_lin, middle_lin, left_lin1, left_lin2, left_lin3, left_lin4, upload_photo_text;
    Spinner spinner1;
    String[] imageUrls2, names, laatste_bericht, fotos, fotos_nums, aantal_new_ber, fids;
    String[] stockArr, stockArr2, stockArr3, stockArr4, stockArr5, stockArr6, stockArr7;
    String username, password, naam, foto, foto_num;
    ArrayList<String> stock_list, stock_list2, stock_list3, stock_list4, stock_list5, stock_list6, stock_list7;
    String naam_to_delete;
    String fid_to_set;
    TextView tv, res;
    String rand;

    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.fileuploadtest2);
        //ac_image_grid
        TextView textView2_under_title;
        final ImageLoader imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(getApplicationContext()));
        progressBar_hole = (ProgressBar) findViewById(R.id.progressBar_hole);
        progressBar_hole.setVisibility(View.INVISIBLE);
        right_lin = (LinearLayout) findViewById(R.id.right_lin);
        rand = CommonUtilities.randInt(111, 999);
        middle_lin = (LinearLayout) findViewById(R.id.middle_lin);
        //right_lin.setBackgroundColor(Color.BLUE);
        right_lin = (LinearLayout) findViewById(R.id.right_lin);
        left_lin1 = (LinearLayout) findViewById(R.id.left_lin1);

        left_lin3 = (LinearLayout) findViewById(R.id.left_lin3);
        left_lin4 = (LinearLayout) findViewById(R.id.left_lin4);
        middle_lin = (LinearLayout) findViewById(R.id.middle_lin);

        upload_photo_text = (LinearLayout) findViewById(R.id.upload_photo_text);

        textView2_under_title = (TextView) findViewById(R.id.textView2_under_title);
        ((LinearLayout) textView2_under_title.getParent()).removeView(textView2_under_title);
        textView2_under_title.setVisibility(View.GONE);
        ImageView imageView2_dashboard = (ImageView) findViewById(R.id.imageView2_dashboard);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        Button upload_photo0 = (Button) findViewById(R.id.upload_photo0);
        Button upload_photo1 = (Button) findViewById(R.id.upload_photo1);
        Button upload_photo2 = (Button) findViewById(R.id.upload_photo2);

        upload_photo0.setVisibility(View.GONE);
        upload_photo1.setVisibility(View.GONE);
        upload_photo2.setVisibility(View.GONE);

        upload_photo0.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                CommonUtilities.custom_toast(getApplicationContext(), FileUploadTest.this, "UploadActivity! ", null,
                        R.drawable.iconbd);

                Intent dashboard = new Intent(getApplicationContext(), UploadActivity.class);

                startActivity(dashboard);
            }
        });
        upload_photo1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Toast.makeText(getApplicationContext(), "FileChooserExampleActivity!", Toast.LENGTH_LONG).show();
                Intent dashboard = new Intent(getApplicationContext(), FileChooserExampleActivity.class);

                startActivity(dashboard);
            }
        });

        upload_photo2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "FileChooserExampleActivity!", Toast.LENGTH_LONG).show();
                Intent dashboard = new Intent(getApplicationContext(), FileChooserExampleActivity.class);

                startActivity(dashboard);
            }
        });

        final ImageView left_button;

        left_button = (ImageView) findViewById(R.id.imageView1_back);
        Button button1 = (Button) findViewById(R.id.upload_photo1);

        SharedPreferences sp = getApplicationContext().getSharedPreferences("loginSaved", Context.MODE_PRIVATE);
        naam = sp.getString("naam", null);
        username = sp.getString("username", null);
        password = sp.getString("password", null);
        foto = sp.getString("foto", null);
        foto_num = sp.getString("foto_num", null);
        imageLoader.displayImage("http://sjizl.com/fotos/" + foto_num + "/thumbs/" + foto, imageView2_dashboard,
                options);

        Brows();

        listView.setLongClickable(true);
        registerForContextMenu(listView);

        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //startImagePagerActivity(position);

                if (position == 0) {
                    openGallery(SELECT_FILE1);
                } else {

                    listView.showContextMenuForChild(view);
                    //  registerForContextMenu(view); 
                    //  openContextMenu(view);
                    //  unregisterForContextMenu(view);
                }

            }
        });

        left_lin1.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE
                        || event.getAction() == MotionEvent.ACTION_POINTER_DOWN) {
                    left_lin1.setBackgroundColor(Color.DKGRAY);
                    v.setBackgroundColor(Color.DKGRAY);
                    onBackPressed();
                } else if (event.getAction() == MotionEvent.ACTION_UP
                        || event.getAction() == MotionEvent.ACTION_CANCEL) {
                    left_lin1.setBackgroundColor(Color.BLACK);
                    v.setBackgroundColor(Color.BLACK);
                }
                return false;
            }
        });
        CommonUtilities u = new CommonUtilities();
        u.setHeaderConrols(getApplicationContext(), this,

                right_lin,

                left_lin3, left_lin4, left_lin1, left_button);
        ;

        middle_lin.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE
                        || event.getAction() == MotionEvent.ACTION_POINTER_DOWN) {
                    middle_lin.setBackgroundColor(Color.DKGRAY);
                    v.setBackgroundColor(Color.DKGRAY);
                } else if (event.getAction() == MotionEvent.ACTION_UP
                        || event.getAction() == MotionEvent.ACTION_CANCEL) {
                    middle_lin.setBackgroundColor(Color.BLACK);
                    v.setBackgroundColor(Color.BLACK);
                }
                return false;
            }
        });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.cancel();
        }
    }

    private void Brows() {
        JSONArray json31;
        UserFunctions userFunctions = new UserFunctions();
        json31 = userFunctions.getFotos(username, password, naam);
        String str = json31.toString();
        String aaaa = CommonUtilities.randInt(111, 999);
        stock_list = new ArrayList<String>();
        stock_list2 = new ArrayList<String>();
        stock_list3 = new ArrayList<String>();
        stock_list4 = new ArrayList<String>();
        stock_list5 = new ArrayList<String>();
        stock_list6 = new ArrayList<String>();
        stock_list7 = new ArrayList<String>();

        stock_list7.add("0");
        stock_list6.add("0");
        stock_list4.add("0");
        stock_list5.add("0");
        stock_list2.add("0");
        stock_list3.add("0");
        stock_list.add("drawable://" + R.drawable.add_photo);

        for (int i = 0; i < json31.length(); i++) { // **line 2**
            JSONObject childJSONObject = null;
            try {
                childJSONObject = json31.getJSONObject(i);
                String fid = childJSONObject.getString("fid");
                String name = childJSONObject.getString("pid");
                String foto2 = childJSONObject.getString("foto");
                String foto_mum2 = childJSONObject.getString("foto_num");
                String laatste_berichten2 = childJSONObject.getString("laatst_online");
                String aantal_new = childJSONObject.getString("woonplaats");

                MemoryCacheUtils.removeFromCache("http://sjizl.com/fotos/" + foto_mum2 + "/thumbs/" + foto2 + "",
                        ImageLoader.getInstance().getMemoryCache());
                DiskCacheUtils.removeFromCache("http://sjizl.com/fotos/" + foto_mum2 + "/thumbs/" + foto2 + "",
                        ImageLoader.getInstance().getDiscCache());

                stock_list7.add(fid);
                stock_list6.add(aantal_new);
                stock_list4.add(foto2);
                stock_list5.add(foto_mum2);
                stock_list2.add(name);
                stock_list3.add(laatste_berichten2);
                stock_list.add("http://sjizl.com/fotos/" + foto_mum2 + "/thumbs/" + foto2 + "");
                //imageUrls[] =url;

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        stockArr = new String[stock_list.size()];
        stockArr2 = new String[stock_list2.size()];
        stockArr3 = new String[stock_list3.size()];
        stockArr4 = new String[stock_list4.size()];
        stockArr5 = new String[stock_list5.size()];
        stockArr6 = new String[stock_list6.size()];
        stockArr7 = new String[stock_list7.size()];

        aantal_new_ber = stock_list6.toArray(stockArr6);
        imageUrls2 = stock_list.toArray(stockArr);
        names = stock_list2.toArray(stockArr2);
        laatste_bericht = stock_list3.toArray(stockArr3);
        fotos = stock_list4.toArray(stockArr4);
        fotos_nums = stock_list5.toArray(stockArr5);
        fids = stock_list7.toArray(stockArr7);

        if (stock_list4.toString().contains("geen")) {

            String mess = getResources().getString(R.string.app_name);

            TextView textv1 = new TextView(this);
            textv1.setText("To use all features of " + mess + " you need to upload a photo of yourself");
            upload_photo_text.addView(textv1);

            do_animation_top(upload_photo_text);
        } else {

            upload_photo_text.setVisibility(View.GONE);
        }

        listView = (GridView) findViewById(R.id.gridview);
        ImageAdapter aaa = new ImageAdapter();
        ((GridView) listView).setAdapter(aaa);
        aaa.notifyDataSetChanged();
    }

    private String[] getString(String images) {
        // TODO Auto-generated method stub
        return null;
    }

    public class ImageAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return imageUrls2.length;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_grid_image, null);
            }
            ImageView image_online = (ImageView) convertView.findViewById(R.id.image_online);
            if (laatste_bericht[position].equals("true")) {
                image_online.bringToFront();
            } else {
                image_online.setVisibility(View.GONE);
            }
            ImageView image_photo = (ImageView) convertView.findViewById(R.id.image_photo);
            //imageLoader.displayImage(imageUrls2[position], image_online, options_vierkant);
            imageLoader.displayImage(imageUrls2[position], image_photo, options_vierkant);
            return convertView;
        }
    }

    public void openGallery(int req_code) {

        //   Intent intent2 = new Intent();
        //   intent2.setType("image/*");
        //   intent2.setAction(Intent.ACTION_GET_CONTENT);
        //   startActivityForResult(Intent.createChooser(intent2,"Select file to upload "), req_code);

        // Use the GET_CONTENT intent from the utility class
        Intent target = FileUtils.createGetContentIntent();

        Intent intent = Intent.createChooser(target, getResources().getText(R.string.app_name));
        try {
            startActivityForResult(intent, req_code);
        } catch (ActivityNotFoundException e) {
            // The reason for the existence of aFileChooser
        }

    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            if (data != null) {
                // Get the URI of the selected file
                final Uri uri = data.getData();
                Log.i("ffff:", "Uri = " + uri.toString());
                try {
                    // Get the file path from the URI
                    final String path = FileUtils.getPath(this, uri);
                    Toast.makeText(FileUploadTest.this, "File Selected: " + path, Toast.LENGTH_LONG).show();

                    CommonUtilities.custom_toast(getApplicationContext(), FileUploadTest.this,
                            "File Selected: " + path, null, R.drawable.iconbd);

                    Thread thread = new Thread(new Runnable() {
                        public void run() {
                            doFileUpload(path);
                            runOnUiThread(new Runnable() {
                                public void run() {

                                }
                            });
                        }
                    });
                    thread.start();

                } catch (Exception e) {
                    Log.e("FileSelectorTestActivity", "File select error", e);
                }
            }
        }

    }

    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    private void doFileUpload(String path) {

        String username = "";
        String password = "";
        String foto = "";
        String foto_num = "";
        SharedPreferences sp = getApplicationContext().getSharedPreferences("loginSaved", Context.MODE_PRIVATE);
        username = sp.getString("username", null);
        password = sp.getString("password", null);
        foto = sp.getString("foto", null);
        foto_num = sp.getString("foto_num", null);

        File file1 = new File(path);

        String urlString = "http://sjizl.com/postBD/UploadToServer.php?username=" + username + "&password="
                + password;
        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(urlString);
            FileBody bin1 = new FileBody(file1);

            MultipartEntity reqEntity = new MultipartEntity();
            reqEntity.addPart("uploadedfile1", bin1);

            reqEntity.addPart("user", new StringBody("User"));
            post.setEntity(reqEntity);
            HttpResponse response = client.execute(post);
            resEntity = response.getEntity();
            final String response_str = EntityUtils.toString(resEntity);
            if (resEntity != null) {
                Log.i("RESPONSE", response_str);
                runOnUiThread(new Runnable() {
                    public void run() {
                        try {
                            // res.setTextColor(Color.GREEN);
                            // res.setText("n Response from server : n " + response_str);

                            CommonUtilities.custom_toast(getApplicationContext(), FileUploadTest.this,
                                    "Upload Complete! ", null, R.drawable.iconbd);

                            Brows();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        } catch (Exception ex) {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
        }

        //RegisterActivity.login(username,password,getApplicationContext());

    }

    public void do_animation_top(LinearLayout left_button) {

        float px = dipToPixels(getBaseContext(), -30);
        Animation animation1 = new TranslateAnimation(0, 0, -50, 0);
        animation1.setDuration(1000);

        animation1.setFillEnabled(true);
        animation1.setFillAfter(true);

        left_button.startAnimation(animation1);

    }

    public float dipToPixels(Context context, float dipValue) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.photo_menu_list, menu);

    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        int index = info.position;
        String textTocopy = stock_list3.get(index);

        switch (item.getItemId()) {
        case R.id.rotate_left:
            //   quoteResult.remove(info.position);
            //   ((StockQuoteAdapter)getListAdapter()).notifyDataSetChanged();
            naam_to_delete = stock_list.get(info.position);

            new RotateToLeft().execute();
            //  Toast.makeText(getApplicationContext(), "Rotate left"+naam_to_delete, Toast.LENGTH_SHORT).show();
            return true;

        case R.id.rotate_right:
            naam_to_delete = stock_list.get(info.position);
            //   quoteResult.remove(info.position);
            //   ((StockQuoteAdapter)getListAdapter()).notifyDataSetChanged();
            new RotateToRight().execute();
            //  Toast.makeText(getApplicationContext(), "Rotate right"+naam_to_delete, Toast.LENGTH_SHORT).show();

            return true;

        case R.id.profile_photo:
            fid_to_set = stock_list7.get(info.position);

            //   Toast.makeText(getApplicationContext(), "profile_photo:"+stock_list7.get(info.position)+":fid_to_set"+fid_to_set, Toast.LENGTH_SHORT).show();
            //   quoteResult.remove(info.position);
            //   ((StockQuoteAdapter)getListAdapter()).notifyDataSetChanged();
            new SetAsProfilePhoto().execute();
            //  Toast.makeText(getApplicationContext(), "Rotate right"+naam_to_delete, Toast.LENGTH_SHORT).show();

            return true;
        }
        return false;
    }

    private class SetAsProfilePhoto extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... arg0) {
            UserFunctions userFunctions = new UserFunctions();
            JSONObject json31 = userFunctions.SetAsProfilePhoto(username, password, fid_to_set);

            return null;
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onPostExecute(Void result) {
            rand = CommonUtilities.randInt(111, 999);
            Brows();
        }
    }

    private class RotateToRight extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... arg0) {
            UserFunctions userFunctions = new UserFunctions();
            JSONObject json31 = userFunctions.rotatePhoto(username, password, naam_to_delete, "1");

            return null;
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onPostExecute(Void result) {
            rand = CommonUtilities.randInt(111, 999);
            Brows();
        }
    }

    private class RotateToLeft extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... arg0) {
            UserFunctions userFunctions = new UserFunctions();
            JSONObject json31 = userFunctions.rotatePhoto(username, password, naam_to_delete, "0");

            return null;
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onPostExecute(Void result) {
            rand = CommonUtilities.randInt(111, 999);

            Brows();
        }
    }
}