android小程序之幸运菜谱

android小程序之幸运菜谱

前言:刚刚结束短短5天的android公开课程,收获不少,写下来记录一下吧!(因为学校校企公开课的缘故才偶然接触的android,所以只学了这几天,不喜勿喷)

一开始得知这公开课最后得做个项目,还是挺懵逼的,不知道整啥。后来看了看聚合数据有啥免费的api,想了想寒假家里人老是问我今天吃啥,最后就有了做这个幸运菜谱的想法。

这app长啥样,下面这样:

 

第一张是主界面,输入你喜欢的一个数字(1-80000),然后就会在第二个界面返回对应的菜谱,你没看错(8万道菜,我一开始用这api的时候都惊呆了!)

接下来放上接口的代码和处理相应界面的java代码:

  1 public class Juhedemo {   //调用接口的代码
  2     public static final String DEF_CHATSET = "UTF-8";
  3     public static final int DEF_CONN_TIMEOUT = 30000;
  4     public static final int DEF_READ_TIMEOUT = 30000;
  5     public static String userAgent =  "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
  6 
  7     //配置您申请的KEY
  8     public static final String APPKEY ="这就不能告诉你了,自己申请账号吧";
  9 
 10     //4.按菜谱ID查看详细
 11     public  menubean getRequest4(String num){
 12         menubean mu=new menubean();
 13         String result =null;
 14         String title,ingredient,burden;
 15         ArrayList<String> b = new ArrayList<>();
 16         String url ="http://apis.juhe.cn/cook/queryid";//请求接口地址
 17         Map params = new HashMap();//请求参数
 18         params.put("id",num);//菜谱的ID
 19         params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
 20         params.put("dtype","json");//返回数据的格式,xml或json,默认json
 21         Log.e("MyLog","====num===="+num);
 22         try {
 23             result =net(url, params, "GET");
 24             Log.e("MyLog","====result===="+result);
 25             org.json.JSONObject object = new org.json.JSONObject(result);
 26             if(object.getInt("error_code")==0){
 27                 org.json.JSONObject resultObject = object.getJSONObject("result");
 28                 org.json.JSONArray array = resultObject.getJSONArray("data");
 29                 mu.setTitle(array.getJSONObject(0).getString("title"));
 30                 mu.setIngredient(array.getJSONObject(0).getString("ingredients"));
 31                 mu.setBurden(array.getJSONObject(0).getString("burden"));
 32                 org.json.JSONObject o1=array.getJSONObject(0);
 33                 org.json.JSONArray a1=o1.getJSONArray("steps");
 34                 for(int i=0;i<a1.length();i++){
 35                    String step  =a1.getJSONObject(i).getString("step");
 36                    b.add(step);
 37                 }
 38                 mu.setB(b);
 39             }
 40 //            JSONObject object = JSONObject.fromObject(result);
 41 //            Log.e("MyLog","=====object==="+object);
 42 //            JSONObject ob=object.getJSONObject("result");
 43 //            JSONArray ob1=ob.getJSONArray("data");
 44 //            JSONObject o2=ob1.getJSONObject(0);
 45 //            JSONArray po=o2.getJSONArray("steps");
 46 //
 47 //            if(object.getInt("error_code")==0){
 48 //                    title=o2.getString("title");
 49 //                    ingredient=o2.getString("ingredients");
 50 //                    burden=o2.getString("burden");
 51 //                    for(int i=0;i<po.size();i++){
 52 //
 53 //                        JSONObject u=po.getJSONObject(i);
 54 //
 55 //                        b[i]=(u.getString("step"));
 56 //
 57 //                    }
 58 //                mu.setTitle(title);
 59 //                mu.setIngredient(ingredient);
 60 //                mu.setBurden(burden);
 61 //                mu.setB(b);
 62 //
 63 //            }else{
 64 //                System.out.println(object.get("error_code")+":"+object.get("reason"));
 65 //
 66 //            }
 67 
 68         } catch (Exception e) {
 69             e.printStackTrace();
 70             Log.e("MyLog","====+error_code===="+e.getMessage());
 71         }
 72         return mu;
 73     }
 74 
 75     /**
 76      *
 77      * @param strUrl 请求地址
 78      * @param params 请求参数
 79      * @param method 请求方法
 80      * @return  网络请求字符串
 81      * @throws Exception
 82      */
 83     public static String net(String strUrl, Map params,String method) throws Exception {
 84         HttpURLConnection conn = null;
 85         BufferedReader reader = null;
 86         String rs = null;
 87         try {
 88             StringBuffer sb = new StringBuffer();
 89             if(method==null || method.equals("GET")){
 90                 strUrl = strUrl+"?"+urlencode(params);
 91             }
 92             Log.e("MyLog","----url------"+strUrl);
 93             URL url = new URL(strUrl);
 94             conn = (HttpURLConnection) url.openConnection();
 95             if(method==null || method.equals("GET")){
 96                 conn.setRequestMethod("GET");
 97             }else{
 98                 conn.setRequestMethod("POST");
 99                 conn.setDoOutput(true);
100             }
101             conn.setRequestProperty("User-agent", userAgent);
102             conn.setUseCaches(false);
103             conn.setConnectTimeout(DEF_CONN_TIMEOUT);
104             conn.setReadTimeout(DEF_READ_TIMEOUT);
105             conn.setInstanceFollowRedirects(false);
106             conn.connect();
107             if (params!= null && method.equals("POST")) {
108                 try {
109                     DataOutputStream out = new DataOutputStream(conn.getOutputStream());
110                     out.writeBytes(urlencode(params));
111                 } catch (Exception e) {
112                     Log.e("MyLog","---- e------"+ e.getMessage());
113                 }
114             }
115             InputStream is = conn.getInputStream();
116             rs = read(is);
117 //            reader = new BufferedReader(new InputStreamReader(is));
118 //            String strRead = null;
119 //            while ((strRead = reader.readLine()) != null) {
120 //                sb.append(strRead);
121 //            }
122 //            rs = sb.toString();
123             Log.e("MyLog","----rs------"+rs);
124         } catch (IOException e) {
125             Log.e("MyLog","----e------"+e.getMessage());
126             e.printStackTrace();
127         } finally {
128             if (reader != null) {
129                 reader.close();
130             }
131             if (conn != null) {
132                 conn.disconnect();
133             }
134         }
135         return rs;
136     }
137 
138     private static String read(InputStream is) throws IOException {
139         StringBuilder builder = new StringBuilder();
140         int byteCount = 0;
141         byte[] bytes = new byte[1024];
142         while ((byteCount = is.read(bytes)) != -1) {
143             String text = new String(bytes,0,byteCount);
144             Log.e("MyLog","----=======------"+ text);
145             builder.append(text);
146         }
147         Log.e("MyLog","----???????????------"+ builder.toString());
148         return builder.toString();
149     }
150 
151     //将map型转为请求参数型
152     public static String urlencode(Map<String,Object>data) {
153         StringBuilder sb = new StringBuilder();
154         for (Map.Entry i : data.entrySet()) {
155             try {
156                 sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
157             } catch (UnsupportedEncodingException e) {
158                 e.printStackTrace();
159             }
160         }
161         return sb.toString();
162     }
163 }

这一部分当初遇到的问题是:我最初是用eclipse上调用接口测试的,一点问题都没有。后来把那部分代码放回到AS中就出问题了,总是数据获取不全,后来把json解析文件改了,就好了(上面注释部分就是之前的JSon解析代码)

 1 public class MainActivity extends AppCompatActivity {   //主界面
 2 private EditText med;
 3 private Button mb;
 4     private List<Food> foodlist = new ArrayList<>();
 5 
 6     @Override
 7     protected void onCreate(Bundle savedInstanceState) {
 8         super.onCreate(savedInstanceState);
 9         setContentView(R.layout.activity_main);
10         initFoods();
11         FoodAdapter adapter = new FoodAdapter(MainActivity.this,R.layout.food,foodlist);
12         med=findViewById(R.id.edit_text);
13         mb=findViewById(R.id.button);
14         mb.setOnClickListener(new View.OnClickListener() {
15             @Override
16             public void onClick(View view) {
17                 String num=med.getText().toString();
18                 Intent in=new Intent(MainActivity.this,DetailActivity.class);
19                 in.putExtra("med",num);
20                 startActivity(in);
21             }
22         });
23         EditText editText = (EditText) findViewById(R.id.edit_text);
24 
25         ListView listView = (ListView) findViewById(R.id.list_view);
26         listView.setAdapter(adapter);
27     }
28     private  void initFoods(){
29         Food a = new Food(R.drawable.food1);
30         foodlist.add(a);
31         Food b= new Food(R.drawable.food2);
32         foodlist.add(b);
33         Food c= new Food(R.drawable.food3);
34         foodlist.add(c);
35 
36     }
37 }

public class DetailActivity extends AppCompatActivity {  //显示界面
    private TextView tv,tv2,tv3,tv4;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        tv=findViewById(R.id.tvTitle);
        tv2=findViewById(R.id.tvIngredients);
        tv3=findViewById(R.id.tvBunder);
        tv4=findViewById(R.id.tvSteps);
        Intent f= getIntent();
        String ji=f.getStringExtra("med");
        new NetworkTask().execute(ji);


    }

    private class NetworkTask extends AsyncTask<String,Void,menubean>{
        @Override
        protected menubean doInBackground(String... ji) {

            Juhedemo nu2=new Juhedemo();
            menubean kk=nu2.getRequest4(ji[0]);
            Log.e("MyLog","========"+kk);
//            String title2=kk.getTitle();
            return kk;
        }

        @Override
        protected void onPostExecute(menubean kk) {
            ArrayList<String> ad=new ArrayList<String>();
            String dg="";
            ad=kk.getB();
            for(int i=0;i<ad.size();i++){
                dg=dg+ad.get(i);
            }

            super.onPostExecute(kk);
            tv.setText(kk.getTitle());
            tv2.setText(kk.getIngredient());
            tv3.setText(kk.getBurden());
            tv4.setText(dg);
        }
    }
}

这就告一段落,接下来继续努力吧!(想知道自己幸运数字对应的是什么菜就给我留言,留下一个数字,我给你一道菜

posted @ 2018-03-10 09:42  xtu熊大  阅读(703)  评论(2编辑  收藏  举报