php - Android应用程序无法连接到MySQL数据库

标签 php android mysql android-listview

我有以下代码,用于访问本地数据库并返回单个值(出于测试目的,该值是“烤宽面条”。它应该返回它并使其成为列表中项目的名称。 访问 Activity 时应用程序崩溃。

我真的陷入困境,任何帮助都会很棒。

public class RecipeMethodActivity extends ListActivity {

Intent myIntent;
String value;
TextView editvalue;
TextView buttonPressed;
Intent intent;
String result = null;
InputStream is = null;
StringBuilder sb=null;
String result2 = null;


final Recipe[] mRecipesArray = {    new Recipe("Lasagna",  new String[]{"1 Brown lean ground beef in skillet until lightly browned and cooked through. Put a few layers of paper towels in large bowl. With slotted spoon, remove browned beef from skillet draining off excess beef fat and put on top of blotting towels. After all the browned beef has been removed from the skillet, drain off and dispose of excess beef fat. Wipe skillet clean with paper towel. (If your ground beef is sufficiently lean, there will not be any excess fat to drain.)Add diced green pepper and onion to skillet. Brown for a few minutes on medium high heat. Add the garlic and cook for 30 seconds more. Add browned beef back to the skillet, lower the heat to low and continue to cook for 5 more minutes stirring frequently.", 
                                                "2 Transfer browned beef, green pepper and onions to 3 Qt. pot. Add tomato sauce, tomato paste. Open stewed tomatoes and dice, then add to 3 Qt. pot. Add oregano, parsley, Italian Spice Mix to taste, probably 2 teaspoons of each. Add a pinch of garlic powder and a pinch of garlic salt, to taste. Add a dash of white wine vinegar. Add sugar a tablespoon at a time, until desired level of sweetness, no more than 1/4 cup of sugar. Note that it is hard to follow a pure recipe when it comes to pasta sauce. One Italian spice mix is not like the other, nor is one can of tomato sauce not like the other. So you really do need to taste the sauce as you are adding the spices, sugar and vinegar. Stir and allow sauce to simmer 15-45 minutes to thicken (do not scorch bottom, stir frequently). Remove from heat.",
                                                "3 Cook lasagna noodles in 6 Qt. Pot per cooking directions (al dente). (Note noodles may be cooked in advance.) Stir often to prevent from sticking and be sure that water remains at a boil during the entire cooking to prevent noodles from sticking. I add Tbsp of salt to the water so the noodles are more flavorful. Drain in colander and place in a cool water filled pan to keep from drying out and sticking together.",
                                                "4 In dry lasagna pan, ladle one cup of sauce and spread along the bottom of the pan. Apply a layer noodles 3 length wise (edges overlapping). Ladle in sauce sparingly into center trough of 3 noodles. Apply a layer of mozzarella cheese slices on top of lasagna sauce. Place ricotta cheese dollops every 2 inches in center of noodles on top of mozzarella cheese slices, sprinkle grated parmesan cheese in thin even layer on top of ricotta cheese. Apply second layer of noodles, topping again with sauce and cheese. Finish with another layer of noodles. If you have extra sauce and cheese you can spread that over the top. Tent lasagna pan with aluminum foil (not touching noodles or sauce). Bake at 375°F for 45 minutes. Allow to cool before serving."}),
                                    new Recipe(result, new String[]{"GlaDOS' wit","Is a lie"}),
                                    new Recipe("EarthDestruction", new String[]{"Asteroid", "Kinetic energy"})};

public class Recipe{
    public String name;
    public String[] steps;

    Recipe(String name, String[] steps){
        this.name = name;
        this.steps = steps;
    }
}

public ArrayList<String> FetchRecipesRawArray(Recipe[] recipes){
    ArrayList<String> ret = new ArrayList<String>();
    for(int i=0;i<recipes.length;i++){
        ret.add(recipes[i].name);
    }
    return ret;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);    

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, FetchRecipesRawArray(mRecipesArray));
    setListAdapter(adapter); 

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

    try{
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://127.0.0.1/index.php");
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();
                }catch(Exception e){
                    Log.e("log_tag", "Error in http connection"+e.toString());
                }
                //convert response to string
                try{
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                    sb = new StringBuilder();
                    sb.append(reader.readLine() + "\n");
                    String line="0";
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    is.close();
                    result=sb.toString();
                    Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
                }catch(Exception e){
                    Log.e("log_tag", "Error converting result "+e.toString());
                }
                //paring data
                String fd_name;
                try{
                    JSONArray jArray = new JSONArray(result);
                    JSONObject json_data=null;
                    for(int i=0;i<jArray.length();i++){
                        json_data = jArray.getJSONObject(i);
                        fd_name=json_data.getString("recipename");
                    }
                }catch(JSONException e1){
                    Toast.makeText(getBaseContext(), "No Food Found", Toast.LENGTH_LONG).show();
                }catch (ParseException e1){
                    e1.printStackTrace();
                }



}

protected void onListItemClick(ListView l, View v, int position, long id){
    Intent intent = new Intent(this, MethodActivity.class);
    intent.putExtra(MethodActivity.EXTRA_RECIPEARRAY, mRecipesArray[position].steps);
    startActivity(intent);

}
}  

即使数据库中有数据,我也遇到无法检索数据的错误。可能是什么问题?

我的 PHP 是:

<?php
mysql_connect("localhost","root","michael2020");
mysql_select_db("finalyearproject");

$q=mysql_query("SELECT recipename FROM recipes WHERE     recipename>'".$_REQUEST['value']."'");
while($e=mysql_fetch_assoc($q))
    $output[]=$e;

print(json_encode($output));

mysql_close();
?>

最佳答案

试试这个吧。

$q=mysql_query("SELECT recipename as recipe FROM recipes WHERE     recipename>'".$_REQUEST['value']."'");

while($e=mysql_fetch_assoc($q))
    $output=$e['recipe'];

print(json_encode($output));

关于php - Android应用程序无法连接到MySQL数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10406370/

相关文章:

php - 按名称分组,但保留与名称关联的所有标签

php - 当数量超过 1 时,在 Woocommerce 中将购物车商品分开

java - 应用程序意外停止错误

php - 使用php填写下拉选择的值

PHP : How to use alert() before header ('location:http://domain.com' );

php - 创建 DOMDocument : match one certain element in a PHP-parser

java - 应用 BlurMaskFilter 时 TextView 被切断

选择了默认选项的 Android 铃声选择器列表

php - 使用内部连接连接 mysql 更新中的字段名称

mysql - 如何将 ADO.NET DbProviderFactory 与 MySQL 一起使用?