2016-12-22 1 views
0

Ich bekomme Bilder vom Server in meine Listview, aber ich bekomme quadratische Bilder statt Kreis ... Ich will es Kreis .Kindlich helfen..Ich bin neu auf android hier ist mein SubMenu Aktivität:Ändern von Bildern vom Server von Quadrat zu Kreis in Android-Listenansicht mit JSON

public class SubMenu extends Activity { 
    // Declare Variables 
    JSONObject jsonobject; 
    JSONArray jsonarray; 
    ListView listview; 
    ListViewAdapter adapter; 
    ProgressDialog mProgressDialog; 
    ArrayList<HashMap<String, String>> arraylist; 
    static String RANK = "id"; 
    static String COUNTRY = "name"; 

    static String FLAG = "image"; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     // Get the view from listview_main.xml 
     setContentView(R.layout.activity_sub_menu); 
     // Execute DownloadJSON AsyncTask 
     new DownloadJSON().execute(); 
    } 

    // DownloadJSON AsyncTask 
    private class DownloadJSON extends AsyncTask<Void, Void, Void> { 

     // @Override 
     // protected void onPreExecute() { 
     // super.onPreExecute(); 
     // Create a progressdialog 
     // mProgressDialog = new ProgressDialog(SubMenu.this); 
     // Set progressdialog title 
     // mProgressDialog.setTitle("Categories of Main categories....."); 
     // Set progressdialog message 
     // mProgressDialog.setMessage("Loading..."); 
     // mProgressDialog.setIndeterminate(false); 
     // Show progressdialog 
     // mProgressDialog.show(); 
     // } 

     @Override 
     protected Void doInBackground(Void... params) { 
      // Create an array 
      arraylist = new ArrayList<HashMap<String, String>>(); 
      // Retrieve JSON Objects from the given URL address 
      jsonarray = JsonFunctions 
        .getJSONfromURL("http://cloud.granddubai.com/broccoli/menu_typeitem.php"); 

      try { 
       // Locate the array name in JSON 
//     jsonarray = jsonobject.getJSONArray("main_menu_items"); 


       for (int i = 0; i < jsonarray.length(); i++) { 
        HashMap<String, String> map = new HashMap<String, String>(); 

        jsonobject = jsonarray.getJSONObject(i); 
        // Retrive JSON Objects 
        map.put("id", jsonobject.getString("id")); 
        map.put("name", jsonobject.getString("name")); 

        map.put("image", jsonobject.getString("image")); 
        // Set the JSON Objects into the array 
        arraylist.add(map); 
       } 
      } catch (JSONException e) { 
       Log.e("Error", e.getMessage()); 
       e.printStackTrace(); 
      } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void args) { 
      // Locate the listview in listview_main.xml 
      listview = (ListView) findViewById(R.id.list1); 
      // Pass the results into ListViewAdapter.java 
      adapter = new ListViewAdapter(SubMenu.this, arraylist); 
      // Set the adapter to the ListView 
      listview.setAdapter(adapter); 
      // Close the progressdialog 
      // mProgressDialog.dismiss(); 
     } 
    } 
} 

das ist mein Imageloader:

public class ImageLoader { 

    MemoryCache memoryCache = new MemoryCache(); 
    FileCache fileCache; 
    private Map<ImageView, String> imageViews = Collections 
      .synchronizedMap(new WeakHashMap<ImageView, String>()); 
    ExecutorService executorService; 
    // Handler to display images in UI thread 
    Handler handler = new Handler(); 

    public ImageLoader(Context context) { 
     fileCache = new FileCache(context); 
     executorService = Executors.newFixedThreadPool(5); 
    } 

    final int stub_id = R.drawable.nicon1; 

    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); 

     Bitmap b = decodeFile(f); 
     if (b != null) 
      return b; 

     // Download Images from the Internet 
     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(); 
      conn.disconnect(); 
      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; 
      FileInputStream stream1 = new FileInputStream(f); 
      BitmapFactory.decodeStream(stream1, null, o); 
      stream1.close(); 

      // Find the correct scale value. It should be the power of 2. 
      // Recommended Size 512 
      final int REQUIRED_SIZE = 70; 
      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; 
      FileInputStream stream2 = new FileInputStream(f); 
      Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2); 
      stream2.close(); 
      return bitmap; 
     } catch (FileNotFoundException e) { 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     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() { 
      try { 
       if (imageViewReused(photoToLoad)) 
        return; 
       Bitmap bmp = getBitmap(photoToLoad.url); 
       memoryCache.put(photoToLoad.url, bmp); 
       if (imageViewReused(photoToLoad)) 
        return; 
       BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad); 
       handler.post(bd); 
      } catch (Throwable th) { 
       th.printStackTrace(); 
      } 
     } 
    } 

wie kann ich es ändern umrunden ??????

das ist mein Listview-Adapter:

public class ListViewAdapter extends BaseAdapter { 

    // Declare Variables 
    Context context; 
    LayoutInflater inflater; 
    ArrayList<HashMap<String, String>> data; 
    ImageLoader imageLoader; 
    HashMap<String, String> resultp = new HashMap<String, String>(); 

    public ListViewAdapter(Context context, 
          ArrayList<HashMap<String, String>> arraylist) { 
     this.context = context; 
     data = arraylist; 
     imageLoader = new ImageLoader(context); 
    } 

    @Override 
    public int getCount() { 
     return data.size(); 
    } 

    @Override 
    public Object getItem(int position) { 
     return null; 
    } 

    @Override 
    public long getItemId(int position) { 
     return 0; 
    } 

    public View getView(final int position, View convertView, ViewGroup parent) { 
     // Declare Variables 
     TextView id; 
     TextView name; 
     TextView population; 
     ImageView image; 

     inflater = (LayoutInflater) context 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     View itemView = inflater.inflate(R.layout.list_item1, parent, false); 
     // Get the position 
     resultp = data.get(position); 

     // Locate the TextViews in listview_item.xml 
     id = (TextView) itemView.findViewById(R.id.idq); 
     name = (TextView) itemView.findViewById(R.id.type1); 


     // Locate the ImageView in listview_item.xml 
     image = (ImageView) itemView.findViewById(R.id.subimg); 

     // Capture position and set results to the TextViews 
     id.setText(resultp.get(SubMenu.RANK)); 
     name.setText(resultp.get(SubMenu.COUNTRY)); 

     // Capture position and set results to the ImageView 
     // Passes flag images URL into ImageLoader.class 
     imageLoader.DisplayImage(resultp.get(SubMenu.FLAG), image); 
     // Capture ListView item click 
     /**itemView.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       // Get the position 
       resultp = data.get(position); 
       Intent intent = new Intent(context, SingleItemView.class); 
       // Pass all data rank 
       intent.putExtra("rank", resultp.get(MainActivity.RANK)); 
       // Pass all data country 
       intent.putExtra("country", resultp.get(MainActivity.COUNTRY)); 
       // Pass all data population 
       intent.putExtra("population",resultp.get(MainActivity.POPULATION)); 
       // Pass all data flag 
       intent.putExtra("flag", resultp.get(MainActivity.FLAG)); 
       // Start SingleItemView Class 
       context.startActivity(intent); 

      } 
     });*/ 
     return itemView; 
    } 
} 

Antwort

0

sehen, wie Sie die URL von Ihrem sind immer JSONArray Sie Picasso und führen Sie dann einen Kreis Transformation auf das Bild verwenden können, wenn wie so geladen:

Fügen Sie die Abhängigkeit zu Ihrer App-Ebene build.gradle

compile 'com.squareup.picasso:picasso:2.5.2' 

Beispiel für Aufruf wäre:

Picasso.with(context).load(imageurl).transform(new CircleTransform()).into(imageview); 

Die CircleTransform benötigt wie so hinzugefügt werden:

import android.graphics.Bitmap; 
import android.graphics.BitmapShader; 
import android.graphics.Canvas; 
import android.graphics.Paint; 

import com.squareup.picasso.Transformation; 

public class CircleTransform implements Transformation { 
    @Override 
    public Bitmap transform(Bitmap source) { 
     int size = Math.min(source.getWidth(), source.getHeight()); 

     int x = (source.getWidth() - size)/2; 
     int y = (source.getHeight() - size)/2; 

     Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size); 
     if (squaredBitmap != source) { 
      source.recycle(); 
     } 

     Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig()); 

     Canvas canvas = new Canvas(bitmap); 
     Paint paint = new Paint(); 
     BitmapShader shader = new BitmapShader(squaredBitmap, 
       BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP); 
     paint.setShader(shader); 
     paint.setAntiAlias(true); 

     float r = size/2f; 
     canvas.drawCircle(r, r, r, paint); 

     squaredBitmap.recycle(); 
     return bitmap; 
    } 

    @Override 
    public String key() { 
     return "circle"; 
    } 
} 

bearbeiten:

Die Linie, wo ist, sagt imageLoader.DisplayImage(resultp.get(SubMenu.FLAG), image); dass 2 mit Picasso.with(context).load(resultp.get(SubMenu.FLAG)).transform(new CircleTransform()).into(image);

bearbeiten ersetzen:

Sie können die Platzhalterfunktion von Picasso mit einem Zeichen in Ihren Ressourcen verwenden, wenn der Pfad leer ist.

Picasso.with(context).load(resultp.get(SubMenu.FLAG)).Placeholder(R.drawable.placeholderimage).transform(new CircleTransform()).into(image);` 

, wenn der Pfad nie leer sein soll, müssen Sie die url Sie, indem Sie die Informationen, die Sie von Json erhalten werden immer überprüfen:

map.put("image", jsonobject.getString("image")); 
Log.e("image_url", jsonobject.getString("image")); 

und dies erscheint entweder in den Run Registerkarte oder Android Monitor Registerkarte unten links von Android Studio. Überprüfen Sie, ob die URL ordnungsgemäß funktioniert, bevor Sie sie mit Code laden.

bearbeiten 3:

So ist die Art, wie ich die Informationen aus dem Activity zum Adapter anstelle eines HashMap Ich verwende ein Modell übergeben.

Also statt der Zugabe des arraylist.add(map); hinzufügen arrayList.add(new DataModel(jsonobject.getString("id"), jsonobject.getString("name"), jsonobject.getString("image"))

dann eine Klasse erstellen DataModel nannte es in etwa so aussehen werde:

public class DataModel { 

private String id; 
private String name; 
private String imageurl; 

public DataModel(String id, String name, String imageurl) { 
    this.id = id; 
    this.name = name; 
    this.imageurl = imageurl; 
} 

public String getId() {return id;} 

public String getName() {return name;} 

public String getImageUrl() { return imageurl; } 

} 

und dann in Ihre ListViewAdapter setzen

statt resultP = data.get(position) tun DataModel dataModel = data.get(position);

dann setTe xt das gleiche wie zuvor:

id.setText(dataModel.getId()); 
name.setText(dataModel.getName()); 
Picasso.with(context).load(dataModel.getImageUrl()).Placeholder(R.drawable.placeholderimage).transform(new CircleTransform()).into(image); 

Dies sollte für Sie arbeiten.

+0

Lassen Sie uns [diese Diskussion im Chat fortsetzen] (http: //chat.stackoverflow. com/zimmer/131435/diskussion-zwischen-bradley-wilson-and-z-al). –

1

In Ihrem Listview-Elemente Layout statt Image Verwendung CircleImageView zu verwenden.

Für CircleImageView diese Bibliothek verwenden: https://github.com/hdodenhof/CircleImageView

+0

wie cane ich diese hinzufügen ... wie ich es heruntergeladen habe, aber sollte ich es in einen lib Ordner kopieren? ich bin neu ,,, so know so viel –

+0

diese Zeile zu app/build.gradle in Abhängigkeit hinzufügen - kompilieren 'de.hdodenhof: circleimageview: 2.1.0'. Und dann starten Sie CircleImageView. –

+0

es funktioniert nicht..ich habe diese Zeile hinzugefügt..und anstelle von Bildansicht habe ich –

Verwandte Themen