从JSON加载Picasso中的图像

问题描述 投票:-1回答:4

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

当放置直接链接而不是TAG_IMAGE时,它会显示一个没有任何问题的图像(因此毕加索本身正在使用字符串)。

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

EDIT TAG_IMAGE需要转换为String(由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();
    }
}
}
android json string crud picasso
4个回答
0
投票
 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");
                }

0
投票

您正在使用TAG_IMAGE这是String变量名称的标签。因此,您必须使用此标记从json获取图像URL,就像获取名称TAG_NAME和描述TAG_DESCRIPTION一样。

获取图片网址

String imageUrl = product.getString(TAG_IMAGE);
Picasso.get().load(imageUrl).into(imagePhoto);

0
投票

这很容易,

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

当你的图像没有加载,并得到一些错误时,显示错误部分


0
投票

你可以使用它

   Picasso.with(this)
   .load(TAG_IMAGE)
   .into(imagePhoto);
© www.soinside.com 2019 - 2024. All rights reserved.