上传图像不显示,但其他人正在显示

时间:2015-09-19 14:35:25

标签: android picasso

我面临一些奇怪的事情,我可以在link中看到我上传的图片,但它没有在应用中显示。但如果我在应用程序中输入另一个图像link。原因是什么?有人可以帮忙吗?

main_actvity

    //Downloading data asynchronously
    public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {

        @Override
        protected Integer doInBackground(String... params) {
            Integer result = 0;
            try {
                // Create Apache HttpClient
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse httpResponse = httpclient.execute(new HttpGet(params[0]));
                int statusCode = httpResponse.getStatusLine().getStatusCode();

                // 200 represents HTTP OK
                if (statusCode == 200) {
                    String response = streamToString(httpResponse.getEntity().getContent());
                    parseResult(response);
                    result = 1; // Successful
                } else {
                    result = 0; //"Failed
                }
            } catch (Exception e) {
                Log.d(TAG, e.getLocalizedMessage());
            }
            return result;
        }

        @Override
        protected void onPostExecute(Integer result) {
            // Download complete. Let us update UI
            if (result == 1) {
                mGridAdapter.setGridData(mGridImages);
            } else {
                Toast.makeText(MainActivity.this, "No Connection found,Check your Connection!", Toast.LENGTH_SHORT).show();
            }
            mProgressBar.setVisibility(View.GONE);
        }
    }

    String streamToString(InputStream stream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
        String line;
        String result = "";
        while ((line = bufferedReader.readLine()) != null) {
            result += line;
        }

        // Close stream
        if (null != stream) {
            stream.close();
        }
        return result;
    }

    /**
     * Parsing the feed results and get the list
     * @param result
     */
    private void parseResult(String result) {
        try {

            JSONObject response = new JSONObject(result);
            JSONArray posts = response.optJSONArray("result");
            GridImages item;
            for (int i = 0; i < posts.length(); i++) {
                JSONObject post = posts.optJSONObject(i);
                String title = post.optString("name");
                String image=post.optString("path");
                item = new GridImages();
                item.Settitle(title);
                item.Setimage(image);

                mGridImages.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }



   // The method that invoke of uploading images
        public   void openGallery() {

            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);

           }
         @Override
         protected void onActivityResult(int requestCode, int resultCode, Intent data) {
             super.onActivityResult(requestCode, resultCode, data);

              if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {

                  //file name
                     Uri selectedImage = data.getData();

                     Intent i = new Intent(this,
                              AddImage.class);
                    i.putExtra("imagePath", selectedImage.toString());
                    startActivity(i);                  
              }
         }

    // the design of the action bar menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
         MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.activity_main_actions, menu);

        return super.onCreateOptionsMenu(menu);
    }

       public boolean onOptionsItemSelected(MenuItem item) 
       { 
          super.onOptionsItemSelected(item); 

     switch (item.getItemId()){

     case R.id.ic_action_person:
         Toast.makeText(this, "Create a new account please", Toast.LENGTH_SHORT).show();
           Intent intent = new Intent(this, Register.class);
             startActivity(intent);
         return true;

     case R.id.ic_action_search:

         Toast.makeText(this, "Search for new images", Toast.LENGTH_SHORT).show();
         Intent  isearch= new Intent(this,Search.class);
            startActivity(isearch);
     return true;

     case R.id.ic_action_picture:
         Toast.makeText(this, "Search for new photos", Toast.LENGTH_SHORT).show();
         Intent  iphotos= new Intent(this,Display.class);
         startActivity(iphotos);
         return true;

     case R.id.ic_add_photo:
         Toast.makeText(this, "Search for new photos", Toast.LENGTH_SHORT).show();

          openGallery();

         return true;
     }
        return true;
       } 
   }

addimage.java我在哪里上传图片

    public void onCreate(Bundle icicle) {
            super.onCreate(icicle);
            setContentView(R.layout.main);

            EditText captionetxt = (EditText) findViewById(R.id.caption);
            caption = captionetxt.getText().toString();
            //spinner
            Spinner dropdown = (Spinner)findViewById(R.id.spinner1);
            String[] items = new String[]{"Lebanese jokes", "Student Jokes", "Quotes"};
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
            dropdown.setAdapter(adapter);
             categorie = dropdown.getSelectedItem().toString(); 
            imageview = (ImageView) findViewById(R.id.imageView);           
                }
        public void onclick(View view)
        {
            Toast.makeText(AddImage.this, "Uploading Image", Toast.LENGTH_LONG).show();                         
            upload();

              Intent i = new Intent(this,
                        MainActivity.class);
              startActivity(i);
        }
        public void upload()
        {
              Calendar thisCal = Calendar.getInstance();
              thisCal.getTimeInMillis();
                Intent intent = getIntent();
                String selectedImage= intent.getStringExtra("imagePath");
                Uri fileUri = Uri.parse(selectedImage);

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

        public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{

             String res = "";
             StringBuffer buffer = new StringBuffer();
             inputStream = response.getEntity().getContent();
             final int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
              runOnUiThread(new Runnable() {

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

             if (contentLength < 0){
             }
             else{
                    byte[] data = new byte[512];
                    int len = 0;
                    try
                    {
                        while (-1 != (len = inputStream.read(data)) )
                        {
                            buffer.append(new String(data, 0, len)); //converting to string and appending  to stringbuffer…..
                        }
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                    try
                    {
                        inputStream.close(); // closing the stream…..
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                    res = buffer.toString();     // converting stringbuffer to string…..

                    runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                       Toast.makeText(AddImage.this, "Result : res", Toast.LENGTH_LONG).show();
                    }
                });
                    //System.out.println("Response => " +  EntityUtils.toString(response.getEntity()));
             }
             return res;
        }

        public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
            int width = image.getWidth();
            int height = image.getHeight();

            float bitmapRatio = (float)width / (float) height;
            if (bitmapRatio > 0) {
                width = maxSize;
                height = (int) (width / bitmapRatio);
            } else {
                height = maxSize;
                width = (int) (height * bitmapRatio);
            }
            return Bitmap.createScaledBitmap(image, width, height, true);
    }



}

main xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/caption"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:hint="Insert a caption" />
 <Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/caption"
android:paddingLeft="10dp"
android:background="@android:drawable/btn_dropdown"
android:spinnerMode="dropdown" />

<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/spinner1"
android:layout_weight="1"
android:text="Post"
android:onClick="onclick" />


<ImageView 
    android:id="@+id/imageView"
       android:layout_width="300dp"
       android:layout_height="300dp"
       android:layout_below="@+id/btn1"
       android:paddingLeft="20dp"/>

</RelativeLayout>

mgridadapter

public class GridImageMainAdapter extends ArrayAdapter<GridImages> {

    private Context mContext;
    private int layoutResourceId;
    private ArrayList<GridImages> mGridImages = new ArrayList<GridImages>();

    public GridImageMainAdapter(Context mContext, int layoutResourceId, ArrayList<GridImages> mGridImages) {
        super(mContext, layoutResourceId, mGridImages);
        this.layoutResourceId = layoutResourceId;
        this.mContext = mContext;
        this.mGridImages = mGridImages;
    }


    /**
     * Updates grid data and refresh grid items.
     * @param mGridData
     */
    public void setGridData(ArrayList<GridImages> mGridImages) {
        this.mGridImages = mGridImages;
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        ViewHolder holder;
        if (BuildConfig.DEBUG) {
            Picasso.with(mContext).setIndicatorsEnabled(true);
            Picasso.with(mContext).setLoggingEnabled(true);
        }
        if (row == null) {
            LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);
            holder = new ViewHolder();
            holder.titleTextView = (TextView) row.findViewById(R.id.grid_item_title);
            holder.imageView = (ImageView) row.findViewById(R.id.grid_item_image);
            row.setTag(holder);
        } else {
            holder = (ViewHolder) row.getTag();
        }

        GridImages item = mGridImages.get(position);
        holder.titleTextView.setText(Html.fromHtml(item.Gettitle()));

        Picasso.
        with(mContext).
        load(item.Getimage())
        .placeholder(R.drawable.ic_launcher) // can also be a drawable
         .fit() // will explain later
        .into(holder.imageView);

        return row;
    }

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

1 个答案:

答案 0 :(得分:1)

更改gridview数据后添加mGridAdapter.notifyDatasetChange()