.
This tutorial continues from http://android-steps.blogspot.my/2015/11/android-fragment-sqlite-3.html
Modify the Fragment1.java as follows
package com.notarazi.myviewpagertablayout1;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.notarazi.myviewpagertablayout1.db.EmployeeDAO;
import com.notarazi.myviewpagertablayout1.model.Employee;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class FragmentPage1 extends Fragment implements View.OnClickListener {
// UI references
private EditText empNameEtxt;
private EditText empSalaryEtxt;
private EditText empDobEtxt;
private Button addButton;
private Button resetButton;
private static final SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd", Locale.ENGLISH);
DatePickerDialog datePickerDialog;
Calendar dateCalendar;
Employee employee = null;
private EmployeeDAO employeeDAO;
private AddEmpTask task;
private AddEmpTask1 task1;
public static final String ARG_ITEM_ID = "emp_add_fragment";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
employeeDAO = new EmployeeDAO(getActivity());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_page1, container, false);
findViewsById(rootView);
setListeners();
//For orientation change.
if (savedInstanceState != null) {
dateCalendar = Calendar.getInstance();
if (savedInstanceState.getLong("dateCalendar") != 0)
dateCalendar.setTime(newDate(savedInstanceState.getLong("dateCalendar")));
}
return rootView;
}
private void setListeners() {
empDobEtxt.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
datePickerDialog = new DatePickerDialog(getActivity(),
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
dateCalendar = Calendar.getInstance();
dateCalendar.set(year, monthOfYear, dayOfMonth);
empDobEtxt.setText(formatter.format(dateCalendar
.getTime()));
}
}, newCalendar.get(Calendar.YEAR),
newCalendar.get(Calendar.MONTH),
newCalendar.get(Calendar.DAY_OF_MONTH));
addButton.setOnClickListener(this);
resetButton.setOnClickListener(this);
}
protected void resetAllFields() {
empNameEtxt.setText("");
empSalaryEtxt.setText("");
empDobEtxt.setText("");
}
private void setEmployee() {
employee = new Employee();
employee.setName(empNameEtxt.getText().toString());
employee.setSalary(Double.parseDouble(empSalaryEtxt.getText()
.toString()));
if (dateCalendar != null)
employee.setDateOfBirth(dateCalendar.getTime());
}
@Override
public void onResume() {
//getActivity().setTitle(R.string.add_emp);
//getActivity().getActionBar().setTitle(R.string.add_emp);
super.onResume();
}
@Override
public void onSaveInstanceState(Bundle outState) {
if (dateCalendar != null)
outState.putLong("dateCalendar", dateCalendar.getTime().getTime());
}
private void findViewsById(View rootView) {
empNameEtxt = (EditText) rootView.findViewById(R.id.etxt_name);
empSalaryEtxt = (EditText) rootView.findViewById(R.id.etxt_salary);
empDobEtxt = (EditText) rootView.findViewById(R.id.etxt_dob);
empDobEtxt.setInputType(InputType.TYPE_NULL);
addButton = (Button) rootView.findViewById(R.id.button_add);
resetButton = (Button) rootView.findViewById(R.id.button_reset);
}
@Override
public void onClick(View view) {
if (view == empDobEtxt) {
datePickerDialog.show();
} else if (view == addButton) {
setEmployee();
task = new AddEmpTask(getActivity());
task.execute((Void) null);
Gson gson = new Gson();
String json = gson.toJson(employee);
task1 = new AddEmpTask1(getActivity());
task1.execute(json);
Toast.makeText(getActivity().getApplicationContext(), json, Toast.LENGTH_LONG).show();
} else if (view == resetButton) {
resetAllFields();
}
}
public class AddEmpTask extends AsyncTask<Void, Void, Long> {
private final WeakReference<Activity> activityWeakRef;
public AddEmpTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
@Override
protected Long doInBackground(Void... arg0) {
long result = employeeDAO.save(employee);
return result;
}
@Override
protected void onPostExecute(Long result) {
if (activityWeakRef.get() != null
&& !activityWeakRef.get().isFinishing()) {
if (result != -1)
Toast.makeText(activityWeakRef.get(), "Employee Saved",
Toast.LENGTH_LONG).show();
}
}
}
public class AddEmpTask1 extends AsyncTask<String, String, String>{
private final WeakReference<Activity> activityWeakRef;
public AddEmpTask1(Activity context){
this.activityWeakRef = new WeakReference<Activity>(context);
}
@Override
protected String doInBackground(String... arg0){
try {
sresult=makeRequest("http://tuts.razi.net.my/jsontest/withoutarrayname.txt","");
} catch (IOException e) {
e.printStackTrace();
}
return sresult;
}
@Override
protected void onPostExecute(String result){
Toast.makeText(getActivity().getApplicationContext(), result, Toast.LENGTH_LONG).show();
String data="";
try {
JSONArray arrJsonArray = new JSONArray(result);
for (int i = 0; i < arrJsonArray.length(); i++) {
JSONObject object = arrJsonArray.getJSONObject(i);
data+=("Url :" + object.getString("url"));
data+=("Display :" + object.getString("display"));
}
} catch (Exception e) {
}
Toast.makeText(getActivity().getApplicationContext(), data, Toast.LENGTH_LONG).show();
}
}
public static String makeRequest(String uri, String json) throws IOException {
HttpURLConnection urlConnection;
String url;
String data = json;
String result = null;
try {
//Connect
urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.connect();
//Write
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(newOutputStreamWriter(outputStream, "UTF-8"));
writer.write(data);
writer.close();
outputStream.close();
//Read
BufferedReader bufferedReader = new BufferedReader(newInputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
|
No comments:
Post a Comment