- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我创建了一个 ListView 来从 PHP 服务器加载图像和文本。我编写的代码运行良好,没有错误,但我的 ListView 是空白的,不显示任何图像或文本。
LazyAdapter.java
package mygp.gptrade.imageListAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import mygp.gptrade.AllProductActivity;
import mygp.gptrade.R;
import mygp.gptrade.image.ImageLoader;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_item, null);
TextView pid = (TextView)vi.findViewById(R.id.pid);
TextView itemname = (TextView)vi.findViewById(R.id.name);
TextView price = (TextView)vi.findViewById(R.id.price);
ImageView thumb_image = (ImageView)vi.findViewById(R.id.imageView1); //
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
pid.setText(song.get(AllProductActivity.TAG_PID));
itemname.setText(song.get(AllProductActivity.TAG_NAME));
price.setText(song.get(AllProductActivity.TAG_PRICE));
imageLoader.DisplayImage(song.get(AllProductActivity.TAG_PATH), thumb_image); //
return vi;
}
}
AllProductActivity.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import mygp.gptrade.imageListAdapter.LazyAdapter;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AllProductActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser2 jParser = new JSONParser2();
ArrayList<HashMap<String, String>> productsList;
ListView list;
LazyAdapter adapter;
// url to get all products list
private static String url_all_products = "http://gemini888.tk/test4/android_connect/get_all_products.php";
// JSON Node names
public static final String TAG_SUCCESS = "success";
public static final String TAG_PRODUCTS = "products";
public static final String TAG_PID = "uid";
public static final String TAG_NAME = "itemname";
public static final String TAG_PRICE = "price";
public static final String TAG_PATH = "path";
// products JSONArray
JSONArray products = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
list = (ListView)findViewById(android.R.id.list);
//testing
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// on seleting single product
// launching Edit Product Screen
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String iname = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
String path = c.getString(TAG_PATH);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, iname);
map.put(TAG_PRICE, price);
map.put(TAG_PATH, path);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
adapter=new LazyAdapter(AllProductActivity.this, productsList);
list.setAdapter(adapter);
}
});
}
}
}
ImageLoader.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import mygp.gptrade.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
public class ImageLoader {
MemoryCache memoryCache=new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
public ImageLoader(Context context){
fileCache=new FileCache(context);
executorService=Executors.newFixedThreadPool(5);
}
final int stub_id=R.drawable.ic_launcher;
public void DisplayImage(String url, ImageView imageView)
{
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
{
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView)
{
PhotoToLoad p=new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex){
ex.printStackTrace();
if(ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=210;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
//Task for the queue
private class PhotoToLoad
{
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i){
url=u;
imageView=i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad){
this.photoToLoad=photoToLoad;
}
@Override
public void run() {
if(imageViewReused(photoToLoad))
return;
Bitmap bmp=getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if(imageViewReused(photoToLoad))
return;
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
Activity a=(Activity)photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
boolean imageViewReused(PhotoToLoad photoToLoad){
String tag=imageViews.get(photoToLoad.imageView);
if(tag==null || !tag.equals(photoToLoad.url))
return true;
return false;
}
//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
public void run()
{
if(imageViewReused(photoToLoad))
return;
if(bitmap!=null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
AllProduct.php
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
// include db connect class
require_once 'include/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT *FROM image_detail") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["uid"] = $row["uid"];
$product["itemname"] = $row["itemname"];
$product["price"] = $row["price"];
$product["description"] = $row["description"];
// push single product into final response array
array_push($response["products"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
日志
05-15 03:44:07.809: D/All Products:(1248): {"success":1,"products": [{"uid":"1","itemname":"Sdsda","description":"Dsadasdasd","price":"0.00"},{"uid":"2","itemname":"Gagagaga","description":"Gagagaga","price":"0.00"},{"uid":"3","itemname":"Gtr 35","description":"Rm30","price":"0.00"},{"uid":"4","itemname":"Lycan Hypersport","description":"Rm 40","price":"0.00"},{"uid":"5","itemname":"laptop asus","description":"so cheap","price":"20.00"},{"uid":"6","itemname":"xiaomi3","description":"condition 9\/10","price":"50.00"},{"uid":"7","itemname":"acer laptop","description":"freeeeee wajajaja","price":"10.00"},{"uid":"8","itemname":"dell laptop","description":"for sell","price":"60000.00"},{"uid":"9","itemname":"abyss kang","description":"grab it fast","price":"3000000.00"},{"uid":"10","itemname":"botol","description":"cheap je mari la","price":"1.00"},{"uid":"11","itemname":"diao nsksjs","description":"sghsjsjs","price":"444.00"},{"uid":"12","itemname":"cook","description":"cook","price":"20.00"},{"uid":"13","itemname":"cookw","description":"cookw","price":"20.00"},{"uid":"14","itemname":"hahahhaha","description":"hahahhahaa","price":"20.00"},{"uid":"15","itemname":"bola","description":"football yes la","price":"10.00"},{"uid":"16","itemname":"try","description":"try","price":"20.00"},{"uid":"17","itemname":"try2","description":"try2","price":"25.00"},{"uid":"18","itemname":"try3","description":"try3","price":"555.00"},{"uid":"19","itemname":"try4","description":"try4","price":"0.00"},{"uid":"20","itemname":"try5","description":"try5","price":"5.00"},{"uid":"21","itemname":"try6","description":"try6","price":"555.00"},{"uid":"22","itemname":"try7","description":"try7","price":"0.00"},{"uid":"23","itemname":"try8","description":"try8","price":"25.00"},{"uid":"24","itemname":"try9","description":"try9","price":"0.00"},{"uid":"25","itemname":"trt10","description":"trt10","price":"25.00"},{"uid":"26","itemname":"tryee","description":"rrrf","price":"0.00"},{"uid":"27","itemname":"trydd","description":"fff","price":"0.00"},{"uid":"28","itemname":"sr-","description":"dftycfyyhhhy","price":"0.00"},{"uid":"29","itemname":"display flow","description":"display flow","price":"20.00"},{"uid":"30","itemname":"yamcha","description":"yamcha","price":"0.00"},{"uid":"31","itemname":"louis","description":"louis","price":"0.00"}]}
05-15 03:44:07.809: W/System.err(1248): org.json.JSONException: No value for path
05-15 03:44:07.819: W/System.err(1248): at org.json.JSONObject.get(JSONObject.java:355)
05-15 03:44:07.819: W/System.err(1248): at org.json.JSONObject.getString(JSONObject.java:515)
05-15 03:44:07.819: W/System.err(1248): at mygp.gptrade.AllProductActivity$LoadAllProducts.doInBackground(AllProductActivity.java:166)
05-15 03:44:07.909: I/Choreographer(1248): Skipped 99 frames! The application may be doing too much work on its main thread.
05-15 03:44:07.999: I/Choreographer(1248): Skipped 47 frames! The application may be doing too much work on its main thread.
05-15 03:44:08.089: W/System.err(1248): at mygp.gptrade.AllProductActivity$LoadAllProducts.doInBackground(AllProductActivity.java:1)
05-15 03:44:08.179: I/Choreographer(1248): Skipped 47 frames! The application may be doing too much work on its main thread.
05-15 03:44:08.449: I/Choreographer(1248): Skipped 37 frames! The application may be doing too much work on its main thread.
05-15 03:44:08.529: W/System.err(1248): at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-15 03:44:08.529: W/System.err(1248): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-15 03:44:08.579: I/Choreographer(1248): Skipped 59 frames! The application may be doing too much work on its main thread.
05-15 03:44:08.649: I/Choreographer(1248): Skipped 32 frames! The application may be doing too much work on its main thread.
05-15 03:44:08.729: I/Choreographer(1248): Skipped 30 frames! The application may be doing too much work on its main thread.
05-15 03:44:08.789: I/Choreographer(1248): Skipped 32 frames! The application may be doing too much work on its main thread.
05-15 03:44:08.879: I/Choreographer(1248): Skipped 34 frames! The application may be doing too much work on its main thread.
05-15 03:44:08.939: I/Choreographer(1248): Skipped 31 frames! The application may be doing too much work on its main thread.
05-15 03:44:09.039: I/Choreographer(1248): Skipped 31 frames! The application may be doing too much work on its main thread.
05-15 03:44:09.299: I/Choreographer(1248): Skipped 44 frames! The application may be doing too much work on its main thread.
05-15 03:44:09.379: W/System.err(1248): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
05-15 03:44:09.379: W/System.err(1248): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-15 03:44:09.429: I/Choreographer(1248): Skipped 61 frames! The application may be doing too much work on its main thread.
05-15 03:44:09.499: I/Choreographer(1248): Skipped 42 frames! The application may be doing too much work on its main thread.
05-15 03:44:09.599: I/Choreographer(1248): Skipped 43 frames! The application may be doing too much work on its main thread.
05-15 03:44:09.859: I/Choreographer(1248): Skipped 38 frames! The application may be doing too much work on its main thread.
05-15 03:44:10.049: I/Choreographer(1248): Skipped 42 frames! The application may be doing too much work on its main thread.
05-15 03:44:10.069: W/System.err(1248): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-15 03:44:10.069: W/System.err(1248): at java.lang.Thread.run(Thread.java:841)
05-15 03:44:10.109: I/Choreographer(1248): Skipped 36 frames! The application may be doing too much work on its main thread.
05-15 03:44:10.319: I/MemoryCache(1248): MemoryCache will use up to 12.0MB
05-15 03:44:10.359: I/Choreographer(1248): Skipped 162 frames! The application may be doing too much work on its main thread.
最佳答案
添加这个
$product["path"] = $row["path"];
里面
while ($row = mysql_fetch_array($result)) {
希望这能解决您的问题。
关于java - 带有自定义适配器的 ListView 图像和文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30294243/
我想使用 li 和 ul 制作一个多级下拉列表,以便显示我博客中按年和月排序的所有文章。我希望我的下拉菜单看起来像 Google Blogspot 下拉菜单: 这是我的 CSS 和 HTML 代码 u
我在 Win 7 64 机器上将 CodeBlocks 与 gcc 4.7.2 和 gmp 5.0.5 结合使用。开始使用 gmpxx 后,我看到一个奇怪的段错误,它不会出现在 +、- 等运算符中,但
我正在使用 tern 为使用 CodeMirror 运行的窗口提供一些增强的智能感知,它工作正常,但我遇到了一个问题,我想添加一些自定义“types”,可以这么说,这样下拉列表中它们旁边就有图标了。我
我正在尝试让我的 PC 成为 Android 2.3.4 设备的 USB 主机,以便能够在不需要实际“附件”的情况下开发 API。为此,我需要将 PC 设置为 USB 主机和“设备”(在我的例子中是运
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 9
我在设置服务器方面几乎是个新手,但遇到了一个问题。我有一个 Ubuntu 16.04 VPS 并安装了 Apache2 和 Tomcat7。我正在为 SSL 使用 LetsEncrypt 和 Cert
我在一个基于谷歌地图的项目上工作了超过 6 个月。我使用的是 Google Maps API V1 及其开发人员 API key 。当我尝试发布应用程序时,我了解到 Google API V1 已被弃
我是 Python 的新手,所以如果我对一些简单的事情感到困惑,请原谅。 我有一个这样的对象: class myObject(object): def __init__(self):
这个问题已经有答案了: How can I access object properties containing special characters? (2 个回答) 已关闭 9 年前。 我正在尝
我有下面的 CSS。我想要的是一种流体/液体(因为缺乏正确的术语)css。我正在为移动设备开发,当我改变模式时 从纵向 View 到陆地 View ,我希望它流畅。现在的图像 在陆地 View 中效
我正在尝试使用可以接受参数的缓存属性装饰器。 我查看了这个实现:http://www.daniweb.com/software-development/python/code/217241/a-cac
这个问题在这里已经有了答案: Understanding slicing (36 个答案) 关闭 6 年前。 以a = [1,2,3,4,5]为例。根据我的直觉,我认为 a[::-1] 与 a[0:
mysqldump -t -u root -p mytestdb mytable --where=datetime LIKE '2014-09%' 这就是我正在做的事情,它会返回: mysqldum
我正在制作销售税计算器,除了总支付金额部分外,其他一切都正常。在我的程序中,我希望能够输入一个数字并获得该项目的税额我还希望能够获得支付的总金额,包括交易中的税金。到目前为止,我编写的代码完成了所有这
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许在 Stack Overflow 上提出有关通用计算硬件和软件的问题。您可以编辑问题,使其成为
我是否必须进行任何额外的设置才能让 apache-airflow 在任务失败时向我发送电子邮件。我的配置文件中有以下内容(与默认值保持不变): [email] email_backend = airf
这个问题在这里已经有了答案: What does the $ symbol do in VBA? (5 个回答) 3年前关闭。 使用返回字符串(如 Left)的内置函数有什么区别吗?或使用与 $ 相同
我有一个用VB6编写的应用程序,我需要使用一个用.NET编写的库。有什么方法可以在我的应用程序上使用该库吗? 谢谢 最佳答案 这取决于。您可以控制.NET库吗? 如果是这样,则可以修改您的库,以便可以
当我创建一个以 ^ 开头的类方法时,我尝试调用它,它给了我一个错误。 class C { method ^test () { "Hi" } } dd C.new.test; Too m
我已经使用 bower 安装了 angularjs 和 materialjs。 凉亭安装 Angular Material 并将“ngMaterial”注入(inject)我的应用程序,但出现此错误。
我是一名优秀的程序员,十分优秀!