![](/img/trans.png)
[英]Retrieve data from a azure mobile service into a android apllication in java
[英]How to retrieve data from Azure Mobile Service and bind to Android ListView
我目前正在嘗試將已插入Azure移動服務的數據檢索到Android應用程序中的ListView中。 我試圖按照Microsoft提供的教程進行操作,但是我的項目沒有顯示在ListView中。 他們提供的示例中有一個復選框,我不需要。 我只想顯示我的條目名稱以及我已插入數據庫表到ListView中的日期和時間。 這是我的列表視圖布局:
entry_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="@+id/tvEntryName"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Entry name"/>
<TextView
android:id="@+id/tvEntryDateTime"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="date/time"/>
</LinearLayout>
然后這是我的適配器Entry Item Adapter
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import java.security.KeyStore;
public class EntryItemAdapter extends ArrayAdapter<EntryItem> {
Context mContext;
int mLayoutResourceId;
public EntryItemAdapter(Context context, int layoutResourceId) {
super(context, layoutResourceId);
mContext = context;
mLayoutResourceId = layoutResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
final EntryItem currentItem = getItem(position);
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(mLayoutResourceId, parent, false);
}
row.setTag(currentItem);
return row;
}
}
最后但並非最不重要的一點是,我要顯示ListView AllEntriesActivity.java的活動
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.net.MalformedURLException;
import com.microsoft.windowsazure.mobileservices.MobileServiceClient;
import com.microsoft.windowsazure.mobileservices.table.MobileServiceTable;
import com.microsoft.windowsazure.mobileservices.table.sync.MobileServiceSyncContext;
import com.microsoft.windowsazure.mobileservices.table.sync.localstore.ColumnDataType;
import com.microsoft.windowsazure.mobileservices.table.sync.localstore.MobileServiceLocalStoreException;
import com.microsoft.windowsazure.mobileservices.table.sync.localstore.SQLiteLocalStore;
import com.microsoft.windowsazure.mobileservices.table.sync.synchandler.SimpleSyncHandler;
import static com.microsoft.windowsazure.mobileservices.table.query.QueryOperations.val;
import android.os.AsyncTask;
public class AllEntriesActivity extends BaseActivity {
private MobileServiceClient mClient;
private MobileServiceTable<EntryItem> mEntryTable;
private EntryItemAdapter mAdapter;
private String[] navMenuTitles;
private TypedArray navMenuIcons;
Button btnAddEntry;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_entries);
try {
// Create the Mobile Service Client instance, using the provided
// Mobile Service URL and key
mClient = new MobileServiceClient(
"https://skerydiary.azure-mobile.net/",
"farvbebCTbuqVueYGNugUivXktrljJ72",
this);
mEntryTable = mClient.getTable(EntryItem.class);
//initLocalStore().get();
// Create an adapter to bind the items with the view
mAdapter = new EntryItemAdapter(this, R.layout.entry_listview);
ListView listViewEntryItems = (ListView) findViewById(R.id.listViewEntries);
listViewEntryItems.setAdapter(mAdapter);
// Load the items from the Mobile Service
refreshItemsFromTable();
} catch (MalformedURLException e) {
e.printStackTrace();
}
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items); // load
// titles
// from
// strings.xml
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);// load icons from
// strings.xml
set(navMenuTitles, navMenuIcons);
btnAddEntry = (Button) findViewById(R.id.btnAddNewEntry);
btnAddEntry.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent addEntryIntent = new Intent(AllEntriesActivity.this, AddNewEntry.class);
addEntryIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
overridePendingTransition(0, 0);
startActivity(addEntryIntent);
}
});
}
// public void loadItem(final EntryItem item) {
// if (mClient == null) {
// return;
// }
//
// // Set the item as completed and update it in the table
// //item.setComplete(true);
//
// AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
// @Override
// protected Void doInBackground(Void... params) {
// try {
//
// //checkItemInTable(item);
// runOnUiThread(new Runnable() {
//// @Override
//// public void run() {
//// if (item.isComplete()) {
//// mAdapter.remove(item);
//// }
//// }
// });
// } catch (final Exception e) {
// createAndShowDialogFromTask(e, "Error");
// }
//
// return null;
// }
// };
//
// runAsyncTask(task);
// }
private void refreshItemsFromTable() {
// Get the items that weren't marked as completed and add them in the
// adapter
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
@Override
protected Void doInBackground(Void... params) {
try {
final List<EntryItem> results = refreshItemsFromMobileServiceTable();
//Offline Sync
//final List<ToDoItem> results = refreshItemsFromMobileServiceTableSyncTable();
runOnUiThread(new Runnable() {
@Override
public void run() {
mAdapter.clear();
for (EntryItem item : results) {
mAdapter.add(item);
}
}
});
} catch (final Exception e){
createAndShowDialogFromTask(e, "Error");
}
return null;
}
};
runAsyncTask(task);
}
private List<EntryItem> refreshItemsFromMobileServiceTable() throws ExecutionException, InterruptedException {
return mEntryTable.where().field("active").
eq(val(true)).execute().get();
}
private AsyncTask<Void, Void, Void> initLocalStore() throws MobileServiceLocalStoreException, ExecutionException, InterruptedException {
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
MobileServiceSyncContext syncContext = mClient.getSyncContext();
if (syncContext.isInitialized())
return null;
SQLiteLocalStore localStore = new SQLiteLocalStore(mClient.getContext(), "OfflineStore", null, 1);
Map<String, ColumnDataType> tableDefinition = new HashMap<String, ColumnDataType>();
tableDefinition.put("id", ColumnDataType.String);
tableDefinition.put("date", ColumnDataType.String);
tableDefinition.put("time", ColumnDataType.String);
tableDefinition.put("newentry", ColumnDataType.String);
tableDefinition.put("description", ColumnDataType.String);
tableDefinition.put("location", ColumnDataType.String);
tableDefinition.put("image", ColumnDataType.String);
localStore.defineTable("EntryItem", tableDefinition);
SimpleSyncHandler handler = new SimpleSyncHandler();
syncContext.initialize(localStore, handler).get();
} catch (final Exception e) {
createAndShowDialogFromTask(e, "Error");
}
return null;
}
};
return runAsyncTask(task);
}
private void createAndShowDialogFromTask(final Exception exception, String title) {
runOnUiThread(new Runnable() {
@Override
public void run() {
createAndShowDialog(exception, "Error");
}
});
}
private void createAndShowDialog(Exception exception, String title) {
Throwable ex = exception;
if (exception.getCause() != null) {
ex = exception.getCause();
}
createAndShowDialog(ex.getMessage(), title);
}
private void createAndShowDialog(final String message, final String title) {
final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
builder.setMessage(message);
builder.setTitle(title);
builder.create().show();
}
private AsyncTask<Void, Void, Void> runAsyncTask(AsyncTask<Void, Void, Void> task) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
return task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
return task.execute();
}
}
}
我不知道出了什么問題,沒有錯誤,並且我的活動在列表視圖中未顯示任何內容。
驗證移動服務正在返回數據。 在以下行上設置斷點:
最終列表結果= refreshItemsFromMobileServiceTable()
然后,查看結果列表的結果 。
->如果結果為空,則說明您沒有數據,或者您的移動服務存在問題,或者您的移動服務呼叫存在問題。
->如果結果包含預期的數據,則您的代碼在向表單顯示此數據時會遇到問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.