Android实现头像上传至数据库与保存 简易新闻(十七 上)

  • 关于
  • 实现步骤
    • 第一步,修改styles.xml
    • 第二步,添加对应Anim
    • 第三步,添加弹出Actionsheet的选择器
    • 第四步,添加ActionSheet.java
    • 第五步,修改MainActivity.java

关于

由于直接一篇实现拍照图片的base64上传至数据库,再从数据库中取出转换成图片显示涉及较多,篇幅较长,所以改为上下两篇,本篇实现点击头像进行自定义弹出选择拍照还是图像模式。下篇实现图片转码上传与查询显示。关于图片实现baseEncoder64的编码与解码可以参考:Android使用 BASE64Encoder实现图片的Base64编码转换(可用来存储到数据库中)学习笔记(一)与
Android实现将Base64Encoder编码转为图片学习笔记(二)
本篇实现效果如下:

实现步骤

第一步,修改styles.xml

添加弹出Actionsheet的style

<style name="ActionSheetStyle" parent="@android:style/Theme.Dialog"><!-- 背景透明 --><item name="android:windowBackground">@android:color/transparent</item><item name="android:windowContentOverlay">@null</item><!-- 浮于Activity之上 --><item name="android:windowIsFloating">true</item><!-- 边框 --><item name="android:windowFrame">@null</item><!-- Dialog以外的区域模糊效果 --><item name="android:backgroundDimEnabled">true</item><!-- 无标题 --><item name="android:windowNoTitle">true</item><!-- 半透明 --><item name="android:windowIsTranslucent">true</item><!-- Dialog进入及退出动画 --><item name="android:windowAnimationStyle">@style/ActionSheetAnimation</item></style><!-- ActionSheet进出动画 --><style name="ActionSheetAnimation" parent="@android:style/Animation.Dialog"><item name="android:windowEnterAnimation">@anim/actionsheet_in</item><item name="android:windowExitAnimation">@anim/actionsheet_out</item></style>

第二步,添加对应Anim

在res下新建文件夹anim,在anim文件夹下新增actionsheet的进出动画设置
actionsheet_in.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"android:duration="200"android:fromYDelta="100%"android:toYDelta="0" />

actionsheet_out.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"android:duration="200"android:fromYDelta="0"android:toYDelta="100%" />

第三步,添加弹出Actionsheet的选择器

dialog_bottom_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"><item android:drawable="@drawable/dialog_bottom_up" android:state_pressed="false"></item><item android:drawable="@drawable/dialog_bottom_down" android:state_pressed="true"></item></selector>

dialog_bottom_up.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"><solid android:color="#e3ffffff" /><cornersandroid:bottomLeftRadius="10dp"android:bottomRightRadius="10dp" /></shape>

dialog_bottom_down.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"><solid android:color="#e3eeeeee" /><cornersandroid:bottomLeftRadius="10dp"android:bottomRightRadius="10dp" /></shape>

layout_white_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"><item android:drawable="@drawable/layout_white_up" android:state_pressed="false"></item><item android:drawable="@drawable/layout_white_down" android:state_pressed="true"></item></selector>

layout_white_up.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"><solid android:color="#e3ffffff" /></shape>

layout_white_down.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"><solid android:color="#e3eeeeee" /></shape>

dialog_white_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"><item android:drawable="@drawable/dialog_white_up" android:state_pressed="false"></item><item android:drawable="@drawable/dialog_white_down" android:state_pressed="true"></item></selector>

dialog_white_up.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"><solid android:color="#e3ffffff" /><corners android:radius="10dp" /></shape>

dialog_white_down.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"><solid android:color="#e3eeeeee" /></shape>

dialog_top_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"><item android:drawable="@drawable/dialog_top_up" android:state_pressed="false"></item><item android:drawable="@drawable/dialog_top_down" android:state_pressed="true"></item></selector>

dialog_top_up.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"><solid android:color="#e3ffffff" /><cornersandroid:topLeftRadius="10dp"android:topRightRadius="10dp" /></shape>

dialog_top_down.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"><solid android:color="#e3eeeeee" /><cornersandroid:topLeftRadius="10dp"android:topRightRadius="10dp" /></shape>

第四步,添加ActionSheet.java

package com.example.frametest.tools;import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;import com.example.frametest.R;import java.util.ArrayList;public class ActionSheet extends Dialog {private Context context;private LinearLayout parentLayout;private TextView titleTextView;private ArrayList<Button> sheetList;private Button cancelButton;// 标题private String title;//就取消按钮文字private String cancel;// 选择项文字列表private ArrayList<String> sheetTextList;// 标题颜色private int titleTextColor;// 取消按钮文字颜色private int cancelTextColor;// 选择项文字颜色private int sheetTextColor;// 标题大小private int titleTextSize;// 取消按钮文字大小private int cancelTextSize;// 选择项文字大小private int sheetTextSize;// 标题栏高度private int titleHeight;// 取消按钮高度private int cancelHeight;// 选择项高度private int sheetHeight;// 弹出框距离底部的高度private int marginBottom;// 取消按钮点击回调private View.OnClickListener cancelListener;// 选择项点击回调列表private ArrayList<View.OnClickListener> sheetListenerList;public ActionSheet(Context context) {super(context, R.style.ActionSheetStyle);init(context);}public ActionSheet(Context context, int theme) {super(context, theme);init(context);}private void init(Context context) {this.context = context;cancel = "取消";titleTextColor = Color.parseColor("#aaaaaa");cancelTextColor = Color.parseColor("#666666");sheetTextColor = Color.parseColor("#1E90FF");titleTextSize = 14;cancelTextSize = 16;sheetTextSize = 16;titleHeight = dp2px(40);cancelHeight = dp2px(40);sheetHeight = dp2px(40);marginBottom = dp2px(10);sheetList = new ArrayList<>();sheetTextList = new ArrayList<>();sheetListenerList = new ArrayList<>();}private ActionSheet createDialog() {parentLayout = new LinearLayout(context);parentLayout.setBackgroundColor(Color.parseColor("#00000000"));parentLayout.setOrientation(LinearLayout.VERTICAL);if (title != null) {titleTextView = new TextView(context);titleTextView.setGravity(Gravity.CENTER);titleTextView.setText(title);titleTextView.setTextColor(titleTextColor);titleTextView.setTextSize(titleTextSize);titleTextView.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.dialog_top_up));LinearLayout.LayoutParams titleLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, titleHeight);parentLayout.addView(titleTextView, titleLayoutParams);}for (int i = 0; i < sheetTextList.size(); i++) {if (i == 0 && title != null) {View topDividerLine = new View(context);topDividerLine.setBackgroundColor(Color.parseColor("#eeeeee"));parentLayout.addView(topDividerLine, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp2px(1)));}Button button = new Button(context);button.setGravity(Gravity.CENTER);button.setText(sheetTextList.get(i));button.setTextColor(sheetTextColor);button.setTextSize(sheetTextSize);if (title != null) {if (i == sheetTextList.size() - 1) {button.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.dialog_bottom_selector));} else {button.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.layout_white_selector));}} else {if (sheetTextList.size() == 1) {button.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.dialog_white_selector));} else {if (i == 0) {button.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.dialog_top_selector));} else if (i == sheetTextList.size() - 1) {button.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.dialog_bottom_selector));} else {button.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.layout_white_selector));}}}button.setOnClickListener(sheetListenerList.get(i));LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, sheetHeight);parentLayout.addView(button, layoutParams);sheetList.add(button);if (i != sheetTextList.size() - 1) {View bottomDividerLine = new View(context);bottomDividerLine.setBackgroundColor(Color.parseColor("#8A8A8A"));parentLayout.addView(bottomDividerLine, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp2px(1)));}}cancelButton = new Button(context);cancelButton.setGravity(Gravity.CENTER);cancelButton.setText(cancel);cancelButton.setTextColor(cancelTextColor);cancelButton.setTextSize(cancelTextSize);cancelButton.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.dialog_white_selector));cancelButton.setOnClickListener(cancelListener);LinearLayout.LayoutParams cancelParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, cancelHeight);cancelParams.setMargins(0, dp2px(10), 0, 0);parentLayout.addView(cancelButton, cancelParams);getWindow().setGravity(Gravity.BOTTOM);getWindow().getAttributes().y = marginBottom;show();setContentView(parentLayout);setCancelable(true);setCanceledOnTouchOutside(true);return this;}private void addSheet(String text, View.OnClickListener listener) {sheetTextList.add(text);sheetListenerList.add(listener);}public void setCancel(String text) {this.cancel = text;}public void setCancelHeight(int height) {this.cancelHeight = dp2px(height);}public void setCancelTextColor(int color) {this.cancelTextColor = color;}public void setCancelTextSize(int textSize) {this.cancelTextSize = textSize;}public void setSheetHeight(int height) {this.sheetHeight = dp2px(height);}public void setSheetTextColor(int color) {this.sheetTextColor = color;}public void setSheetTextSize(int textSize) {this.sheetTextSize = textSize;}public void setTitle(String text) {this.title = text;}public void setTitleHeight(int height) {this.titleHeight = height;}public void setTitleTextColor(int color) {this.titleTextColor = color;}public void setTitleTextSize(int textSize) {this.titleTextSize = textSize;}public void setMargin(int bottom) {this.marginBottom = dp2px(bottom);}public void addCancelListener(View.OnClickListener listener) {this.cancelListener = listener;}private int dp2px(float dipValue) {float scale = context.getResources().getDisplayMetrics().density;return (int) (dipValue * scale + 0.5f);}public static class DialogBuilder {ActionSheet dialog;public DialogBuilder(Context context) {dialog = new ActionSheet(context);}/*** 添加一个选择项* @param text 选择项文字* @param listener 选择项点击回调监听* @return 当前DialogBuilder*/public DialogBuilder addSheet(String text, View.OnClickListener listener) {dialog.addSheet(text, listener);return this;}/*** 设置取消按钮文字* @param text 文字内容* @return 当前DialogBuilder*/public DialogBuilder setCancel(String text) {dialog.setCancel(text);return this;}/*** 设置取消按钮高度* @param height 高度值,单位dp* @return 当前DialogBuilder*/public DialogBuilder setCancelHeight(int height) {dialog.setCancelHeight(height);return this;}/*** 设置取消按钮文字颜色* @param color 颜色值* @return 当前DialogBuilder*/public DialogBuilder setCancelTextColor(int color) {dialog.setCancelTextColor(color);return this;}/*** 设置取消按钮文字大小* @param textSize 大小值,单位sp* @return 当前DialogBuilder*/public DialogBuilder setCancelTextSize(int textSize) {dialog.setCancelTextSize(textSize);return this;}/*** 设置选择项高度* @param height 高度值,单位dp* @return 当前DialogBuilder*/public DialogBuilder setSheetHeight(int height) {dialog.setSheetHeight(height);return this;}/*** 设置选择项文字颜色* @param color 颜色值* @return 当前DialogBuilder*/public DialogBuilder setSheetTextColor(int color) {dialog.setSheetTextColor(color);return this;}/*** 设置选择项文字大小* @param textSize 大小值,单位sp* @return 当前DialogBuilder*/public DialogBuilder setSheetTextSize(int textSize) {dialog.setSheetTextSize(textSize);return this;}/*** 设置标题* @param text 文字内容* @return 当前DialogBuilder*/public DialogBuilder setTitle(String text) {dialog.setTitle(text);return this;}/*** 设置标题栏高度* @param height 高度值,单位dp* @return 当前DialogBuilder*/public DialogBuilder setTitleHeight(int height) {dialog.setTitleHeight(height);return this;}/*** 设置标题颜色* @param color 颜色值* @return 当前DialogBuilder*/public DialogBuilder setTitleTextColor(int color) {dialog.setTitleTextColor(color);return this;}/*** 设置标题大小* @param textSize 大小值,单位sp* @return 当前DialogBuilder*/public DialogBuilder setTitleTextSize(int textSize) {dialog.setTitleTextSize(textSize);return this;}/*** 设置弹出框距离底部的高度* @param bottom 距离值,单位dp* @return 当前DialogBuilder*/public DialogBuilder setMargin(int bottom) {dialog.setMargin(bottom);return this;}/*** 设置取消按钮的点击回调* @param listener 回调监听* @return*/public DialogBuilder addCancelListener(View.OnClickListener listener) {dialog.addCancelListener(listener);return this;}/*** 创建弹出框,放在最后执行* @return 创建的 ActionSheet 实体*/public ActionSheet create() {return dialog.createDialog();}}}

第五步,修改MainActivity.java

关于头像的原型化引用:

implementation 'de.hdodenhof:circleimageview:2.1.0'

这个在之前编写DrawerLayout的时候已经介绍过了,就不再附上MainActivity的布局文件了。

package com.example.frametest;import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.cazaea.sweetalert.SweetAlertDialog;
import com.example.frametest.CrashHandle.AppStatus;
import com.example.frametest.CrashHandle.AppStatusManager;
import com.example.frametest.PersonSettings.HomeSettingsActivity;
import com.example.frametest.UserMode.LoginActivity;
import com.example.frametest.UserMode.SplashActivity;
import com.example.frametest.UserMode.User;
import com.example.frametest.UserMode.UserFavoriteActivity;
import com.example.frametest.UserMode.User_DataActivity;
import com.example.frametest.tools.ActionSheet;
import com.example.frametest.tools.ActivityCollector;
import com.example.frametest.tools.BasicActivity;
import com.example.frametest.tools.DBOpenHelper;
import com.example.frametest.tools.MyApplication;
import com.example.frametest.tools.NetworkStateUtil;
import com.example.frametest.tools.ToastUtil;
import com.google.gson.Gson;import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import de.hdodenhof.circleimageview.CircleImageView;
import interfaces.heweather.com.interfacesmodule.bean.Lang;
import interfaces.heweather.com.interfacesmodule.bean.Unit;
import interfaces.heweather.com.interfacesmodule.bean.air.now.AirNow;
import interfaces.heweather.com.interfacesmodule.bean.weather.now.Now;
import interfaces.heweather.com.interfacesmodule.view.HeWeather;
import jp.wasabeef.glide.transformations.BlurTransformation;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;public class MainActivity extends BasicActivity {private android.support.v7.widget.Toolbar toolbar;private DrawerLayout mDrawerLayout;private NavigationView navigationView;private TabLayout tabLayout;private ViewPager viewPager;private List<String> list;private TextView tvhuoqu, tvName;String phonenumber, userName;private static final int USER_LOOK_NAME = 0;private static final int USER_FEEDBACK = 1;private static final int USER_ISNULL = 2;private static final int NO_WORK_CONNECTED = 999;private static boolean mBackKeyPressed = false;//记录是否有首次按键private TextView tv_tianqi, tv_kongqi, tv_airqlty;ImageView image_weather, image_exit;ImageView imageView_beij;CircleImageView circleImageView;//添加resultcodeprivate final int IMAGE_RESULT_CODE = 3;//表示打开照相机private final int PICK = 4;//选择图片public AMapLocationClient mLocationClient = null;//声明定位回调监听器public AMapLocationClientOption mLocationOption = null;private ActionSheet actionSheet;private String CityId;static Context mContext;  @SuppressLint("HandlerLeak")private Handler userFeedHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {String admin_title, admin_url, user_name;switch (msg.what) {case USER_LOOK_NAME:User user = (User) msg.obj;user_name = user.getUser_name();      tvName = (TextView) findViewById(R.id.text_username);tvName.setText(user_name);break;case USER_FEEDBACK:Toast.makeText(MainActivity.this, "反馈成功", Toast.LENGTH_SHORT).show();break;case USER_ISNULL:Toast.makeText(MainActivity.this, "用户未登录!", Toast.LENGTH_SHORT).show();break;case NO_WORK_CONNECTED://无网络连接显示tvName = (TextView) findViewById(R.id.text_username);tvName.setText("无网络连接,请检查网络");Toast.makeText(MainActivity.this, "无网络连接", Toast.LENGTH_SHORT).show();break;    default:break;}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);if (AppStatusManager.getInstance().getAppStatus() == AppStatus.STATUS_RECYCLE) {Intent intent = new Intent(this, SplashActivity.class);startActivity(intent);finish();return;}setContentView(R.layout.activity_main);mContext = getApplicationContext();initMap();toolbar = findViewById(R.id.toolbar);mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); //获取抽屉布局navigationView = (NavigationView) findViewById(R.id.nav_design);//获取菜单控件实例View v = navigationView.getHeaderView(0);circleImageView = (CircleImageView) v.findViewById(R.id.icon_image);//背景图片imageView_beij = v.findViewById(R.id.image_beij);tabLayout = (TabLayout) findViewById(R.id.tabLayout);viewPager = (ViewPager) findViewById(R.id.viewPager);list = new ArrayList<>();tvhuoqu = (TextView) findViewById(R.id.text_huoqu);tv_tianqi = (TextView) findViewById(R.id.tv_tianqi);tv_kongqi = (TextView) findViewById(R.id.tv_kongqi);image_weather = (ImageView) findViewById(R.id.img_weather);tv_airqlty = (TextView) findViewById(R.id.tv_airqlty);}RelativeLayout relativeLayout_beijing;private void initMap() {//初始化定位mLocationClient = new AMapLocationClient(MainActivity.this);//设置定位回调监听mLocationClient.setLocationListener(mLocationListener);mLocationOption = new AMapLocationClientOption();
//设置定位模式为高精度模式,AMapLocationMode.Battery_Saving为低功耗模式,AMapLocationMode.Device_Sensors是仅设备模式mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);mLocationOption.setNeedAddress(true);//设置是否返回地址信息(默认返回地址信息)mLocationOption.setOnceLocation(false);//设置是否只定位一次,默认为falsemLocationOption.setWifiActiveScan(true);//设置是否强制刷新WIFI,默认为强制刷新mLocationOption.setMockEnable(false);//设置是否允许模拟位置,默认为false,不允许模拟位置mLocationOption.setInterval(15000);//设置定位间隔,单位毫秒,默认为2000msmLocationOption.setOnceLocation(false);//可选,是否设置单次定位默认为false即持续定位mLocationOption.setOnceLocationLatest(false); //可选,设置是否等待wifi刷新,默认为false.如果设置为true,会自动变为单次定位,持续定位时不要使用mLocationOption.setWifiScan(true); //可选,设置是否开启wifi扫描。默认为true,如果设置为false会同时停止主动刷新,停止以后完全依赖于系统刷新,定位位置可能存在误差mLocationOption.setLocationCacheEnable(true); //可选,设置是否使用缓存定位,默认为true
//给定位客户端对象设置定位参数mLocationClient.setLocationOption(mLocationOption);
//启动定位mLocationClient.startLocation();     }public AMapLocationListener mLocationListener = new AMapLocationListener() {@Overridepublic void onLocationChanged(AMapLocation aMapLocation) {if (aMapLocation != null) {if (aMapLocation.getErrorCode() == 0) {//定位成功回调信息,设置相关消息aMapLocation.getLocationType();//获取当前定位结果来源,如网络定位结果,详见定位类型表// aMapLocation.getLatitude();//获取纬度// aMapLocation.getLongitude();//获取经度aMapLocation.getAccuracy();//获取精度信息java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//  aMapLocation.getAddress();//地址,如果option中设置isNeedAddress为false,则没有此结果,网络定位结果中会有地址信息,GPS定位不返回地址信息。//  aMapLocation.getCountry();//国家信息//  aMapLocation.getProvince();//省信息//  aMapLocation.getCity();//城市信息//   aMapLocation.getDistrict();//城区信息//    aMapLocation.getStreet();//街道信息//     aMapLocation.getStreetNum();//街道门牌号信息//    aMapLocation.getCityCode();//城市编码//     aMapLocation.getAdCode();//地区编码//获取经纬度double LongitudeId = aMapLocation.getLongitude();double LatitudeId = aMapLocation.getLatitude();//获取定位城市定位的IDrequestCityInfo(LongitudeId, LatitudeId);mLocationClient.stopLocation();//停止定位} else {//显示错误信息ErrCode是错误码,errInfo是错误信息,详见错误码表。Log.e("info", "location Error, ErrCode:"+ aMapLocation.getErrorCode() + ", errInfo:"+ aMapLocation.getErrorInfo());}}}};public void requestCityInfo(double longitude, double latitude) {//这里的key是webapi key 系列文章中有关于高德city城市编码的获取过程String cityUrl = "https://search.heweather.net/find?location=" + longitude + "," + latitude + "&key=6529xxxxxxxxxxxxxxx94d900dc2ca67e96";sendRequestWithOkHttp(cityUrl);}//解析根据经纬度获取到的含有城市id的json数据private void sendRequestWithOkHttp(String cityUrl) {new Thread(new Runnable() {@Overridepublic void run() {OkHttpClient okHttpClient = new OkHttpClient();Request request = new Request.Builder().url(cityUrl).build();try {Response response = okHttpClient.newCall(request).execute();//返回城市列表json数据String responseData = response.body().string();System.out.println("变成json数据的格式:" + responseData);JSONObject jsonWeather = null;try {jsonWeather = new JSONObject(responseData);JSONArray jsonArray = jsonWeather.getJSONArray("HeWeather6");JSONObject jsonObject = jsonArray.getJSONObject(0);String jsonStatus = jsonObject.getString("status");if (jsonStatus.equals("ok")) {JSONArray jsonBasic = jsonObject.getJSONArray("basic");JSONObject jsonCityId = jsonBasic.getJSONObject(0);CityId = jsonCityId.getString("cid");getWether();}} catch (JSONException e) {e.printStackTrace();}} catch (IOException e) {e.printStackTrace();}}}).start();}private void getWether() {/*** 实况天气* 实况天气即为当前时间点的天气状况以及温湿风压等气象指数,具体包含的数据:体感温度、* 实测温度、天气状况、风力、风速、风向、相对湿度、大气压强、降水量、能见度等。** @param context  上下文* @param location 地址详解* @param lang       多语言,默认为简体中文* @param unit        单位选择,公制(m)或英制(i),默认为公制单位* @param listener  网络访问回调接口*/HeWeather.getWeatherNow(MainActivity.this, CityId, Lang.CHINESE_SIMPLIFIED, Unit.METRIC, new HeWeather.OnResultWeatherNowBeanListener() {public static final String TAG = "he_feng_now";@Overridepublic void onError(Throwable e) {Log.i(TAG, "onError: ", e);System.out.println("Weather Now Error:" + new Gson());}@Overridepublic void onSuccess(Now dataObject) {Log.i(TAG, " Weather Now onSuccess: " + new Gson().toJson(dataObject));String jsonData = new Gson().toJson(dataObject);System.out.println("返回的数据内容:" + dataObject.getStatus());String tianqi = null, wendu = null, tianqicode = null;if (dataObject.getStatus().equals("ok")) {String JsonNow = new Gson().toJson(dataObject.getNow());JSONObject jsonObject = null;try {jsonObject = new JSONObject(JsonNow);tianqi = jsonObject.getString("cond_txt");wendu = jsonObject.getString("tmp");tianqicode = jsonObject.getString("cond_code");} catch (JSONException e) {e.printStackTrace();}} else {Toast.makeText(MainActivity.this, "有错误", Toast.LENGTH_SHORT).show();return;}String wendu2 = wendu + "℃";tv_tianqi.setText(tianqi);tv_kongqi.setText(wendu2);String tagurl = "https://cdn.heweather.com/cond_icon/" + tianqicode + ".png";Glide.with(MainActivity.this).load(tagurl).into(image_weather);}});HeWeather.getAirNow(MainActivity.this, CityId, Lang.CHINESE_SIMPLIFIED, Unit.METRIC, new HeWeather.OnResultAirNowBeansListener() {public static final String TAG2 = "he_feng_air";@Overridepublic void onError(Throwable throwable) {Log.i(TAG2, "ERROR IS:", throwable);}@Overridepublic void onSuccess(AirNow airNow) {Log.i(TAG2, "Air Now onSuccess:" + new Gson().toJson(airNow));String airStatus = airNow.getStatus();if (airStatus.equals("ok")) {String jsonData = new Gson().toJson(airNow.getAir_now_city());String aqi = null, qlty = null;JSONObject objectAir = null;try {objectAir = new JSONObject(jsonData);aqi = objectAir.getString("aqi");qlty = objectAir.getString("qlty");tv_airqlty.setText(qlty + "(" + aqi + ")");} catch (JSONException e) {e.printStackTrace();}} else {Toast.makeText(MainActivity.this, "有错误", Toast.LENGTH_SHORT).show();return;}}});}@Overrideprotected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {super.onActivityResult(requestCode, resultCode, data);switch (requestCode) {//表示调用照相机拍照case IMAGE_RESULT_CODE:if (resultCode == RESULT_OK) {    //result 返回的是-1 表示拍照成功 返回的是 0 表示拍照失败Bundle bundle = data.getExtras();Bitmap bitmap = (Bitmap) bundle.get("data");circleImageView.setImageBitmap(bitmap);              RequestOptions options = new RequestOptions().transforms(new BlurTransformation());//这里只是试一试Glide的模糊效果Glide.with(this).load(bitmap).apply(options).into(imageView_beij);            break;case PICK:if (resultCode == RESULT_OK) {Uri uri = data.getData();// photo_base64 = MainActivity.bitmapToString(uri);circleImageView.setImageURI(uri);RequestOptions options = new RequestOptions().transforms(new BlurTransformation());Glide.with(this).load(uri).apply(options).into(imageView_beij);}break;default:break;}}@Overrideprotected void onStart() {super.onStart();circleImageView.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {//本篇重点弹出actionSheet = new ActionSheet.DialogBuilder(MainActivity.this).addSheet("拍照", new View.OnClickListener() {@Overridepublic void onClick(View v) {Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);startActivityForResult(intent, IMAGE_RESULT_CODE);actionSheet.dismiss();}}).addSheet("图库", new View.OnClickListener() {@Overridepublic void onClick(View v) {Intent uintent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);startActivityForResult(uintent, PICK);actionSheet.dismiss();}}).addCancelListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {actionSheet.dismiss();}}).create();}});/* toolbar.setLogo(R.drawable.icon);//设置图片logo,你可以添加自己的图片*/toolbar.setTitle("简易新闻");setSupportActionBar(toolbar);ActionBar actionBar = getSupportActionBar();if (actionBar != null) {//通过HomeAsUp来让导航按钮显示出来actionBar.setDisplayHomeAsUpEnabled(true);//设置Indicator来添加一个点击图标actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_24dp);}navigationView.setCheckedItem(R.id.nav_call);//设置第一个默认选中navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {//设置菜单项的监听事件@Overridepublic boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {mDrawerLayout.closeDrawers();switch (menuItem.getItemId()) {case R.id.nav_call:phonenumber = MyApplication.getMoublefhoneUser();//通过判断手机号是否存在,来决定是进入编辑资料页面还是进入登陆页面if (phonenumber != null) {Intent unIntent = new Intent(MainActivity.this, User_DataActivity.class);unIntent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);startActivity(unIntent);} else {Intent exitIntent = new Intent(MainActivity.this, LoginActivity.class);exitIntent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);startActivity(exitIntent);}break;case R.id.nav_friends:Intent settingIntent = new Intent(MainActivity.this, HomeSettingsActivity.class);settingIntent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);startActivity(settingIntent);break;case R.id.nav_location:Toast.makeText(MainActivity.this, "你点击了发布新闻,下步实现", Toast.LENGTH_SHORT).show();break;case R.id.nav_favorite:phonenumber = MyApplication.getMoublefhoneUser();if (phonenumber != null) {Intent userFavIntent = new Intent(MainActivity.this, UserFavoriteActivity.class);startActivity(userFavIntent);} else {Intent exitIntent = new Intent(MainActivity.this, LoginActivity.class);startActivity(exitIntent);}break;case R.id.nav_settings:// Intent logoutIntent = new Intent(MainActivity.this,User_LogoutActivity.class);//  startActivity(logoutIntent);//  Toast.makeText(MainActivity.this,"需要做出注销功能,可扩展夜间模式,离线模式等,检查更新",Toast.LENGTH_LONG).show();break;case R.id.nav_exit:Intent intent = new Intent(MainActivity.this, LoginActivity.class);intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);startActivity(intent);break;default:}return true;}});list.add("头条");list.add("社会");list.add("国内");list.add("国际");list.add("娱乐");list.add("体育");list.add("军事");list.add("科技");list.add("财经");/* viewPager.setOffscreenPageLimit(1);*/viewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {//得到当前页的标题,也就是设置当前页面显示的标题是tabLayout对应标题@Nullable@Overridepublic CharSequence getPageTitle(int position) {return list.get(position);}@Overridepublic Fragment getItem(int position) {NewsFragment newsFragment = new NewsFragment();//判断所选的标题,进行传值显示Bundle bundle = new Bundle();if (list.get(position).equals("头条")) {bundle.putString("name", "top");} else if (list.get(position).equals("社会")) {bundle.putString("name", "shehui");} else if (list.get(position).equals("国内")) {bundle.putString("name", "guonei");} else if (list.get(position).equals("国际")) {bundle.putString("name", "guoji");} else if (list.get(position).equals("娱乐")) {bundle.putString("name", "yule");} else if (list.get(position).equals("体育")) {bundle.putString("name", "tiyu");} else if (list.get(position).equals("军事")) {bundle.putString("name", "junshi");} else if (list.get(position).equals("科技")) {bundle.putString("name", "keji");} else if (list.get(position).equals("财经")) {bundle.putString("name", "caijing");} else if (list.get(position).equals("时尚")) {bundle.putString("name", "shishang");}newsFragment.setArguments(bundle);return newsFragment;}@NonNull@Overridepublic Object instantiateItem(@NonNull ViewGroup container, int position) {NewsFragment newsFragment = (NewsFragment) super.instantiateItem(container, position);return newsFragment;}@Overridepublic int getItemPosition(@NonNull Object object) {return FragmentStatePagerAdapter.POSITION_NONE;}@Overridepublic int getCount() {return list.size();}});//TabLayout要与ViewPAger关联显示tabLayout.setupWithViewPager(viewPager);String inputText = load();if (!TextUtils.isEmpty(inputText)) {        phonenumber = inputText;MyApplication.setMoublefhoneUser(phonenumber);}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {//获取toolbar菜单项getMenuInflater().inflate(R.menu.toolbar, menu);return true;}   @SuppressLint("ResourceAsColor")@Overridepublic boolean onOptionsItemSelected(MenuItem item) {switch (item.getItemId()) {//R.id.home修改导航按钮的点击事件为打开侧滑栏case android.R.id.home:if (MyApplication.getMoublefhoneUser() != null) {phonenumber = MyApplication.getMoublefhoneUser();}mDrawerLayout.openDrawer(GravityCompat.START);  //打开侧滑栏tvhuoqu = (TextView) findViewById(R.id.text_huoqu);tvhuoqu.setText(phonenumber);if (NetworkStateUtil.isNetDisconnected(MyApplication.getContext())) {Message Nomessage = Message.obtain();Nomessage.what = NO_WORK_CONNECTED;userFeedHandler.sendMessage(Nomessage);} else {//用户开启侧滑栏时,查询数据库对应手机号的用户名,并显示在侧滑栏头部new Thread(new Runnable() {@Overridepublic void run() {Connection conn = null;conn = (Connection) DBOpenHelper.getConn();String sql = "select user_name from user_info where  user_phone ='" + phonenumber + "'";Statement pstmt;try {pstmt = (Statement) conn.createStatement();ResultSet rs = pstmt.executeQuery(sql);while (rs.next()) {User user = new User();user.setUser_name(rs.getString(1));                       //此处优化方法,去掉以前的new Message()这样会不断地新增一个Handle增加内存空间响应时间//Message msg = userFeedHandler.obtainMessage();msg.what = USER_LOOK_NAME;msg.obj = user;userFeedHandler.sendMessage(msg);}pstmt.close();conn.close();} catch (SQLException e) {e.printStackTrace();}}}).start();}break;case R.id.userFeedback:new MaterialDialog.Builder(MainActivity.this).title("意见反馈").inputRangeRes(2, 20, R.color.danlanse).inputType(InputType.TYPE_CLASS_TEXT).input("请输入反馈信息", null, new MaterialDialog.InputCallback() {@Overridepublic void onInput(@NonNull MaterialDialog dialog, CharSequence input) {new Thread(new Runnable() {@Overridepublic void run() {String input_text = input.toString();if ("".equals(MyApplication.getMoublefhoneUser()) || MyApplication.getMoublefhoneUser() == null) {Message msg = Message.obtain();msg.what = USER_ISNULL;userFeedHandler.sendMessage(msg);} else if ("".equals(input_text) || input_text == null) {Message msg = Message.obtain();msg.what = USER_FEEDBACK;userFeedHandler.sendMessage(msg);} else {if (NetworkStateUtil.isNetDisconnected(MyApplication.getContext())) {Message Nomessage = Message.obtain();Nomessage.what = NO_WORK_CONNECTED;userFeedHandler.sendMessage(Nomessage);} else {Connection conn = null;conn = (Connection) DBOpenHelper.getConn();String sql = "insert into user_feedback(user_feed,user_phone) values(?,?)";int i = 0;PreparedStatement pstmt;try {pstmt = (PreparedStatement) conn.prepareStatement(sql);pstmt.setString(1, input_text);pstmt.setString(2, MyApplication.getMoublefhoneUser());i = pstmt.executeUpdate();pstmt.close();conn.close();} catch (SQLException e) {e.printStackTrace();}Message msg = Message.obtain();msg.what = USER_FEEDBACK;userFeedHandler.sendMessage(msg);}}}}).start();}}).positiveText("确定").positiveColor(R.color.danlanse).negativeText("取消").negativeColor(R.color.black).show();break;case R.id.userExit:final SweetAlertDialog mDialog = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.NORMAL_TYPE).setTitleText("提示").setContentText("您是否要退出?").setCustomImage(null).setCancelText("取消").setConfirmText("确定").setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {@Overridepublic void onClick(SweetAlertDialog sweetAlertDialog) {sweetAlertDialog.dismiss();}}).setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {@Overridepublic void onClick(SweetAlertDialog sweetAlertDialog) {sweetAlertDialog.dismiss();ActivityCollector.finishAll();}});mDialog.show();break;default:break;}return true;}public String load() {FileInputStream in = null;BufferedReader reader = null;StringBuilder content = new StringBuilder();try {in = openFileInput("data");System.out.println("是否读到文件内容" + in);reader = new BufferedReader(new InputStreamReader(in));String line = "";while ((line = reader.readLine()) != null) {content.append(line);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (reader != null) {try {reader.close();} catch (IOException e) {e.printStackTrace();}}}return content.toString();}@Overridepublic void onBackPressed() {if (!mBackKeyPressed) {Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();mBackKeyPressed = true;new Timer().schedule(new TimerTask() {//延时两秒,如果超出则擦错第一次按键记录@Overridepublic void run() {mBackKeyPressed = false;}}, 2000);} else {//退出程序this.finish();System.exit(0);}}}

好啦,本篇到此结束,下篇实现图片转码与存储解码。

Android实现头像上传至数据库与保存 简易新闻(十七 上)相关推荐

  1. 带上传文件的ajax保存,ajaxfileupload带参数上传文件

    使用Jquery Ajax File Uploader这个控件上传 这个控件有个缺点,就是不能传递自定义参数.通过更改ajaxfileupload.js文件可以解决此问题. 主要更改点32行,增加42 ...

  2. webuploader结合php实现图片上传到本地和保存数据库

    webuploader结合php实现图片上传到本地和保存数据库,核心功能是以下三点: 一.上传前图片预览 二.上传图片到本地文件夹 三.上传图片路径和图片对应的设备编号到mysql数据库 Webupl ...

  3. jeesite同一表单多fileupload图片上传失败,bizType保存失败

    项目场景: 提示:其中一个图片回显失败 jeesite统一表单提交多图片上传显示错误,bizType保存失败 问题描述 同一表单包含2个图片上传,数据库字段保存成功,其中一个预览图回显失败 原因分析: ...

  4. ElementUI + express实现头像上传及后台图片保存

    ElementUI + express实现头像上传及后台图片保存 记录大创项目中的解决方式.只说明基本的实现方法,不代表实际代码.如果你需要在后台保存头像图片的话. 当然也可以直接使用base64格式 ...

  5. mysql如何上传照片_MySQL数据库之图片上传存储数据库的2种方法讲解(Mysql)

    本文主要向大家介绍了MySQL数据库之图片上传存储数据库的2种方法讲解(Mysql) ,通过具体的内容向大家展现,希望对大家学习MySQL数据库有所帮助. 数据库Mysql存储,读取图片 在项目中,很 ...

  6. 【报错笔记】在做图片上传时上传图片后可以跳转到上传成功界面,也没有报错,数据库中也传入了值,可是eclipse中webapp下怎样都无法生存目录。

    在做图片上传时上传图片后可以跳转到上传成功界面,也没有报错,数据库中也传入了值,可是eclipse中webapp下怎样都无法生存目录. 我使用UUID生成8级目录,在webapp下创建目录,将图片传进 ...

  7. C#:将图片文件上传到数据库两种方法。

    (推荐)方法1: 将图片复制到指定文件夹,在数据库中存储图片路径,通过读取路径来显示图片. string str;private void toolStripButton1_Click(object ...

  8. asp如何将图片文件上传到mysql数据库中_怎样才能利用ASP把图片上传到数据库

    欢迎来到小编的文章进行学习阅读,想必大家又有很多问题吧,在这里会有你想要收获的答案,请大家慢慢学习吧! ASP(Active Server Pages)是Microsoft很早就推出的一种WEB应用程 ...

  9. geodatabase怎么连接MySQL_实用帖-手把手教你如何上传GEO数据库

    点击进去如下图: 可以看见我们上传数据需要准备三个文件,分别为:Metadata spreadsheet.Processed data files.Raw data files.下面分别介绍每个文件如 ...

  10. word表格导出html代码,(网页源代码中的表格数据怎么导出excel)如何将把从WORD、EXCEL中复制的内容转换成HTML源代码,再通过网页表单提交上传到数据库?...

    如何将ASP页面中的表格生成一个Excel表,求源码 '给你个例子吧.保存为 asp文件看看.具体就在第一句. New Page 1PJ计画 第版 案件No 案件名 主门 顾客 PJ责任者 営业担当 ...

最新文章

  1. php为什么学的人越来越少,为什么PHP这么受欢迎?
  2. Python最热,PyTorch增速是TF的13倍:2019数据分析/机器学习工具调查发布
  3. latex 引用_VS Code + LaTex + Zotero 写作毕业论文
  4. oracle linux rdac,redhat 6.4 安装RDAC
  5. 利用nginx建立windows软连,实现IP访问文件
  6. 心得体会:分治法 || 做题也有模板
  7. rabbitmq之window环境启动
  8. Invalid maximum heap size: -Xmx
  9. matlab怎么画地震反应谱,地震工程学-反应谱和地震时程波的相互转化matlab编程...
  10. U盘插入苹果电脑后被分区,在Windows系统用不了怎么办。
  11. es 创建索引 指定id_Elasticsearch创建索引流程
  12. NVIDIA 图像显卡参数列表
  13. 什么是智能颈部按摩仪低频脉冲电流?它会对人体有何影响?
  14. wx.canIUse
  15. k8s 二进制集群部署
  16. Photoshop中的渐变工具
  17. Hexo+Yilia 所遇问题解决方法汇总
  18. 金融计算机杂志排名,中国核心期刊排名_中国金融文化属于核心期刊吗_计算机八大核心期刊...
  19. python分组统计标准化_分组计算和汇总_Python数据分析实战应用_数据挖掘与分析视频-51CTO学院...
  20. 尚硅谷java练习题to循环

热门文章

  1. phython入门开始
  2. ZYJ7型转辙设备安装调试工法
  3. ANDROID_MARS学习笔记_S04_004_用HTTPCLENT发带参数的get和post请求
  4. etoken显示连接服务器失败,etoken
  5. 场面火爆!5G+智慧灯杆融合发展论坛在北京顺利召开
  6. 前端大文件下载(带进度条)
  7. C - Write the program expr which evaluates a reverse Polish expression from the command line
  8. JavaScript加法运算
  9. 阅读笔记-HTTP返回状态码
  10. html 设置td最小宽度,HTML–td 宽度调整