android+myeclipse+mysql自定义控件下拉框的数据绑定
原创作品,允许转载,转载时请务必声明作者信息和本声明。http://www.cnblogs.com/zhu520/p/8031936.html
本人小白,那个大神看到有问题可指出,谢谢。。。。
这个是接着之前的 android+myeclipse+mysql下拉框数据绑定 的服务器(后台)来做的,所以这里就只给 Android的代码,如果想要服务器的代码去 android+myeclipse+mysql下拉框数据绑定找就好了
一:Android studio
- 1);先进行准备前工作先 在build.gradle四个地方要加入代码
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() mavenCentral()//apllay // add plugin } dependencies { classpath 'com.android.tools.build:gradle:2.3.3' classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() } } task clean(type: Delete) { delete rootProject.buildDir }
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// 这个非常重要,会生成Dao的类
greendao { //add plugin
schemaVersion 2
//生成greedao的对象类的路径
设置DaoMaster,DaoSession,Dao包的路径,我不太喜欢它原来的路径,每次找都很麻烦,所以把它放在一个自己方便看的路径下来,你也可以不要下面这两句!
daoPackage 'zhu.com.sprnner_cbo.greendao'
targetGenDir 'src/main/java'//保存到java代码路径 ==》这句你可以不要
}
有这俩句,那么DaoMaster,DaoSession,Dao那么路径挺好找的
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
apply plugin: 'com.android.application' apply plugin: 'org.greenrobot.greendao'//add plugin android { compileSdkVersion 26 buildToolsVersion "27.0.3" defaultConfig { applicationId "com.example.pearl.customdropdownbox" minSdkVersion 15 targetSdkVersion 26 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } // 这个非常重要,会生成Dao的类 greendao { //add plugin schemaVersion 2 //生成greedao的对象类的路径 ==》我不太喜欢它原来的路径,所以把它放在一个自己方便看的路径下来,所以这句你可以不要! daoPackage 'com.example.pearl.customdropdownbox.greendao' targetGenDir 'src/main/java'//保存到java代码路径 ==》这句你可以不要 } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:26.+' compile 'com.android.support.constraint:constraint-layout:1.0.2' testCompile 'junit:junit:4.12' compile 'com.loopj.android:android-async-http:1.4.9'// add library==》这个是添加 网络请求的插件 compile 'org.greenrobot:greendao:3.2.2' // add library ==>这个是 添加 greedao插件 }
a):因为需要网络的请求 所以 要必须 要在AndroidManifest.xml加一句代码,不加就会出现下面这种错误的情况
12-26 02:45:25.969 5267-5334/zhu.com.sprnner_cbo W/System.err: java.net.SocketException: Permission denied 12-26 02:45:25.970 5267-5334/zhu.com.sprnner_cbo W/System.err: at java.net.Socket.createImpl(Socket.java:473) 12-26 02:45:25.970 5267-5334/zhu.com.sprnner_cbo W/System.err: at java.net.Socket.getImpl(Socket.java:536) 12-26 02:45:25.971 5267-5334/zhu.com.sprnner_cbo W/System.err: at java.net.Socket.setSoTimeout(Socket.java:1127) 12-26 02:45:25.971 5267-5334/zhu.com.sprnner_cbo W/System.err: at cz.msebera.android.httpclient.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:116) 12-26 02:45:25.971 5267-5334/zhu.com.sprnner_cbo W/System.err: at cz.msebera.android.httpclient.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:157) 12-26 02:45:25.971 5267-5334/zhu.com.sprnner_cbo W/System.err: at cz.msebera.android.httpclient.conn.scheme.SchemeSocketFactoryAdaptor.connectSocket(SchemeSocketFactoryAdaptor.java:65) 12-26 02:45:25.972 5267-5334/zhu.com.sprnner_cbo W/System.err: at cz.msebera.android.httpclient.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:177) 12-26 02:45:25.972 5267-5334/zhu.com.sprnner_cbo W/System.err: at cz.msebera.android.httpclient.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:145) 12-26 02:45:25.972 5267-5334/zhu.com.sprnner_cbo W/System.err: at cz.msebera.android.httpclient.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:131) 12-26 02:45:25.972 5267-5334/zhu.com.sprnner_cbo W/System.err: at cz.msebera.android.httpclient.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:611) 12-26 02:45:25.973 5267-5334/zhu.com.sprnner_cbo W/System.err: at cz.msebera.android.httpclient.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:446) 12-26 02:45:25.973 5267-5334/zhu.com.sprnner_cbo W/System.err: at cz.msebera.android.httpclient.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:860) 12-26 02:45:25.973 5267-5334/zhu.com.sprnner_cbo W/System.err: at cz.msebera.android.httpclient.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82) 12-26 02:45:25.973 5267-5334/zhu.com.sprnner_cbo W/System.err: at com.loopj.android.http.AsyncHttpRequest.makeRequest(AsyncHttpRequest.java:146) 12-26 02:45:25.974 5267-5334/zhu.com.sprnner_cbo W/System.err: at com.loopj.android.http.AsyncHttpRequest.makeRequestWithRetries(AsyncHttpRequest.java:177) 12-26 02:45:25.974 5267-5334/zhu.com.sprnner_cbo W/System.err: at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:106) 12-26 02:45:25.974 5267-5334/zhu.com.sprnner_cbo W/System.err: at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428) 12-26 02:45:25.974 5267-5334/zhu.com.sprnner_cbo W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237) 12-26 02:45:25.975 5267-5334/zhu.com.sprnner_cbo W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 12-26 02:45:25.975 5267-5334/zhu.com.sprnner_cbo W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 12-26 02:45:25.975 5267-5334/zhu.com.sprnner_cbo W/System.err: at java.lang.Thread.run(Thread.java:761)
好了配置弄好剩下的就 很好解决了
b):设置实体类:
实体类 要根据返回的json中 相对于的key 一一对应
注意: 主键:id必须要设置Long的类型 ,切记 必须要加入 @Entity, 和@Id
设置好变量后 ,还有一个操作 设置 生成DaoMaster,DaoSession,Dao类的操作,这它就会自动补全我们实体类剩下的get和set的方法了
================生成的========》
最后在实体类中再加 一个方法 得到 从 服务器专递的json的数据 // 将json ==>转化为 Bean的对象(即Tb_Cbo_CLDL的对象) public static Tbmep json_To_Bean(JSONObject object){ try { return new Tbmep(object.getLong("did"), object.getString("dname") ); }catch (Exception e){ } return null; }
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~··
Tbmep
package com.example.pearl.customdropdownbox; import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation.Id; import org.greenrobot.greendao.annotation.Generated; import org.json.JSONObject; /** * Created by Pearl on 2017/12/27. */ @Entity public class Tbmep { @Id private Long did; private String dname; @Generated(hash = 1103728403) public Tbmep(Long did, String dname) { this.did = did; this.dname = dname; } @Generated(hash = 1857599075) public Tbmep() { } public Long getDid() { return this.did; } public void setDid(Long did) { this.did = did; } public String getDname() { return this.dname; } public void setDname(String dname) { this.dname = dname; } // 将json ==>转化为 Bean的对象(即Tb_Cbo_CLDL的对象) public static Tbmep json_To_Bean(JSONObject object){ try { return new Tbmep(object.getLong("did"), object.getString("dname") ); }catch (Exception e){ } return null; } }
2):界面
a):activity_cbo.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.pearl.customdropdownbox.CBOActivity"> <RelativeLayout android:id="@+id/relativelayout" android:padding="2dp" android:layout_width="wrap_content" android:layout_height="42dp" > <TextView android:id="@+id/kj_tv_tbmep" android:background="@drawable/etitext_frame_radiuo" android:layout_width="130dp" android:layout_height="35dp" android:layout_centerVertical="true" android:gravity="left|center" android:hint="~部门~" android:paddingLeft="10dp" android:textColor="#ff000000" android:textSize="11sp" > </TextView> <LinearLayout android:id="@+id/bt_dropdown" android:layout_width="25dp" android:layout_height="match_parent" android:layout_marginLeft="109dp" android:gravity="center" > <ImageView android:layout_width="20dp" android:layout_height="20dp" android:background="@drawable/btn_click_radius_press" /> </LinearLayout> </RelativeLayout> </RelativeLayout>
b):spiner_item_layout.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#00000000" android:minHeight="40dp"> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#00000000" android:gravity="center" android:textColor="@color/text_yellow" android:textSize="18sp" /> <TextView android:id="@+id/text_provinceId" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#00000000" android:gravity="center" android:visibility="invisible" android:textColor="@color/text_yellow" android:textSize="18sp" /> </RelativeLayout>
spiner_listview_layout.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:background="#ffffff" android:orientation="vertical"> <ListView android:id="@+id/listview" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/sprinner_line_background" android:cacheColorHint="#00000000" android:scrollbars="none"></ListView> </LinearLayout>
需要用到 一些应用来设置界面
a):values的设置
b)drawable的设置
btn_click_radius_press.xml
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/btn_press"/> <item android:drawable="@drawable/btn_radius"/> </selector> <!--要是button可以变色: 那么要把在btn_radius.xml的btn_bg和btn_press.xml没按的效果组合起来就可以进行变色的效果-->
btn_press.xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@android:color/holo_red_dark"> </solid><!--solid是一个填充的的颜色--> <stroke android:width="1dp" android:color="#A3AAAA"> </stroke> <corners android:radius="5dp"/> </shape> <!--这个是按的效果: 这个是定义进度条的时候使用 button 变色的情况-->
btn_radius.xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@android:color/holo_green_light"> </solid> <stroke android:width="1dp" android:color="#fff"> </stroke> <corners android:radius="5dp"/> </shape>
etitext_frame_radiuo.xml
<?xml version="1.0" encoding="utf-8" ?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" android:padding="10dp"> <padding android:bottom="5dp" android:left="5dp" android:right="5dp" android:top="5dp" /> <!-- 设置圆角矩形 --> <corners android:radius="7dp" /> <stroke android:width="5px" android:color="#1199EF" /> </shape>
sprinner_line_background.xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <stroke android:width="0.01dp" android:color="#C6C7CE" /> <padding android:bottom="5dp" /> <solid android:color="@android:color/holo_red_dark"> </solid><!--solid是一个填充的的颜色--> <stroke android:width="1dp" android:color="#A3AAAA"> </stroke> <corners android:radius="5dp"/> </shape>
3):代码
MyBaseAdapter
package com.example.pearl.customdropdownbox; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.List; /** * Created by XiaoZhu on 2017/9/26. */ public class MyBaseAdapter extends BaseAdapter { public static interface IOnItemSelectListener { public void onItemClick(int pos); } ; private List<String> mObjects; private LayoutInflater mInflater; public MyBaseAdapter(Context context, List<String> mObjects) { this.mObjects = mObjects; mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void refreshData(List<String> objects, int selIndex) { mObjects = objects; if (selIndex < 0) { selIndex = 0; } if (selIndex >= mObjects.size()) { selIndex = mObjects.size() - 1; } } @Override//在此适配器中所代表的数据集的条目数 public int getCount() { return mObjects.size(); } @Override//获取数据集中与指定索引对应的数据项 public Object getItem(int pos) { return mObjects.get(pos).toString(); } @Override//取在列表中与指定索引对应的行id public long getItemId(int pos) { return pos; } @Override //下面的是重点 public View getView(int pos, View convertView, ViewGroup arg2) { ViewHolder viewHolder; if (convertView == null) { convertView = mInflater.inflate( R.layout.spiner_item_layout, null); viewHolder = new ViewHolder(); viewHolder.mTextView = (TextView) convertView.findViewById(R.id.textView); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } //Object item = getItem(pos); viewHolder.mTextView.setText(mObjects.get(pos)); return convertView; } public static class ViewHolder { public TextView mTextView; } }
SpinerPopWindow
package com.example.pearl.customdropdownbox; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.ListView; import android.widget.PopupWindow; import java.util.List; /** * Created by XiaoZhu on 2017/12/12. */ public class SpinerPopWindow extends PopupWindow implements AdapterView.OnItemClickListener { private Context mContext; private ListView mListView; private MyBaseAdapter mAdapter; private MyBaseAdapter.IOnItemSelectListener mItemSelectListener; public SpinerPopWindow(Context context) { super(context); mContext = context; init(); } public void setItemListener(MyBaseAdapter.IOnItemSelectListener listener) { mItemSelectListener = listener; } public void setAdatper(MyBaseAdapter adapter) { mAdapter = adapter; mListView.setAdapter(mAdapter); } private void init() { View view = LayoutInflater.from(mContext).inflate(R.layout.spiner_listview_layout, null); setContentView(view); setWidth(LayoutParams.WRAP_CONTENT); setHeight(LayoutParams.WRAP_CONTENT); setFocusable(true); ColorDrawable dw = new ColorDrawable(0x00); setBackgroundDrawable(dw); mListView = (ListView) view.findViewById(R.id.listview); mListView.setOnItemClickListener(this); } public void refreshData(List<String> list, int selIndex) { if (list != null && selIndex != -1) { if (mAdapter != null) { mAdapter.refreshData(list, selIndex); } } } @Override public void onItemClick(AdapterView<?> arg0, View view, int pos, long arg3) { dismiss(); if (mItemSelectListener != null) { mItemSelectListener.onItemClick(pos); } } }
CBOActivity
package com.example.pearl.customdropdownbox; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import cz.msebera.android.httpclient.Header; public class CBOActivity extends Activity implements View.OnClickListener ,MyBaseAdapter.IOnItemSelectListener { private List< String> list_Tbmep =null; private TextView tv_sprnner_Tbmep; private MyBaseAdapter mAdapter; private RelativeLayout relativeLayout; private SpinerPopWindow mSpinerPopWindow; private List<Tbmep> list_cboTbmep=null; private long TbmepID=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cbo); relativeLayout = (RelativeLayout) findViewById(R.id.relativelayout); relativeLayout.setOnClickListener(this);//自已下拉框 tv_sprnner_Tbmep= (TextView) findViewById(R.id.kj_tv_tbmep); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.relativelayout: cbo_tbmep(); break; } } @Override public void onItemClick(int pos) { TbmepID =list_cboTbmep.get((int) pos).getDid(); String value = list_Tbmep.get(pos); tv_sprnner_Tbmep.setText(value.toString()); } public void cbo_tbmep(){ AsyncHttpClient client =new AsyncHttpClient(); //第一个参数是访问 后台的路径,第二是:参数根据 id获取 string 查询数据 ,第三个:回调函数 client.get("http://192.168.191.2:8080/2017_1214_cbo/Binding_Cbo/android_cbo.json", null, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { if (statusCode==200){ try { JSONObject object = new JSONObject(new String(responseBody));//获取json数据 JSONArray jsonArray = object.getJSONArray("cbo_bm");//获取数据集名称为obj的数据 Log.d("jsonArray数据输出:", String.valueOf(jsonArray)); list_cboTbmep = new ArrayList<>(); for(int i=0;i<jsonArray.length();i++){ JSONObject json_one=jsonArray.getJSONObject(i); //把 json 转换为 ==》bean的对象形式 //方法1; Tbmep cbo=Tbmep.json_To_Bean(json_one); if (cbo!=null){ list_cboTbmep.add(cbo);//把对象放入 list的数组中 } } if (jsonArray.length() > 0) { // TbmepID = list_cboTbmep.get(0).getDid(); list_Tbmep = new ArrayList< String >(); for (int i = 0; i < list_cboTbmep.size(); i++) { Tbmep section = list_cboTbmep.get(i); list_Tbmep.add(section.getDname()); } } mAdapter=new MyBaseAdapter(CBOActivity.this,list_Tbmep); mAdapter.refreshData(list_Tbmep, 0); //初始化PopWindow mSpinerPopWindow = new SpinerPopWindow(CBOActivity.this); mSpinerPopWindow.setAdatper(mAdapter); mSpinerPopWindow.setItemListener(CBOActivity.this); showSpinWindow();//显示SpinerPopWindow } catch (JSONException e) { Toast.makeText(CBOActivity.this, "下拉框加载失败!", Toast.LENGTH_SHORT).show(); } mAdapter.notifyDataSetChanged();// 数据加载 完毕, 通知列表去更新 }else if(statusCode==400){ Toast.makeText(CBOActivity.this, "若返回值400,则是返回网络异常!", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(int statusCode,cz.msebera.android.httpclient.Header[] headers, byte[] responseBody, Throwable error) { } }) ; } //设置PopWindow private void showSpinWindow() { //设置mSpinerPopWindow显示的宽度 mSpinerPopWindow.setWidth(relativeLayout.getWidth()); //设置显示的位置在哪个控件的下方 mSpinerPopWindow.showAsDropDown(relativeLayout); } }
运行效果:
源码:http://download.csdn.net/download/qq_35812301/10176025