android小程序之幸运菜谱
前言:刚刚结束短短5天的android公开课程,收获不少,写下来记录一下吧!(因为学校校企公开课的缘故才偶然接触的android,所以只学了这几天,不喜勿喷)
一开始得知这公开课最后得做个项目,还是挺懵逼的,不知道整啥。后来看了看聚合数据有啥免费的api,想了想寒假家里人老是问我今天吃啥,最后就有了做这个幸运菜谱的想法。
这app长啥样,下面这样:
第一张是主界面,输入你喜欢的一个数字(1-80000),然后就会在第二个界面返回对应的菜谱,你没看错(8万道菜,我一开始用这api的时候都惊呆了!)
接下来放上接口的代码和处理相应界面的java代码:
public class Juhedemo { //调用接口的代码
public static final String DEF_CHATSET = "UTF-8";
public static final int DEF_CONN_TIMEOUT = 30000;
public static final int DEF_READ_TIMEOUT = 30000;
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"; //配置您申请的KEY
public static final String APPKEY ="这就不能告诉你了,自己申请账号吧"; //4.按菜谱ID查看详细
public menubean getRequest4(String num){
menubean mu=new menubean();
String result =null;
String title,ingredient,burden;
ArrayList<String> b = new ArrayList<>();
String url ="http://apis.juhe.cn/cook/queryid";//请求接口地址
Map params = new HashMap();//请求参数
params.put("id",num);//菜谱的ID
params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
params.put("dtype","json");//返回数据的格式,xml或json,默认json
Log.e("MyLog","====num===="+num);
try {
result =net(url, params, "GET");
Log.e("MyLog","====result===="+result);
org.json.JSONObject object = new org.json.JSONObject(result);
if(object.getInt("error_code")==0){
org.json.JSONObject resultObject = object.getJSONObject("result");
org.json.JSONArray array = resultObject.getJSONArray("data");
mu.setTitle(array.getJSONObject(0).getString("title"));
mu.setIngredient(array.getJSONObject(0).getString("ingredients"));
mu.setBurden(array.getJSONObject(0).getString("burden"));
org.json.JSONObject o1=array.getJSONObject(0);
org.json.JSONArray a1=o1.getJSONArray("steps");
for(int i=0;i<a1.length();i++){
String step =a1.getJSONObject(i).getString("step");
b.add(step);
}
mu.setB(b);
}
// JSONObject object = JSONObject.fromObject(result);
// Log.e("MyLog","=====object==="+object);
// JSONObject ob=object.getJSONObject("result");
// JSONArray ob1=ob.getJSONArray("data");
// JSONObject o2=ob1.getJSONObject(0);
// JSONArray po=o2.getJSONArray("steps");
//
// if(object.getInt("error_code")==0){
// title=o2.getString("title");
// ingredient=o2.getString("ingredients");
// burden=o2.getString("burden");
// for(int i=0;i<po.size();i++){
//
// JSONObject u=po.getJSONObject(i);
//
// b[i]=(u.getString("step"));
//
// }
// mu.setTitle(title);
// mu.setIngredient(ingredient);
// mu.setBurden(burden);
// mu.setB(b);
//
// }else{
// System.out.println(object.get("error_code")+":"+object.get("reason"));
//
// } } catch (Exception e) {
e.printStackTrace();
Log.e("MyLog","====+error_code===="+e.getMessage());
}
return mu;
} /**
*
* @param strUrl 请求地址
* @param params 请求参数
* @param method 请求方法
* @return 网络请求字符串
* @throws Exception
*/
public static String net(String strUrl, Map params,String method) throws Exception {
HttpURLConnection conn = null;
BufferedReader reader = null;
String rs = null;
try {
StringBuffer sb = new StringBuffer();
if(method==null || method.equals("GET")){
strUrl = strUrl+"?"+urlencode(params);
}
Log.e("MyLog","----url------"+strUrl);
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
if(method==null || method.equals("GET")){
conn.setRequestMethod("GET");
}else{
conn.setRequestMethod("POST");
conn.setDoOutput(true);
}
conn.setRequestProperty("User-agent", userAgent);
conn.setUseCaches(false);
conn.setConnectTimeout(DEF_CONN_TIMEOUT);
conn.setReadTimeout(DEF_READ_TIMEOUT);
conn.setInstanceFollowRedirects(false);
conn.connect();
if (params!= null && method.equals("POST")) {
try {
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(urlencode(params));
} catch (Exception e) {
Log.e("MyLog","---- e------"+ e.getMessage());
}
}
InputStream is = conn.getInputStream();
rs = read(is);
// reader = new BufferedReader(new InputStreamReader(is));
// String strRead = null;
// while ((strRead = reader.readLine()) != null) {
// sb.append(strRead);
// }
// rs = sb.toString();
Log.e("MyLog","----rs------"+rs);
} catch (IOException e) {
Log.e("MyLog","----e------"+e.getMessage());
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
if (conn != null) {
conn.disconnect();
}
}
return rs;
} private static String read(InputStream is) throws IOException {
StringBuilder builder = new StringBuilder();
int byteCount = 0;
byte[] bytes = new byte[1024];
while ((byteCount = is.read(bytes)) != -1) {
String text = new String(bytes,0,byteCount);
Log.e("MyLog","----=======------"+ text);
builder.append(text);
}
Log.e("MyLog","----???????????------"+ builder.toString());
return builder.toString();
} //将map型转为请求参数型
public static String urlencode(Map<String,Object>data) {
StringBuilder sb = new StringBuilder();
for (Map.Entry i : data.entrySet()) {
try {
sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
这一部分当初遇到的问题是:我最初是用eclipse上调用接口测试的,一点问题都没有。后来把那部分代码放回到AS中就出问题了,总是数据获取不全,后来把json解析文件改了,就好了(上面注释部分就是之前的JSon解析代码)
public class MainActivity extends AppCompatActivity { //主界面
private EditText med;
private Button mb;
private List<Food> foodlist = new ArrayList<>(); @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initFoods();
FoodAdapter adapter = new FoodAdapter(MainActivity.this,R.layout.food,foodlist);
med=findViewById(R.id.edit_text);
mb=findViewById(R.id.button);
mb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String num=med.getText().toString();
Intent in=new Intent(MainActivity.this,DetailActivity.class);
in.putExtra("med",num);
startActivity(in);
}
});
EditText editText = (EditText) findViewById(R.id.edit_text); ListView listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(adapter);
}
private void initFoods(){
Food a = new Food(R.drawable.food1);
foodlist.add(a);
Food b= new Food(R.drawable.food2);
foodlist.add(b);
Food c= new Food(R.drawable.food3);
foodlist.add(c); }
}
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);
}
}
}
这就告一段落,接下来继续努力吧!(想知道自己幸运数字对应的是什么菜就给我留言,留下一个数字,我给你一道菜)