从 JSON 加载 Picasso 中的图像

Load image in Picasso from JSON

我想从存储在 MySQL 数据库中的 url 中加载 Picasso 中的图像。
但是返回的代码在 JSON 中,我无法让它工作。

当直接使用 link 而不是 TAG_IMAGE 时,它显示的图像没有任何问题(因此 picasso 本身正在使用字符串)。

如何将 JSON 解析为字符串,以便 Picasso 可以加载它?

编辑 TAG_IMAGE 需要转换为字符串(Punit 回答)。

代码:

import ...

public class ViewRecipeActivity extends Activity {

TextView txtName;
TextView txtTime;
TextView txtPrice;
TextView txtDesc;
ImageView imagePhoto;
TextView txtCreatedAt;

String pid;

// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

// single product url
private static final String url_recipe_details = "phpfiletoloadall.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_RECIPE = "recipes";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_TIME = "time";
private static final String TAG_PRICE = "price";
private static final String TAG_IMAGE = "image";
private static final String TAG_DESCRIPTION = "description";

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

    //toolbar back button
    ImageView btnBack = findViewById( R.id.btnBack );
    btnBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick (View view) {
            startActivity(new Intent(ViewRecipeActivity.this, ActivityTwo.class));
            finish();
            }
            }
    );


    BottomNavigationView bottomNavigationView = (BottomNavigationView)      findViewById(R.id.bottomNavView_Bar);
    BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
    Menu menu = bottomNavigationView.getMenu();
    MenuItem menuItem = menu.getItem(2);
    menuItem.setChecked(true);

    bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()){
                case R.id.ic_home:
                    Intent intent0 = new Intent(ViewRecipeActivity.this, MainActivity.class);
                    startActivity(intent0);
                    finish();
                    break;

                case R.id.ic_ingredients:
                    Intent intent1 = new Intent(ViewRecipeActivity.this, ActivityOne.class);
                    startActivity(intent1);
                    finish();
                    break;

                case R.id.ic_dining:

                    break;

                case R.id.ic_center_focus:
                    Intent intent3 = new Intent(ViewRecipeActivity.this, ActivityThree.class);
                    startActivity(intent3);
                    finish();
                    break;

                case R.id.ic_backup:
                    Intent intent4 = new Intent(ViewRecipeActivity.this, ActivityFour.class);
                    startActivity(intent4);
                    finish();
                    break;
            }


            return false;
        }
    });

    //Make network connect access (temp)
    StrictMode.ThreadPolicy policy = new
            StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    // Make textview scrollable
    TextView textView = (TextView) findViewById(R.id.inputDesc);
    textView.setMovementMethod(new ScrollingMovementMethod());

    // getting product details from intent
    Intent i = getIntent();

    // getting product id (pid) from intent
    pid = i.getStringExtra(TAG_PID);

    // Getting complete product details in background thread
    new GetProductDetails().execute();

    }
    /**
 * Background Async Task to Get complete product details
 * */
class GetProductDetails extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ViewRecipeActivity.this);
        pDialog.setMessage("Loading recipe details. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Getting product details in background thread
     * */
    protected String doInBackground(String... params) {


        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                // Check for success tag
                int success;
                try {

                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("pid", pid));

                    // getting product details by making HTTP request
                    // Note that product details url will use GET request
                    JSONObject json = jsonParser.makeHttpRequest(
                            url_recipe_details, "GET", params);


                    // check your log for json response
                    Log.d("Single Recipe Details", json.toString());

                    // json success tag
                    success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        // successfully received product details
                        JSONArray productObj = json
                                .getJSONArray(TAG_RECIPE); // JSON Array

                        // get first product object from JSON Array
                        JSONObject product = productObj.getJSONObject(0);

                        // product with this pid found
                        // Edit Text
                        txtName = (TextView) findViewById(R.id.inputName);
                        txtDesc = (TextView) findViewById(R.id.inputDesc);
                        imagePhoto = (ImageView) findViewById( R.id.imagePhoto );

                        // display product data in EditText
                        txtName.setText(product.getString(TAG_NAME));
                        txtDesc.setText(product.getString(TAG_DESCRIPTION));
                        Picasso.get().load(TAG_IMAGE).into(imagePhoto);

                        Log.d("good", "shows recipe");
                    }else{
                        // product with pid not found
                        Log.d("bad", "recipe not found");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        return null;

    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once got all details
        pDialog.dismiss();
    }
}
}

您正在使用 TAG_IMAGE,它是标签的 String 变量名。因此,您必须像获取名称 TAG_NAME 和描述 TAG_DESCRIPTION.

一样使用此标签从 json 获取图像 url

获取图像 Url

String imageUrl = product.getString(TAG_IMAGE);
Picasso.get().load(imageUrl).into(imagePhoto);
 if (success == 1) {
                    // successfully received product details
                    JSONArray productObj = json
                            .getJSONArray(TAG_RECIPE); // JSON Array

                    // get first product object from JSON Array
                    JSONObject product = productObj.getJSONObject(0);

                    // product with this pid found
                    // Edit Text
                    txtName = (TextView) findViewById(R.id.inputName);
                    txtDesc = (TextView) findViewById(R.id.inputDesc);
                    imagePhoto = (ImageView) findViewById( R.id.imagePhoto );

                    // display product data in EditText
                    txtName.setText(product.getString(TAG_NAME));
                    txtDesc.setText(product.getString(TAG_DESCRIPTION));
                    Picasso.get().load(product.getString(TAG_IMAGE)).into(imagePhoto);

                    Log.d("good", "shows recipe");
                }

这很容易,

 Picasso.with(this)
 .load(TAG_IMAGE)
 .error(R.mipmap.no_image_available)
 .into(imagePhoto);

当您的图片未加载时,出现一些错误,此时显示错误部分

你可以使用它

   Picasso.with(this)
   .load(TAG_IMAGE)
   .into(imagePhoto);