我的应用程序上有一个方法,它显示来自 SQLite 数据库的随机图像,这些图像是从网络 (JSON) 获取的。我在图像中放置了一个 OnClickListener,因此当单击它时,它将导致一个新的 Activity,该 Activity 通过 Cursor 携带随机显示图像的属性(来自保存到 SQLite 数据库中的 JSON)。
我面临的问题是,只有当我的设备未连接到互联网时,图像才可单击并导致新的活动。
HashMap<ImageView, Long> aaa = new HashMap<ImageView, Long>();
final ImageView[] images = new ImageView[3];
ImageLoader loader = new ImageLoader(this);
images[0] = (ImageView)findViewById(R.id.top1);
images[1] = (ImageView)findViewById(R.id.top2);
images[2] = (ImageView)findViewById(R.id.top3);
images[0].setOnClickListener(this);
images[1].setOnClickListener(this);
images[2].setOnClickListener(this);
int counter = 0;
Cursor c = managedQuery(Uri.withAppendedPath(Provider.CONTENT_URI,
Database.Project.NAME), new String[] { BaseColumns._ID,
Database.Project.C_SMALLIMAGE}, null, null, "RANDOM() LIMIT 3");
if(c!=null && c.moveToFirst()){
do{
String url = c.getString(1);
images[counter].setTag(url);
loader.DisplayImage(url, this, images[counter]);
aaa.put(images[counter], c.getLong(c.getColumnIndex(BaseColumns._ID)));
counter++;
}while(c.moveToNext());
}
@Override
public void onClick(View v)
{
Intent listIntent = new Intent(MainActivity.this, DetailsActivity.class);
long id = aaa.get(v);
listIntent.setData(Uri.withAppendedPath(Uri.withAppendedPath(
Provider.CONTENT_URI, Database.Project.NAME), Long
.toString(id)));
startActivity(listIntent);
}
详细活动类:
public class DetailsActivity extends Activity implements OnClickListener {
ImageLoader loader = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
loader = new ImageLoader(this);
Intent intent = getIntent();
if (intent != null) {
Uri uri = intent.getData();
if (uri != null) {
Cursor cursor = managedQuery(uri, new String[] {
BaseColumns._ID, Database.Project.C_PROJECTTITLE, Database.Project.C_ORGANIZATIONTITLE,
Database.Project.C_PROJECTDESCRIPTION,Database.Project.C_SMALLIMAGE}, null, null, null);
if (cursor == null) {
finish();
} else {
if (cursor.moveToFirst()) {
ImageView img = (ImageView) findViewById(R.id.project_image);
TextView project_title = (TextView)findViewById(R.id.txt_project_title);
project_title.setText(cursor.getString(1));
TextView organization_title = (TextView)findViewById(R.id.txt_organization_title);
organization_title.setText(Html.fromHtml("von " +cursor.getString(2)));
TextView project_description = (TextView)findViewById(R.id.txt_project_description);
project_description.setText(Html.fromHtml(cursor.getString(3)));
String imageUrl = cursor.getString(4);
img.setTag(imageUrl);
loader.DisplayImage(imageUrl, this, img);
} else {
finish();
}
}
}
}
}
我该如何解决这个问题?
这只是一个盲目的射击 - 可能当你没有互联网连接时,你的 onCreate() 你的应用程序很快就会得到答案(我假设,第一个列表来自你的活动的 onCreate 方法。如果有连接,它会等待超时(数据由于某种原因未加载)。 一般来说,使用主 UI 线程下载数据不是一个好主意。更好的方法是将这项工作转移到另一个线程 - 在这种情况下,您可能需要熟悉
AsyncTask
类。