[英]How to retrieve data from Azure Mobile Service and bind to Android ListView
I am currently trying to retrieve the data I have inserted into Azure Mobile Services into a ListView in my Android application. 我目前正在尝试将已插入Azure移动服务的数据检索到Android应用程序中的ListView中。 I tried to follow the tutorial Microsoft provided but my items are not showing up in the ListView.
我试图按照Microsoft提供的教程进行操作,但是我的项目没有显示在ListView中。 The example they provided had a checkbox in it, which I do not need.
他们提供的示例中有一个复选框,我不需要。 I just wanna display my Entry Name and the Date + Time I have inserted into the database table into the ListView.
我只想显示我的条目名称以及我已插入数据库表到ListView中的日期和时间。 This is my list view layout:
这是我的列表视图布局:
entry_listview.xml 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>
and then this is my adapter Entry Item Adapter 然后这是我的适配器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;
}
}
last but not least, the activity where I wanna display the ListView AllEntriesActivity.java 最后但并非最不重要的一点是,我要显示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();
}
}
}
I have no idea what's wrong, no error is thrown and my activity doesn't show anything in the list view. 我不知道出了什么问题,没有错误,并且我的活动在列表视图中未显示任何内容。
Verify that the mobile service is returning data. 验证移动服务正在返回数据。 Set a breakpoint on the following line:
在以下行上设置断点:
final List results = refreshItemsFromMobileServiceTable() 最终列表结果= refreshItemsFromMobileServiceTable()
Then, view the results of the results List. 然后,查看结果列表的结果 。
->If results is empty, you either have no data or there is a problem with your mobile service or there is a problem with the call to your mobile service. ->如果结果为空,则说明您没有数据,或者您的移动服务存在问题,或者您的移动服务呼叫存在问题。
->If results contains the expected data, you have a problem with the code displaying this data to your form. ->如果结果包含预期的数据,则您的代码在向表单显示此数据时会遇到问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.