sjizl.com.FileUploadTest2.java Source code

Java tutorial

Introduction

Here is the source code for sjizl.com.FileUploadTest2.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 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 sjizl.com.ProfileActivity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
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.Bundle;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
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.ProgressBar;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import sjizl.com.Constants.Extra;
import sjizl.com.libary.UserFunctions;

import com.navdrawer.SimpleSideDrawer;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import static sjizl.com.CommonUtilities.options;

/**
 * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
 */
@SuppressLint("NewApi")
public class FileUploadTest2 extends AbsListViewBaseActivity {

    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;
    Spinner spinner1;
    String[] imageUrls2, names, laatste_bericht, fotos, fotos_nums, aantal_new_ber;
    String[] stockArr, stockArr2, stockArr3, stockArr4, stockArr5, stockArr6;
    String username, password, naam, foto, foto_num;
    ArrayList<String> stock_list, stock_list2, stock_list3, stock_list4, stock_list5, stock_list6, stock_list7;

    TextView tv, res;

    @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);

        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);
        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.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "UploadActivity!", Toast.LENGTH_LONG).show();
                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);

        Brows();

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

                Intent dashboard = new Intent(getApplicationContext(), ProfileActivity.class);
                dashboard.putExtra("user", naam);
                dashboard.putExtra("user_foto", foto);
                dashboard.putExtra("user_foto_num", foto_num);

                startActivity(dashboard);

            }
        });

        CommonUtilities u = new CommonUtilities();
        u.setHeaderConrols(getApplicationContext(), this,

                right_lin,

                left_lin3, left_lin4, left_lin1, left_button);
        ;

    }

    @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();

        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>();

        for (int i = 0; i < json31.length(); i++) { // **line 2**
            JSONObject childJSONObject = null;
            try {
                childJSONObject = json31.getJSONObject(i);

                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");

                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()];

        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);

        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) {
            final ImageView imageView;
            if (convertView == null) {
                imageView = (ImageView) getLayoutInflater().inflate(R.layout.item_grid_image, parent, false);
            } else {
                imageView = (ImageView) convertView;
            }

            imageLoader.displayImage(imageUrls2[position], imageView, options);

            return imageView;
        }
    }

    public void openGallery(int req_code) {

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

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

        if (resultCode == RESULT_OK) {
            Uri selectedImageUri = data.getData();
            if (requestCode == SELECT_FILE1) {
                selectedPath1 = getPath(selectedImageUri);
                progressDialog = ProgressDialog.show(FileUploadTest2.this, "", "Uploading files to server.....",
                        false);
                Thread thread = new Thread(new Runnable() {
                    public void run() {
                        doFileUpload();
                        runOnUiThread(new Runnable() {
                            public void run() {
                                if (progressDialog.isShowing())
                                    progressDialog.dismiss();
                            }
                        });
                    }
                });
                thread.start();
            }
            finish();
        }
    }

    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 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(selectedPath1);

        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(), FileUploadTest2.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());

    }

}