【发布时间】:2016-10-05 04:38:00
【问题描述】:
我想用文本和图像填充列表视图。 我通过我的 mysql 数据库以 JSON 格式接收此信息。 我有一个名为“FOTO”的字段,我将照片的路径存储在其中:“http://....../1.png”。
我得到和 android.os.NetworkOnMainThreadException 使用这段代码,但我不知道该怎么做。
我解析 JSON 并将值传递给 listadapter。我还需要传递图标和位图值,但我需要从服务器下载它。
public class DisplayListView extends AppCompatActivity {
final static String TAG = "sb.dl";
String json_string;
JSONObject jsonObject;
JSONArray jsonArray;
TeamAdapter teamAdapter;
ListView listView;
Bitmap icon = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_listview_layout);
teamAdapter = new TeamAdapter(this, R.layout.row_layout);
listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(teamAdapter);
json_string = getIntent().getExtras().getString("json_data");
Log.d(TAG, "json_string " + json_string);
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("risposta");
int count = 0;
String nome, num, data;
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
nome = JO.getString("NOME");
num = JO.getString("NUMERO");
data = JO.getString("DATA_NASCITA");
String url = JO.getString("FOTO");
icon = LoadImageFromWebOperations(url);
Team team = new Team(nome, num, data, icon);
teamAdapter.add(team);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("Simone", e.toString());
Log.d("Simone", e.getMessage());
}
}
public static Bitmap LoadImageFromWebOperations() {
try {
URL url = new URL("url");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
return bmp;
} catch (Exception e) {
Log.d(TAG, "bitmap error: " + e.toString());
Log.d(TAG, "bitmap error: " + e.getMessage());
return null;
}
}
}
【问题讨论】:
-
你能看看这个问题吗? [如何修复 NetworkOnMainThreadException] (stackoverflow.com/questions/6343166/…)。您基本上不想在 MainThread 上进行任何网络活动。
-
我已经完成了.. 但我需要一个提示
-
不能使用主线程进行网络操作。阅读有关 AsyncTask 的一些示例或使用 Volley 库
-
如果我使用异步任务,是否可以等待图标出现然后添加项目?
标签: android android-studio asynchronous bitmap phpmyadmin