简体   繁体   中英

Android - get image from JSON using Picasso

I'm learning about creating a news app in Android Studio with JSON and so far the app is working except when fetching the image. Is there something wrong with my codes and can anyone help me with it?

I already used these in my manifest:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

I also used this in my gradle

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

and here's my java

Detail.java

import...

public class Detail extends Activity{

public ImageLoader imageLoader;{
    imageLoader = new ImageLoader(null);
}

JSONArray string_json = null;
String idkbj;
private ProgressDialog progressDialog;

JSONParser jsonParser = new JSONParser();
public static final String TAG_ID = "id";
public static final String TAG_CAT = "category";
public static final String TAG_TITLE = "title";
public static final String TAG_AUTHOR = "author";
public static final String TAG_DATE = "date";
public static final String TAG_CON = "content";
public static final String TAG_IMG = "featured_image";
public static final String TAG_DATE_CRE = "date_created";

private  static final String url_kbj = "https://api.url_api_here";

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.single_list_item);

    Intent i = getIntent();
    idkbj = i.getStringExtra(TAG_ID);
    Toast.makeText(getApplicationContext(), "id berita = " + idkbj,  Toast.LENGTH_SHORT).show();
    new GetDetail().execute();
}

class GetDetail extends AsyncTask<String,String, String>{
    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        progressDialog = new ProgressDialog(Detail.this);
        progressDialog.setMessage("loading...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(true);
        progressDialog.show();

    }

    protected String doInBackground(String... params){
        try{
            List<NameValuePair> params1 = new ArrayList<>();
            params1.add(new BasicNameValuePair("id", idkbj));
            final JSONObject json = jsonParser.makeHttpRequest(url_kbj + "/" + idkbj + "/", "GET", params1);
            //Log.i("jsonda =", String.valueOf(json));
            final JSONObject data = json.getJSONObject("data");
            //Log.e("json2 =", String.valueOf(data));
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ImageView thumb_img = (ImageView) findViewById(R.id.featured_image);
                    TextView title = (TextView) findViewById(R.id.title);
                    //TextView id = (TextView) findViewById(R.id.id);
                    TextView category = (TextView) findViewById(R.id.category);
                    TextView author = (TextView) findViewById(R.id.author);
                    TextView date = (TextView) findViewById(R.id.date);
                    TextView content = (TextView) findViewById(R.id.content);

                    try{

                        String cat_d = data.getString(TAG_CAT);
                        String tit_d = data.getString(TAG_TITLE);
                        String aut_d = data.getString(TAG_AUTHOR);
                        String con_d = data.getString(TAG_CON);
                        String url_detail_img = data.getString(TAG_IMG);

                        JSONObject date_cre = data.getJSONObject(TAG_DATE_CRE);
                        String date_d = date_cre.getString(TAG_DATE);

                        category.setText(cat_d);
                        title.setText(tit_d);
                        author.setText(aut_d);
                        content.setText(con_d);
                        date.setText(date_d);

                        Picasso.with(getApplicationContext())
                                .load(url_detail_img)
                                .error(R.drawable.temp_img)
                                .into(thumb_img);

                        Log.d("detail image = ", url_detail_img);
                    }
                    catch (JSONException e){
                        e.printStackTrace();
                    }
                    catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
        }
        catch (JSONException e){
            e.printStackTrace();
        }
        return null;
    }
    protected void onPostExecute(String file_url){
        progressDialog.dismiss();
}

}

}

JSON object example in onClickItem that I want to get:

{
"data": 
 {
  "id": 3255,
  "permalink": "http://kawaiibeautyjapan.com/article/3255/5-tips-diet-mudah-yang-bisa-kamu-lakukan-bersama-pasanganmu",
  "slug": "5-tips-diet-mudah-yang-bisa-kamu-lakukan-bersama-pasanganmu",
  "title": "5 Tips Diet Mudah yang Bisa Kamu Lakukan Bersama Pasanganmu",
"featured_image": "http://kawaiibeautyjapan.com/upload/article/pc/article_3255.jpg"}

}

when I try to debug it, it always ends up like this

在此处输入图片说明

EDIT

I sort of find the problem.

in "featured_image" object, the url is using HTTP.

but when I tried to click it, it turns into HTTPS

is there any way to change this?

change this line

 Picasso.with(getApplicationContext())
                            .load(url_detail_img)
                            .error(R.drawable.temp_img)
                            .into(thumb_img);

to

 Picasso.with(YourActivityName.this)
                            .load(url_detail_img)
                            .error(R.drawable.temp_img)
                            .into(thumb_img);

updated

final JSONObject data = json.getJSONObject("data");

data is not object in your JSON it's array. so you can get this like

final JSONArray data = json.getJSONArray("data");
final JSONObject dataObject = json.getJSONObject(0);
String img_url = dataObject.getString(TAG_IMG);

you are using local server for load image " http://kawaiibeautyjapan.com/upload/article/pc/article_3255.jpg "

please update this to " https://kawaiibeautyjapan.com/upload/article/pc/article_3255.jpg " from server side in JSON

import...

public class Detail extends Activity{

public ImageLoader imageLoader;{
    imageLoader = new ImageLoader(null);
}

JSONArray string_json = null;
String idkbj;
private ProgressDialog progressDialog;

JSONParser jsonParser = new JSONParser();
public static final String TAG_ID = "id";
public static final String TAG_CAT = "category";
public static final String TAG_TITLE = "title";
public static final String TAG_AUTHOR = "author";
public static final String TAG_DATE = "date";
public static final String TAG_CON = "content";
public static final String TAG_IMG = "featured_image";
public static final String TAG_DATE_CRE = "date_created";

private  static final String url_kbj = "https://api.url_api_here";

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.single_list_item);

    Intent i = getIntent();
    idkbj = i.getStringExtra(TAG_ID);
    Toast.makeText(getApplicationContext(), "id berita = " + idkbj,  Toast.LENGTH_SHORT).show();
    new GetDetail().execute();
}

class GetDetail extends AsyncTask<String,String, String>{
    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        progressDialog = new ProgressDialog(Detail.this);
        progressDialog.setMessage("loading...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(true);
        progressDialog.show();

    }

    protected String doInBackground(String... params){
        try{
            List<NameValuePair> params1 = new ArrayList<>();
            params1.add(new BasicNameValuePair("id", idkbj));
            final JSONObject json = jsonParser.makeHttpRequest(url_kbj + "/" + idkbj + "/", "GET", params1);
            //Log.i("jsonda =", String.valueOf(json));
            final JSONArray data = json.getJSONArray("data");
            final JSONObject object = data.getJSONObject(0);
            //Log.e("json2 =", String.valueOf(data));
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ImageView thumb_img = (ImageView) findViewById(R.id.featured_image);
                    TextView title = (TextView) findViewById(R.id.title);
                    //TextView id = (TextView) findViewById(R.id.id);
                    TextView category = (TextView) findViewById(R.id.category);
                    TextView author = (TextView) findViewById(R.id.author);
                    TextView date = (TextView) findViewById(R.id.date);
                    TextView content = (TextView) findViewById(R.id.content);

                    try{

                        String cat_d = object.getString(TAG_CAT);
                        String tit_d = object.getString(TAG_TITLE);
                        String aut_d = object.getString(TAG_AUTHOR);
                        String con_d = object.getString(TAG_CON);
                        String url_detail_img = object.getString(TAG_IMG);

                        JSONObject date_cre = object.getJSONObject(TAG_DATE_CRE);
                        String date_d = date_cre.getString(TAG_DATE);

                        category.setText(cat_d);
                        title.setText(tit_d);
                        author.setText(aut_d);
                        content.setText(con_d);
                        date.setText(date_d);

                        Picasso.with(getApplicationContext())
                                .load(url_detail_img)
                                .error(R.drawable.temp_img)
                                .into(thumb_img);

                        Log.d("detail image = ", url_detail_img);
                    }
                    catch (JSONException e){
                        e.printStackTrace();
                    }
                    catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
        }
        catch (JSONException e){
            e.printStackTrace();
        }
        return null;
    }
    protected void onPostExecute(String file_url){
        progressDialog.dismiss();
}

}
}
public class MainActivity extends AppCompatActivity {

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

         imageView = (ImageView) findViewById(R.id.imageView);
        new LoadImage().execute();

    }

    public class LoadImage extends AsyncTask<Void , Void , Void>{

        @Override
        protected Void doInBackground(Void... params) {

            //do network operations to get the response string 

            //Get JSON Object here
            JSONObject jsonObject = new JSONObject("the response string");
            final String url  = jsonObject.getString("featured_image");

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Picasso.with(getApplicationContext()).load(url).into(imageView);
                }
            });


            return null;
        }
    }
}

Try in this way

if(!TextUtils.isEmpty(url_detail_img)){
                Picasso.with(YourActivityname.this)
                        .load(url_detail_img)
                        .into(thumb_img );
            }

finally got it working

here's what I do

URL aURL = new URL(url_detail_img);
String image_url = "https://"+ aURL.getHost() + aURL.getFile();
imageLoader.DisplayImage(data.getString(TAG_IMG), thumb_img);

                        Picasso.with(Detail.this)
                                .load(image_url)
                                .error(R.drawable.temp_img)
                                .into(thumb_img);

thanks anyways for all your help, guys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM