Adding a functionality to accept input

Now we need to accept the input and create a map to hold the values. We will then convert the map into a JSON object so that it can be passed as the data in the POST API request.

Traverse to the MainActivity.java file and open it in the edit panel of Android Studio. Declare the following class variables:

 private EditText bizprop, rooms, age, highways, tax, ptratio, lstat;
private Button estimate;
private TextView value;

You will find a function called onCreate() that is already created. Add the following code into the onCreate() function to initialize the elements of the layout:

 bizprop = (EditText) findViewById(R.id.bizprop_edit);
rooms = (EditText) findViewById(R.id.rooms_edit);
age = (EditText) findViewById(R.id.age_edit);
highways = (EditText) findViewById(R.id.highways_edit);
tax = (EditText) findViewById(R.id.tax_edit);
ptratio = (EditText) findViewById(R.id.ptratio_edit);
lstat = (EditText) findViewById(R.id.lstat_edit);
value = (TextView) findViewById(R.id.value);
estimate = (Button) findViewById(R.id.button);

Now add another function called makeJSON() to the Java class. This function accepts the values from the edit boxes and returns the JSON object we need to pass as data in our API call:

public JSONObject makeJSON() {

JSONObject jObj = new JSONObject();
try {

jObj.put("bizprop", bizprop.getText().toString());
jObj.put("rooms", rooms.getText().toString());
jObj.put("age", age.getText().toString());
jObj.put("tax", tax.getText().toString() );
jObj.put("highways", highways.getText().toString());
jObj.put("ptratio", ptratio.getText().toString());
jObj.put("lstat", lstat.getText().toString());

} catch (Exception e) {
System.out.println("Error:" + e);
}

Log.i("", jObj.toString());

return jObj;
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset