我有MainActivity,它以json格式从数据库中获取数据。我正在尝试使用LazyAdapter.class在列表的每一行中加载图像。这是我的MainActivity.class和我的LazyAdapter.class
public class MainActivity extends SherlockListActivity implements iRibbonMenuCallback {
ActionBar mActionBar;
private RibbonMenuView rbmView;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
// Progress Dialog
private ProgressDialog pDialog;
public static ArrayList<String> spinnerArray = new ArrayList<String>(); ;
public static ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://********************/app/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "movies";
private static final String TAG_PID = "id";
public static final String TAG_FIRSTNAME = "movie_name";
public static final String TAG_MOVIE_URL = "movie_url";
public static final String TAG_MOVIE_IMAGE = "movie_image";
String url;
// products JSONArray
JSONArray products = null;
ListView lv;
ListAdapter adapter;
LazyAdapter lazy;
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inbox_list);
//ribbonmenu
rbmView = (RibbonMenuView) findViewById(R.id.ribbonMenuView1);
rbmView.setMenuClickCallback(this);
rbmView.setMenuItems(R.menu.ribbon_menu);
/** Getting a reference to action bar of this activity */
mActionBar = getSupportActionBar();
//test
mActionBar.setDisplayHomeAsUpEnabled(true);
// creating connection detector class instance
cd = new ConnectionDetector(getApplicationContext());
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent)
{
productsList = new ArrayList<HashMap<String, String>>();
Log.d("URL get log: ", url_all_products);
new LoadAllProducts().execute();
}else{
// Internet connection is not present
// Ask user to connect to Internet
showAlertDialog(this, "No Internet Connection",
"You don't have internet connection.", false);
}
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String movie_url = ((TextView) view.findViewById(R.id.movie_url)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
TestActivity.class);
// sending pid to next activity
in.putExtra(url, movie_url);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
@Override
public 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);
}
}
/**
* Function to display simple Alert Dialog
* @param androidFragment - application context
* @param title - alert dialog title
* @param message - alert message
* @param status - success/failure (used to set icon)
* */
public void showAlertDialog(Context androidFragment, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(androidFragment).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Showing Alert Message
alertDialog.show();
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case android.R.id.home:
rbmView.toggleMenu();
break;
}
return true;
}
@Override
public void RibbonMenuItemClick(int itemId) {
// TODO Auto-generated method stub
}
// Response from Edit Product Activity
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading movies...");
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
Log.d("URL get log: ", url_all_products);
JSONObject json = jParser.getJSONFromUrl(url_all_products, "POST", 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 name = c.getString(TAG_FIRSTNAME);
String movie_url = c.getString(TAG_MOVIE_URL);
String movie_image = c.getString(TAG_MOVIE_IMAGE);
// 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_FIRSTNAME, name);
map.put(TAG_MOVIE_URL, movie_url);
map.put(TAG_MOVIE_IMAGE, movie_image);
// adding HashList to ArrayList
productsList.add(map);
//spinnerArray.add(name);
}
}
} 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();
/*
if(pDialog.isShowing())
{
try
{
pDialog.dismiss();
}
catch(Exception e) {// nothing }
}
}
*/
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
/*
ListAdapter adapter = new SimpleAdapter(MainActivity.this, productsList,R.layout.inbox_list_item, new String[] { TAG_PID,TAG_FIRSTNAME,TAG_MOVIE_URL},new int[] { R.id.pid, R.id.name, R.id.movie_url });
// updating listview
setListAdapter(adapter);
*/
// Getting adapter by passing xml data ArrayList
lazy=new LazyAdapter(MainActivity.this, productsList);
lv.setAdapter(lazy);
}
}
);
}
}
}
还有我的LazyAdapter
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());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.inbox_list_item, null);
TextView name = (TextView)vi.findViewById(R.id.name); // title
//TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
//TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
// Setting all values in listview
name.setText(song.get(MainActivity.TAG_FIRSTNAME));
//artist.setText(song.get(MainActivity.TAG_MOVIE_URL));
//duration.setText(song.get(MainActivity.KEY_DURATION));
imageLoader.DisplayImage(song.get(MainActivity.TAG_MOVIE_IMAGE), thumb_image);
return vi;
}
}
我收到这个错误
11-23 19:04:48.049: E/AndroidRuntime(28672): FATAL EXCEPTION: main
11-23 19:04:48.049: E/AndroidRuntime(28672): java.lang.NullPointerException
11-23 19:04:48.049: E/AndroidRuntime(28672): at com.example.goldmovies.MainActivity$LoadAllProducts$1.run(MainActivity.java:311)
11-23 19:04:48.049: E/AndroidRuntime(28672): at android.app.Activity.runOnUiThread(Activity.java:4175)
11-23 19:04:48.049: E/AndroidRuntime(28672): at com.example.goldmovies.MainActivity$LoadAllProducts.onPostExecute(MainActivity.java:297)
11-23 19:04:48.049: E/AndroidRuntime(28672): at com.example.goldmovies.MainActivity$LoadAllProducts.onPostExecute(MainActivity.java:1)
11-23 19:04:48.049: E/AndroidRuntime(28672): at android.os.AsyncTask.finish(AsyncTask.java:602)
11-23 19:04:48.049: E/AndroidRuntime(28672): at android.os.AsyncTask.access$600(AsyncTask.java:156)
11-23 19:04:48.049: E/AndroidRuntime(28672): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
11-23 19:04:48.049: E/AndroidRuntime(28672): at android.os.Handler.dispatchMessage(Handler.java:99)
11-23 19:04:48.049: E/AndroidRuntime(28672): at android.os.Looper.loop(Looper.java:137)
11-23 19:04:48.049: E/AndroidRuntime(28672): at android.app.ActivityThread.main(ActivityThread.java:4517)
11-23 19:04:48.049: E/AndroidRuntime(28672): at java.lang.reflect.Method.invokeNative(Native Method)
11-23 19:04:48.049: E/AndroidRuntime(28672): at java.lang.reflect.Method.invoke(Method.java:511)
11-23 19:04:48.049: E/AndroidRuntime(28672): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
11-23 19:04:48.049: E/AndroidRuntime(28672): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
11-23 19:04:48.049: E/AndroidRuntime(28672): at dalvik.system.NativeStart.main(Native Method)
最佳答案
您在课堂上使用ListView lv;
在oncreate内
两者是不同的。lv
为空
关于java - 从Android中的网址加载图片,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20165259/