0

我目前正在做一个从php服务器检索数据的页面,现在尝试使用setImageResource从drawable中检索和图像但不工作,我不知道它有什么问题,我是否可以将图像名称保存在数据库中然后检索使用图像名称的图像?除此之外,我尝试为数量做一个简单的加减按钮,但是一旦我点击按钮,应用程序就会强制停止..

public class FoodDetailActivity extends Activity 
{
TextView FoodName;
TextView FoodDesc;
TextView FoodPrice;
ImageView FoodImg;
EditText Number;
Button plus;
Button minus;
Button Addcart;

String fid;
int number;

// Progress Dialog
private ProgressDialog pDialog;

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

// single product url
private static final String url_food_details = "http://10.0.2.2/android_user/FoodDetail.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_FOOD = "food";
private static final String TAG_FID = "fid";
private static final String TAG_FOODNAME = "food_name";
private static final String TAG_FOODPRICE = "food_price";
private static final String TAG_FOODDESCRIPTION = "food_description";
private static final String TAG_FOODURL = "food_url";

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


    // button
    plus = (Button)findViewById(R.id.btn_plus);
    plus.setOnClickListener(increase);
    minus = (Button)findViewById(R.id.btn_minus);
    minus.setOnClickListener(decrease);
    Addcart = (Button)findViewById(R.id.btn_submit);
    Number = (EditText)findViewById(R.id.text_number);

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

    // getting food id (fid) from intent
    fid = i.getStringExtra(TAG_FID);

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

// Increase number of quantity
    private OnClickListener increase = new OnClickListener()
    {
        public void onClick(View v) 
        {
            String quantity = Number.getText().toString().trim();
            number = Integer.parseInt(quantity);
            if(number > 0 && number < 99)
            {
                number = number + 1;
                Number.setText(Integer.toString(number));
            }
            else if(number == 99)
            {
                number = 1;
                Number.setText(Integer.toString(number));
            }
        }
    };
 // Decrease number of quantity
    private OnClickListener decrease = new OnClickListener()
    {
        public void onClick(View v) 
        {
            String quantity = Number.getText().toString();
            number = Integer.valueOf(quantity);
            if(number > 1 && number <= 99)
            {
                number = number - 1;
                Number.setText(Integer.toString(number));
            }
            else if(number == 1)
            {
                number = 99;
                Number.setText(Integer.toString(number));
            }
        }
    };

class GetFoodDetails extends AsyncTask<String, String, String> 
{
    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() 
    {
        super.onPreExecute();
        pDialog = new ProgressDialog(FoodDetailActivity.this);
        pDialog.setMessage("Loading food 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("fid", fid));

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

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

                    // json success tag
                    success = json.getInt(TAG_SUCCESS);

                    if (success == 1) 
                    {
                        // successfully received food details
                        JSONArray foodObj = json.getJSONArray(TAG_FOOD); // JSON Array

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

                        // Loader image - will be shown before loading image
                        int loader = R.drawable.loader;

                        String image_url = food.getString(TAG_FOODURL);

                        // product with this fid found
                        // Edit Text
                        FoodName = (TextView)findViewById(R.id.food_name);
                        FoodPrice = (TextView)findViewById(R.id.food_price);
                        FoodDesc = (TextView)findViewById(R.id.food_desc);
                        FoodImg = (ImageView)findViewById(R.id.img_food);

                        // display product data in EditText
                        FoodName.setText(food.getString(TAG_FOODNAME));
                        FoodPrice.setText("RM" + food.getString(TAG_FOODPRICE));
                        FoodDesc.setText(food.getString(TAG_FOODDESCRIPTION));

                        // ImageLoader class instance
                        ImageLoader imgLoader = new ImageLoader(getApplicationContext());

                        // display image
                        imgLoader.DisplayImage(image_url, loader, FoodImg);

                    }
                    else
                    {
                        // no food detail found
                        // Launch error message
                        AlertDialog.Builder ad = new AlertDialog.Builder(FoodDetailActivity.this);
                        ad.setTitle("Error");
                        ad.setMessage("Food Detail is empty!");
                        ad.setPositiveButton("OK", new DialogInterface.OnClickListener() 
                        {
                            public void onClick(DialogInterface dialoginterface, int i)
                            {

                            }
                        });
                        ad.show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        return null;
    }

    protected void onPostExecute(String file_url) 
    {
        // dismiss the dialog once got all details
        pDialog.dismiss();
    }
}

}

问题已经解决,我在服务器端使用 ImageLoader 检索图像,并将 url 存储在数据库中。

4

2 回答 2

2

在这里:

Drawable d = getResources().getDrawable(R.drawable.mcchicken); //<<<<

您正在尝试在onCreate调用之前使用 Activity 的上下文。在Activity 方法内部移动Drawable d初始化为:onCreatesetContentView

Drawable d; //<<< declare d here
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_food_detail);
    d = getResources().getDrawable(R.drawable.mcchicken);  //<< initialize d here
    ....
}

编辑 :doInBackground :您尝试访问 UI 元素的内部方法。而不是使用 doInBackground 更新 UI runOnUiThreadonPostExecute在 doInBackground 执行完成后,您将需要移动所有调用 UI 线程的 UI 相关代码。

于 2013-03-30T13:33:14.300 回答
1

在您的代码中有很多杂乱无章的材料。从一开始就很好。首先是唯一的问题。

为什么要放入doInBackground()方法runOnUiThread()?如果您想UI使用后台运行的任务中的一些信息来更新您的信息,为此您可以使用与 UI 线程同步并允许其更新的onProgressUpdate()或方法。doInBackground()方法直接指定用于后台处理,您不应该破坏它。onPostExecute()

Then this line:

if (food.getString(TAG_FOODNAME) == "McChicken")

will always return false because you are comparing references and not values. Always you are comparing strings, you have to use equals() method that makes a trick.

And last thing is this:

Drawable d = getResources().getDrawable(R.drawable.mcchicken);

You can't call that before setContentView() is called. Reason is that main purpose of setContentView() is that it creates all instances of UI elements and resources and if you something that requires resources call before this method, always you will get NPE

于 2013-03-30T13:38:49.387 回答