android - 获取移动服务客户端作为全局变量,并将来自 Android 中另一个类的数据存储在 Azure 中
问题描述
我已经使用 azure 进行了身份验证,为此我在一个活动中使用了移动服务客户端,下一个活动必须添加一些数据,因此我需要移动服务客户端将数据存储在 Azure DB 中。我怎样才能做到这一点?请给我一些解决方案。
以下是在登录活动中使用移动服务客户端进行身份验证的代码:
public static MobileServiceClient mClient;
public MobileServiceTable<User> mUser;
public static MobileServiceTable<Location> mLocation;
try {
// Create the client instance, using the provided mobile app URL.
mClient = new MobileServiceClient(url, this);
mClient.setAndroidHttpClientFactory(new OkHttpClientFactory() {
@Override
public OkHttpClient createOkHttpClient() {
OkHttpClient client = new OkHttpClient();
client.setReadTimeout(20, TimeUnit.SECONDS);
client.setWriteTimeout(40, TimeUnit.SECONDS);
return client;
}
});
//connecting the azure user table dbo.users
mUser = mClient.getTable("User", User.class);
mLocation = mClient.getTable("Location", Location.class);
在 azure db 中添加用户就像
公共用户 addItemInTable(用户数据)抛出 ExecutionException,
中断异常{
User entity;
entity = mUser.insert(data).get();
gotomaps();
return entity;
}
现在我需要使用上面的 mclient 将位置存储在 Azure 中供用户使用。
解决方案
根据你的描述。
要将数据存储在 Azure 中,我们可以执行以下操作:
public Location addLocation(MobileServiceTable<Location> table, Location location){
return table.insert(location).get();
}
用法:
MobileServiceTable<Location> table = mClient.getTable("Location", Location.class);
Location location=new Location();
//....
addLocation(table, location);
要将服务客户端设置为全局变量,我们可以使用 [android.app.Application] 来实现。
[android.app.Application] 在整个应用生命周期中只有一个实例。这是一个简单的演示:
创建一个类扩展 [android.app.Application]
package cn.azurepro.test.global;
import android.app.Application;
import com.microsoft.windowsazure.mobileservices.MobileServiceClient;
public class MyApplication extends Application {
private MobileServiceClient mobileServiceClient=null;
public void setMobileServiceClient(MobileServiceClient mobileServiceClient){
this.mobileServiceClient=mobileServiceClient;
}
public MobileServiceClient getMobileServiceClient(){
return mobileServiceClient;
}
@Override
public void onCreate() {
super.onCreate();
}
}
将这个类的全名设置为Application的name属性如下:
然后我们可以在不同的活动中使用它,如下所示:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyApplication myApplication= (MyApplication) this.getApplication();
mClient = myApplication.getMobileServiceClient();