3

one image is displaying on my app and the other is not, however both can be accesses from the browser.

this one in my free host is not displaying on my app. Please not that I can see the image from the free host server :

   http://www.justedhak.comlu.com/images/uploaded_images.jpg

this one is from a random site and its showing on the app.

http://api.androidhive.info/json/movies/1.jpg

My question, is it could the problem in the way I am uploading the image ? or could be the free host (000webhost) ? please give me your opinion

I am uploading image to server then displaying in the activity I can see the url but its not showing in the app. however I also add another image url and its showing in the app.

this is the code of getting url image

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 + "\n");
                }
                result = sb.toString();
            } catch (Exception e) {
                // Oops
            }
            finally {
                try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
            }
            return result;
        }

this is uploading image

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

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

php file

$con = mysqli_connect($host,$uname,$pwd,$db);

$description= $_GET['description'];
$categorie= $_GET['categorie'];
$imageurl="www.justedhak.comlu.com/images/uploaded_images.jpg";
$image=$_POST['image'];



     $binary=base64_decode($image);
    header('Content-Type: bitmap; charset=utf-8');
    $file = fopen('uploaded_images.jpg', 'wb');
    fwrite($file, $binary);
    fclose($file);

$sql = "insert into image (description,categorie,path) values ('$categorie','$description','$imageurl')";
 if(mysqli_query($con,$sql)){
  echo 'success';
}
else{
echo 'failure';
  }
mysqli_close($con);

    echo 'Image upload complete!!, Please check your php file directory……';
BNK
  • 23,994
  • 8
  • 77
  • 87
Moudiz
  • 7,211
  • 22
  • 78
  • 156
  • Hey there! http://www.justedhak.comlu.com/uploaded_images1.jpg I've opened this link and gets back a white Screen. this one -> http://www.justedhak.comlu.com/uploaded_image.jpg displays an Android Image – Asis Oct 04 '15 at 09:43
  • Your uploaded image has 0 bytes of data, which means that your upload chain is not working properly (which upload script are you using server side? do you have set the permission to the upload script?) Post your `upload_image.php` – bonnyz Oct 04 '15 at 09:45
  • @bonnyz please check my edit , any advise is welcome. by the way I registered a new host. it needs till tomorow to get active – Moudiz Oct 04 '15 at 09:57
  • @Asis it was wrong link , I edit my question it is this link http://www.justedhak.comlu.com/images/uploaded_images.jpg – Moudiz Oct 04 '15 at 09:58
  • To handle images use Picasso in Android that works great. – Asis Oct 04 '15 at 10:07
  • @Asis I am using picasson in my listimageadapter – Moudiz Oct 04 '15 at 10:11
  • Do you mean that the file http://www.justedhak.comlu.com/images/uploaded_images.jpg is always not displayed in android app? – BNK Oct 04 '15 at 10:38
  • If I were you I would try to use OkHttpClient. It has a lot of options, it always worked out for me. Especially in combination with Picasso. – Andrei T Oct 04 '15 at 11:01
  • @WanaAnt I tried to use okhttp but I had problem with it http://stackoverflow.com/questions/32782219/what-is-the-reason-of-parameter-expected-in-okhttp If you know some examples about that tell me ill look at them – Moudiz Oct 04 '15 at 11:23
  • Does the logcat display any error ? – Satyen Udeshi Oct 04 '15 at 11:44
  • The URLs in the output of `http://justedhak.comlu.com/get-data.php` look like this: `www.justedhak.comlu.com\/images\/uploaded_images.jpg` Try to add an http:// and remove the backslashes ('\'). The URL should look like this: `http://www.justedhak.comlu.com/images/uploaded_images.jpg` – Torben Kohlmeier Oct 04 '15 at 11:47
  • @SatyenUdeshi hello no error displayed in logcat , the picasso is displaying empty image. – Moudiz Oct 04 '15 at 15:21
  • @TorbenKohlmeier sorry I didnt understand , what should I change? I added a system output to know what url I am getting and this is message `10-04 14:25:19.060: I/System.out(14944): www.justedhak.comlu.com/images/uploaded_images.jpg` – Moudiz Oct 04 '15 at 15:24

1 Answers1

2

UPDATE:

I have found the main reason that Picasso does not display your image is the image Url in your JSON does not start with http://.

Here is my working sample code (only for getting the image Url and displaying by Picasso, not including image uploading)

public class MainActivity extends AppCompatActivity {

    private final Context mContext = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final TextView textView = (TextView) findViewById(R.id.textView);
        final ImageView imageView = (ImageView) findViewById(R.id.imageView);
        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) {
                            // get only one element for testing display image
                            JSONObject jsonObject = jsonArray.getJSONObject(1);
                            if (jsonObject != null && !jsonObject.isNull("path")) {
                                String imagePath = jsonObject.getString("path");
                                if (imagePath != null && !imagePath.isEmpty()) {
                                    textView.setText(imagePath);
                                    Picasso.with(mContext).load("http://" + imagePath).into(imageView);
                                }
                            }
                        }
                    } catch (JSONException e) {
                        textView.setText(e.toString());
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                textView.setText(error.toString());
            }
        });

        queue.add(jsonObjectRequest);            
    }
}

And here is the result screenshot (you can pay attention to the textView's value, without http:// prefix)

BNK's screenshot

P/S: GET request works also (you can check by access the http://justedhak.comlu.com/get-data.php simply by any web browser such as Chrome)

To sum up, you will have 2 options:

  • Option 1: Update the image Urls in your server database so that all of them start with http://
  • Option 2: Check the image Urls in your android client code, if not started with http://, must add this prefix as in my above sample code

END OF UPDATE


I think you can try using HttpGet instead of HttpPost for getting the image Urls. I have just tried and get the following results;

{"result":[{"id":"1","name":null,"path":"http://api.androidhive.info/json/movies/1.jpg"},{"id":"2","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"28","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"27","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"26","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"25","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"24","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"23","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"22","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"21","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"20","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"19","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"},{"id":"18","name":null,"path":"www.justedhak.comlu.com/images/uploaded_images.jpg"}]}

Moreover, try using HttpUrlConnection, OkHttp... instead of Apache HttpClient because of its deprecation now.

Hope this helps!

BNK
  • 23,994
  • 8
  • 77
  • 87
  • I changed it to HttpGet and it didnt work , I cleard the cache. I add a system output and the url of the image is being passed to picasso . but the image is not loading. If you have any question tell me – Moudiz Oct 04 '15 at 11:20
  • Try using a simple ImageView instead of Picasso to check if the image can be displayed or not – BNK Oct 04 '15 at 11:50
  • is it ok if we go to a chat and give you my full code to try it on your side ? – Moudiz Oct 04 '15 at 15:26
  • You can post it to GitHub or Google Drive or OneDrive... so that I can download to check tomorrow morning, sorry I am busy to help my wife at this moment :) – BNK Oct 04 '15 at 15:31
  • 1
    I apreciat your support , if nobody here was able to help me ill post it to github tomorow thanks – Moudiz Oct 04 '15 at 15:32
  • 1
    wow it worked , your smart. thank you. I just wonder how did you found out. – Moudiz Oct 04 '15 at 17:46
  • This is the first time I use Picasso :). At first I hard-code the image Url you wrote at the beginning of your question and it worked (you see it is the full address, right?). Then, use Volley to get data from server, at first run, nothing displayed, must review carefully what is the difference and soon found :) – BNK Oct 04 '15 at 22:07
  • yes I had same problem with volley , weird why http:// is essential. anyway I have another problem still I didnt time to investigate maybe you can figure it out quickly. not all images are displaying , the url from justedhak.comlu.com one is displaying and the others not however the url from api.adroidhive is also displaying , should I add something in my code? – Moudiz Oct 05 '15 at 05:42
  • hehe you are right about that. ill post it a question now – Moudiz Oct 05 '15 at 05:50
  • I have to wait 3 hours till i able to give you the bounty. btw check my new question http://stackoverflow.com/questions/32942144/all-images-not-displaying-from-the-same-url – Moudiz Oct 05 '15 at 06:03