Lesson 10: Search data and display in List View (in Fragment)
Step 1: Create file “search.php” in your application folder
list.php
<?php$conn = new mysqli("localhost", "greenski_food", "~MyFooD9%*", "greenski_food");
$sql = "SELECT * FROM f_drink";
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
}
else {
echo "No Results Found.";
}
echo $json;
?>
Step 2: Create Fragment
Create fragment and name it “SearchRecord”
Step 3: Create/Modify Layout File
activity_success_drawer
fragment_search_record
activity_success_drawer.xml
<?xml version="1.0" encoding="utf-8"?>menu xmlns:android="
xmlns:tools="
tools:showIn="navigation_view"
<group android:checkableBehavior="single"
<item
android:id="@+id/nav_add"
android:icon="@drawable/ic_add"
android:title="@string/menu_addNew" />
<item
android:id="@+id/nav_list"
android:icon="@drawable/ic_list"
android:title="@string/menu_listRecord" />
<item
android:id="@+id/nav_search"
android:icon="@drawable/ic_search"
android:title="@string/menu_listRecord" />
<item
android:id="@+id/nav_logout"
android:icon="@drawable/ic_logout"
android:title="@string/menu_logout" />
</group
</menu
fragment_search_record.xml
RelativeLayout xmlns:android="xmlns:tools="
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="p.my.myfood.SearchRecord"
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/edittext1"
android:gravity="center"/>
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible"
/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listview1"
android:layout_below="@id/edittext1" />
</RelativeLayout
Step 4: Create/Modify Java File
SuccessActivity
SearchRecord.
HttpServicesClass
SuccessActivity.java
else if (id == R.id.nav_search) {setTitle("Search Record");
SearchRecord searchRecord = new SearchRecord();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.mainLayout, searchRecord).commit();
}
SearchRecord.java
package p.my.myfood;import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class SearchRecord extends Fragment {
ListView listView;
ProgressBar progressBar;
String HTTP_JSON_URL = ";
EditText editText ;
List SubjectArrayList = new ArrayList();
ArrayAdapter arrayAdapter ;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search_record, container, false);
listView = (ListView)view.findViewById(R.id.listview1);
progressBar = (ProgressBar)view.findViewById(R.id.progressBar);
editText = (EditText)view.findViewById(R.id.edittext1);
// Calling Method to Parese JSON data into listView.
new GetHttpResponse(getActivity()).execute();
// Calling EditText addTextChangedListener method which controls the EditText type sequence.
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//Updating Array Adapter ListView after typing inside EditText.
SearchRecord.this.arrayAdapter.getFilter().filter(charSequence);
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
}
});
// Adding On item click listener on ListView.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
String Item = parent.getItemAtPosition(position).toString();
// Showing ListView click item using Toast message on screen.
Toast.makeText(getActivity(), Item, Toast.LENGTH_LONG).show();
}
});
return view;
}
// Creating GetHttpResponse message to parse JSON.
public class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
// Creating context.
public Context context;
// Creating string to hold Http response result.
String ResultHolder;
// Creating constructor .
public GetHttpResponse(FragmentActivity context)
{
this.context = context;
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0)
{
// Sending the Http URL into HttpServicesClass to parse JSON.
HttpServicesClass httpServiceObject = new HttpServicesClass(HTTP_JSON_URL);
try
{
httpServiceObject.ExecutePostRequest();
// If the server response code = 200 then JSON parsing start.
if(httpServiceObject.getResponseCode() == 200)
{
// Adding Http response into ResultHolder string.
ResultHolder = httpServiceObject.getResponse();
// If there is response present into ResultHolder.
if(ResultHolder != null)
{
// Creating JSONArray and set it to null.
JSONArray jsonArray = null;
try {
// Adding ResultHolder into JSONArray.
jsonArray = new JSONArray(ResultHolder);
// Creating JSONObject.
JSONObject jsonObject;
// Starting for loop at the end of jsonArray length.
for(int i=0; i<jsonArray.length(); i++)
{
// Adding JSON array object .
jsonObject = jsonArray.getJSONObject(i);
// Adding the JSON parse object into SubjectArrayList.
SubjectArrayList.add(jsonObject.getString("drinkName").toString() + " - RM" + jsonObject.getString("drinkPrice").toString()) ;
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
// If something goes wrong then showing the error message on screen.
Toast.makeText(context, httpServiceObject.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// This block will execute after done all background processing.
@Override
protected void onPostExecute(Void result)
{
// Hiding the progress bar after done loading JSON.
progressBar.setVisibility(View.GONE);
// Showing the ListView after done loading JSON.
listView.setVisibility(View.VISIBLE);
// Setting up the SubjectArrayList into Array Adapter.
arrayAdapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_2, android.R.id.text1, SubjectArrayList);
// Passing the Array Adapter into ListView.
listView.setAdapter(arrayAdapter);
}
}
}
HttpServicesClass.java
package p.my.myfood;import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
public class HttpServicesClass {
public int responseCode;
public String message;
public String response;
public ArrayList<NameValuePair> ArrayListParams;
public ArrayList <NameValuePair> headers;
public String UrlHolder;
public String getResponse()
{
return response;
}
public String getErrorMessage()
{
return message;
}
public int getResponseCode()
{
return responseCode;
}
public HttpServicesClass(String url)
{
HttpServicesClass.this.UrlHolder = url;
ArrayListParams = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void AddParam(String name, String value)
{
ArrayListParams.add(new BasicNameValuePair(name, value));
}
public void AddHeader(String name, String value)
{
headers.add(new BasicNameValuePair(name, value));
}
public void ExecuteGetRequest() throws Exception
{
String MixParams = "";
if(!ArrayListParams.isEmpty())
{
MixParams += "?";
for(NameValuePair p : ArrayListParams)
{
String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
if(MixParams.length() > 1)
{
MixParams += "&" + paramString;
}
else
{
MixParams += paramString;
}
}
}
HttpGet httpGet = new HttpGet(UrlHolder + MixParams);
for(NameValuePair h : headers)
{
httpGet.addHeader(h.getName(), h.getValue());
}
executeRequest(httpGet, UrlHolder);
}
public void ExecutePostRequest() throws Exception
{
HttpPost httpPost = new HttpPost(UrlHolder);
for(NameValuePair h : headers)
{
httpPost.addHeader(h.getName(), h.getValue());
}
if(!ArrayListParams.isEmpty())
{
httpPost.setEntity(new UrlEncodedFormEntity(ArrayListParams, HTTP.UTF_8));
}
executeRequest(httpPost, UrlHolder);
}
private void executeRequest(HttpUriRequest request, String url)
{
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse;
try
{
httpResponse = httpClient.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null)
{
InputStream inputStream = entity.getContent();
response = convertStreamToString(inputStream);
inputStream.close();
}
}
catch (ClientProtocolException e)
{
httpClient.getConnectionManager().shutdown();
e.printStackTrace();
}
catch (IOException e)
{
httpClient.getConnectionManager().shutdown();
e.printStackTrace();
}
}
private String convertStreamToString(InputStream is)
{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try
{
while ((line = bufferedReader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return stringBuilder.toString();
}
}