Android - 使用Picasso从JSON获取图像

时间:2017-07-26 07:42:25

标签: java android json picasso

我正在学习如何在Android Studio中使用JSON创建新闻应用程序,到目前为止应用程序正在工作,除非在获取图像时。我的代码有什么问题,有人可以帮我吗?

我已经在我的清单中使用了这些:

<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"/>

我也在我的gradle中使用了这个

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

这是我的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();
}

}

}

我想获得的onClickItem中的JSON对象示例:

{
"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"}

}

当我尝试调试它时,它总是像这样结束

enter image description here

修改

我找到了问题。

在“featured_image”对象中,网址正在使用HTTP。

但是当我尝试点击它时,它变成了HTTPS

有没有办法改变这个?

5 个答案:

答案 0 :(得分:2)

更改此行

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

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

更新

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

数据不是JSON数组中的对象。所以你可以得到这个

\eclipse\p2\org.eclipse.equinox.p2.repository\cache

您正在使用本地服务器来加载图片 的http://kawaiibeautyjapan.com/upload/article/pc/article_3255.jpg

请在JSON中从服务器端更新为https://kawaiibeautyjapan.com/upload/article/pc/article_3255.jpg

答案 1 :(得分:2)

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

}
}

答案 2 :(得分:1)

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

答案 3 :(得分:1)

尝试这种方式

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

答案 4 :(得分:1)

终于搞定了

这就是我做的事情

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

非常感谢你的帮助,伙计们。