一、实验目的
二、实验环境
Windows,android studio
三、项目分析
该项目是一个天气预报的小程序,主要功能包括:
1、启动程序,显示默认值; 当点击“刷新”按钮时,从Tomcat服务器端读取天气信息(存在服务器端“weather.json”文件中),并更新UI。
2、当点击“刷新”按钮时,从Tomcat服务器端读取天气信息(存在服务器端“weather.json”文件中),并更新UI。
下面,我们来看下效果图,我们将会开了发出一款以下界面的app。

四、实验步骤
1、新建工程。
2、导入需要的图片资源等
3、修改设计主界面
4、实现界面逻辑
1)初始化控件
2)创建WeatherInfo类,存储天气信息
3)实现getWeatherInfo方法,在子线程中,实现网络请求,获取数据流
4)实现getInfosFromJson方法,完成输入流到对象的转换方法
5)创建Handler对象,重写它的HandlerMessage()方法,实现UI更新
6)在getWeatherInfo()方法中,补充代码,完成处理网络请求得到的响应结果,并发送消息7)在OnClickListener监听器的OnClick()方法中,补充代码,调用getWeatherInfo()方法,通过网络获取天气信息,再将其转换为天气信息对象列表
接下来我们按步骤完成这个项目的实现。
1、创建工程
File->New->New Project



2、导入需要的图片资源
在project工具窗口中,将视图切换到“Project”,然后在res目录下,创建一个drawable-hdpi文件夹;打开“New Resource Directory”窗口,在Resource Type对应的下拉列表中,选择drawable;在左侧“Available qualifies”下方的下拉列表中,选择density,然后点击;然后在density对应的下拉列表中,选择High density,此时就可以看到“Directory Name”自动变为“drawable-hdpi”,然后点击OK;





将资源文件夹下的四张图片以及xml文件,拷贝到文件夹res/drawable-hdpi下。将weather.json文件放入你存放TomCat路径的Webapps文件夹里(这里我还创建了一个文件夹weather来存放)。
资源下载:https://download.csdn.net/download/weixin_45467625/86151681




在res/values/strings.xml:

3.、设计修改主页面:

activity_main.xml如下:
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_city"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="40dp"
android:layout_marginStart="45dp"
android:text="@string/city"
android:textSize="50sp"/>
<ImageView
android:id="@+id/iv_icon"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignEnd="@id/tv_city"
android:layout_below="@+id/tv_city"
android:layout_marginTop="40dp"
android:paddingBottom="5dp"
android:src="@drawable/clouds"/>
<TextView
android:id="@+id/tv_weather"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/iv_icon"
android:layout_below="@+id/iv_icon"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
android:gravity="center"
android:text="@string/weather"
android:textSize="18sp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/iv_icon"
android:layout_toEndOf="@+id/iv_icon"
android:layout_marginStart="30dp"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/tv_temp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center_vertical"
android:text="@string/temp"
android:textSize="22sp"/>
<TextView
android:id="@+id/tv_wind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/wind"
android:textSize="18sp"/>
<TextView
android:id="@+id/tv_pm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pm"
android:textSize="18sp"/>
</LinearLayout>
<Button
android:id="@+id/btn_refresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginEnd="10dp"
android:layout_marginBottom="10dp"
android:text="@string/refresh"/>
</RelativeLayout>
4、实现界面逻辑
创建WeatherInfo类,存储天气信息


定义成员变量:

在类中,空白行,按alt+insert健(或右键单击,选择Generate),打开Generate窗口,选择Getter and Setter,打开select fields to Generate Getters and Setters窗口,选中所有需要生成get,set方法的域名,点击确定,相应的方法就自动生成了。



在子线程中,实现网络请求:在AndroidManifests.xml中开启网络访问权限

在AndroidManifests.xml中,设置Application的属性“usesCleartextTraffic”为true(目标SDKversion为27或更低的应用程序的默认值为“true”。SDKversion是28或更高级别的应用默认为“false”)

实现从输入流到对象的转换方法:右键单击app,选择open module setting,选择模块app,在右边tab栏中点击Dependency,在右边选择“+”号,选择library dependency,在其中输入Gson,搜索找到“com.google.code.gson:gson:2.8.5”,点击OK,添加Gson依赖。


MainActivity.java的编写:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
public class MainActivity extends AppCompatActivity {
//初始化控件和变量
protected static final int CHANG_UI = 0;
protected static final int ERROR = 1;
protected static final int LINK = 2;
private TextView tvCity;
private TextView tvWeather;
private TextView tvTemp;
private TextView tvWind;
private TextView tvPm;
private ImageView ivIcon;
private int clickCount = 0;
//创建Handler对象,重写它的HandlerMessage()方法,实现UI更新
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg.what == CHANG_UI) {
List<WeatherInfo> lstWeather = (List<WeatherInfo>)msg.obj;
if (clickCount<lstWeather.size()) {
WeatherInfo objWI = lstWeather.get(clickCount);
refreshUI(objWI);
clickCount++;
}
if (clickCount == lstWeather.size())
clickCount = 0;
Toast.makeText(MainActivity.this,msg.obj.toString(),Toast.LENGTH_SHORT).show();
} else if (msg.what == ERROR) {
Toast.makeText(MainActivity.this, "获取网络数据失败",
Toast.LENGTH_SHORT).show();
}
}
};
private void refreshUI(WeatherInfo objInfo){
if(objInfo!=null){
tvCity.setText(objInfo.getCity());
tvWeather.setText(objInfo.getWeather());
tvTemp.setText(objInfo.getTemp());
tvWind.setText(objInfo.getWind());
tvPm.setText(objInfo.getPm());
String strWeather=objInfo.getWeather();
if(strWeather.contains("晴转多云"))
ivIcon.setImageResource(R.drawable.cloud_sun);
else if(strWeather.contains("多云"))
ivIcon.setImageResource(R.drawable.clouds);
else
ivIcon.setImageResource(R.drawable.sun);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InitView();
}
private void InitView() {
tvCity = (TextView) findViewById(R.id.tv_city);
tvWeather = (TextView) findViewById(R.id.tv_weather);
tvTemp = (TextView) findViewById(R.id.tv_temp);
tvWind = (TextView) findViewById(R.id.tv_wind);
tvPm = (TextView) findViewById(R.id.tv_pm);
ivIcon = (ImageView) findViewById(R.id.iv_icon);
final String strURL ="http://192.168.10.188:8080/weather/weather.json";
//在OnClickListener监听器的OnClick()方法中,补充代码,调用getWeatherInfo()方法,通过网络获取天气信息,再将其转换为天气信息对象列表
findViewById(R.id.btn_refresh).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (strURL.isEmpty()){
Toast.makeText(MainActivity.this,"路径不能为空",Toast.LENGTH_SHORT).show();
}else{
getWeatherInfo(strURL);
}
}
});
}
//定义getInfosFromJson方法,实现从InputStream到List<WeatherInfo>的转换
public List<WeatherInfo> getInfosFromJson(InputStream is) throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[4096];
int count = -1;
while ((count = is.read(data, 0, 4096)) != -1)
outStream.write(data, 0, count);
data = null;
String json = new String(outStream.toByteArray(), "utf-8");
//使用gson库解析JSON数据
Gson gson = new Gson();
Type listType = new TypeToken<List<WeatherInfo>>() {
}.getType();
List<WeatherInfo> weatherInfos = gson.fromJson(json, listType);
return weatherInfos;
}
//在getWeatherInfo()方法中,补充代码,完成处理网络请求得到的响应
public void getWeatherInfo(final String urlPath) {
//子线程请求网络,Android4.0以后访问网络不能放在主线程中
new Thread() {
private HttpURLConnection conn;
public void run() {
// 连接服务器 get 请求 获取图片
try {
//创建URL对象
URL url = new URL(urlPath);
// 根据url 发送 http的请求
conn = (HttpURLConnection) url.openConnection();
// 设置请求的方式
conn.setRequestMethod("GET");
//设置超时时间
conn.setConnectTimeout(5000);
// 得到服务器返回的响应码
int code = conn.getResponseCode();
//请求网络成功后返回码是200
if (code == 200) {
//获取输入流
InputStream is = conn.getInputStream();
//解析输入流
List<WeatherInfo> lstWeatherInfo = getInfosFromJson(is);
if (lstWeatherInfo != null) {
//将更改主界面的消息发送给主线程
Message msg = new Message();
msg.what = CHANG_UI;
msg.obj = lstWeatherInfo;
handler.sendMessage(msg);
}
} else {
//返回码不等于200 请求服务器失败
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
}
//关闭连接
conn.disconnect();
}
}.start();
}
}
5、调试、运行



最后附上源码:https://download.csdn.net/download/weixin_45467625/87301318
我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack
我想用ruby编写一个小的命令行实用程序并将其作为gem分发。我知道安装后,Guard、Sass和Thor等某些gem可以从命令行自行运行。为了让gem像二进制文件一样可用,我需要在我的gemspec中指定什么。 最佳答案 Gem::Specification.newdo|s|...s.executable='name_of_executable'...endhttp://docs.rubygems.org/read/chapter/20 关于ruby-在Ruby中编写命令行实用程序
我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此
我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r
刚入门rails,开始慢慢理解。有人可以解释或给我一些关于在application_controller中编码的好处或时间和原因的想法吗?有哪些用例。您如何为Rails应用程序使用应用程序Controller?我不想在那里放太多代码,因为据我了解,每个请求都会调用此Controller。这是真的? 最佳答案 ApplicationController实际上是您应用程序中的每个其他Controller都将从中继承的类(尽管这不是强制性的)。我同意不要用太多代码弄乱它并保持干净整洁的态度,尽管在某些情况下ApplicationContr
我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R
我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden
如何检查Ruby文件是否是通过“require”或“load”导入的,而不是简单地从命令行执行的?例如:foo.rb的内容:puts"Hello"bar.rb的内容require'foo'输出:$./foo.rbHello$./bar.rbHello基本上,我想调用bar.rb以不执行puts调用。 最佳答案 将foo.rb改为:if__FILE__==$0puts"Hello"end检查__FILE__-当前ruby文件的名称-与$0-正在运行的脚本的名称。 关于ruby-检查是否
是否可以在应用程序中包含的gem代码中知道应用程序的Rails文件系统根目录?这是gem来源的示例:moduleMyGemdefself.included(base)putsRails.root#returnnilendendActionController::Base.send:include,MyGem谢谢,抱歉我的英语不好 最佳答案 我发现解决类似问题的解决方案是使用railtie初始化程序包含我的模块。所以,在你的/lib/mygem/railtie.rbmoduleMyGemclassRailtie使用此代码,您的模块将在