Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

android - all images not displaying from the same url

Not all images are displaying when running my app. I am getting from json this result

{"result":[{"id":"1","name":null,"path":"http://api.androidhive.info/json/movies/1.jpg"},{"id":"2","name":null,"path":"http://www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"32","name":null,"path":"http://www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"31","name":null,"path":"http://www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"30","name":null,"path":"http://www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"29","name":null,"path":"http://www.justedhak.comlu.com/images/uploaded_images.jpg"}]}

the first 2 url images are displaying correctly in the app however the rest of the url are not displaying

these are working

[{"id":"1","name":null,"path":"http:api.androidhive.infojsonmovies1.jpg"},{"id":"2","name":null,"path":"http:justedhak.comlu.comimagesuploaded_images.jpg"}

these is my code of reading the image

//showlist() is under asynctask  prePostExecute
protected void showList(){
    try {
        JSONObject jsonObj = new JSONObject(myJSON);
        peoples = jsonObj.getJSONArray(TAG_RESULTS);

        for(int i=0;i<peoples.length();i++){
            JSONObject c = peoples.getJSONObject(i);
            String id = c.getString(TAG_ID);
            String url = c.getString(TAG_PATH); 
            Listitem.add(new Listitem(id,url));
        }

        GridViewAdapter adapter = new GridViewAdapter(this, R.layout.grid_item_layout, Listitem);
     //   gridView.setAdapter(gridAdapter); 

       list.setAdapter(adapter);

    } catch (JSONException e) {
        e.printStackTrace();
    }

}
public class GetDataJSON extends AsyncTask<String, Void, String>{
     @Override
        protected String doInBackground(String... params) {
            DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
            HttpPost httppost = new HttpPost("http://justedhak.comlu.com/get-data.php");

            // Depends on your web service
            httppost.setHeader("Content-type", "application/json");

            InputStream inputStream = null;
            String result = null;
            try {
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();

                inputStream = entity.getContent();
                // json is UTF-8 by default
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();

                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "
");
                }
                result = sb.toString();
            } catch (Exception e) {
                // Oops
            }
            finally {
                try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
            }
            return result;
        }

I guess my error is here grid view adapter

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder;

if (row == null) {
LayoutInflater inflater = LayoutInflater.from(mcontext);
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.imageView = (ImageView) row.findViewById(R.id.imageView);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
Listitem item = getItem(position);
System.out.println(item.getUrl());

holder.imageTitle.setText(item.getId());
Picasso.
with(mcontext).
load(item.getUrl())
.placeholder(R.drawable.ic_launcher)
.fit()
.into(holder.imageView);

return row;
}

static class ViewHolder {
TextView imageTitle;
ImageView imageView;
}
}

upload

public void upload()
{
      Calendar thisCal = Calendar.getInstance();
      thisCal.getTimeInMillis();

      //  android.util.Log.i("Time Class ", " Time value in millisecinds "+ thisCal);

   // Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);  
 //   ByteArrayOutputStream stream = new ByteArrayOutputStream();
   // bmp.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.

        Intent intent = getIntent();
        String selectedImage= intent.getStringExtra("imagePath");
        Uri fileUri = Uri.parse(selectedImage);

   // Uri selectedImage = intent.getData();
    System.out.println(fileUri);
    InputStream imageStream = null;
    try {
        imageStream = getContentResolver().openInputStream(fileUri);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    Bitmap bmp = BitmapFactory.decodeStream(imageStream);

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 30, stream);


    byte[] byteArray = stream.toByteArray();
    Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
    imageview.setImageBitmap(bitmap);
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    System.out.println(width);
    System.out.println(height);


    getResizedBitmap( bitmap, 200);
    try {
        stream.close();
        stream = null;
    } catch (IOException e) {

        e.printStackTrace();
    }

    String image_str = Base64.encodeBytes(byteArray);
    final ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("image",image_str));
    nameValuePairs.add(new BasicNameValuePair("caption",caption));
    nameValuePairs.add(new BasicNameValuePair("name","je"));
    nameValuePairs.add(new BasicNameValuePair("categorie",categorie));
     Thread t = new Thread(new Runnable() {

    @Override
    public void run() {
          try{

                 HttpClient httpclient = new DefaultHttpClient();
                 HttpPost httppost = new HttpPost("http://justedhak.comlu.com/images/upload_image.php");
                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                 HttpResponse response = httpclient.execute(httppost);
                 final String the_string_response = convertResponseToString(response);
                 runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            Toast.makeText(AddImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();                         
                        }
                    });

             }catch(final Exception e){
                  runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(AddImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();                             
                    }
                });
                   System.out.println("Error in http connection "+e.toString());
             }  
    }
});
 t.start();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Getting reference for GridView sample from here, I have just customized and tested loading all your images with it.

Item.java:

public class Item {
    String imageUrl;
    String title;
    public Item(String imageUrl, String title) {
        super();
        this.imageUrl = imageUrl;
        this.title = title;
    }
    public String getImageUrl() {
        return imageUrl;
    }
    public String getTitle() {
        return title;
    }
}

CustomGridViewAdapter.java:

public class CustomGridViewAdapter extends ArrayAdapter<Item> {
    Context context;
    int layoutResourceId;
    ArrayList<Item> data = new ArrayList<>();
    public CustomGridViewAdapter(Context context, int layoutResourceId,
                                 ArrayList<Item> data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        RecordHolder holder;
        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);
            holder = new RecordHolder();
            holder.txtTitle = (TextView) row.findViewById(R.id.item_text);
            holder.imageItem = (ImageView) row.findViewById(R.id.item_image);
            row.setTag(holder);
        } else {
            holder = (RecordHolder) row.getTag();
        }
        Item item = data.get(position);
        holder.txtTitle.setText(item.getTitle());
        Picasso.with(context).load(item.getImageUrl()).into(holder.imageItem);
        return row;
    }
    static class RecordHolder {
        TextView txtTitle;
        ImageView imageItem;
    }
}

And MainActivity.java:

customGridAdapter = new CustomGridViewAdapter(this, R.layout.row_grid, gridArray);
gridView.setAdapter(customGridAdapter);
String url = "http://justedhak.comlu.com/get-data.php";
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                if (response != null && !response.isNull("result")) {
                    try {
                        JSONArray jsonArray = response.getJSONArray("result");
                        if (jsonArray != null && jsonArray.length() > 0) {
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                if (jsonObject != null && !jsonObject.isNull("path")) {
                                    String imagePath = jsonObject.getString("path");
                                    if (imagePath != null && !imagePath.isEmpty()) {
                                        gridArray.add(new Item(imagePath,"BNK"));
                                    }
                                }
                            }
                            customGridAdapter.notifyDataSetChanged();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("VOLLEY", error.toString());
            }
        });
queue.add(jsonObjectRequest);

Other files such as layout... I think you know already

Here is the screenshot

BNK's screenshot


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...