diff --git a/README.md b/README.md index b83a2c50..baec916d 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,8 @@ 实验要求:https://github.com/hzuapps/android-labs/blob/master/labs.md ## Android中文教材 -http://hukai.me/android-training-course-in-chinese/index.html +http://hukai.me/android-training-course-in-chinese/index.html +https://www.gitbook.com/book/mobile100/android/details ## Android英文教程 http://www.tutorialspoint.com/index.htm diff --git a/app/libs/AMap_Location_V2.4.1_20160414.jar b/app/libs/AMap_Location_V2.4.1_20160414.jar new file mode 100644 index 00000000..3bed5aa6 Binary files /dev/null and b/app/libs/AMap_Location_V2.4.1_20160414.jar differ diff --git a/app/libs/android-support-v4.jar b/app/libs/android-support-v4.jar new file mode 100644 index 00000000..2ff47f4f Binary files /dev/null and b/app/libs/android-support-v4.jar differ diff --git a/app/src/main/assets/sound/net1313071001221_shake.mp3 b/app/src/main/assets/sound/net1313071001221_shake.mp3 new file mode 100644 index 00000000..6cd208a5 Binary files /dev/null and b/app/src/main/assets/sound/net1313071001221_shake.mp3 differ diff --git a/app/src/main/assets/sound/net1313071001221_shakeResult.mp3 b/app/src/main/assets/sound/net1313071001221_shakeResult.mp3 new file mode 100644 index 00000000..354bcef1 Binary files /dev/null and b/app/src/main/assets/sound/net1313071001221_shakeResult.mp3 differ diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/BackActivity.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/BackActivity.java deleted file mode 100644 index 70c51b53..00000000 --- a/app/src/main/java/edu/hzuapps/androidworks/homeworks/BackActivity.java +++ /dev/null @@ -1,49 +0,0 @@ -package edu.hzuapps.androidworks.homeworks; - -import android.os.Bundle; -import android.support.v7.app.ActionBarActivity; -import android.util.Log; -import android.view.Menu; -import android.view.MenuItem; - -import edu.hzuapps.androidworks.R; - -/** - * 实现的默认返回按钮,所有作业可继续此类. - */ -public class BackActivity extends ActionBarActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_back); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.menu_subactivity, menu); - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - int id = item.getItemId(); - if (id == R.id.action_back) { - finish(); - return true; - } - return super.onOptionsItemSelected(item); - } - - @Override - protected void onStop() { - super.onStop(); - Log.i(this.getClass().getSimpleName(), "停止!"); - } - - @Override - protected void onDestroy() { - super.onDestroy(); - Log.i(this.getClass().getSimpleName(), "回收!"); - } -} diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/Net1314080903230/Net1314080903230.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/Net1314080903230/Net1314080903230.java new file mode 100644 index 00000000..d9a8afef --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/Net1314080903230/Net1314080903230.java @@ -0,0 +1,52 @@ +package edu.hzuapps.androidworks.homeworks.net1314080903230; + +import android.os.Bundle; +import android.support.design.widget.FloatingActionButton; +import android.support.design.widget.Snackbar; +import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.Toolbar; +import android.view.View; +import android.view.Menu; +import android.view.MenuItem; + +public class Net1314080903230 extends AppCompatActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_net1314080903230); + Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + + FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); + fab.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) + .setAction("Action", null).show(); + } + }); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.menu_net1314080903230, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + + //noinspection SimplifiableIfStatement + if (id == R.id.action_settings) { + return true; + } + + return super.onOptionsItemSelected(item); + } +} diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901102/Card.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901102/Card.java new file mode 100644 index 00000000..597a5f30 --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901102/Card.java @@ -0,0 +1,43 @@ +package edu.hzuapps.androidworks.homeworks.com1314080901102; + +import android.content.Context; +import android.view.Gravity; +import android.view.ViewGroup; +import android.widget.FrameLayout; +import android.widget.TextView; + +/** + * Created by Administrator on 2016/5/11. + */ +public class Card extends FrameLayout { + + public Card(Context context){ + super(context); + label = new TextView(getContext()); + label.setTextSize(32); + label.setBackgroundColor(0x33ffffff); + label.setGravity(Gravity.CENTER); + + LayoutParams lp = new LayoutParams(-1,-1); + lp.setMargins(10, 10, 0, 0); + addView(label,lp); + + setNum(0); + } + + public int getNum() { + return num; + } + + public void setNum(int num) { + if(num<0){ + label.setText(""); + }else{ + label.setText(num+""); + } + this.num = num; + } + + private int num = 0; + private TextView label; +} diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901102/Com1314080901102MainActivity.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901102/Com1314080901102MainActivity.java new file mode 100644 index 00000000..1ebaba03 --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901102/Com1314080901102MainActivity.java @@ -0,0 +1,65 @@ +package edu.hzuapps.androidworks.homeworks.com1314080901102; + +import android.content.Intent; +import android.support.v7.app.ActionBarActivity; +import android.os.Bundle; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; + +import android.util.Log; + +import edu.hzuapps.androidworks.homeworks.simple_2048.R; + + +public class Com1314080901102MainActivity extends ActionBarActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_com1314080901102_main); + + Button bt1 = (Button) findViewById(R.id.Paly); + Button bt2 = (Button) findViewById(R.id.check); + + bt1.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(Com1314080901102MainActivity.this,HomeActivity.class); + startActivity(intent); + } + }); + bt2.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(Com1314080901102MainActivity.this,ScoreActivity.class); + startActivity(intent); + } + }); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.menu_com1314080901102_main, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + + //noinspection SimplifiableIfStatement + if (id == R.id.action_settings) { + return true; + } + + return super.onOptionsItemSelected(item); + } + +} diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901102/GameView.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901102/GameView.java new file mode 100644 index 00000000..52c52d72 --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901102/GameView.java @@ -0,0 +1,296 @@ +package edu.hzuapps.androidworks.homeworks.com1314080901102; + +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.SharedPreferences; +import android.content.res.TypedArray; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.Point; +import android.graphics.drawable.Drawable; +import android.text.TextPaint; +import android.util.AttributeSet; +import android.view.MotionEvent; +import android.view.View; +import android.widget.GridLayout; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import edu.hzuapps.androidworks.homeworks.simple_2048.R; + +/** + * TODO: document your custom view class. + */ +public class GameView extends GridLayout { + private HomeActivity homeActivity = HomeActivity.getHomeActivity(); + + public GameView(Context context) { + super(context); + init(); + } + + public GameView(Context context, AttributeSet attrs) { + super(context, attrs); + init(); + } + + public GameView(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + init(); + } + + + private void init() { + + setColumnCount(4); + setBackgroundColor(0xffbbada0); + + setOnTouchListener(new OnTouchListener() { + private float startX, startY, offsetX, offsetY; + + @Override + public boolean onTouch(View v, MotionEvent event) { + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN: + startX = event.getX(); + startY = event.getY(); + break; + case MotionEvent.ACTION_UP: + offsetX = event.getX() - startX; + offsetY = event.getY() - startY; + if (Math.abs(offsetX) > Math.abs(offsetY)) { + if (offsetX < -5) { + swipeLeft(); + } else if (offsetX > 5) { + swipeRight(); + } + } else { + if (offsetY > 5) { + swipeUp(); + } else if (offsetY < -5) { + swipeDown(); + } + } + break; + } + + return true; + } + }); + + } + + @Override + protected void onSizeChanged(int w,int h,int oldw,int oldh){ + super.onSizeChanged(w, h, oldw, oldh); + int cardWeith = (Math.min(w,h)-10)/4; + addCards(cardWeith,cardWeith); + startGame(); + } + private void addCards(int cardWidth,int cardHeith){ + Card c; + for(int y = 0;y<4;y++){ + for(int x = 0;x<4;x++){ + c = new Card(getContext()); + c.setNum(0); + addView(c,cardWidth,cardHeith); + cardsMap[x][y] = c; + } + } + } + + public void startGame(){ + + for (int x=0;x<4;x++){ + for (int y=0;y<4;y++){ + cardsMap[x][y].setNum(0); + } + } + + addRandomNum(); + addRandomNum(); + } + + + public void swipeLeft(){ + boolean mergen = false; + for(int y=0;y<4;y++){ + for(int x=0;x<4;x++){ + for(int x1=x+1;x1<4;x1++){ + if(cardsMap[x1][y].getNum()>0){ + if(cardsMap[x][y].getNum()<=0){ + cardsMap[x][y].setNum(cardsMap[x1][y].getNum()); + cardsMap[x1][y].setNum(0); + x--; + mergen = true; + }else if(cardsMap[x][y].getNum() == cardsMap[x1][y].getNum()){ + cardsMap[x][y].setNum(cardsMap[x1][y].getNum()*2); + cardsMap[x1][y].setNum(0); + //getScore; + homeActivity.addScore(cardsMap[x][y].getNum()); + mergen = true; + } + break; + } + } + } + } + if(mergen){ + addRandomNum(); + } + } + + public void swipeRight(){ + boolean mergen = false; + + for(int y=0;y<4;y++){ + for(int x=3;x>-1;x--){ + for(int x1=x-1;x1>-1;x1--){ + if(cardsMap[x1][y].getNum()>0){ + if(cardsMap[x][y].getNum()<=0){ + cardsMap[x][y].setNum(cardsMap[x1][y].getNum()); + cardsMap[x1][y].setNum(0); + x++; + mergen = true; + }else if(cardsMap[x][y].getNum() == cardsMap[x1][y].getNum()){ + cardsMap[x][y].setNum(cardsMap[x1][y].getNum()*2); + cardsMap[x1][y].setNum(0); + homeActivity.addScore(cardsMap[x][y].getNum()); + mergen = true; + } + break; + } + } + } + } + if(mergen){ + addRandomNum(); + } + } + + public void swipeDown(){ + boolean mergen = false; + for(int x=0;x<4;x++){ + for(int y=0;y<4;y++){ + for(int y1=y+1;y1<4;y1++){ + if(cardsMap[x][y1].getNum()>0){ + if(cardsMap[x][y].getNum()<=0){ + cardsMap[x][y].setNum(cardsMap[x][y1].getNum()); + cardsMap[x][y1].setNum(0); + y--; + mergen = true; + }else if(cardsMap[x][y].getNum() == cardsMap[x][y1].getNum()){ + cardsMap[x][y].setNum(cardsMap[x][y1].getNum()*2); + cardsMap[x][y1].setNum(0); + //getScore; + homeActivity.addScore(cardsMap[x][y].getNum()); + mergen = true; + } + break; + } + } + } + } + if(mergen){ + addRandomNum(); + } + + } + + public void swipeUp(){ + boolean mergen = false; + + for(int x=0;x<4;x++){ + for(int y=3;y>-1;y--){ + for(int y1=y-1;y1>-1;y1--){ + if(cardsMap[x][y1].getNum()>0){ + if(cardsMap[x][y].getNum()<=0){ + cardsMap[x][y].setNum(cardsMap[x][y1].getNum()); + cardsMap[x][y1].setNum(0); + y++; + mergen = true; + }else if(cardsMap[x][y].getNum() == cardsMap[x][y1].getNum()){ + cardsMap[x][y].setNum(cardsMap[x][y1].getNum()*2); + cardsMap[x][y1].setNum(0); + //getScore; + homeActivity.addScore(cardsMap[x][y].getNum()); + mergen = true; + } + break; + } + } + } + } + if(mergen){ + addRandomNum(); + } + + } + + public void addRandomNum(){ + emptyList.clear(); + for (int y=0;y<4;y++){ + for (int x=0;x<4;x++){ + if(cardsMap[x][y].getNum()<=0){ + emptyList.add(new Point(x,y)); + } + } + } + Point p = emptyList.remove((int)(Math.random()*emptyList.size())); + cardsMap[p.x][p.y].setNum(Math.random()>0.1?2:4); + checkComplete(); + } + + private void checkComplete(){ + boolean complete = true; + targ: + for (int x=0;x<4;x++){ + for (int y=0;y<4;y++){ + if(cardsMap[x][y].getNum()==0|| + x>0&&cardsMap[x][y].getNum()==cardsMap[x-1][y].getNum()|| + x<3&&cardsMap[x][y].getNum()==cardsMap[x+1][y].getNum()|| + y>0&&cardsMap[x][y].getNum()==cardsMap[x][y-1].getNum()|| + y<3&&cardsMap[x][y].getNum()==cardsMap[x][y+1].getNum()){ + complete = false; + break; + } + } + } + + SharedPreferences preferences = homeActivity.getSharedPreferences("score", Context.MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + int score = preferences.getInt("highscore",0); + + if(complete){ + int newScore = homeActivity.getScore(); + if(newScore>score){ + editor.putInt("highscore", newScore); + editor.putString("time", new SimpleDateFormat("yyyyMMdd" + "hh:mm:ss").format(new Date())); + editor.commit(); + new AlertDialog.Builder(getContext()).setTitle("You Win!").setMessage("ˢ¼¼").setPositiveButton("", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + startGame(); + } + }).show(); + }else{ + new AlertDialog.Builder(getContext()).setTitle("Game Over!").setMessage("Ϸ").setPositiveButton("", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + startGame(); + } + }).show(); + } + + } + + } + + private List emptyList = new ArrayList(); + private Card[][] cardsMap = new Card[4][4]; +} diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901102/HomeActivity.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901102/HomeActivity.java new file mode 100644 index 00000000..ce335631 --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901102/HomeActivity.java @@ -0,0 +1,80 @@ +package edu.hzuapps.androidworks.homeworks.com1314080901102; + +import android.content.Intent; +import android.content.SharedPreferences; +import android.support.v7.app.ActionBarActivity; +import android.os.Bundle; +import android.util.Log; +import android.view.Menu; +import android.view.MenuItem; +import android.widget.TextView; + +import edu.hzuapps.androidworks.homeworks.simple_2048.R; + + +public class HomeActivity extends ActionBarActivity { + + public static HomeActivity homeActivity = null; + private int score = 0; + private TextView tv; + private GameView gameView; + + public HomeActivity(){ homeActivity = HomeActivity.this;} + public static HomeActivity getHomeActivity(){return homeActivity;} + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_home); + gameView = (GameView)findViewById(R.id.gameView); + tv = (TextView) findViewById(R.id.tvScore); + } + + private void showScore(){ + tv.setText(score + ""); + } + + public void addScore(int s){ + score+=s; + showScore(); + } + + public int getScore(){ + return score; + } + + public void clearScore(){ + score = 0; + } + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.menu_home, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + + //noinspection SimplifiableIfStatement + if (id == R.id.action_settings) { + return true; + } + switch (id){ + case R.id.repaly: + gameView.startGame(); + clearScore(); + return true; + case R.id.mainmenu: + Intent intent = new Intent(HomeActivity.this,Com1314080901102MainActivity.class); + startActivity(intent); + return true; + default: + return super.onOptionsItemSelected(item); + } + } +} diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901102/ScoreActivity.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901102/ScoreActivity.java new file mode 100644 index 00000000..9498626e --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901102/ScoreActivity.java @@ -0,0 +1,50 @@ +package edu.hzuapps.androidworks.homeworks.com1314080901102; + +import android.content.SharedPreferences; +import android.support.v7.app.ActionBarActivity; +import android.os.Bundle; +import android.view.Menu; +import android.view.MenuItem; +import android.widget.TextView; + +import edu.hzuapps.androidworks.homeworks.simple_2048.R; + +public class ScoreActivity extends ActionBarActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_score); + TextView scoreView = (TextView)findViewById(R.id.score); + TextView timeView = (TextView)findViewById(R.id.time); + + SharedPreferences preferences = this.getSharedPreferences("highScore",MODE_PRIVATE); + int score = preferences.getInt("score",0); + String time = preferences.getString("time",null); + + scoreView.setText(score + ""); + timeView.setText(time); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.menu_score, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + + //noinspection SimplifiableIfStatement + if (id == R.id.action_settings) { + return true; + } + + return super.onOptionsItemSelected(item); + } +} diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/AndroidManifest.xml b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/AndroidManifest.xml new file mode 100644 index 00000000..e6675dd8 --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/AndroidManifest.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/Com1314080901103Activity.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/Com1314080901103Activity.java deleted file mode 100644 index 7f4104f8..00000000 --- a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/Com1314080901103Activity.java +++ /dev/null @@ -1,15 +0,0 @@ -package edu.hzuapps.androidworks.homeworks.com1314080901103; - -import android.os.Bundle; -import android.support.v7.app.AppCompatActivity; -import android.view.Window; - -public class Com1314080901103Activity extends AppCompatActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - requestWindowFeature(Window.FEATURE_NO_TITLE); - setContentView(R.layout.activity_com1314080901103); - } -} diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/activity/ActivityCollector.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/activity/ActivityCollector.java new file mode 100644 index 00000000..7c9ba18b --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/activity/ActivityCollector.java @@ -0,0 +1,26 @@ +package edu.hzuapps.androidworks.homeworks.com1314080901103.activity; + +import android.app.Activity; + +import java.util.ArrayList; +import java.util.List; + +public class ActivityCollector { + public static List activities = new ArrayList<>(); + + public static void addActivity(Activity activity) { + activities.add(activity); + } + + public static void removeActivity(Activity activity) { + activities.remove(activity); + } + + public static void finishAll() { + for (Activity activity : activities) { + if (!activity.isFinishing()) { + activity.finish(); + } + } + } +} diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/activity/ChooseAreaActivity.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/activity/ChooseAreaActivity.java new file mode 100644 index 00000000..c5bd09d6 --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/activity/ChooseAreaActivity.java @@ -0,0 +1,276 @@ +package edu.hzuapps.androidworks.homeworks.com1314080901103.activity; + +import android.app.Activity; +import android.app.ProgressDialog; +import android.content.Intent; +import android.os.Bundle; +import android.text.TextUtils; +import android.view.View; +import android.view.Window; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.ImageView; +import android.widget.ListView; +import android.widget.TextView; +import android.widget.Toast; + +import java.util.ArrayList; +import java.util.List; + +import edu.hzuapps.androidworks.homeworks.com1314080901103.R; +import edu.hzuapps.androidworks.homeworks.com1314080901103.db.WeatherDB; +import edu.hzuapps.androidworks.homeworks.com1314080901103.model.City; +import edu.hzuapps.androidworks.homeworks.com1314080901103.model.County; +import edu.hzuapps.androidworks.homeworks.com1314080901103.model.Province; +import edu.hzuapps.androidworks.homeworks.com1314080901103.util.HttpCallbackListener; +import edu.hzuapps.androidworks.homeworks.com1314080901103.util.HttpUtil; +import edu.hzuapps.androidworks.homeworks.com1314080901103.util.Utility; + +public class ChooseAreaActivity extends Activity { + + public static final int LEVEL_PROVINCE = 0; + public static final int LEVEL_CITY = 1; + public static final int LEVEL_COUNTY = 2; + private ProgressDialog progressDialog; + private ImageView imageView; + private TextView titleText; + private ListView listView; + private ArrayAdapter adapter; + private WeatherDB weatherDB; + private List dataList = new ArrayList<>(); + /** + * 省列表 + */ + private List provinceList; + /** + * 市列表 + */ + private List cityList; + /** + * 县列表 + */ + private List countyList; + /** + * 选中的省份 + */ + private Province selectedProvince; + /** + * 选中的城市 + */ + private City selectedCity; + /** + * 当前选中的级别 + */ + private int currentLevel; + /** + * 是否从WeatherActivity 中跳转过来。 + */ + private boolean isFromWeatherActivity; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + requestWindowFeature(Window.FEATURE_NO_TITLE); + setContentView(R.layout.activity_com1314080901103_show_area); + isFromWeatherActivity = getIntent().getBooleanExtra("from_weather_activity", false); + initView(); + adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, dataList); + listView.setAdapter(adapter); + weatherDB = WeatherDB.getInstance(this); + imageView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + onBackPressed(); + } + }); + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView arg0, View view, int index, + long arg3) { + if (currentLevel == LEVEL_PROVINCE) { + selectedProvince = provinceList.get(index); + queryCities(); + } else if (currentLevel == LEVEL_CITY) { + selectedCity = cityList.get(index); + queryCounties(); + } else if (currentLevel == LEVEL_COUNTY) { + String countyCode = countyList.get(index).getCountyCode(); + String countyName = countyList.get(index).getCountyName(); + Intent intent = new Intent(ChooseAreaActivity.this, + WeatherActivity.class); + intent.putExtra("county_code", countyCode); + intent.putExtra("county_name", countyName); + intent.putExtra("is_form_choose_area", true); + startActivity(intent); + finish(); + } + } + }); + queryProvinces(); // 加载省级数据 + ActivityCollector.addActivity(this); + } + + private void initView() { + imageView = (ImageView) findViewById(R.id.back); + listView = (ListView) findViewById(R.id.list_view); + titleText = (TextView) findViewById(R.id.title_text); + } + + /** + * 查询全国所有的省,优先从数据库查询,如果没有查询到再去服务器上查询。 + */ + private void queryProvinces() { + provinceList = weatherDB.loadProvinces(); + if (provinceList.size() > 0) { + dataList.clear(); + for (Province province : provinceList) { + dataList.add(province.getProvinceName()); + } + adapter.notifyDataSetChanged(); + listView.setSelection(0); + titleText.setText("添加城市"); + currentLevel = LEVEL_PROVINCE; + } else { + queryFromServer(null, "province"); + } + } + + /** + * 查询选中省内所有的市,优先从数据库查询,如果没有查询到再去服务器上查询。 + */ + private void queryCities() { + cityList = weatherDB.loadCities(selectedProvince.getId()); + if (cityList.size() > 0) { + dataList.clear(); + for (City city : cityList) { + dataList.add(city.getCityName()); + } + adapter.notifyDataSetChanged(); + listView.setSelection(0); + titleText.setText(selectedProvince.getProvinceName()); + currentLevel = LEVEL_CITY; + } else { + queryFromServer(selectedProvince.getProvinceCode(), "city"); + } + } + + /** + * 查询选中市内所有的县,优先从数据库查询,如果没有查询到再去服务器上查询。 + */ + private void queryCounties() { + countyList = weatherDB.loadCounties(selectedCity.getId()); + if (countyList.size() > 0) { + dataList.clear(); + for (County county : countyList) { + dataList.add(county.getCountyName()); + } + adapter.notifyDataSetChanged(); + listView.setSelection(0); + titleText.setText(selectedCity.getCityName()); + currentLevel = LEVEL_COUNTY; + } else { + queryFromServer(selectedCity.getCityCode(), "county"); + } + } + + /** + * 根据传入的代号和类型从服务器上查询省市县数据 + * + * @param code + * @param type + */ + private void queryFromServer(final String code, final String type) { + String address; + if (!TextUtils.isEmpty(code)) { + address = "http://www.weather.com.cn/data/list3/city" + code + + ".xml"; + } else { + address = "http://www.weather.com.cn/data/list3/city.xml"; + } + showProgressDialog(); + HttpUtil.sendHttpRequest(address, new HttpCallbackListener() { + @Override + public void onFinish(String response) { + boolean result = false; + if ("province".equals(type)) { + result = Utility.handleProvincesResponse(weatherDB, + response); + } else if ("city".equals(type)) { + result = Utility.handleCitiesResponse(weatherDB, + response, selectedProvince.getId()); + } else if ("county".equals(type)) { + result = Utility.handleCountiesResponse(weatherDB, + response, selectedCity.getId()); + } + if (result) { + // 通过runOnUiThread()方法回到主线程处理逻辑 + runOnUiThread(new Runnable() { + @Override + public void run() { + closeProgressDialog(); + if ("province".equals(type)) { + queryProvinces(); + } else if ("city".equals(type)) { + queryCities(); + } else if ("county".equals(type)) { + queryCounties(); + } + } + }); + } + } + + @Override + public void onError(Exception e) { + // 通过runOnUiThread()方法回到主线程处理逻辑 + runOnUiThread(new Runnable() { + @Override + public void run() { + closeProgressDialog(); + Toast.makeText(ChooseAreaActivity.this, + "加载失败", Toast.LENGTH_SHORT).show(); + } + }); + } + }); + } + + /** + * 显示进度对话框 + */ + private void showProgressDialog() { + if (progressDialog == null) { + progressDialog = new ProgressDialog(this); + progressDialog.setMessage("正在加载..."); + progressDialog.setCanceledOnTouchOutside(false); + } + progressDialog.show(); + } + + /** + * 关闭进度对话框 + */ + private void closeProgressDialog() { + if (progressDialog != null) { + progressDialog.dismiss(); + } + } + + /** + * 捕获Back按键,根据当前的级别来判断,此时应该返回市列表、省列表、还是直接退出。 + */ + @Override + public void onBackPressed() { + if (currentLevel == LEVEL_COUNTY) { + queryCities(); + } else if (currentLevel == LEVEL_CITY) { + queryProvinces(); + } else { + if (isFromWeatherActivity) { + Intent intent = new Intent(this, WeatherActivity.class); + startActivity(intent); + } + finish(); + } + } +} \ No newline at end of file diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/activity/DeleteAreaActivity.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/activity/DeleteAreaActivity.java new file mode 100644 index 00000000..42125ab6 --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/activity/DeleteAreaActivity.java @@ -0,0 +1,120 @@ +package edu.hzuapps.androidworks.homeworks.com1314080901103.activity; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.content.Intent; +import android.os.Bundle; +import android.util.Log; +import android.view.View; +import android.view.Window; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.ImageView; +import android.widget.ListView; +import android.widget.TextView; +import android.widget.Toast; + +import java.util.ArrayList; +import java.util.List; + +import edu.hzuapps.androidworks.homeworks.com1314080901103.R; +import edu.hzuapps.androidworks.homeworks.com1314080901103.db.WeatherDB; +import edu.hzuapps.androidworks.homeworks.com1314080901103.model.County; + +public class DeleteAreaActivity extends Activity { + + private ImageView imageView; + private TextView titleText; + private ListView listView; + private ArrayAdapter adapter; + private List countyList = new ArrayList<>(); + private List countyNameList = new ArrayList<>(); + private WeatherDB weatherDB; + private String selectedCountyName; + private int toWeatherActivityPosition; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + requestWindowFeature(Window.FEATURE_NO_TITLE); + setContentView(R.layout.activity_com1314080901103_show_area); + + toWeatherActivityPosition = getIntent().getIntExtra("to_delete_area_position", -1); + + weatherDB = WeatherDB.getInstance(this); + countyList = weatherDB.loadAddCounties(); + if (countyList.size() > 0) { + countyNameList.clear(); + for (County county : countyList) { + countyNameList.add(county.getCountyName()); + } + } + + imageView = (ImageView) findViewById(R.id.back); + titleText = (TextView) findViewById(R.id.title_text); + titleText.setText("删除城市"); + listView = (ListView) findViewById(R.id.list_view); + adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, countyNameList); + listView.setAdapter(adapter); + imageView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + onBackPressed(); + } + }); + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + selectedCountyName = countyNameList.get(position); + AlertDialog.Builder dialog = new AlertDialog.Builder + (DeleteAreaActivity.this); + dialog.setTitle("友情提示"); + dialog.setMessage("确认删除" + selectedCountyName + "么?"); + dialog.setCancelable(true); + dialog.setPositiveButton("确认", new DialogInterface. + OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + weatherDB.deleteFromAddCountiesByCountyName(selectedCountyName); + weatherDB.deleteFromAddCountiesWeatherByCountyName(selectedCountyName); + Toast.makeText(DeleteAreaActivity.this, selectedCountyName + " 删除成功", Toast.LENGTH_SHORT).show(); + countyList = weatherDB.loadAddCounties(); + weatherDB.deleteAddCounties(); + weatherDB.createAddCounties(); + if (countyList.size() > 0) { + countyNameList.clear(); + for (County county : countyList) { + countyNameList.add(county.getCountyName()); + weatherDB.saveAddCounty(county); + } + } else { + countyNameList.clear(); + } + adapter.notifyDataSetChanged(); + } + }); + dialog.setNegativeButton("取消", new DialogInterface. + OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + } + }); + dialog.show(); + } + }); + ActivityCollector.addActivity(this); + } + + /** + * 捕获Back按键,回到WeatherActivity + */ + @Override + public void onBackPressed() { + Intent intent = new Intent(DeleteAreaActivity.this, WeatherActivity.class); + intent.putExtra("to_weather_activity_position", toWeatherActivityPosition); + startActivity(intent); + finish(); + Log.d("DeleteAreaActivity", "xyz onBackPressed has finished"); + } +} \ No newline at end of file diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/activity/WeatherActivity.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/activity/WeatherActivity.java new file mode 100644 index 00000000..b996cec1 --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/activity/WeatherActivity.java @@ -0,0 +1,566 @@ +package edu.hzuapps.androidworks.homeworks.com1314080901103.activity; + +import android.app.Activity; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Color; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.support.v4.view.ViewPager; +import android.support.v4.widget.SwipeRefreshLayout; +import android.text.TextUtils; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.View; +import android.view.Window; +import android.widget.Button; +import android.widget.RelativeLayout; +import android.widget.TextView; + +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 java.util.ArrayList; +import java.util.List; + +import edu.hzuapps.androidworks.homeworks.com1314080901103.R; +import edu.hzuapps.androidworks.homeworks.com1314080901103.adapter.ViewPageAdapter; +import edu.hzuapps.androidworks.homeworks.com1314080901103.db.WeatherDB; +import edu.hzuapps.androidworks.homeworks.com1314080901103.model.County; +import edu.hzuapps.androidworks.homeworks.com1314080901103.model.CountyWeather; +import edu.hzuapps.androidworks.homeworks.com1314080901103.util.HttpCallbackListener; +import edu.hzuapps.androidworks.homeworks.com1314080901103.util.HttpUtil; +import edu.hzuapps.androidworks.homeworks.com1314080901103.util.Utility; + +public class WeatherActivity extends Activity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener { + + /** + * 所用到的类的声明 + */ + private RelativeLayout relativeLayout; + private SwipeRefreshLayout swipeRefreshLayout; + public WeatherDB weatherDB; + private ViewPager listPager; + private List listView; + private ViewPageAdapter viewPageAdapter; + /** + * 用于显示城市名 + */ + private TextView cityNameText; + /** + * 用于显示发布时间 + */ + private TextView publishText; + /** + * 用于显示天气描述信息 + */ + private TextView weatherDespText; + /** + * 用于显示气温1 + */ + private TextView temp1Text; + /** + * 用于显示气温2 + */ + private TextView temp2Text; + /** + * 用于显示当前日期 + */ + private TextView currentDateText; + /** + * 切换城市按钮 + */ + private Button switchCity; + /** + * 更新天气按钮 + */ + private Button refreshWeather; + /** + * 保存已查询过的天气代号 + */ + private String weatherCode; + /** + * 保存当前定位到的城市 + */ + public String cityName; + /** + * 保存从上一活动传递过来的城市代码 + */ + public String countyCode; + /** + * 保存从上一活动传递过来的城市名 + */ + public String countyName; + /** + * 保存当前显示的页数 + */ + public int currentPosition; + /** + * 判断是否来自ChooseAreaActivity + */ + private Boolean isFromChooseAreaActivity; + /** + * 判断是否来自DeleteAreaActivity + */ + private int formDeleteAreaActivityPosition; + /** + * 声明AMapLocationClient类对象 + */ + public AMapLocationClient mLocationClient = null; + /** + * 声明定位回调监听器 + */ + public AMapLocationListener mLocationListener = new AMapLocationListener() { + @Override + public void onLocationChanged(AMapLocation aMapLocation) { + if (aMapLocation != null) { + if (aMapLocation.getErrorCode() == 0) { + //定位成功回调信息,设置相关消息 + cityName = aMapLocation.getCity(); //获得当前城市信息 + SharedPreferences prefs = PreferenceManager. + getDefaultSharedPreferences(WeatherActivity.this); + String defaultLocation = prefs.getString("city_name_juhe", "") + "市"; + if (defaultLocation.equals(cityName)) { + showWeatherFromJuHe(); + } else if (!TextUtils.isEmpty(cityName)) { + queryWeatherInfoFromJuHe(cityName); + } + if (mLocationClient != null) { + mLocationClient.stopLocation();//停止定位 + mLocationClient.onDestroy();//销毁定位客户端 + } + } else { + //显示错误信息ErrCode是错误码,errInfo是错误信息,详见错误码表。 + Log.e("AmapError", "location Error, ErrCode:" + + aMapLocation.getErrorCode() + ", errInfo:" + + aMapLocation.getErrorInfo()); + } + } + } + }; + /** + * 声明mLocationOption对象 + */ + public AMapLocationClientOption mLocationOption = null; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + requestWindowFeature(Window.FEATURE_NO_TITLE); + setContentView(R.layout.activity_com1314080901103_pager_adapter); + initView(); + countyCode = getIntent().getStringExtra("county_code"); + countyName = getIntent().getStringExtra("county_name"); + isFromChooseAreaActivity = getIntent().getBooleanExtra("is_form_choose_area", false); + formDeleteAreaActivityPosition = getIntent().getIntExtra("to_weather_activity_position", -1); + weatherDB = WeatherDB.getInstance(this); + judgeDBToAdd(); + initViewPage(); + initSwipeRefreshLayout(); + switchCity.setOnClickListener(this); + refreshWeather.setOnClickListener(this); + //设置下拉刷新的监听 + swipeRefreshLayout.setOnRefreshListener(this); + ActivityCollector.addActivity(this); + } + + /** + * 初始化所有控件 + */ + private void initView() { + relativeLayout = (RelativeLayout) this.findViewById(R.id.weather_main); + cityNameText = (TextView) this.findViewById(R.id.city_name); + switchCity = (Button) this.findViewById(R.id.switch_city); + refreshWeather = (Button) this.findViewById(R.id.refresh_weather); + } + + /** + * 初始化页面fragment + */ + private void initViewPage() { + listPager = (ViewPager) findViewById(R.id.list_pager); + listView = new ArrayList<>(); + //这里只设置了4.因为在实现应用中,我们在页面加载的时候,你会根据数据的多少,而知道这个页面的数量 + //一般情况下,我们会根据list<>或是string[]这样的数组的数量来判断要有多少页 + int count = weatherDB.selectAddCountySize(); + for (int i = 0; i <= count; i++) { + View view = LayoutInflater.from(this).inflate(R.layout.activity_com1314080901103_fragment_main, null); + relativeLayout = (RelativeLayout) view.findViewById(R.id.weather_main); + publishText = (TextView) view.findViewById(R.id.publish_text); + weatherDespText = (TextView) view.findViewById(R.id.weather_desp); + temp1Text = (TextView) view.findViewById(R.id.temp1); + temp2Text = (TextView) view.findViewById(R.id.temp2); + currentDateText = (TextView) view.findViewById(R.id.current_date); + if (i == 0) { + SharedPreferences prefs = PreferenceManager. + getDefaultSharedPreferences(this); + if (TextUtils.isEmpty(prefs.getString("city_name_juhe", ""))) { + initMap(); + } + temp1Text.setText(prefs.getString("temp1_juhe", "")); + temp2Text.setText(prefs.getString("temp2_juhe", "")); + weatherDespText.setText(prefs.getString("weather_juhe", "")); + selectPictureByWeather(prefs.getString("weather_juhe", "")); + publishText.setText("今天" + prefs.getString("update_time_juhe", "") + "更新"); + currentDateText.setText(prefs.getString("current_date_juhe", "")); + } else { + County county = weatherDB.loadAddCounties(i); + Log.d("WeatherActivity", "xyz county.getCountyName() is " + county.getCountyName()); + CountyWeather countyWeather = weatherDB.loadAddCountiesWeatherByCountyName(county.getCountyName()); + temp1Text.setText(countyWeather.getTemp1()); + temp2Text.setText(countyWeather.getTemp2()); + weatherDespText.setText(countyWeather.getWeatherDesp()); + if (!TextUtils.isEmpty(countyWeather.getWeatherDesp())) { + selectPictureByWeather(countyWeather.getWeatherDesp()); + } + publishText.setText("今天" + countyWeather.getUpdateTime() + "更新"); + currentDateText.setText(countyWeather.getCurrentDate()); + } + listView.add(view); + } + viewPageAdapter = new ViewPageAdapter(listView); + listPager.setAdapter(viewPageAdapter); + if (isFromChooseAreaActivity) { + listPager.setCurrentItem(listView.size()); + County county = weatherDB.loadAddCounties(listView.size()); + cityNameText.setText(county.getCountyName()); + } else if (formDeleteAreaActivityPosition != -1) { + listPager.setCurrentItem(formDeleteAreaActivityPosition); + if (formDeleteAreaActivityPosition == 0) { + SharedPreferences prefs = PreferenceManager. + getDefaultSharedPreferences(WeatherActivity.this); + cityNameText.setText(prefs.getString("city_name_juhe", "")); + } else { + County county = weatherDB.loadAddCounties(formDeleteAreaActivityPosition); + cityNameText.setText(county.getCountyName()); + } + } else { + listPager.setCurrentItem(0); + SharedPreferences prefs = PreferenceManager. + getDefaultSharedPreferences(WeatherActivity.this); + cityNameText.setText(prefs.getString("city_name_juhe", "")); + } + listPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { + @Override + public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { + } + + @Override + public void onPageSelected(int position) { + if (position == 0) { + SharedPreferences prefs = PreferenceManager. + getDefaultSharedPreferences(WeatherActivity.this); + cityNameText.setText(prefs.getString("city_name_juhe", "")); + } else { + County county = weatherDB.loadAddCounties(position); + cityNameText.setText(county.getCountyName()); + } + currentPosition = position; + Log.d("WeatherActivity", "xyz 当前是第" + position + "页"); + } + + @Override + public void onPageScrollStateChanged(int state) { + } + }); + } + + /** + * 设置下拉刷新的相关属性 + */ + private void initSwipeRefreshLayout() { + swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeLayout); + swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary); + // 设置手指在屏幕下拉多少距离会触发下拉刷新 + swipeRefreshLayout.setDistanceToTriggerSync(300); + // 设定下拉圆圈的背景 + swipeRefreshLayout.setProgressBackgroundColorSchemeColor(Color.WHITE); + // 设置圆圈的大小 + swipeRefreshLayout.setSize(SwipeRefreshLayout.LARGE); + } + + /** + * 判断数据库是否已经存在此城市,若不存在则将其存入数据库 + */ + private void judgeDBToAdd() { + List countyList = weatherDB.loadAddCounties(); + if (!TextUtils.isEmpty(countyCode) && !TextUtils.isEmpty(countyName) && !countyCode.equals("location")) { + if (countyList.size() >= 0) { + Boolean isExist = false; + for (County county1 : countyList) { + if (countyCode.equals(county1.getCountyCode())) { + isExist = true; + } + } + if (!isExist) { + County county = new County(); + county.setCountyCode(countyCode); + county.setCountyName(countyName); + weatherDB.saveAddCounty(county); + queryWeatherCode(countyCode); + } + } + } + } + + /** + * 高德地图定位初始化 + */ + public void initMap() { + //初始化定位 + mLocationClient = new AMapLocationClient(getApplicationContext()); + //设置定位回调监听 + mLocationClient.setLocationListener(mLocationListener); + //初始化定位参数 + mLocationOption = new AMapLocationClientOption(); + //设置定位模式为高精度模式,Battery_Saving为低功耗模式,Device_Sensors是仅设备模式 + mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy); + //设置是否返回地址信息(默认返回地址信息) + mLocationOption.setNeedAddress(true); + //设置是否只定位一次,默认为false + mLocationOption.setOnceLocation(false); + //设置是否强制刷新WIFI,默认为强制刷新 + mLocationOption.setWifiActiveScan(true); + //设置是否允许模拟位置,默认为false,不允许模拟位置 + mLocationOption.setMockEnable(false); + //设置定位间隔,单位毫秒,默认为2000ms + mLocationOption.setInterval(2000); + //给定位客户端对象设置定位参数 + mLocationClient.setLocationOption(mLocationOption); + //启动定位 + mLocationClient.startLocation(); + } + + /** + * 对标题栏的图标进行点击事件注册,并对其进行相应处理 + * + * @param v + */ + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.switch_city: + Intent intent = new Intent(this, ChooseAreaActivity.class); + intent.putExtra("from_weather_activity", true); + startActivity(intent); + finish(); + break; + case R.id.refresh_weather: + Intent intentDelete = new Intent(this, DeleteAreaActivity.class); + intentDelete.putExtra("to_delete_area_position", currentPosition); + startActivity(intentDelete); + finish(); + break; + default: + break; + } + } + + /* + * 根据当前位置获得页面对应的view + * */ + public void getView() { + View view = listView.get(currentPosition); + relativeLayout = (RelativeLayout) view.findViewById(R.id.weather_main); + publishText = (TextView) view.findViewById(R.id.publish_text); + weatherDespText = (TextView) view.findViewById(R.id.weather_desp); + temp1Text = (TextView) view.findViewById(R.id.temp1); + temp2Text = (TextView) view.findViewById(R.id.temp2); + currentDateText = (TextView) view.findViewById(R.id.current_date); + } + + /* + * 监听器SwipeRefreshLayout.OnRefreshListener中的方法,当下拉刷新后触发 + */ + public void onRefresh() { + if (currentPosition > 0) { + County county = weatherDB.loadAddCounties(currentPosition); + queryWeatherCode(county.getCountyCode()); + viewPageAdapter.notifyDataSetChanged(); + getView(); + showWeather(county.getCountyName()); + swipeRefreshLayout.setRefreshing(false); + Log.d("WeatherActivity", "xyz REFRESH_COUNTY has finished"); + } else { + SharedPreferences prefs = PreferenceManager. + getDefaultSharedPreferences(WeatherActivity.this); + String defaultLocation = prefs.getString("city_name_juhe", ""); + queryWeatherInfoFromJuHe(defaultLocation); + viewPageAdapter.notifyDataSetChanged(); + getView(); + showWeatherFromJuHe(); + swipeRefreshLayout.setRefreshing(false); + Log.d("WeatherActivity", "xyz REFRESH_LOCATION has finished"); + } + } + + /** + * 查询县级代号所对应的天气代号 + * + * @param countyCode + */ + private void queryWeatherCode(String countyCode) { + String address = "http://www.weather.com.cn/data/list3/city" + + countyCode + ".xml"; + queryFromServer(address, "countyCode"); + } + + /** + * 查询天气代号所对应的天气 + * + * @param weatherCode + */ + private void queryWeatherInfo(String weatherCode) { + String address = "http://www.weather.com.cn/data/cityinfo/" + + weatherCode + ".html"; + queryFromServer(address, "weatherCode"); + } + + /** + * 通过聚合数据的接口查询城市天气 + * + * @param cityName + */ + private void queryWeatherInfoFromJuHe(String cityName) { + // 组装反向地理编码的接口地址 + StringBuilder url = new StringBuilder(); + url.append("http://v.juhe.cn/weather/index?cityname="); + url.append(cityName); + url.append("&dtype=&format=&key=38a866e9c3aa7066994f99a0a2998a31"); + String address = url.toString(); + queryFromServer(address, "location"); + } + + /** + * 根据传入的地址和类型去向服务器查询天气代号或者天气信息 + * + * @param address + * @param type + */ + private void queryFromServer(final String address, final String type) { + HttpUtil.sendHttpRequest(address, new HttpCallbackListener() { + @Override + public void onFinish(final String response) { + if ("location".equals(type)) { + Utility.handleWeatherResponseFromJuHe(WeatherActivity.this, response); + // 通过runOnUiThread()方法回到主线程处理逻辑 + runOnUiThread(new Runnable() { + @Override + public void run() { + showWeatherFromJuHe(); + } + }); + } else if ("countyCode".equals(type)) { + if (!TextUtils.isEmpty(response)) { + // 从服务器返回的数据中解析出天气代号 + String[] array = response.split("\\|"); + if (array != null && array.length == 2) { + weatherCode = array[1]; + queryWeatherInfo(weatherCode); + } + } + } else if ("weatherCode".equals(type)) { + // 处理服务器返回的天气信息 + final String returnCountyName = Utility.handleWeatherResponse(WeatherActivity.this, + response); + runOnUiThread(new Runnable() { + @Override + public void run() { + showWeather(returnCountyName); + } + }); + } + } + + @Override + public void onError(Exception e) { + Log.d("WeatherActivity", "xyz 548 Exception is " + e.toString()); + runOnUiThread(new Runnable() { + @Override + public void run() { + publishText.setText("同步失败"); + } + }); + } + }); + } + + /** + * 从SharedPreferences文件中读取存储的天气信息,并显示到界面上 + * + * @param countyName + */ + private void showWeather(String countyName) { + CountyWeather countyWeather = weatherDB.loadAddCountiesWeatherByCountyName(countyName); + cityNameText.setText(countyWeather.getCountyName()); + temp1Text.setText(countyWeather.getTemp1()); + temp2Text.setText(countyWeather.getTemp2()); + weatherDespText.setText(countyWeather.getWeatherDesp()); + selectPictureByWeather(countyWeather.getWeatherDesp()); + publishText.setText("今天" + countyWeather.getUpdateTime() + "更新"); + currentDateText.setText(countyWeather.getCurrentDate()); + } + + /** + * 从SharedPreferences文件中读取存储的JuHe天气信息,并显示到界面上 + */ + private void showWeatherFromJuHe() { + SharedPreferences prefs = PreferenceManager. + getDefaultSharedPreferences(this); + Log.d("WeatherActivity", "xyz 512 city_name is " + prefs.getString("city_name_juhe", "")); + cityNameText.setText(prefs.getString("city_name_juhe", "")); + temp1Text.setText(prefs.getString("temp1_juhe", "")); + temp2Text.setText(prefs.getString("temp2_juhe", "")); + weatherDespText.setText(prefs.getString("weather_juhe", "")); + selectPictureByWeather(prefs.getString("weather_juhe", "")); + publishText.setText("今天" + prefs.getString("update_time_juhe", "") + "更新"); + currentDateText.setText(prefs.getString("current_date_juhe", "")); + } + + /** + * 根据天气选择不同的背景图 + * + * @param weatherDesp + */ + private void selectPictureByWeather(String weatherDesp) { + if (weatherDesp.contains("晴")) { + relativeLayout.setBackgroundResource(R.drawable.com1314080901103_sunny); + } else if (weatherDesp.contains("多云")) { + relativeLayout.setBackgroundResource(R.drawable.com1314080901103_cloud); + } else if (weatherDesp.contains("阴")) { + relativeLayout.setBackgroundResource(R.drawable.com1314080901103_night); + } else if (weatherDesp.contains("雷阵雨")) { + relativeLayout.setBackgroundResource(R.drawable.com1314080901103_thunder_shower); + } else if (weatherDesp.contains("阵雨")) { + relativeLayout.setBackgroundResource(R.drawable.com1314080901103_shower); + } else if (weatherDesp.contains("小雨")) { + relativeLayout.setBackgroundResource(R.drawable.com1314080901103_light_rain); + } else if (weatherDesp.contains("中雨")) { + relativeLayout.setBackgroundResource(R.drawable.com1314080901103_mid_rain); + } else if (weatherDesp.contains("雨")) { + relativeLayout.setBackgroundResource(R.drawable.com1314080901103_rain); + } else { + relativeLayout.setBackgroundResource(R.drawable.com1314080901103_default_weather); + } + } + + /** + * 销毁全部活动,退出APP + */ + @Override + protected void onDestroy() { + super.onDestroy(); + ActivityCollector.removeActivity(this); + Log.d("WeatherActivity", "xyz onDestroy() is finished"); + } + + /** + * 捕获Back按键,根据当前的级别来判断,此时应该返回市列表、省列表、还是直接退出 + */ + @Override + public void onBackPressed() { + ActivityCollector.finishAll(); + } +} \ No newline at end of file diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/adapter/ViewPageAdapter.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/adapter/ViewPageAdapter.java new file mode 100644 index 00000000..ee507349 --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/adapter/ViewPageAdapter.java @@ -0,0 +1,44 @@ +package edu.hzuapps.androidworks.homeworks.com1314080901103.adapter; + +import android.support.v4.view.PagerAdapter; +import android.view.View; +import android.view.ViewGroup; + +import java.util.List; + +public class ViewPageAdapter extends PagerAdapter { + + private List list_view; + + public ViewPageAdapter(List list_view) { + this.list_view = list_view; + } + + @Override + public int getCount() { + return list_view.size(); + } + + @Override + public boolean isViewFromObject(View view, Object object) { + return view == object; + } + + @Override + public Object instantiateItem(ViewGroup container, int position) { + container.addView(list_view.get(position % list_view.size()), 0); + return list_view.get(position % list_view.size()); + } + + @Override + public void destroyItem(ViewGroup container, int position, Object object) { + // 把 Object 强转为 View,然后将 view 从 ViewGroup 中清除 + container.removeView((View) object); + } + + @Override + public int getItemPosition(Object object) { + // 最简单解决 notifyDataSetChanged() 页面不刷新问题的方法 + return POSITION_NONE; + } +} \ No newline at end of file diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/db/WeatherDB.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/db/WeatherDB.java new file mode 100644 index 00000000..225fe385 --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/db/WeatherDB.java @@ -0,0 +1,347 @@ +package edu.hzuapps.androidworks.homeworks.com1314080901103.db; + +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; + +import java.util.ArrayList; +import java.util.List; + +import edu.hzuapps.androidworks.homeworks.com1314080901103.model.City; +import edu.hzuapps.androidworks.homeworks.com1314080901103.model.County; +import edu.hzuapps.androidworks.homeworks.com1314080901103.model.CountyWeather; +import edu.hzuapps.androidworks.homeworks.com1314080901103.model.Province; + +public class WeatherDB { + + /** + * 数据库名 + */ + public static final String DB_NAME = "my_weather"; + + /** + * 数据库版本 + */ + public static final int VERSION = 1; + private static WeatherDB weatherDB; + private SQLiteDatabase db; + /** + * AddCounty表建表语句 + */ + public static final String CREATE_ADD_COUNTY = "create table AddCounty (" + + "id integer primary key autoincrement, " + + "county_name text, " + + "county_code text) "; + /** + * AddCounty表删除语句 + */ + public static final String DROP_ADD_COUNTY = "DROP TABLE AddCounty"; + + /** + * 将构造方法私有化 + */ + private WeatherDB(Context context) { + WeatherOpenHelper dbHelper = new WeatherOpenHelper(context, + DB_NAME, null, VERSION); + db = dbHelper.getWritableDatabase(); + } + + /** + * 获取WeatherDB的实例 + */ + public synchronized static WeatherDB getInstance(Context context) { + if (weatherDB == null) { + weatherDB = new WeatherDB(context); + } + return weatherDB; + } + + /** + * 将Province实例存储到数据库 + */ + public void saveProvince(Province province) { + if (province != null) { + ContentValues values = new ContentValues(); + values.put("province_name", province.getProvinceName()); + values.put("province_code", province.getProvinceCode()); + db.insert("Province", null, values); + } + } + + /** + * 从数据库读取全国所有的省份信息 + */ + public List loadProvinces() { + List list = new ArrayList<>(); + Cursor cursor = db + .query("Province", null, null, null, null, null, null); + if (cursor.moveToFirst()) { + do { + Province province = new Province(); + province.setId(cursor.getInt(cursor.getColumnIndex("id"))); + province.setProvinceName(cursor.getString(cursor + .getColumnIndex("province_name"))); + province.setProvinceCode(cursor.getString(cursor + .getColumnIndex("province_code"))); + list.add(province); + } while (cursor.moveToNext()); + } + cursor.close(); + return list; + } + + /** + * 将City实例存储到数据库 + */ + public void saveCity(City city) { + if (city != null) { + ContentValues values = new ContentValues(); + values.put("city_name", city.getCityName()); + values.put("city_code", city.getCityCode()); + values.put("province_id", city.getProvinceId()); + db.insert("City", null, values); + } + } + + /** + * 从数据库读取某省下所有的城市信息 + */ + public List loadCities(int provinceId) { + List list = new ArrayList<>(); + Cursor cursor = db.query("City", null, "province_id = ?", + new String[]{String.valueOf(provinceId)}, null, null, null); + if (cursor != null && cursor.moveToFirst()) { + do { + City city = new City(); + city.setId(cursor.getInt(cursor.getColumnIndex("id"))); + city.setCityName(cursor.getString(cursor + .getColumnIndex("city_name"))); + city.setCityCode(cursor.getString(cursor + .getColumnIndex("city_code"))); + city.setProvinceId(provinceId); + list.add(city); + } while (cursor.moveToNext()); + } + cursor.close(); + return list; + } + + /** + * 将County实例存储到数据库 + */ + public void saveCounty(County county) { + if (county != null) { + ContentValues values = new ContentValues(); + values.put("county_name", county.getCountyName()); + values.put("county_code", county.getCountyCode()); + values.put("city_id", county.getCityId()); + db.insert("County", null, values); + } + } + + /** + * 从数据库读取某城市下所有的县信息 + */ + public List loadCounties(int cityId) { + List list = new ArrayList<>(); + Cursor cursor = db.query("County", null, "city_id = ?", + new String[]{String.valueOf(cityId)}, null, null, null); + if (cursor != null && cursor.moveToFirst()) { + do { + County county = new County(); + county.setId(cursor.getInt(cursor.getColumnIndex("id"))); + county.setCountyName(cursor.getString(cursor + .getColumnIndex("county_name"))); + county.setCountyCode(cursor.getString(cursor + .getColumnIndex("county_code"))); + county.setCityId(cityId); + list.add(county); + } while (cursor.moveToNext()); + } + cursor.close(); + return list; + } + + /** + * 将AddCounty实例存储到数据库 + */ + public void saveAddCounty(County county) { + if (county != null) { + ContentValues values = new ContentValues(); + values.put("county_name", county.getCountyName()); + values.put("county_code", county.getCountyCode()); + db.insert("AddCounty", null, values); + } + } + + /** + * 查询AddCounty表的城市数 + */ + public int selectAddCountySize() { + Cursor cursor = db.query("AddCounty", null, null, null, null, null, null); + int count = cursor.getCount(); + cursor.close(); + return count; + } + + /** + * 从数据库读取某县的信息 + */ + public County loadAddCounties(int cityId) { + Cursor cursor = db.query("AddCounty", null, "id = ?", + new String[]{String.valueOf(cityId)}, null, null, null); + County county = new County(); + if (cursor != null && cursor.moveToFirst()) { + do { + county.setId(cursor.getInt(cursor.getColumnIndex("id"))); + county.setCountyName(cursor.getString(cursor + .getColumnIndex("county_name"))); + county.setCountyCode(cursor.getString(cursor + .getColumnIndex("county_code"))); + } while (cursor.moveToNext()); + } + cursor.close(); + return county; + } + + /** + * 从数据库读取某县的Id信息 + */ + public int loadAddCountiesId(String countyCode) { + Cursor cursor = db.query("AddCounty", null, "county_code = ?", + new String[]{countyCode}, null, null, null); + int id = 0; + if (cursor != null && cursor.moveToFirst()) { + do { + id = cursor.getInt(cursor.getColumnIndex("id")); + } while (cursor.moveToNext()); + } + cursor.close(); + return id; + } + + /** + * 从数据库读取所有的添加城市信息 + * + * @return + */ + public List loadAddCounties() { + List list = new ArrayList<>(); + Cursor cursor = db.query("AddCounty", null, null, null, null, null, null); + if (cursor.moveToFirst()) { + do { + County county = new County(); + county.setId(cursor.getInt(cursor.getColumnIndex("id"))); + county.setCountyName(cursor.getString(cursor + .getColumnIndex("county_name"))); + county.setCountyCode(cursor.getString(cursor + .getColumnIndex("county_code"))); + list.add(county); + } while (cursor.moveToNext()); + } + cursor.close(); + return list; + } + + /** + * 删除添加城市表中的县 + * + * @param countyName + */ + public void deleteFromAddCountiesByCountyName(String countyName) { + db.delete("AddCounty", "county_name = ?", new String[]{countyName}); + } + + /** + * 删除AddCounty表 + */ + public void deleteAddCounties() { + db.execSQL(DROP_ADD_COUNTY); + } + + /** + * 重新创建AddCounty表 + */ + public void createAddCounties() { + db.execSQL(CREATE_ADD_COUNTY); + } + + /** + * 将AddCounty实例存储到数据库 + */ + public void saveAddCountyWeather(CountyWeather countyWeather) { + if (countyWeather != null) { + ContentValues values = new ContentValues(); + values.put("county_name", countyWeather.getCountyName()); + values.put("weather_code", countyWeather.getWeatherCode()); + values.put("temp1", countyWeather.getTemp1()); + values.put("temp2", countyWeather.getTemp2()); + values.put("weather_desp", countyWeather.getWeatherDesp()); + values.put("update_time", countyWeather.getUpdateTime()); + values.put("current_date", countyWeather.getCurrentDate()); + db.insert("AddCountyWeather", null, values); + } + } + + /** + * 根据城市名查找对应天气的城市信息 + * + * @return + */ + public CountyWeather loadAddCountiesWeatherByCountyName(String countyName) { + Cursor cursor = db.query("AddCountyWeather", null, "county_name = ?", + new String[]{countyName}, null, null, null); + CountyWeather countyWeather = new CountyWeather(); + if (cursor.moveToFirst()) { + do { + countyWeather.setId(cursor.getInt(cursor.getColumnIndex("id"))); + countyWeather.setCountyName(cursor.getString(cursor + .getColumnIndex("county_name"))); + countyWeather.setWeatherCode(cursor.getString(cursor + .getColumnIndex("weather_code"))); + countyWeather.setTemp1(cursor.getString(cursor + .getColumnIndex("temp1"))); + countyWeather.setTemp2(cursor.getString(cursor + .getColumnIndex("temp2"))); + countyWeather.setWeatherDesp(cursor.getString(cursor + .getColumnIndex("weather_desp"))); + countyWeather.setUpdateTime(cursor.getString(cursor + .getColumnIndex("update_time"))); + countyWeather.setCurrentDate(cursor.getString(cursor + .getColumnIndex("current_date"))); + } while (cursor.moveToNext()); + } + cursor.close(); + return countyWeather; + } + + /** + * 删除添加城市天气表中的县 + * + * @param countyName + */ + public void deleteFromAddCountiesWeatherByCountyName(String countyName) { + db.delete("AddCountyWeather", "county_name = ?", new String[]{countyName}); + } + + public void updateAddCountiesWeather(String countyName, + String weatherCode, String temp1, String temp2, String weatherDesp, String updateTime, String currentDate) { + String sql = "UPDATE AddCountyWeather SET weather_code = \' " + weatherCode + + "\' , temp1 = \'" + temp1 + "\' , temp2 = \'" + temp2 + "\' , weather_desp = \'" + weatherDesp + + "\' , update_time = \'" + updateTime + "\' , current_date = \'" + currentDate + "\' WHERE county_name = \'" + + countyName + "\'"; + db.execSQL(sql); + } + + public boolean selectAddCountiesWeatherByCountyName(String countyName) { + Cursor cursor = db.rawQuery("SELECT * FROM AddCountyWeather WHERE county_name = ?", new String[]{countyName}); + if (cursor.getCount() > 0) { + cursor.close(); + return true; + } else { + cursor.close(); + return false; + } + } +} \ No newline at end of file diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/db/WeatherOpenHelper.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/db/WeatherOpenHelper.java new file mode 100644 index 00000000..44c9a268 --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/db/WeatherOpenHelper.java @@ -0,0 +1,68 @@ +package edu.hzuapps.androidworks.homeworks.com1314080901103.db; + +import android.content.Context; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; + +public class WeatherOpenHelper extends SQLiteOpenHelper { + + /** + * Province表建表语句 + */ + public static final String CREATE_PROVINCE = "create table Province (" + + "id integer primary key autoincrement, " + + "province_name text, " + + "province_code text)"; + /** + * City表建表语句 + */ + public static final String CREATE_CITY = "create table City (" + + "id integer primary key autoincrement, " + + "city_name text, " + + "city_code text, " + + "province_id integer)"; + /** + * County表建表语句 + */ + public static final String CREATE_COUNTY = "create table County (" + + "id integer primary key autoincrement, " + + "county_name text, " + + "county_code text, " + + "city_id integer)"; + /** + * AddCounty表建表语句 + */ + public static final String CREATE_ADD_COUNTY = "create table AddCounty (" + + "id integer primary key autoincrement, " + + "county_name text, " + + "county_code text) "; + /** + * AddCounty表建表语句 + */ + public static final String CREATE_ADD_COUNTY_WEATHER = "create table AddCountyWeather (" + + "id integer primary key autoincrement, " + + "county_name text, " + + "weather_code text, " + + "temp1 text, " + + "temp2 text, " + + "weather_desp text, " + + "update_time text, " + + "current_date text) "; + + public WeatherOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { + super(context, name, factory, version); + } + + @Override + public void onCreate(SQLiteDatabase db) { + db.execSQL(CREATE_PROVINCE); // 创建Province表 + db.execSQL(CREATE_CITY); // 创建City表 + db.execSQL(CREATE_COUNTY); // 创建County表 + db.execSQL(CREATE_ADD_COUNTY); // 创建AddCounty表 + db.execSQL(CREATE_ADD_COUNTY_WEATHER); // 创建AddCountyWeather表 + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + } +} \ No newline at end of file diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/model/City.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/model/City.java new file mode 100644 index 00000000..d96b59d1 --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/model/City.java @@ -0,0 +1,41 @@ +package edu.hzuapps.androidworks.homeworks.com1314080901103.model; + +public class City { + + private int id; + private String cityName; + private String cityCode; + private int provinceId; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getCityName() { + return cityName; + } + + public void setCityName(String cityName) { + this.cityName = cityName; + } + + public String getCityCode() { + return cityCode; + } + + public void setCityCode(String cityCode) { + this.cityCode = cityCode; + } + + public int getProvinceId() { + return provinceId; + } + + public void setProvinceId(int provinceId) { + this.provinceId = provinceId; + } +} \ No newline at end of file diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/model/County.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/model/County.java new file mode 100644 index 00000000..f9383b3d --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/model/County.java @@ -0,0 +1,41 @@ +package edu.hzuapps.androidworks.homeworks.com1314080901103.model; + +public class County { + + private int id; + private String countyName; + private String countyCode; + private int cityId; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getCountyCode() { + return countyCode; + } + + public void setCountyCode(String countyCode) { + this.countyCode = countyCode; + } + + public String getCountyName() { + return countyName; + } + + public void setCountyName(String countyName) { + this.countyName = countyName; + } + + public int getCityId() { + return cityId; + } + + public void setCityId(int cityId) { + this.cityId = cityId; + } +} diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/model/CountyWeather.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/model/CountyWeather.java new file mode 100644 index 00000000..8e3c6748 --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/model/CountyWeather.java @@ -0,0 +1,77 @@ +package edu.hzuapps.androidworks.homeworks.com1314080901103.model; + +public class CountyWeather { + + private int id; + private String countyName; + private String weatherCode; + private String temp1; + private String temp2; + private String weatherDesp; + private String updateTime; + private String currentDate; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getCountyName() { + return countyName; + } + + public void setCountyName(String countyName) { + this.countyName = countyName; + } + + public String getWeatherCode() { + return weatherCode; + } + + public void setWeatherCode(String weatherCode) { + this.weatherCode = weatherCode; + } + + public String getTemp1() { + return temp1; + } + + public void setTemp1(String temp1) { + this.temp1 = temp1; + } + + public String getTemp2() { + return temp2; + } + + public void setTemp2(String temp2) { + this.temp2 = temp2; + } + + public String getWeatherDesp() { + return weatherDesp; + } + + public void setWeatherDesp(String weatherDesp) { + this.weatherDesp = weatherDesp; + } + + public String getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(String updateTime) { + this.updateTime = updateTime; + } + + public String getCurrentDate() { + return currentDate; + } + + public void setCurrentDate(String currentDate) { + this.currentDate = currentDate; + } +} diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/model/Province.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/model/Province.java new file mode 100644 index 00000000..a758500c --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/model/Province.java @@ -0,0 +1,32 @@ +package edu.hzuapps.androidworks.homeworks.com1314080901103.model; + +public class Province { + + private int id; + private String provinceName; + private String provinceCode; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getProvinceName() { + return provinceName; + } + + public void setProvinceName(String provinceName) { + this.provinceName = provinceName; + } + + public String getProvinceCode() { + return provinceCode; + } + + public void setProvinceCode(String provinceCode) { + this.provinceCode = provinceCode; + } +} diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/util/HttpCallbackListener.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/util/HttpCallbackListener.java new file mode 100644 index 00000000..adacacd9 --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/util/HttpCallbackListener.java @@ -0,0 +1,8 @@ +package edu.hzuapps.androidworks.homeworks.com1314080901103.util; + +public interface HttpCallbackListener { + + void onFinish(String response); + + void onError(Exception e); +} diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/util/HttpUtil.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/util/HttpUtil.java new file mode 100644 index 00000000..a0c91b56 --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/util/HttpUtil.java @@ -0,0 +1,48 @@ +package edu.hzuapps.androidworks.homeworks.com1314080901103.util; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; + +public class HttpUtil { + + public static void sendHttpRequest(final String address, + final HttpCallbackListener listener) { + new Thread(new Runnable() { + @Override + public void run() { + HttpURLConnection connection = null; + try { + URL url = new URL(address); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.setConnectTimeout(8000); + connection.setReadTimeout(8000); + InputStream in = connection.getInputStream(); + BufferedReader reader = new BufferedReader(new + InputStreamReader(in)); + StringBuilder response = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + response.append(line); + } + if (listener != null) { + // 回调onFinish()方法 + listener.onFinish(response.toString()); + } + } catch (Exception e) { + if (listener != null) { + // 回调onError()方法 + listener.onError(e); + } + } finally { + if (connection != null) { + connection.disconnect(); + } + } + } + }).start(); + } +} \ No newline at end of file diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/util/Utility.java b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/util/Utility.java new file mode 100644 index 00000000..2724e56e --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901103/util/Utility.java @@ -0,0 +1,192 @@ +package edu.hzuapps.androidworks.homeworks.com1314080901103.util; + +import android.content.Context; +import android.content.SharedPreferences; +import android.preference.PreferenceManager; +import android.text.TextUtils; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; + +import edu.hzuapps.androidworks.homeworks.com1314080901103.db.WeatherDB; +import edu.hzuapps.androidworks.homeworks.com1314080901103.model.City; +import edu.hzuapps.androidworks.homeworks.com1314080901103.model.County; +import edu.hzuapps.androidworks.homeworks.com1314080901103.model.CountyWeather; +import edu.hzuapps.androidworks.homeworks.com1314080901103.model.Province; + +public class Utility { + + /** + * 解析和处理服务器返回的省级数据 + */ + public synchronized static boolean handleProvincesResponse(WeatherDB + cWeatherDB, String response) { + if (!TextUtils.isEmpty(response)) { + String[] allProvinces = response.split(","); + if (allProvinces != null && allProvinces.length > 0) { + for (String p : allProvinces) { + String[] array = p.split("\\|"); + Province province = new Province(); + province.setProvinceCode(array[0]); + province.setProvinceName(array[1]); + // 将解析出来的数据存储到Province表 + cWeatherDB.saveProvince(province); + } + return true; + } + } + return false; + } + + /** + * 解析和处理服务器返回的市级数据 + */ + public static boolean handleCitiesResponse(WeatherDB cWeatherDB, + String response, int provinceId) { + if (!TextUtils.isEmpty(response)) { + String[] allCities = response.split(","); + if (allCities != null && allCities.length > 0) { + for (String c : allCities) { + String[] array = c.split("\\|"); + City city = new City(); + city.setCityCode(array[0]); + city.setCityName(array[1]); + city.setProvinceId(provinceId); + // 将解析出来的数据存储到City表 + cWeatherDB.saveCity(city); + } + return true; + } + } + return false; + } + + /** + * 解析和处理服务器返回的县级数据 + */ + public static boolean handleCountiesResponse(WeatherDB cWeatherDB, + String response, int cityId) { + if (!TextUtils.isEmpty(response)) { + String[] allCounties = response.split(","); + if (allCounties != null && allCounties.length > 0) { + for (String c : allCounties) { + String[] array = c.split("\\|"); + County county = new County(); + county.setCountyCode(array[0]); + county.setCountyName(array[1]); + county.setCityId(cityId); + // 将解析出来的数据存储到County表 + cWeatherDB.saveCounty(county); + } + return true; + } + } + return false; + } + + /** + * 解析服务器返回的 JSON 数据,并将解析出的数据存储到本地 + */ + public static String handleWeatherResponse(Context context, String response) { + try { + JSONObject jsonObject = new JSONObject(response); + JSONObject weatherInfo = jsonObject.getJSONObject("weatherinfo"); + String cityName = weatherInfo.getString("city"); + String weatherCode = weatherInfo.getString("cityid"); + String temp1 = weatherInfo.getString("temp1"); + String temp2 = weatherInfo.getString("temp2"); + String weatherDesp = weatherInfo.getString("weather"); + saveWeatherInfo(context, cityName, weatherCode, temp1, temp2, + weatherDesp); + return cityName; + } catch (JSONException e) { + e.printStackTrace(); + } + return ""; + } + + /** + * 将服务器返回的所有天气信息存储到AddCountyWeather表中 + */ + public static void saveWeatherInfo(Context context, String countyName, + String weatherCode, String temp1, String temp2, String weatherDesp) { + WeatherDB weatherDB = WeatherDB.getInstance(context); + CountyWeather countyWeather = new CountyWeather(); + Calendar c = Calendar.getInstance(); + String updateTime = c.get(Calendar.HOUR_OF_DAY) + ":"; + if (c.get(Calendar.MINUTE) <= 9) { + updateTime = updateTime + "0" + c.get(Calendar.MINUTE); + } else { + updateTime = updateTime + c.get(Calendar.MINUTE); + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyy 年 M 月 d 日", + Locale.CHINA); + String currentDate = sdf.format(new Date()); + if (!weatherDB.selectAddCountiesWeatherByCountyName(countyName)) { + countyWeather.setCountyName(countyName); + countyWeather.setWeatherCode(weatherCode); + countyWeather.setTemp1(temp1); + countyWeather.setTemp2(temp2); + countyWeather.setWeatherDesp(weatherDesp); + countyWeather.setUpdateTime(updateTime); + countyWeather.setCurrentDate(currentDate); + weatherDB.saveAddCountyWeather(countyWeather); + } else { + weatherDB.updateAddCountiesWeather(countyName, weatherCode, temp1, temp2, weatherDesp, updateTime, currentDate); + } + + } + + /** + * 解析从聚合数据返回的 JSON 数据,并将解析出的数据存储到本地 + */ + public static void handleWeatherResponseFromJuHe(Context context, String response) { + try { + JSONObject jsonObject = new JSONObject(response); + // 获取result节点下的位置信息 + JSONObject resultObject = jsonObject.getJSONObject + ("result"); + JSONObject JSONObjectToday = resultObject.getJSONObject + ("today"); + String cityName = JSONObjectToday.getString("city"); + String[] temp = JSONObjectToday.getString("temperature").split("~"); + String temp1 = temp[0]; + String temp2 = temp[1]; + String weather = JSONObjectToday.getString("weather"); + saveWeatherInfoFromJuHe(context, cityName, temp1, temp2, weather); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + /** + * 将聚合数据返回的所有天气信息存储到 SharedPreferences 文件中 + */ + public static void saveWeatherInfoFromJuHe(Context context, String cityName, + String temp1, String temp2, String weather) { + SharedPreferences.Editor editor = PreferenceManager + .getDefaultSharedPreferences(context).edit(); + Calendar c = Calendar.getInstance(); + String updateTime = c.get(Calendar.HOUR_OF_DAY) + ":"; + if (c.get(Calendar.MINUTE) < 9) { + updateTime = updateTime + "0" + c.get(Calendar.MINUTE); + } else { + updateTime = updateTime + c.get(Calendar.MINUTE); + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyy 年 M 月 d 日", + Locale.CHINA); + String currentDate = sdf.format(new Date()); + editor.putString("city_name_juhe", cityName); + editor.putString("temp1_juhe", temp1); + editor.putString("temp2_juhe", temp2); + editor.putString("weather_juhe", weather); + editor.putString("update_time_juhe", updateTime); + editor.putString("current_date_juhe", currentDate); + editor.commit(); + } +} \ No newline at end of file diff --git a/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901107/activity_com1314080901107.xml b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901107/activity_com1314080901107.xml new file mode 100644 index 00000000..a3944f06 --- /dev/null +++ b/app/src/main/java/edu/hzuapps/androidworks/homeworks/com1314080901107/activity_com1314080901107.xml @@ -0,0 +1,73 @@ + + + + + \ + + + + \ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/Net1314080903237_viewuser.xml b/app/src/main/res/layout/Net1314080903237_viewuser.xml new file mode 100644 index 00000000..5fde3c30 --- /dev/null +++ b/app/src/main/res/layout/Net1314080903237_viewuser.xml @@ -0,0 +1,146 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/act_net1314080903204.xml b/app/src/main/res/layout/act_net1314080903204.xml new file mode 100644 index 00000000..bf7b7239 --- /dev/null +++ b/app/src/main/res/layout/act_net1314080903204.xml @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/activity_net1314080903113.xml b/app/src/main/res/layout/activity_net1314080903113.xml new file mode 100644 index 00000000..7bcf7418 --- /dev/null +++ b/app/src/main/res/layout/activity_net1314080903113.xml @@ -0,0 +1,23 @@ + + + + + + diff --git a/app/src/main/res/layout/activity_net1314080903114__home.xml b/app/src/main/res/layout/activity_net1314080903114__home.xml new file mode 100644 index 00000000..783a89e4 --- /dev/null +++ b/app/src/main/res/layout/activity_net1314080903114__home.xml @@ -0,0 +1,34 @@ + + + + + + + diff --git a/app/src/main/res/layout/net1314080903127_course_set.xml b/app/src/main/res/layout/net1314080903127_course_set.xml new file mode 100644 index 00000000..073781ec --- /dev/null +++ b/app/src/main/res/layout/net1314080903127_course_set.xml @@ -0,0 +1,30 @@ + + + + + + + + + + diff --git a/app/src/main/res/layout/net1314080903127_diary_edit.xml b/app/src/main/res/layout/net1314080903127_diary_edit.xml new file mode 100644 index 00000000..dc7a8e0b --- /dev/null +++ b/app/src/main/res/layout/net1314080903127_diary_edit.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/net1314080903129activity_chat.xml b/app/src/main/res/layout/net1314080903129activity_chat.xml new file mode 100644 index 00000000..95cde2fa --- /dev/null +++ b/app/src/main/res/layout/net1314080903129activity_chat.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/net1314080903237viewuser.xml b/app/src/main/res/layout/net1314080903237viewuser.xml new file mode 100644 index 00000000..b7f15cd5 --- /dev/null +++ b/app/src/main/res/layout/net1314080903237viewuser.xml @@ -0,0 +1,143 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/net1314080903238_activity_main.xml b/app/src/main/res/layout/net1314080903238_activity_main.xml new file mode 100644 index 00000000..9183bd2f --- /dev/null +++ b/app/src/main/res/layout/net1314080903238_activity_main.xml @@ -0,0 +1,259 @@ + + + + + + + + + + + + + + + + + + + + + +