Kombinera min kod med Universal Image Loader?

Diskussion i 'Frågor, support och diskussion' startad av PoulZen, 25 okt 2012.

  1. PoulZen

    PoulZen Infant Droid Medlem

    Blev medlem:
    16 okt 2011
    Inlägg:
    7
    Mottagna gillanden:
    0

    MINA ENHETER

    Jag skulle behöva hjälp med att implementera denna kod https://github.com/nostra13/Android-Universal-Image-Loader, med min kod som jag har nu för att kunna ladda in bilder i en ListView.
    Finns det någon som skulle vilja hjälpa mig med det?

    Nedan är min kod hur den ser ut nu.
    TAG_RANDOM innehåller hela sökvägen till var på servern filen ligger inklusive filnamnet.

    Kod:
    package com.example.android;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    
    import org.apache.http.NameValuePair;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import android.app.ListActivity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ImageView;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.TextView;
    
    public class AllProductsActivity extends ListActivity {
    	
    	ImageView image;
    
    	// Progress Dialog
    	private ProgressDialog pDialog;
    
    	// Creating JSON Parser object
    	JSONParser jParser = new JSONParser();
    
    	ArrayList<HashMap<String, String>> productsList;
    	
    
        // JSON Node names
    	private static final String TAG_SUCCESS = "success";
    	private static final String TAG_PRODUCTS = "products";
    	private static final String TAG_PID = "pid";
    	private static final String TAG_RANDOM = "randomkey";
    	private static final String TAG_NAME = "name";
    	private static final String TAG_PRICE = "price";
    
       	// products JSONArray
    	JSONArray products = null;
    
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.all_products);
    		
    
    		// Hashmap for ListView
    		productsList = new ArrayList<HashMap<String, String>>();
    		
    		// Loading products in Background Thread
    		new LoadAllProducts().execute();
    
    		// 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 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(AllProductsActivity.this);
    			pDialog.setMessage("Laddar...");
    			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>();
    			params.add(new BasicNameValuePair("username", Extra.USERNAME));
    			// getting JSON string from URL
    			JSONObject json = jParser.makeHttpRequest(Extra.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 random = c.getString(TAG_RANDOM);
    						String name = c.getString(TAG_NAME);
    						String price = c.getString(TAG_PRICE);
    
    						// 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_RANDOM, random);
    						map.put(TAG_NAME, name);
    						map.put(TAG_PRICE, price);
    
    						// adding HashList to ArrayList
    						productsList.add(map);
    					}
    				}
    			} 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();
    			// updating UI from Background Thread
    			runOnUiThread(new Runnable() {
    				public void run() {
    					/**
    					 * Updating parsed JSON data into ListView
    					 * */
    					ListAdapter adapter = new SimpleAdapter(
    							AllProductsActivity.this, productsList,
    							R.layout.list_item, new String[] { TAG_PID,
    									TAG_NAME, TAG_PRICE, TAG_RANDOM },								
    							new int[] { R.id.pid, R.id.name, R.id.price,
    									R.id.random });
    					// Imageview to show
    					// updating listview
    					setListAdapter(adapter);
    				}
    			});
    
    		}
    
    	}
    }
     
  2. e7andy

    e7andy Professional Droid Hedersmedlem

    Blev medlem:
    14 okt 2009
    Inlägg:
    2 349
    Mottagna gillanden:
    835
    Telefon:
    Huawei P10 Plus

    MINA ENHETER

    Telefon:
    Huawei P10 Plus
    Telefon 2:
    Nexus 5
    Telefon 3:
    ADP1
    Övrigt:
    LG G Watch R, ChromeCast
  3. PoulZen

    PoulZen Infant Droid Medlem

    Blev medlem:
    16 okt 2011
    Inlägg:
    7
    Mottagna gillanden:
    0

    MINA ENHETER

    Ja, jag har testat deras exempel och får det inte till att fungera.
    Nu får jag ett NullPointerException, och sen står det Activity.java:34.
    Kan någon hjälpa mig med vad det betyder?

    Kod:
    package com.example.androidhive;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    
    import org.apache.http.NameValuePair;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
    import com.nostra13.universalimageloader.core.DisplayImageOptions;
    import com.nostra13.universalimageloader.core.ImageLoader;
    import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
    import android.app.ListActivity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ImageView;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.TextView;
    
    public class AllProductsActivity extends ListActivity {
    	
    	ImageView image = (ImageView)findViewById(R.id.image);
    	
    	protected ImageLoader imageLoader = ImageLoader.getInstance();
    		
    	private DisplayImageOptions options
    	= new DisplayImageOptions.Builder()
    	.showStubImage(R.drawable.stub_image)
    	.cacheInMemory()
    	.cacheOnDisc()
    	.build();
    
    	// Progress Dialog
    	private ProgressDialog pDialog;
    
    	// Creating JSON Parser object
    	JSONParser jParser = new JSONParser();
    
    	ArrayList<HashMap<String, String>> productsList;
    	
    
        // JSON Node names
    	private static final String TAG_SUCCESS = "success";
    	private static final String TAG_PRODUCTS = "products";
    	private static final String TAG_PID = "pid";
    	private static final String TAG_RANDOM = "randomkey";
    	private static final String TAG_NAME = "name";
    	private static final String TAG_PRICE = "price";
    
       	// products JSONArray
    	JSONArray products = null;
    
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.all_products);
    		
    				ImageLoaderConfiguration config = new
    				ImageLoaderConfiguration.Builder(getApplicationContext())
    				.threadPoolSize(5)
    				.threadPriority(Thread.MIN_PRIORITY + 3)
    				.denyCacheImageMultipleSizesInMemory()
    				.memoryCache(new UsingFreqLimitedMemoryCache(2000000)) // You can pass your own memory cache implementation
    				.defaultDisplayImageOptions(DisplayImageOptions.createSimple())
    				.build();
    				
    		ImageLoader.getInstance().init(config);
    		
    		
    		
    
    		// Hashmap for ListView
    		productsList = new ArrayList<HashMap<String, String>>();
    		
    		// Loading products in Background Thread
    		new LoadAllProducts().execute();
    
    		// 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 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(AllProductsActivity.this);
    			pDialog.setMessage("Laddar...");
    			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>();
    			params.add(new BasicNameValuePair("username", Extra.USERNAME));
    			// getting JSON string from URL
    			JSONObject json = jParser.makeHttpRequest(Extra.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 random = c.getString(TAG_RANDOM);
    						String name = c.getString(TAG_NAME);
    						String price = c.getString(TAG_PRICE);
    
    						// 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_RANDOM, random);
    						map.put(TAG_NAME, name);
    						map.put(TAG_PRICE, price);
    
    						// adding HashList to ArrayList
    						productsList.add(map);
    					}
    				}
    			} 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
    			imageLoader.displayImage(TAG_RANDOM, image, options);
    			pDialog.dismiss();
    			// updating UI from Background Thread
    			runOnUiThread(new Runnable() {
    				public void run() {
    					/**
    					 * Updating parsed JSON data into ListView
    					 * */
    					ListAdapter adapter = new SimpleAdapter(
    							AllProductsActivity.this, productsList,
    							R.layout.list_item, new String[] { TAG_PID,
    									TAG_NAME, TAG_PRICE, TAG_RANDOM },								
    							new int[] { R.id.pid, R.id.name, R.id.price,
    									R.id.random });
    					// Imageview to show
    					// updating listview
    					setListAdapter(adapter);
    				}
    			});
    
    		}
    
    	}
    }
     
  4. e7andy

    e7andy Professional Droid Hedersmedlem

    Blev medlem:
    14 okt 2009
    Inlägg:
    2 349
    Mottagna gillanden:
    835
    Telefon:
    Huawei P10 Plus

    MINA ENHETER

    Telefon:
    Huawei P10 Plus
    Telefon 2:
    Nexus 5
    Telefon 3:
    ADP1
    Övrigt:
    LG G Watch R, ChromeCast
    Får du deras exempel att fungera? Hur utvecklar du din app? Kör du i en utvecklingsmiljö, t.ex. Eclipse?

    NullPointerException betyder att du försöker accessa ett objekt som är null.
    Att det står Activity.java:34 bör betyda att på rad 34 i Activity.java så har du ett fel. Står det inte AllProductsActivity.java?

    På rad 34 i AllProductsActivity.java står det:
    ImageView image = (ImageView)findViewById(R.id.image);

    Du kan inte hämta ut en vy där. Du måste vänta tills du har satt din layout och så måste det finnas en vy i den som har id:et "image".
     
    Last edited: 26 okt 2012
  5. PoulZen

    PoulZen Infant Droid Medlem

    Blev medlem:
    16 okt 2011
    Inlägg:
    7
    Mottagna gillanden:
    0

    MINA ENHETER

    Jo, deras exempel fungerar. Men inte ihop med det jag försöker få det till.
    Ja, jag är nybörjare, men försöker mig på det här ändå.

    Jag förstod att det troligen var något med ImageView.
    Men var i så fall ska jag sätta det?
    Ska jag sätta de i min SimpleAdapter?

    Tack för att du tar dig tid att svara på mina nybörjarfrågor. :)
     
  6. e7andy

    e7andy Professional Droid Hedersmedlem

    Blev medlem:
    14 okt 2009
    Inlägg:
    2 349
    Mottagna gillanden:
    835
    Telefon:
    Huawei P10 Plus

    MINA ENHETER

    Telefon:
    Huawei P10 Plus
    Telefon 2:
    Nexus 5
    Telefon 3:
    ADP1
    Övrigt:
    LG G Watch R, ChromeCast
    Fungerar din kod utan bilder? Se till att det verkligen fungerar utan bilder först.
    Hur ser R.layout.list_item ut?

    Bilderna ska sen i in i adaptern.
    Jag är dock lite tveksam till om du kan använda SimpleAdapter när du vill använda Android-Universal-Image-Loader. Du bör nog skapa en custom adapter precis som i exemplet:
    https://github.com/nostra13/Android...e/universalimageloader/ImageListActivity.java
     
  7. PoulZen

    PoulZen Infant Droid Medlem

    Blev medlem:
    16 okt 2011
    Inlägg:
    7
    Mottagna gillanden:
    0

    MINA ENHETER

    Ja, den fungerar helt utan problem utan bilder.
    Så här ser list_item ut.

    HTML:
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
    
        <!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
        <TextView
            android:id="@+id/pid"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:visibility="gone" />
    		
    	<!-- Product random (random) - will be HIDDEN - used to pass to other activity -->
        <TextView
            android:id="@+id/random"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="6dip"
            android:paddingLeft="6dip"
            android:textSize="17dip" />
    		
    	<ImageView
            android:id="@+id/image"
            android:layout_width="72dip"
            android:layout_height="72dip"
            android:adjustViewBounds="true" />
    
    
        <!-- Name Label -->
        <TextView
            android:id="@+id/name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="6dip"
            android:paddingLeft="6dip"
            android:textSize="17dip"
            android:textStyle="bold" />
    		
    	<!-- Price Label -->
        <TextView
            android:id="@+id/price"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="6dip"
            android:paddingLeft="6dip"
            android:textSize="17dip"
            android:textStyle="bold" />
    
    </LinearLayout>
    Jag testade att skriva in i list_item en bild som ligger i res mappen, och den visas när jag testar appen.
    Men så fort jag försöker lägga in en ImageView i koden så får jag samma problem varje gång.
    Så jag antar att det handlar om att skriva in rätt i SimpleAdaptern, osäker på hur bara.