我的应用程序上有一个方法,它显示来自SQLite数据库的随机图像,这些图像是从Web(JSON)获取的。 我将一个OnClickListener放到图像中,这样当它被单击时,它将导致一个新的Activity通过Cursor携带随机显示图像的属性(从JSON保存到SQLite数据库中)。
我遇到的问题是,只有当我的设备未连接到互联网时,图像才可以点击并导致新的活动。
有人可以在下面分析我的代码并为我提供解决方案吗?提前谢谢。
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);
}
DetailsActivity类。
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();
}
}
}
}
}
答案 0 :(得分:2)
这只是一个盲目的镜头 - 可能当你没有互联网连接你的onCreate()你的应用程序得到很快的回答(我假设,第一个列表来自您活动的onCreate方法。如果有连接它等待超时(由于某些原因,数据无法加载)。
一般来说,使用主UI线程下载数据并不是一个好主意。更好的方法是将这项工作转移到另一个线程 - 在这种情况下,您可能需要熟悉AsyncTask
类。