2012-05-02 95 views
0

我有以下代碼是爲了訪問本地數據庫並返回一個值(用於測試目的,值爲'lasagna'),它應該返回並使其名稱爲在列表中Android應用程序無法連接到MySQL數據庫

我真的卡住,任何幫助將是巨大的項目。 當活動被訪問的應用程序崩潰。

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(); 
?> 
+0

我不確定android是否理解或有路由到主機的127.0.0.1。 AFAIK,當指向127.0.0.1時,它將指向設備本身。 – ariefbayu

+0

是的,現在已經更改爲10.0.2.2。現在它運行,但是當它應該返回一個值時,它說什麼都沒有。我相信我的PHP沒有正常運行。我怎麼知道它是? –

+0

'我怎麼知道它是什麼?'怎麼樣,在瀏覽器上運行URL並查看結果?並檢查日誌(錯誤和訪問日誌)。 – ariefbayu

回答

1

只是試試這一個。

$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)); 
相關問題