常常在開發時,最頭痛的就是設計元件的UI了,現在有很多網友做好的第三方library,只要在gradle文件中貼上lib的來源,就可以開始使用別人設計好的lib了。
介紹一個網站,這個網站整合了許多在GitHub上一些熱門的library:红鸟网络Android团队Blog
<?php
$db_link=@mysqli_connect("資料庫位置","資料庫帳號","資料庫密碼");
if(!$db_link){
die("資料庫連線失敗<br>");
}else{
echo"資料庫連線成功<br>";
}
mysqli_query($db_link,"SET NAMES 'utf-8'"); //設定字元集與編碼為utf-8
$seldb=@mysqli_select_db($db_link,"資料庫名稱");
if(!$seldb){
die("資料庫選擇失敗<br>");
}else{
echo"資料庫選擇成功<br>";
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<form method="POST" action="login_php.php">
請輸入帳號:<input type="text" name="username"/><br>
請輸入密碼:<input type="Password" name="password"/><br>
<input type="submit" value="登入"/>
</form>
</body>
</html>
<?php
header('Content-Type: text/html; charset=utf-8');
$username=$_POST['username'];
$password=$_POST['password'];
require("conn_mysql.php");
$sql_query_login="SELECT * FROM employee where username='$username' AND password='$password'";
$result1=mysqli_query($db_link,$sql_query_login) or die("查詢失敗");
if(mysqli_num_rows($result1)){
$sql_query="SELECT * FROM books";
$result=mysqli_query($db_link,$sql_query);
echo "<table border=1 width=400 cellpadding=5>";
echo "<tr>
<td>書籍編號</td>
<td>書籍名稱</td>
<td>負責員工編號</td>
<td>價錢</td>
</tr>";
while($row=mysqli_fetch_array($result)){
echo "<tr>
<td>$row[0]</td>
<td>$row[1]</td>
<td>$row[2]</td>
<td>$row[3]</td>
</tr>";
}
echo"</table>";
}else{
echo"登入失敗";
}
?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:orientation="vertical" >
<TextView
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="書名" />
<EditText
android:id="@+id/edt"
android:layout_width="150dp"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="search"
/>
</LinearLayout>
public class MainActivity extends Activity {
private Button btn;
private EditText edt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findviewbyid();
}
private void findviewbyid(){
btn = (Button)findViewById(R.id.btn);
edt = (EditText)findViewById(R.id.edt);
btn.setOnClickListener(btnlistener);
}
private View.OnClickListener btnlistener = new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Loose Coupling
// Intent it = new Intent("com.mchen.Activity2");
// it.putExtra("bookName", edt.getText().toString());
Uri uri = Uri.parse("Tom:"+edt.getText().toString()); //使用自訂的Scheme
Intent it = new Intent(Intent.ACTION_VIEW,uri); //跳頁到DisplayBooks
startActivity(it);
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown=true)
public class BookInfo2 {
private int totalItems;
private List<items> items = new ArrayList<items>();
public BookInfo2(){
}
public BookInfo2(int totalItems,List<items> items){
this.totalItems = totalItems;
this.items = items;
}
public int getTotalItems() {
return totalItems;
}
public void setTotalItems(int totalItems) {
this.totalItems = totalItems;
}
public List<items> getItems() {
return items;
}
public void setItems(List<items> items) {
this.items = items;
}
}
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown=true)
public class items {
private volumeInfo volumeInfo;
public items(){
}
public items(volumeInfo volumeInfo){
this.volumeInfo = volumeInfo;
}
public volumeInfo getVolumeInfo() {
return volumeInfo;
}
public void setVolumeInfo(volumeInfo volumeInfo) {
this.volumeInfo = volumeInfo;
}
}
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown=true)
public class volumeInfo {
private String subtitle;
private String title;
public String getSubtitle() {
return subtitle;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:dividerHeight="5dp"
android:id="@+id/listview">
</ListView>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/txtTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/txtSubTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
public class DisplayBooks extends Activity {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.book);
listView = (ListView)findViewById(R.id.listview);
Log.i("mutin","action-"+this.getIntent().getAction());
Log.i("mutin", "data-"+this.getIntent().getData().getSchemeSpecificPart());
final String param = this.getIntent().getData().getSchemeSpecificPart();
int cpuCount = Runtime.getRuntime().availableProcessors(); //取得可以建立Thread的最大數量
ExecutorService es = Executors.newFixedThreadPool(cpuCount); //建立Thread
Future<String> f = es.submit(new Callable<String>(){ //可以取得Callable回傳結果
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
URL url = new URL("https://www.googleapis.com/books/v1/volumes?q="+param);
java.net.URLConnection con = url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String data = null;
StringBuffer result = new StringBuffer();
while((data=br.readLine())!=null){
result.append(data);
}
return result.toString();
}
});
try{
String result = f.get();
es.shutdown();
//產生Jackson函式庫負責解析的ObjectMapper類別
ObjectMapper mapper = new ObjectMapper();
//呼叫ObjectMapper的readValue方法進行Json格式轉換為Java資料的工作
BookInfo2 bi = mapper.readValue(result,BookInfo2.class);
HashMap<String,String> map;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
for(items item:bi.getItems()){
Log.i("mutin", "Title="+item.getVolumeInfo().getTitle());
Log.i("mutin", "SubTitle="+item.getVolumeInfo().getSubtitle());
map = new HashMap<String,String>();
map.put("title", "Title:"+item.getVolumeInfo().getTitle());
map.put("subTitle", "SubTitle:" + item.getVolumeInfo().getSubtitle());
list.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(this,list,R.layout.row,new String[]{"title","subTitle"},new int[]{R.id.txtTitle,R.id.txtSubTitle});
listView.setAdapter(adapter);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
PS:用HightLight上色程式碼,格式會跑掉,請見諒
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromAlpha="0.0"
android:toAlpha="1.0" />
將動畫添加到view上:
view.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:pivotX="0%"
android:pivotY="100%"
android:toXScale="1.5"
android:toYScale="1.5" />
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="2000"
android:fromXDelta="-100%"
android:fromYDelta="0"
android:toXDelta="100%p"
android:toYDelta="0" />
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="2000"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%" />
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:fromYDelta="100%p"
android:toYDelta="0"
android:duration="2000"/>
<alpha
android:fromAlpha="0.0"
android:toAlpha="1.0"
android:duration="2000" />
</set>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp" />
<RadioGroup
android:id="@+id/id_radioGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<RadioButton
android:id="@+id/id_one"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:button="@null"
android:drawableTop="@mipmap/ic_launcher"
android:gravity="center_horizontal"
android:text="page1"
android:onClick="onClick"/>
<RadioButton
android:id="@+id/id_two"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:button="@null"
android:drawableTop="@mipmap/ic_launcher"
android:gravity="center_horizontal"
android:text="page2"
android:onClick="onClick"/>
<RadioButton
android:id="@+id/id_three"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:button="@null"
android:drawableTop="@mipmap/ic_launcher"
android:gravity="center_horizontal"
android:text="page3"
android:onClick="onClick"/>
<RadioButton
android:id="@+id/id_four"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:button="@null"
android:drawableTop="@mipmap/ic_launcher"
android:gravity="center_horizontal"
android:text="page4"
android:onClick="onClick"/>
</RadioGroup>
</RelativeLayout>
public class MainActivity extends FragmentActivity {
private RadioButton id_one,id_two,id_three,id_four;
private int page = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findviewbyid();
changeFragment(DetailsFragment.newInstance(page));
}
public void onClick(View view){
switch (view.getId()){
case R.id.id_one:
changeFragment(DetailsFragment.newInstance(1));
break;
case R.id.id_two:
changeFragment(DetailsFragment.newInstance(2));
break;
case R.id.id_three:
changeFragment(DetailsFragment.newInstance(3));
break;
case R.id.id_four:
changeFragment(DetailsFragment.newInstance(4));
break;
}
}
private void findviewbyid(){
id_one = (RadioButton)findViewById(R.id.id_one);
id_two = (RadioButton)findViewById(R.id.id_two);
id_three = (RadioButton)findViewById(R.id.id_three);
id_four = (RadioButton)findViewById(R.id.id_four);
}
private void changeFragment(Fragment f) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, f);
transaction.commitAllowingStateLoss();
}
protected void onStart(){
super.onStart();
Log.i("tag","Activity onStart()");
}
protected void onResume(){
super.onResume();
Log.i("tag","Activity onResume()");
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/text_view"
android:text="fragment"
android:gravity="center"
android:textSize="20sp"/>
</LinearLayout>
public class DetailsFragment extends Fragment {
private View v;
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i("tag","Fragment onCreateView()");
v = inflater.inflate(R.layout.fragment_tmp, container, false);
TextView text = (TextView)v.findViewById(R.id.text_view);
text.setText("Page" + getShownIndex());
return v;
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp" />
<RadioGroup
android:id="@+id/id_radioGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<RadioButton
android:id="@+id/id_one"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:button="@null"
android:drawableTop="@mipmap/ic_launcher"
android:gravity="center_horizontal"
android:text="page1"
android:onClick="onClick"/>
<RadioButton
android:id="@+id/id_two"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:button="@null"
android:drawableTop="@mipmap/ic_launcher"
android:gravity="center_horizontal"
android:text="page2"
android:onClick="onClick"/>
</RadioGroup>
</RelativeLayout>
public class MainActivity extends AppCompatActivity {
private RadioButton id_one,id_two;
private Fragment1 mFragment01;
private Fragment2 mFragment02;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findviewbyid();
mFragment01 = new Fragment1();
mFragment02 = new Fragment2();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, mFragment01,"TAG-mFragment01");
transaction.commitAllowingStateLoss();
}
private void findviewbyid(){
id_one = (RadioButton)findViewById(R.id.id_one);
id_two = (RadioButton)findViewById(R.id.id_two);
}
public void onClick(View view){
switch (view.getId()){
case R.id.id_one:
chaangefragment(mFragment01,"TAG-mFragment01");
break;
case R.id.id_two:
chaangefragment(mFragment02,"TAG-mFragment02");
break;
}
}
public void chaangefragment(Fragment fragment,String tag){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
List fragments = fragmentManager.getFragments();
Fragment tmp=null;
for (Fragment f: fragments){
if (f!=null && f.isVisible()) {
System.out.println("hide"+f.getTag());
tmp=f;
}
}
// Fragment fragment = getSupportFragmentManager().findFragmentByTag("TAG-mFragment01");
// System.out.println(fragment);
if (fragment.isAdded()){
transaction.hide(tmp).show(fragment).commit();
}else {
transaction.hide(tmp).add(R.id.fragment_container,fragment,tag).commit();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txt"
android:text="fragment"/>
</LinearLayout>
public class Fragment1 extends Fragment {
private TextView txt;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Log.i("tag","Fragment1 onCreateView");
return inflater.inflate(R.layout.fragment_layout, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i("tag","Fragment1 onActivityCreated");
txt = (TextView)getView().findViewById(R.id.txt);
txt.setText("fragment1");
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
Log.i("tag","Fragment1 onAttach");
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("tag","Fragment1 onCreate");
}
@Override
public void onStart() {
super.onStart();
Log.i("tag","Fragment1 onStart");
}
@Override
public void onResume() {
super.onResume();
Log.i("tag","Fragment1 onResume");
}
}
public class Fragment2 extends Fragment{
private TextView txt;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Log.i("tag","Fragment2 onCreateView");
return inflater.inflate(R.layout.fragment_layout, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i("tag","Fragment2 onActivityCreated");
txt = (TextView)getView().findViewById(R.id.txt);
txt.setText("fragment2");
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
Log.i("tag","Fragment2 onAttach");
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("tag","Fragment2 onCreate");
}
@Override
public void onStart() {
super.onStart();
Log.i("tag","Fragment2 onStart");
}
@Override
public void onResume() {
super.onResume();
Log.i("tag","Fragment2 onResume");
}
}
執行順續page1(起始) -> page2 -> page1 -> page2
執行結果:
可以看到fragment1和fragment2個別被建立1次後,之後再呼叫時就不會再被建立新的Fragment了。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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.user.service.MainActivity"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/txt"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
private TextView txt;
private static final int msgKey1 = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView)findViewById(R.id.txt);
Thread t = new Thread(runnable);
t.start();
}
private Runnable runnable = new Runnable() {
@Override
public void run() {
do{
try {
Thread.sleep(1000);
Message msg = new Message();
msg.what = msgKey1;
mHandler.sendMessage(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}while (true);
}
};
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case msgKey1:
long time = System.currentTimeMillis();
Date date = new Date(time);
SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 EEE");
txt.setText(format.format(date));
break;
default:
break;
}
}
};
}
public class MainActivity extends AppCompatActivity {
private TextView txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView)findViewById(R.id.txt);
Thread t = new Thread(runnable);
t.start();
}
private Runnable runnable = new Runnable() {
@Override
public void run() {
try {
while (true) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
// update TextView here!
long time = System.currentTimeMillis();
Date date = new Date(time);
SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 EEE");
txt.setText(format.format(date));
}
});
}
} catch (InterruptedException e) {
}
}
};
<activity android:name=".MainActivity"
android:launchMode="standard">
Intent intent = new Intent(this, B.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="tw.com.hjchen.sqlitedemo.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="20sp"/>
<EditText
android:id="@+id/editName"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:width="230dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tel"
android:textSize="20sp"/>
<EditText
android:id="@+id/editTel"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:width="230dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:textSize="20sp"/>
<EditText
android:id="@+id/editEmail"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:width="230dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ID"
android:textSize="20sp"/>
<EditText
android:id="@+id/editID"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:width="230dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<Button
android:id="@+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:width="100dp"/>
<Button
android:id="@+id/btnUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update"
android:width="100dp"/>
<Button
android:id="@+id/btnDel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Del"
android:width="100dp"/>
</LinearLayout>
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="120dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/txtResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Result"
android:textSize="20sp"/>
</LinearLayout>
</ScrollView>
<ListView
android:id="@+id/listData"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/txtId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
<TextView
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
<TextView
android:id="@+id/txtTel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
<TextView
android:id="@+id/txtEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"/>
</LinearLayout>
import android.provider.BaseColumns;
public interface DbConstants extends BaseColumns{
public static final String TABLE_NAME="friends";
public static final String NAME="name";
public static final String TEL="tel";
public static final String EMAIL="email";
}
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import static android.provider.BaseColumns._ID;
import static tw.com.hjchen.sqlitedemo.DbConstants.TABLE_NAME;
import static tw.com.hjchen.sqlitedemo.DbConstants.NAME;
import static tw.com.hjchen.sqlitedemo.DbConstants.TEL;
import static tw.com.hjchen.sqlitedemo.DbConstants.EMAIL;
public class DBHelper extends SQLiteOpenHelper{
private final static String DATABASE_NAME="demo.db"; //資料庫檔案名稱
private final static int DATABASE_VERSION=1; //資料庫版本
public DBHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db){
final String INIT_TABLE="create table "+TABLE_NAME+"("+_ID+" integer primary key autoincrement,"+NAME+" char,"+TEL+" char,"+EMAIL+" char)";
db.execSQL(INIT_TABLE);
}
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
final String DROP_TABLE="drop tabel if exists "+TABLE_NAME;
db.execSQL(DROP_TABLE);
onCreate(db);
}
}
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import static android.provider.BaseColumns._ID;
import static tw.com.hjchen.sqlitedemo.DbConstants.TABLE_NAME;
import static tw.com.hjchen.sqlitedemo.DbConstants.NAME;
import static tw.com.hjchen.sqlitedemo.DbConstants.TEL;
import static tw.com.hjchen.sqlitedemo.DbConstants.EMAIL;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
public class MainActivity extends AppCompatActivity implements OnClickListener{
private DBHelper dbHelper;
private TextView result;
private ListView listData;
private EditText editName,editTel,editEmail,editId;
private Button btnAdd,btnDel,btnUpdatel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViews();
openDatabase(); //開啟資料庫
show(); //show scrollview
showInList(); //show listview
}
private void findViews(){
editName=(EditText)findViewById(R.id.editName);
editTel=(EditText)findViewById(R.id.editTel);
editEmail=(EditText)findViewById(R.id.editEmail);
editId=(EditText)findViewById(R.id.editID);
btnAdd=(Button)findViewById(R.id.btnAdd);
btnDel=(Button)findViewById(R.id.btnDel);
btnUpdatel=(Button)findViewById(R.id.btnUpdate);
result=(TextView)findViewById(R.id.txtResult);
listData=(ListView)findViewById(R.id.listData);
btnAdd.setOnClickListener(this);
btnDel.setOnClickListener(this);
btnUpdatel.setOnClickListener(this);
}
protected void onDestroy(){
super.onDestroy();
closeDatabase(); //關閉資料庫
}
private void openDatabase(){
dbHelper=new DBHelper(this); //取得DBHelper物件
}
private void closeDatabase(){
dbHelper.close();
}
public void onClick(View view){
switch (view.getId()){
case R.id.btnAdd:
add();
break;
case R.id.btnDel:
del();
break;
case R.id.btnUpdate:
update();
break;
default:
break;
}
show();
showInList();
}
private void add(){
SQLiteDatabase db=dbHelper.getWritableDatabase(); //透過dbHelper取得讀取資料庫的SQLiteDatabase物件,可用在新增、修改與刪除
ContentValues values=new ContentValues(); //建立 ContentValues 物件並呼叫 put(key,value) 儲存欲新增的資料,key 為欄位名稱 value 為對應值。
values.put(NAME,editName.getText().toString());
values.put(TEL,editTel.getText().toString());
values.put(EMAIL,editEmail.getText().toString());
db.insert(TABLE_NAME,null,values);
cleanEditText();
}
private void del(){
SQLiteDatabase db=dbHelper.getWritableDatabase();
String id=editId.getText().toString();
db.delete(TABLE_NAME,_ID+"="+id,null);
cleanEditText();
}
private void update(){
SQLiteDatabase db=dbHelper.getWritableDatabase();
String id=editId.getText().toString();
ContentValues values=new ContentValues();
values.put(NAME,editName.getText().toString());
values.put(TEL,editTel.getText().toString());
values.put(EMAIL,editEmail.getText().toString());
db.update(TABLE_NAME,values,_ID+"="+id,null);
cleanEditText();
}
private void cleanEditText(){
editName.setText("");
editTel.setText("");
editEmail.setText("");
editId.setText("");
}
private Cursor getCursor(){
SQLiteDatabase db=dbHelper.getReadableDatabase(); //透過dbHelper取得讀取資料庫的SQLiteDatabase物件,可用在查詢
String[] columns={_ID,NAME,TEL,EMAIL};
Cursor cursor = db.query(TABLE_NAME,columns,null,null,null,null,null); //查詢所有欄位的資料
return cursor;
}
private void show(){
Cursor cursor = getCursor(); //取得查詢物件Cursor
StringBuilder resultData = new StringBuilder("Result:\n");
while (cursor.moveToNext()){
int id = cursor.getInt(0);
String name = cursor.getString(1);
String tel = cursor.getString(2);
String email = cursor.getString(3);
resultData.append(id).append(": ");
resultData.append(name).append(": ");
resultData.append(tel).append(": ");
resultData.append(email).append("\n");
}
result.setText(resultData);
}
private void showInList(){
Cursor cursor = getCursor();
String[] from = {_ID,NAME,TEL,EMAIL};
int[] to = {R.id.txtId,R.id.txtName,R.id.txtTel,R.id.txtEmail};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.data_item,cursor,from,to); //SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to)
listData.setAdapter(adapter);
}
}
String sql = " Select name,phone from member where name like ? "
String[] selectionArgs = {"%明%"};
Cursor cursor = db.rawQuery(sql,selectionArgs);
String[] columns = {"name","phone"};
String selection = "name Like ? ";
String[] selectionArgs = {"%明%"};
Cursor cursor = db.query(TABLE_NAME , columns, selection, selectionArgs, null, null, null);
<?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.user.baseadapter.MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listview"></ListView>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:layout_width="10dp"
android:layout_height="20dp"
android:id="@+id/image"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:paddingLeft="30dp"/>
</LinearLayout>
public class ListName {
private String name;
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
public class BaseAdapter extends android.widget.BaseAdapter{
private ArrayList<ListName> listData;
private LayoutInflater layoutInflater;
public BaseAdapter(Context context, ArrayList<ListName> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context); //獲得LayoutInflater
}
@Override
public int getCount() {
return listData.size();
}
@Override
public Object getItem(int position) {
return listData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) { //判斷是否被使用過,如果沒有就初始化它
convertView = layoutInflater.inflate(R.layout.list_row, null); //LayoutInflater.inflate來載入xml文件布局檔
holder = new ViewHolder(); //實體化holder
holder.image = (ImageView)convertView.findViewById(R.id.image);
holder.textview = (TextView) convertView.findViewById(R.id.textview);
convertView.setTag(holder); //把convertView塞入holder裡,下次convertView不是空的條件下 就可以直接把holder拿出來用
} else {
holder = (ViewHolder) convertView.getTag();
}
ListName encapsulation = listData.get(position);
holder.image.setBackgroundColor(Color.parseColor("#f6565a")); //給image設定顏色
// convertView.setBackgroundColor(Color.WHITE);
if (position%2==0){ //判斷是不是偶數列,是的話就把那列設定顏色
convertView.setBackgroundColor(Color.parseColor("#0ce8e2"));
}
holder.textview.setText(encapsulation.getName());
return convertView;
}
static class ViewHolder { //用來裝在listview裡每一列要顯示的元件
TextView textview;
ImageView image;
}
}
public class MainActivity extends AppCompatActivity {
private ListView listview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] s={"Jack","Mary","William","Micheal","Tom","Watson","Alice","Anna","Eve","Jane","Amanda","Laura","Diana","Lydia","Ivy","Vanessa","Ashley","Jennifer","Stephanie","Bella","Catherine","Eileen"};
listview = (ListView)findViewById(R.id.listview);
ArrayList<ListName> list = new ArrayList<>();
for(int i=0;i<s.length;i++){
ListName encapsulation = new ListName();
encapsulation.setName(s[i]);
list.add(encapsulation);
}
listview.setAdapter(new BaseAdapter(this,list));
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.and_sv.MainActivity" >
<EditText
android:id="@+id/edtname"
android:layout_width="100dp"
android:layout_height="wrap_content" >
</EditText>
<EditText
android:id="@+id/edttext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/edtname"
android:layout_marginLeft="20dp"
android:layout_toRightOf="@+id/edtname"
android:ems="10" >
</EditText>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/edttext"
android:layout_below="@+id/edttext"
android:text="送出" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/edtname"
android:layout_below="@+id/button1" />
</RelativeLayout>
public class MainActivity extends Activity {
private EditText edtname,edttext;
private TextView textview1;
private Button button1;
String tmp; // 暫存文字訊息
Socket clientSocket;
public static Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtname = (EditText)findViewById(R.id.edtname);
edttext = (EditText)findViewById(R.id.edttext);
button1 = (Button)findViewById(R.id.button1);
textview1 = (TextView)findViewById(R.id.textView1);
button1.setOnClickListener(btnlistener);
Thread t = new Thread(readData);
// 啟動執行緒
t.start();
}
private OnClickListener btnlistener = new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(clientSocket.isConnected()){
BufferedWriter bw;
try {
// 取得網路輸出串流
bw = new BufferedWriter( new OutputStreamWriter(clientSocket.getOutputStream()));
// 寫入訊息
bw.write(edtname.getText()+":"+edttext.getText()+"\n");
// 立即發送
bw.flush();
} catch (IOException e) {
}
// 將文字方塊清空
edttext.setText("");
}
}
};
// 顯示更新訊息
private Runnable updateText = new Runnable() {
public void run() {
// 加入新訊息並換行
textview1.append(tmp + "\n");
}
};
// 取得網路資料
private Runnable readData = new Runnable() {
public void run() {
// server端的IP
InetAddress serverIp;
try {
// 以內定(本機電腦端)IP為Server端
serverIp = InetAddress.getByName("10.0.2.2");
int serverPort = 5050;
clientSocket = new Socket(serverIp, serverPort);
// 取得網路輸入串流
BufferedReader br = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
// 當連線後
while (clientSocket.isConnected()) {
// 取得網路訊息
tmp = br.readLine();
// 如果不是空訊息則
if(tmp!=null)
// 顯示新的訊息
mHandler.post(updateText);
}
} catch (IOException e) {
}
}
};
}
public class Server {
private static int serverport = 5050;
private static ServerSocket serverSocket;
private static int count=0;
// 用串列來儲存每個client
private static ArrayList players=new ArrayList();
// 程式進入點
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(serverport);
System.out.println("Server is start.");
// 顯示等待客戶端連接
System.out.println("Waiting for clinet connect");
// 當Server運作中時
while (!serverSocket.isClosed()) {
// 呼叫等待接受客戶端連接
waitNewPlayer();
}
} catch (IOException e) {
System.out.println("Server Socket ERROR");
}
}
// 等待接受客戶端連接
public static void waitNewPlayer() {
try {
Socket socket = serverSocket.accept();
++count;
System.out.println("現在使用者個數:"+count);
// 呼叫創造新的使用者
createNewPlayer(socket);
} catch (IOException e) {
}
}
// 創造新的使用者
public static void createNewPlayer(final Socket socket) throws IOException {
// 以新的執行緒來執行
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
// 增加新的使用者
players.add(socket);
// 取得網路串流
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
// 當Socket已連接時連續執行
while (socket.isConnected()) {
// 取得網路串流的訊息
String msg= br.readLine();
if(msg==null){
System.out.println("Client Disconnected!");
break;
}
//輸出訊息
System.out.println(msg);
// 廣播訊息給其它的客戶端
castMsg(msg);
}
} catch (IOException e) {
e.getStackTrace();
}
finally{
// 移除客戶端
players.remove(socket);
--count;
System.out.println("現在使用者個數:"+count);
}
}
});
// 啟動執行緒
t.start();
}
// 廣播訊息給其它的客戶端
public static void castMsg(String Msg){
// 創造socket陣列
Socket[] ps=new Socket[players.size()];
// 將players轉換成陣列存入ps
players.toArray(ps);
// 走訪ps中的每一個元素
for (Socket socket : ps ) {
try {
// 創造網路輸出串流
BufferedWriter bw;
bw = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream()));
// 寫入訊息到串流
bw.write(Msg+"\n");
// 立即發送
bw.flush();
} catch (IOException e) {
}
}
}
}