码迷,mamicode.com
首页 > Web开发 > 详细

个人头像上传

时间:2016-05-12 20:14:42      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

package com.example.washcarproject.activities;

import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.example.washcarproject.R;
import com.example.washcarproject.been.UserInfo;
import com.example.washcarproject.fragments.BaseFragmentActivity;
import com.example.washcarproject.fragments.BookListFragment;
import com.example.washcarproject.fragments.FirstPageFragment;
import com.example.washcarproject.fragments.PersonalInfoFragment;
import com.example.washcarproject.utils.Constant;
import com.example.washcarproject.utils.ToastUtils;
import com.example.washcarproject.webconnection.InternetConnect;
import com.example.washcarproject.webconnection.MyAllHttpMethod;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;

public class WashCarActivity extends BaseFragmentActivity {
    private TextView mTitle;
    private ImageView mImgBack;
    private LinearLayout mLinearWeather;
    private RadioButton mRadioFirstPage;
    private RadioButton mRadioBooklist;
    private RadioButton mRadioPersonalInfo;
    private FirstPageFragment firstPageFragment;
    private BookListFragment bookListFragment;
    private PersonalInfoFragment personalInfoFragment;
    private FragmentTransaction transaction;
    private FragmentManager manager;
    private TextView textAddress;
    private TextView textTmpobj;

    private UserInfo userInfo;
    private ImageView imgHead;
    private static final int REQUST_CODE_IMG = 10;
    private static final int HANDLER_WEATHER = 0X22;
    private ImageView weatherIcon;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case HANDLER_WEATHER:
                    if(!isgetLocation){
                        handler.sendEmptyMessageDelayed(HANDLER_WEATHER,1000);
                    }else {
                        getWeather();
                    }
                break;
            }
        }
    };



    @Override
    protected void setListener() {
        mRadioFirstPage.setOnClickListener(this);
        mRadioBooklist.setOnClickListener(this);
        mRadioPersonalInfo.setOnClickListener(this);
        mLinearWeather.setOnClickListener(this);

    }


    @Override
    public void setView() {
        setContentView(R.layout.activity_wash_car);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void initView() {
        mTitle = (TextView) findViewById(R.id.title);
        mImgBack = (ImageView) findViewById(R.id.img_back);
        textAddress = (TextView) findViewById(R.id.text_address);
        textTmpobj = (TextView) findViewById(R.id.text_temperature);
        mLinearWeather = (LinearLayout) findViewById(R.id.linear_weather);
        mRadioFirstPage = (RadioButton) findViewById(R.id.radio_firstpage);
        mRadioBooklist = (RadioButton) findViewById(R.id.radio_booklist);
        mRadioPersonalInfo = (RadioButton) findViewById(R.id.radio_personinfo);
        weatherIcon = (ImageView) findViewById(R.id.weather_icon);
//        imgHead = (ImageView) findViewById(R.id.img_head);
        mImgBack.setVisibility(View.GONE);
        mLinearWeather.setVisibility(View.VISIBLE);
        mTitle.setText("首页");


    }

    @Override
    protected void setLogicAfterInit() {


        //初始化
        firstPageFragment = new FirstPageFragment();
        bookListFragment = new BookListFragment();
        personalInfoFragment = new PersonalInfoFragment();
        userInfo = getUserInfo();
        Bundle bundle = new Bundle();
        bundle.putSerializable(Constant.KEY_USER_INFO, userInfo);

        firstPageFragment.setArguments(bundle);
        bookListFragment.setArguments(bundle);
        personalInfoFragment.setArguments(bundle);
        manager = getSupportFragmentManager();
        transaction = manager.beginTransaction();
        transaction.add(R.id.linear_fragment_content,firstPageFragment);
        transaction.add(R.id.linear_fragment_content,bookListFragment);
        transaction.add(R.id.linear_fragment_content, personalInfoFragment);
        transaction.hide(bookListFragment);
        transaction.hide(personalInfoFragment);
        transaction.commit();
        switchContent(firstPageFragment, bookListFragment, personalInfoFragment);

        showLoadingDialog(mContext);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg = new Message();
                msg.what = HANDLER_WEATHER;
                handler.sendMessage(msg);
            }
        }).start();





    }


    @Override
    protected void setClick(View v) {
        switch (v.getId()){
            case R.id.radio_firstpage:
                mRadioFirstPage.setTextColor(getResources().getColor(R.color.new_bottom_button_text));
                mRadioBooklist.setTextColor(getResources().getColor(R.color.book_list_button_commen));
                mRadioPersonalInfo.setTextColor(getResources().getColor(R.color.book_list_button_commen));
                mTitle.setText("首页");
                mImgBack.setVisibility(View.GONE);
                switchContent(firstPageFragment,bookListFragment,personalInfoFragment);
//                mHandler.sendEmptyMessageDelayed(AUTO_MSG, PHOTO_CHANGE_TIME);
                break;
            case R.id.radio_booklist:
                mRadioFirstPage.setTextColor(getResources().getColor(R.color.book_list_button_commen));
                mRadioBooklist.setTextColor(getResources().getColor(R.color.new_bottom_button_text));
                mRadioPersonalInfo.setTextColor(getResources().getColor(R.color.book_list_button_commen));
                mTitle.setText("预约列表");
                mImgBack.setVisibility(View.GONE);
                switchContent(bookListFragment,firstPageFragment,personalInfoFragment);
                break;
            case R.id.radio_personinfo:
                mRadioFirstPage.setTextColor(getResources().getColor(R.color.book_list_button_commen));
                mRadioBooklist.setTextColor(getResources().getColor(R.color.book_list_button_commen));
                mRadioPersonalInfo.setTextColor(getResources().getColor(R.color.new_bottom_button_text));
                mTitle.setText("个人信息");
                mImgBack.setVisibility(View.GONE);
                switchContent(personalInfoFragment,firstPageFragment,bookListFragment);
                imgHead = (ImageView) personalInfoFragment.getView().findViewById(R.id.img_head);
                if(userInfo.getUser_logo()!=null){
                    imageLoader(userInfo.getUser_logo(),imgHead);

                }
                imgHead.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                /* 开启Pictures画面Type设定为image */
                        intent.setType("image/*");
                /* 使用Intent.ACTION_GET_CONTENT这个Action */
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                /* 取得相片后返回本画面 */
                        startActivityForResult(intent, REQUST_CODE_IMG);

                    }
                });

                break;
            case R.id.linear_weather:
                mLocationClient.requestLocation();
                getWeather();

                break;
        }
    }

    /**
     * imageloader图片设置
     * @param urlImg
     * @param img
     */
    private void imageLoader(String urlImg,ImageView img) {

        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showStubImage(R.mipmap.one)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.one)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.one)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisc(true)                          // 设置下载的图片是否缓存在SD卡中
                .build();                                   // 创建配置过得DisplayImageOption对象

        ImageLoader.getInstance().displayImage(urlImg, img, options);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode){
                case REQUST_CODE_IMG:
                    Uri uri = data.getData();
                    imgHead.setImageURI(uri);
                    ContentResolver cr = this.getContentResolver();
                    Bitmap bitmap = null;
                    try {
                        bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
                        if(bitmap!=null){
                            commitImg(Bitmap2StrByBase64(bitmap));
                        }else {
                            ToastUtils.show(mContext,"上传异常!");
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }


                    break;
            }

        }

    }

    /**
     * 通过Base32将Bitmap转换成Base64字符串
     * @param bit
     * @return
     */
    public String Bitmap2StrByBase64(Bitmap bit){
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 40, bos);//参数100表示不压缩
        byte[] bytes=bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }


    /**
     * 上传图片
     */
    private void commitImg(String data) {
        if(dialog==null){
            showLoadingDialog(mContext);
        }

        HashMap<String,String> params =  new HashMap<String, String>();
        params.put("image",data);
        MyAllHttpMethod.newInstance().upLoadImg(params, new InternetConnect.onConnectionListener() {
            @Override
            public void onNullInternet() {
                dialog.cancel();
                ToastUtils.show(mContext, "没有网络,请打开网络!");
            }

            @Override
            public void onFailConnection(String message) {
                dialog.cancel();
                ToastUtils.show(mContext, "网络连接错误" + message);
            }

            @Override
            public void onSuccess(String response) {
                dialog.cancel();
                Log.d("car",response);

                try {
                    JSONObject object = new JSONObject(response);//建立response的jsonobject
                    String successCode = object.getString("success");
                    if (TextUtils.equals(successCode, "0")) {
                        String url = object.getString("url");

                        ToastUtils.show(mContext, "上传头像成功!url:"+url);
                        //图片显示

                    } else {
                        ToastUtils.show(mContext, "上传信息失败!");
                    }

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


            }
        });
    }

//    private void submitUploadFile(){
//        final File file=new File(srcPath);
//        final String RequestURL= WebApiConfig.URL_UPLOAD_HEAD;
//        if (file == null || (!file.exists())) {
//            return;
//        }
//
//        Log.i(TAG, "请求的URL=" + RequestURL);
//        Log.i(TAG, "请求的fileName=" + file.getName());
//        final Map<String, String> params = new HashMap<String, String>();
//        params.put("user_id", loginKey);
//        params.put("file_type", "1");
//        params.put("content", img_content.getText().toString());
//
//        new Thread(new Runnable() { //开启线程上传文件
//            @Override
//            public void run() {
//                uploadFile(file, RequestURL,params);
//            }
//        }).start();
//    }

//    }

    public static Intent getIntent(Context context, UserInfo userInfo){
        Intent intent = new Intent(context,WashCarActivity.class);
        intent.putExtra(Constant.KEY_USER_INFO,userInfo);

        return intent;
    }

    public void switchContent(Fragment fragment,Fragment fragmentone,Fragment fragmenttwo){
        transaction = manager.beginTransaction();
        transaction.hide(fragmentone);
        transaction.hide(fragmenttwo);
        transaction.show(fragment);
        transaction.commit();



    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public UserInfo getUserInfo(){
        Intent intent = getIntent();
        UserInfo user = (UserInfo) intent.getSerializableExtra(Constant.KEY_USER_INFO);
        return user;

    }

    public void getWeather() {
        if(dialog==null){
            showLoadingDialog(mContext);
        }

        HashMap<String,String> params =  new HashMap<String, String>();
        Log.d("car","longitude_commit"+BaseFragmentActivity.longitude+"latitude_commit"+BaseFragmentActivity.latitude);
        String location_x = String.valueOf(BaseFragmentActivity.longitude);
        String location_y = String
                .valueOf(BaseFragmentActivity.latitude);
        params.put("location_x",location_x);
        params.put("location_y",location_y);
        Log.d("car", "location_y:"+location_x+"location_y:"+location_y);
        MyAllHttpMethod.newInstance().weather(params, new InternetConnect.onConnectionListener() {
            @Override
            public void onNullInternet() {
                dialog.cancel();
                ToastUtils.show(mContext, "没有网络,请打开网络!");
            }

            @Override
            public void onFailConnection(String message) {
                dialog.cancel();
                ToastUtils.show(mContext, "网络连接错误" + message);
            }

            @Override
            public void onSuccess(String response) {
                dialog.cancel();
                Log.d("car", response);

                try {
                    JSONObject object = new JSONObject(response);//建立response的jsonobject
                    String successCode = object.getString("success");
                    if (TextUtils.equals(successCode, "0")) {
                        JSONObject weather = object.getJSONObject("weather");
                        String city = weather.getString("city");
                        String temobj = weather.getString("temobj");
                        String weatherCurrent = weather.getString("weather");

//                        if(!TextUtils.isEmpty(city)&& !TextUtils.isEmpty(temobj)&& !TextUtils.isEmpty(temobj)){
                            textAddress.setText(city);
                            textTmpobj.setText(temobj);
//                        weatherIcon.setImageResource(getImageIdByName(weatherCurrent));
                        if(TextUtils.equals(weatherCurrent,"晴")){
                            weatherIcon.setImageResource(R.mipmap.sunny);
                        }else if(TextUtils.equals(weatherCurrent,"晴")){
                            weatherIcon.setImageResource(R.mipmap.cloudy);
                        }else if(TextUtils.equals(weatherCurrent,"晴")){
                            weatherIcon.setImageResource(R.mipmap.cloudy_sunny);
                        }else if(TextUtils.equals(weatherCurrent,"晴")){
                            weatherIcon.setImageResource(R.mipmap.snow);

                        }else if(TextUtils.equals(weatherCurrent,"晴")){
                            weatherIcon.setImageResource(R.mipmap.light_rain);

                        }else if(TextUtils.equals(weatherCurrent,"晴")){
                            weatherIcon.setImageResource(R.mipmap.rain);

                        }

//                        }else {
//                            ToastUtils.show(mContext,"获取的信息为空!");
//                        }



                        ToastUtils.show(mContext, "获取天气信息成功!");
                        //图片显示

                    } else {
                        ToastUtils.show(mContext, "获取天气信息失败!");
                    }

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


            }
        });

    }
    /**
     * 根据图片名称获取R.java中对应的id
     *
     * @param name
     * @return
     */
    public static int getImageIdByName (String name) {
        int value = 0;
        if (null != name) {
            if (name.indexOf(".") != -1) {
                name = name.substring(0, name.indexOf("."));
            }
            Class<com.example.washcarproject.R.mipmap> cls = R.mipmap.class;
            try {
                value = cls.getDeclaredField(name).getInt(null);
            } catch (Exception e) {

            }
        }
        return value;
    }


}

个人头像上传

标签:

原文地址:http://blog.csdn.net/womengmengyan/article/details/51352818

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!