[安卓] JSON仲机器人 – 部分 4: 处理Java中检索JSON
您揭示, 规定为这将是该系列的最后部分 JSON仲机器人. 我们会写笔记Java代码的处理,最重要的是,我们已经采取了从上一节的输出JSON.
更新: 21/08/2015 – 优化代码.
我们的Java结构包括下列文件 (由于其相对小的数量的文件没有分类为包).
写作课配置, 准备
说出来有点混乱,但实际上这. 我们需要一些常数,以节省一定的值,它是在课堂上 在哪里. 为了便于操作使用对象 “昔日的恋人” 那么我们就需要有一个类 情夫. 并检索JSON下来,我们需要工人阶级LoadJson.
建设常数
package cachhoc.net.demojson; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.widget.Toast; public class Var { // const for load and put data with server public static final String KEY_METHOD = "method"; public static final String KEY_NICK = "nick"; public static final String KEY_PASS = "pass"; public static final String KEY_ID = "id"; public static final String KEY_NAME = "name"; public static final String KEY_PHONE = "phone"; public static final String KEY_BEGIN_DATE = "begin_date"; public static final String KEY_END_DATE = "end_date"; public static final String KEY_LOGIN = "login"; public static final String KEY_REGISTER = "register"; public static final String KEY_ADD = "add"; public static final int METHOD_LOGIN = 1; public static final int METHOD_REGISTER = 2; public static final int METHOD_GET_OLD_LOVER = 3; public static final int METHOD_ADD_OLD_LOVER = 4; public static void showToast(Context context, String sms) { Toast.makeText(context, sms, Toast.LENGTH_SHORT).show(); } // method for save and get nick and pass user public static void save(Context context, String key, String value) { SharedPreferences.Editor editor = PreferenceManager .getDefaultSharedPreferences(context.getApplicationContext()) .edit(); editor.putString(key, value); editor.apply(); } public static String get(Context context, String key) { SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(context.getApplicationContext()); return settings.getString(key, null); } }
没有什么是混乱, 在他的课堂上只是注意,我们使用 SharedPreferences 存储缺口和口令时用户想要记住以后登录. 并且还常常用于存储设置 (环境) 应用.
建设一流的情人
我们的情人将有 5 学校是ID, 名字, 电话, 开始日期 (开始日期爱情) VA结束日期 (日离别).
package cachhoc.net.demojson; import org.json.JSONException; import org.json.JSONObject; public class Lover { private int id; private String name; private String phone; private String beginDate; private String endDate; public Lover() { } public Lover(int id, String name, String phone, String beginDate, String endDate) { this.id = id; this.name = name; this.phone = phone; this.beginDate = beginDate; this.endDate = endDate; } public int getId() { return id; } public Lover setId(int id) { this.id = id; return this; } public String getName() { return name; } public Lover setName(String name) { this.name = name; return this; } public String getPhone() { return phone; } public Lover setPhone(String phone) { this.phone = phone; return this; } public String getBeginDate() { return beginDate; } public Lover setBeginDate(String beginDate) { this.beginDate = beginDate; return this; } public String getEndDate() { return endDate; } public Lover setEndDate(String endDate) { this.endDate = endDate; return this; } public String toJSON() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put(Var.KEY_ID, getId()); jsonObject.put(Var.KEY_NAME, getName()); jsonObject.put(Var.KEY_PHONE, getPhone()); jsonObject.put(Var.KEY_BEGIN_DATE, getBeginDate()); jsonObject.put(Var.KEY_END_DATE, getEndDate()); return jsonObject.toString(); } catch (JSONException e) { e.printStackTrace(); return ""; } } }
您的关注吸气平时我们不支付任何东西,通常价值 公共无效… 但我写它返回的对象,情人 (返回此). 这使我们更容易操作. 例如,当你想设置 2 姓名和电话的价值,那么你必须写 2 lover.setPhone lover.setName时间之类的可以使机器运行时,你去比较慢的市场像, 你买的蔬菜和运行, 用完后再买豆,… 而我就 lover.setName(…).setPhone(…) 即在购买蔬菜都是买豆子. =))
方法 的toJSON 我写信给转移 1 对象转换成JSON格式为便于数据操作发送到服务器, 然而,在这个应用程序,我不使用它, 写,让你知道,可用于其他应用程序只.
建筑类LoadJSon
其实不仅拍摄而且还发上,以处理更多的JSON数据. 而作为建设文件的前一天 lover.php 我已经说过,我们通过变量法区分行为.
package cachhoc.net.demojson; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import org.apache.http.Header; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; public class LoadJson { public static final String LINK = "https://cachhoc.net/mobile/demo-json/lover.php"; public void sendDataToServer(int method, HashMap<String, String> map) { AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); // put data to server params.put(Var.KEY_METHOD, method); if (map != null) { for (String key : map.keySet()) { params.put(key, map.get(key)); } } System.out.println("Post..."); client.post(LINK, params, new AsyncHttpResponseHandler() { @SuppressWarnings("deprecation") @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { String json = new String(responseBody); System.out.println("onSuccess:" + json); onFinishLoadJSonListener.finishLoadJSon(null, json); } @SuppressWarnings("deprecation") @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { System.out.println("onFailure:" + statusCode); String e; if (statusCode == 404) { e = "Requested resource not found"; } else if (statusCode == 500) { e = "Something went wrong at server end"; } else { e = "Device might not be connected to Internet"; } onFinishLoadJSonListener.finishLoadJSon(e, null); } }); } public static Lover jsonToLover(JSONObject jsonObject) { try { int id = jsonObject.getInt(Var.KEY_ID); String name = jsonObject.getString(Var.KEY_NAME); String phone = jsonObject.getString(Var.KEY_PHONE); String beginDate = jsonObject.getString(Var.KEY_BEGIN_DATE); String endDate = jsonObject.getString(Var.KEY_END_DATE); return new Lover(id, name, phone, beginDate, endDate); } catch (JSONException e) { e.printStackTrace(); return null; } } public static ArrayList<Lover> jsonToListLover(String json) { ArrayList<Lover> list = new ArrayList<>(); try { JSONArray arraySMSJson = new JSONArray(json); for (int i = 0; i < arraySMSJson.length(); i++) { JSONObject jsonObject = arraySMSJson.getJSONObject(i); Lover lover = jsonToLover(jsonObject); if (lover != null) { list.add(lover); } } } catch (JSONException e) { e.printStackTrace(); } return list; } public interface OnFinishLoadJSonListener { void finishLoadJSon(String error, String json); } public OnFinishLoadJSonListener onFinishLoadJSonListener; public void setOnFinishLoadJSonListener(OnFinishLoadJSonListener onFinishLoadJSonListener) { this.onFinishLoadJSonListener = onFinishLoadJSonListener; } }
在这:
- 恒定LINK是路径输出文件的JSON – lover.php文件已建成前夕.
-
方法 sendDataToServer 有 2 参数是区分操作的方法 (登录, 登记, 负载JSON, 加情人) 服务器来区分治疗上lover.php文件. 变量 HashMap中<串, String>的地图 是一个键值对的数据,我们放弃了一个列表, 上的服务器将基于所述键来检索对应的值.
-
当我们所谓的client.post() 系统将执行后台数据发送到服务器. 完成后,系统会自动调用该方法 的onSuccess (成功) 或 onFailure (有罪) 并返回对应的值. 在方法 的onSuccess 然后 responseBody 是.json我们获得有关, 它需要一个字节,并移动到一个字符串.
-
为了得到JSON和服务于其他级别的处理器, 我们建立一个界面, OnFinishLoadJSonListener 模式 finishLoadJSon(字符串错误, JSON字符串) 其他类实现JSON或错误采取的处理之后.
-
在此还附带内置到您的 2 方法 jsonToLover 和 jsonToListLover 转换的字符串JSON对象或列表情人的情人.
快来听,有点长远. 最重要的部分是让JSON有毛刺. 我们将继续处理 4 活动.
处理活动的
类似于接口部, 我们会去转步骤:
构造, 传碧 - >登录 - >注册 - >列表旧情人 - >添加情人
而在他的代号方法也很清楚,它不会需要太多的解释.
活动登录
要登录,那么我们将不得不派缺口,并通过了系统检查, lover.php文件将检查,如果属实,新的登录.
package cachhoc.net.demojson; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; public class LoginActivity extends AppCompatActivity implements View.OnClickListener, LoadJson.OnFinishLoadJSonListener { private EditText editNick, editPass; private CheckBox cbRememberPass; private LoadJson loadJson; private Context context; private ProgressDialog progressDialog; private String nick, pass; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); context = this; setupToolbar(); connectView(); loadJson = new LoadJson(); loadJson.setOnFinishLoadJSonListener(this); progressDialog = new ProgressDialog(context); progressDialog.setMessage(context.getResources().getString(R.string.wait)); } private void setupToolbar() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setTitle(R.string.login); } } } private void connectView() { editNick = (EditText) findViewById(R.id.edit_nick); editPass = (EditText) findViewById(R.id.edit_pass); cbRememberPass = (CheckBox) findViewById(R.id.cb_remember); findViewById(R.id.btn_login).setOnClickListener(this); findViewById(R.id.btn_register).setOnClickListener(this); // get nick and pass if it be remember nick = Var.get(context, Var.KEY_NICK); pass = Var.get(context, Var.KEY_PASS); if (nick != null && pass != null) { editNick.setText(nick); editPass.setText(pass); cbRememberPass.setChecked(true); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_login: login(); break; case R.id.btn_register: register(); break; default: break; } } private void register() { Intent intent = new Intent(context, RegisterActivity.class); startActivity(intent); } private void login() { nick = editNick.getText().toString().trim(); pass = editPass.getText().toString().trim(); // not enter nick name if (nick.length() == 0) { editNick.requestFocus(); Var.showToast(context, context.getResources().getString(R.string.enter_nick)); return; } // not enter pass if (pass.length() == 0) { editPass.requestFocus(); Var.showToast(context, context.getResources().getString(R.string.enter_pass)); return; } // save nick and pass if (cbRememberPass.isChecked()) { Var.save(context, Var.KEY_NICK, nick); Var.save(context, Var.KEY_PASS, pass); } else { Var.save(context, Var.KEY_NICK, null); Var.save(context, Var.KEY_PASS, null); } HashMap<String, String> map = new HashMap<>(); map.put(Var.KEY_NICK, nick); map.put(Var.KEY_PASS, pass); loadJson.sendDataToServer(Var.METHOD_LOGIN, map); progressDialog.show(); } @Override public void finishLoadJSon(String error, String json) { if (progressDialog.isShowing()) { progressDialog.hide(); } try { if (json != null) { JSONObject jsonObject = new JSONObject(json); if (jsonObject.getBoolean(Var.KEY_LOGIN)) { Var.showToast(context, context.getResources().getString(R.string.login_success)); Intent intent = new Intent(context, MainActivity.class); intent.putExtra(Var.KEY_NICK, nick); startActivity(intent); finish(); } else { Var.showToast(context, context.getResources().getString(R.string.login_fail)); } } else { Var.showToast(context, error); } } catch (JSONException e) { e.printStackTrace(); } } }
活动注册
如果不考虑, 我们需要以注册中添加到数据库系统.
package cachhoc.net.demojson; import android.app.ProgressDialog; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.EditText; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; public class RegisterActivity extends AppCompatActivity implements View.OnClickListener, LoadJson.OnFinishLoadJSonListener { private EditText editNick, editPass, editRePass; private LoadJson loadJson; private Context context; private ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); context = this; setupToolbar(); connectView(); loadJson = new LoadJson(); loadJson.setOnFinishLoadJSonListener(this); progressDialog = new ProgressDialog(context); progressDialog.setMessage(context.getResources().getString(R.string.wait)); } private void setupToolbar() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setTitle(R.string.register); } } } private void connectView() { editNick = (EditText) findViewById(R.id.edit_nick); editPass = (EditText) findViewById(R.id.edit_pass); editRePass = (EditText) findViewById(R.id.edit_re_pass); findViewById(R.id.btn_reset).setOnClickListener(this); findViewById(R.id.btn_register).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_reset: reset(); break; case R.id.btn_register: register(); break; default: break; } } private void reset() { editNick.setText(""); editPass.setText(""); editRePass.setText(""); editNick.requestFocus(); } private void register() { String nick = editNick.getText().toString().trim(); String pass = editPass.getText().toString().trim(); String repass = editRePass.getText().toString().trim(); // not enter nick name if (nick.length() == 0) { editNick.requestFocus(); Var.showToast(context, context.getResources().getString(R.string.enter_nick)); return; } // not enter pass if (pass.length() == 0) { editPass.requestFocus(); Var.showToast(context, context.getResources().getString(R.string.enter_pass)); return; } // not enter pass if (repass.length() == 0) { editRePass.requestFocus(); Var.showToast(context, context.getResources().getString(R.string.enter_repass)); return; } if (!repass.equals(pass)) { editPass.requestFocus(); Var.showToast(context, context.getResources().getString(R.string.pass_not_match)); return; } HashMap<String, String> map = new HashMap<>(); map.put(Var.KEY_NICK, nick); map.put(Var.KEY_PASS, pass); loadJson.sendDataToServer(Var.METHOD_REGISTER, map); progressDialog.show(); } @Override public void finishLoadJSon(String error, String json) { if (progressDialog.isShowing()) { progressDialog.hide(); } try { if (json != null) { JSONObject jsonObject = new JSONObject(json); if (jsonObject.getBoolean(Var.KEY_REGISTER)) { Var.showToast(context, context.getResources().getString(R.string.register_success)); finish(); } else { Var.showToast(context, context.getResources().getString(R.string.register_fail)); } } else { Var.showToast(context, error); } } catch (JSONException e) { e.printStackTrace(); } } }
活动添加情人
package cachhoc.net.demojson; import android.app.ProgressDialog; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.wdullaer.materialdatetimepicker.date.DatePickerDialog; import org.json.JSONException; import org.json.JSONObject; import java.util.Calendar; import java.util.HashMap; public class AddLoverActivity extends AppCompatActivity implements View.OnClickListener, LoadJson.OnFinishLoadJSonListener, DatePickerDialog.OnDateSetListener { private EditText editName, editPhone; private Button btnBeginDate, btnEndDate; private LoadJson loadJson; private Context context; private ProgressDialog progressDialog; private String nick; // for begin date or end date private int typeDate; private String beginDate = "", endDate = ""; public static final int BEGIN_DATE = 0; public static final int END_DATE = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_lover); context = this; setupToolbar(); connectView(); loadJson = new LoadJson(); loadJson.setOnFinishLoadJSonListener(this); progressDialog = new ProgressDialog(context); progressDialog.setMessage(context.getResources().getString(R.string.wait)); nick = getIntent().getStringExtra(Var.KEY_NICK); } private void setupToolbar() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setTitle(R.string.title_activity_add_lover); } } } private void connectView() { editName = (EditText) findViewById(R.id.edit_name); editPhone = (EditText) findViewById(R.id.edit_phone); btnBeginDate = (Button) findViewById(R.id.btn_begin_date); btnEndDate = (Button) findViewById(R.id.btn_end_date); btnBeginDate.setOnClickListener(this); btnEndDate.setOnClickListener(this); findViewById(R.id.btn_add).setOnClickListener(this); findViewById(R.id.btn_reset).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_reset: reset(); break; case R.id.btn_add: add(); break; case R.id.btn_begin_date: typeDate = BEGIN_DATE; showDatePicker(); break; case R.id.btn_end_date: typeDate = END_DATE; showDatePicker(); break; default: break; } } private void showDatePicker() { Calendar now = Calendar.getInstance(); DatePickerDialog dpd = DatePickerDialog.newInstance( this, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH) ); String title; if (typeDate == BEGIN_DATE) { title = context.getResources().getString(R.string.begin_date); } else { title = context.getResources().getString(R.string.end_date); } dpd.show(getFragmentManager(), title); } @Override public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) { String date = dayOfMonth + "/" + monthOfYear + "/" + year; if (typeDate == BEGIN_DATE) { beginDate = date; btnBeginDate.setText(date); } else { endDate = date; btnEndDate.setText(date); } } private void reset() { editName.setText(""); editPhone.setText(""); editName.requestFocus(); } private void add() { String name = editName.getText().toString().trim(); String phone = editPhone.getText().toString().trim(); // not enter nick name if (name.length() == 0) { editName.requestFocus(); Var.showToast(context, context.getResources().getString(R.string.enter_nick)); return; } // not enter pass if (phone.length() == 0) { editPhone.requestFocus(); Var.showToast(context, context.getResources().getString(R.string.enter_pass)); return; } HashMap<String, String> map = new HashMap<>(); map.put(Var.KEY_NICK, nick); map.put(Var.KEY_NAME, name); map.put(Var.KEY_PHONE, phone); map.put(Var.KEY_BEGIN_DATE, beginDate); map.put(Var.KEY_END_DATE, endDate); loadJson.sendDataToServer(Var.METHOD_ADD_OLD_LOVER, map); progressDialog.show(); } @Override public void finishLoadJSon(String error, String json) { if (progressDialog.isShowing()) { progressDialog.hide(); } try { if (json != null) { JSONObject jsonObject = new JSONObject(json); if (jsonObject.getBoolean(Var.KEY_ADD)) { Var.showToast(context, context.getResources().getString(R.string.add_success)); finish(); } else { Var.showToast(context, context.getResources().getString(R.string.add_fail)); } } else { Var.showToast(context, error); } } catch (JSONException e) { e.printStackTrace(); } } }
活动主 – 名单情人
在这 2 的一部分,我们需要处理列表,该列表适配器.
文件MainActivity.java
package cachhoc.net.demojson; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends AppCompatActivity implements View.OnClickListener, LoadJson.OnFinishLoadJSonListener { private ItemAdapter adapter; private ArrayList<Lover> list; private LoadJson loadJson; private Context context; private ProgressBar progressBar; private ViewGroup layoutProgress; private TextView tvNotify; private String nick; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); context = this; loadJson = new LoadJson(); loadJson.setOnFinishLoadJSonListener(this); setupToolbar(); setupRecyclerView(); findViewById(R.id.fab_add).setOnClickListener(this); layoutProgress = (ViewGroup) findViewById(R.id.layout_progress); progressBar = (ProgressBar) findViewById(R.id.progress); tvNotify = (TextView) findViewById(R.id.tv_notify); nick = getIntent().getStringExtra(Var.KEY_NICK); } private void setupToolbar() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { setSupportActionBar(toolbar); } } private void setupRecyclerView() { RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv_lover); // If the size of views will not change as the data changes. recyclerView.setHasFixedSize(true); // Setting the LayoutManager. RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); // Setting the adapter. list = new ArrayList<>(); adapter = new ItemAdapter(context, list); recyclerView.setAdapter(adapter); } public void onResume() { super.onResume(); refresh(); } /** * re load data from server */ private void refresh() { HashMap<String, String> map = new HashMap<>(); map.put(Var.KEY_NICK, nick); loadJson.sendDataToServer(Var.METHOD_GET_OLD_LOVER, map); layoutProgress.setVisibility(View.VISIBLE); progressBar.setVisibility(View.VISIBLE); tvNotify.setVisibility(View.GONE); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_logout: logout(); break; case R.id.action_refresh: refresh(); break; } return super.onOptionsItemSelected(item); } private void logout() { Intent intent = new Intent(context, LoginActivity.class); startActivity(intent); finish(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.fab_add: addOldLover(); break; } } private void addOldLover() { Intent intent = new Intent(context, AddLoverActivity.class); intent.putExtra(Var.KEY_NICK, nick); startActivity(intent); } @Override public void finishLoadJSon(String error, String json) { if (json != null) { layoutProgress.setVisibility(View.GONE); updateList(json); } else { showNotify(error); } } private void updateList(String json) { ArrayList<Lover> newList = LoadJson.jsonToListLover(json); list.clear(); list.addAll(newList); adapter.notifyDataSetChanged(); if (list.size() == 0) { showNotify(context.getResources().getString(R.string.no_lover)); } } private void showNotify(String notify) { layoutProgress.setVisibility(View.VISIBLE); progressBar.setVisibility(View.GONE); tvNotify.setVisibility(View.VISIBLE); tvNotify.setText(notify); } /** * double click back then exit app (2 click in 2s to exit) */ @Override public void onBackPressed() { if (doubleBackToExitPressedOnce) { super.onBackPressed(); return; } this.doubleBackToExitPressedOnce = true; Var.showToast(context, context.getResources().getString(R.string.back_to_exit)); new Handler().postDelayed(new Runnable() { @Override public void run() { doubleBackToExitPressedOnce = false; } }, 2000); } private boolean doubleBackToExitPressedOnce; }
在此,你是他的注意力覆盖方法的底部 onBackPressed 通知用户按BACK 2 就逃次. 2 本刊连续多次以2秒之内 (200 毫秒)
文件ItemAdapter.java
package cachhoc.net.demojson; import android.content.Context; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.RecyclerViewHolder> { private List<Lover> list; private Context context; public ItemAdapter(Context context, List<Lover> list) { this.context = context; this.list = list; } @Override public int getItemCount() { return list.size(); } /** * connect to item view */ @Override public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) { LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext()); View itemView = inflater.inflate(R.layout.item, viewGroup, false); return new RecyclerViewHolder(itemView); } /** * set data for item */ @Override public void onBindViewHolder(RecyclerViewHolder viewHolder, int position) { Lover lover = list.get(position); viewHolder.tvName.setText(lover.getName()); viewHolder.tvPhone.setText(lover.getPhone()); viewHolder.tvBeginDate.setText(lover.getBeginDate()); viewHolder.tvEndDate.setText(lover.getEndDate()); } /** * ViewHolder for item view of list */ public class RecyclerViewHolder extends RecyclerView.ViewHolder implements OnClickListener { public CardView container; public TextView tvName; public TextView tvPhone; public TextView tvBeginDate; public TextView tvEndDate; public RecyclerViewHolder(View itemView) { super(itemView); container = (CardView) itemView.findViewById(R.id.item_container); tvName = (TextView) itemView.findViewById(R.id.tv_name); tvPhone = (TextView) itemView.findViewById(R.id.tv_phone); tvBeginDate = (TextView) itemView.findViewById(R.id.tv_begin_date); tvEndDate = (TextView) itemView.findViewById(R.id.tv_end_date); container.setOnClickListener(this); } // click item then display note @Override public void onClick(View v) { Var.showToast(context, list.get(getAdapterPosition()).getName()); } } }
因此,我们已经完成了应用程序. 最后但稍长,但并不难.
你可以下载项目 这里
下载文件斋 OldLover.apk
Chúc các bạn học tập vui vẻ 🙂
在本教程的帖子 JSON仲机器人 由 nguyenvanquan7826
他问我 https://cachhoc.net/mobile/demo-json/lover.php 他的弟弟阅读本不理解是从何而来呢
它从我们的数据库中进行, 你看教程数量 2 NHE
https://www.cachhoc.net/2015/08/18/android-json-trong-android-phan-2-xuat-json-tu-database-bang-php/
问问自己 1 chút được không. Mình tạo database sau đó đẩy dữ liệu vào trong database . Dữ liệu mình đưa vào là công thức toán học nên khi vào trong database nó không hiển thị được dẫn đến việc trả ra chuổi JSON cũng không hiển thị được công thức toán học. Bạn cho hình hỏi có cách nào xử lý không? 谢谢
的, 关于他的数学公式没有试过, 目前尚不清楚如何
问问你自己可以html列表视图显示ķhtml标签,使得?
Cho hỏi, 我不知道这些数据是不正确写在越南发送不能保存到数据库在网络上, 所得=空白, 你如何解决这个错误不, và như JSON của bạn L\u00f2 L\u1ea5p L\u00f3, 从Android的读取可正确地解码它,以免原. 谢谢.
你看,重试格式化数据库视图, 本身或为UTF-8统一
我已经编辑好的, 感谢你多少, 非常有用的文章. 问问自己,如果你想发送多个数组列表, 而不是发送一个, 如何做到在发送 1 时间不.
你刚刚进入 1 某些对象包含列表
我亲爱的朋友,就像你不知道该怎么帮她处理是不是你
你看到的字体上的数据库格式观看. 通常UTF8
服务员, 让我问: 我有联系api_url, POST方法将数据发送到URL中的单独可以逃课和Lover.java Var.java不是? 和类应该怎么改LoadJson.java先生?
瓦尔班只是为了节省唯一不变的网址, 你离开好, 相反,你直接传递网址.