android/app/src/main/java/org/openlp/android2/fragments/SearchFragment.java

252 lines
9.7 KiB
Java

package org.openlp.android2.fragments;
import android.app.Fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Html;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.openlp.android2.R;
import org.openlp.android2.api.Api;
import org.openlp.android2.common.JsonHelpers;
import org.openlp.android2.common.OpenLPHttpClient;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
*/
public class SearchFragment extends Fragment {
private final String LOG_TAG = SearchFragment.class.getName();
private Spinner spinner;
private static AsyncHttpClient client = new AsyncHttpClient();
public Context context;
protected String calledURL;
protected OpenLPHttpClient httpClient;
protected String updateUrl;
public SearchFragment() {
Log.d(LOG_TAG, "Constructor");
}
public static SearchFragment newInstance() {
SearchFragment fragment = new SearchFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = getActivity();
updateUrl = Api.SEARCHABLE_PLUGINS;
httpClient = new OpenLPHttpClient(context);
View view = inflater.inflate(R.layout.fragment_search, container, false);
spinner = (Spinner)view.findViewById(R.id.search_spinner);
triggerTextRequest(Api.SEARCHABLE_PLUGINS);
// Add search listener to text field
EditText editText = (EditText)view.findViewById(R.id.search_text);
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
// Now close the keyboard as finished with
View view = getActivity().getCurrentFocus();
if (view != null) {
InputMethodManager imm =
(InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
String text = spinner.getSelectedItem().toString();
String text1 = v.getText().toString();
Toast.makeText(context, "Search Called " + text + " " + text1, Toast.LENGTH_SHORT).show();
requestSearch(spinner.getSelectedItem().toString(), v.getText().toString());
return true;
}
return false;
}
});
return view;
}
@Override
public void onDetach() {
super.onDetach();
}
public void manageResponse(String response, boolean notInError) {
if (calledURL.equals(updateUrl)) {
populatePluginList(response, notInError);
} else {
populateListDisplay(response, notInError);
}
}
private void populatePluginList(String response, Boolean notInError) {
Log.i(LOG_TAG, "populatePluginList - entry");
List<String> categories = new ArrayList<String>();
if (notInError) {
try {
JSONArray items = new JSONObject(response).getJSONObject("results").getJSONArray("items");
for (int i = 0; i < items.length(); ++i) {
JSONArray item = items.getJSONArray(i);
categories.add(item.get(1).toString());
}
} catch (JSONException e) {
Log.e(LOG_TAG, response);
e.printStackTrace();
}
ArrayAdapter<String> LTRadapter = new ArrayAdapter<String>(getActivity(),
R.layout.spinner_list_item, categories);
LTRadapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
spinner.setAdapter(LTRadapter);
Log.i(LOG_TAG, "populatePluginList - exit");
}
}
public void itemClicked(int position) {
try {
String request = JsonHelpers.createRequestJSON("id", Integer.toString(position));
triggerTextRequest(String.format("%s%s", Api.SERVICE_SET, request));
Log.d(LOG_TAG, String.format("Setting list data. apiBase(%s), position(%s)",
Api.SERVICE_SET, position));
} catch (JsonHelpers.JSONHandlerException e) {
e.printStackTrace();
Toast.makeText(context, "Request Failed", Toast.LENGTH_SHORT).show();
}
}
protected void triggerTextRequest(String url) {
calledURL = url;
Log.d(LOG_TAG, "Trigger Request for url " + url);
String callurl = String.format("%s%s", httpClient.getAbsoluteUrl(client), url );
client.get(callurl, null, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
// called when response HTTP status is "200 OK"
manageResponse(responseString, true);
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
if (statusCode == 401) {
Toast.makeText(context, R.string.httpreturn_unauthorised, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, R.string.unable, Toast.LENGTH_LONG).show();
}
manageResponse(responseString, false);
}
});
}
public void requestSearch(String plugin, String text) {
updateUrl = Api.SEARCH_PLUGIN_FORMATTED;
try {
String request = JsonHelpers.createRequestJSON("text", text);
String url = String.format(Api.SEARCH_PLUGIN_FORMATTED, plugin.toLowerCase());
triggerTextRequest(String.format("%s%s", url, request));
Log.d(LOG_TAG, String.format("Search request. apiBase(%s), text(%s)", plugin, text));
} catch (JsonHelpers.JSONHandlerException e) {
e.printStackTrace();
Toast.makeText(context, "Search Request Failed", Toast.LENGTH_SHORT).show();
}
}
public void populateListDisplay(String json, boolean notInError) {
Log.i(LOG_TAG, "populateListDisplay - entry");
List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
if (notInError) {
try {
JSONArray items = new JSONObject(json).getJSONObject("results").getJSONArray("items");
for (int i = 0; i < items.length(); ++i) {
JSONArray item = items.getJSONArray(i);
HashMap<String, String> hm = new HashMap<String, String>();
//hm.put("tag", item.getString("tag"));
//hm.put("liveListNormal", Html.fromHtml(item.getString("html")).toString());
aList.add(hm);
}
} catch (JSONException e) {
Log.e(LOG_TAG,json);
e.printStackTrace();
}
}
// Keys used in Hashmap
String[] from = {"tag", "liveListNormal", "liveListSelected"};
// Ids of views in live_list_fragment
int[] to = {R.id.tag, R.id.liveListNormal, R.id.liveListSelected};
ListView list = (ListView)getActivity().findViewById(R.id.searchresultsdetails);
int a = 1;
/* ArrayAdapter<String> LTRadapter = new ArrayAdapter<String>(getActivity(),
R.layout.spinner_list_item, categories);
// Instantiating an adapter to store each items
ListAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), aList,
R.layout.fragment_s, from, to) {
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView text1 = (TextView) view.findViewById(R.id.tag);
text1.setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
TextView text2 = (TextView) view.findViewById(R.id.liveListNormal);
text2.setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
if (selected == position) {
text2.setTextColor(Color.parseColor("#000000"));
text2.setTypeface(null, Typeface.BOLD_ITALIC);
} else{
text2.setTypeface(null, Typeface.NORMAL);
}
return view;
}
};
setListAdapter(adapter);*/
Log.i(LOG_TAG, "populateListDisplay - exit");
}
}