Save Fragment State & restore it - android-fragments

I'm trying to develop an app, I've a problem with fragment's state. Main Activity has 2 fragments added using view pager, one of them is used to do search in database, the result (which is like headers) is displayed in a recycler view, on recycler view item click a new fragment is displayed with a web view, just like the picture
My prob is when I rotate screen everything is wiped, & it only displays my search query.
That's Search fragment Layout
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SearchView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/InterSearchView"
android:iconifiedByDefault="false"
android:layout_marginTop="10dp"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:queryHint="#string/search_here"/>
<ScrollView
android:id="#+id/BySearch_Scroll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/InterSearchView"
android:layout_marginTop="10dp"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/BySearch_Recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Search_BySearch_Frag"
android:layout_below="#id/BySearch_Recycler"
android:layout_marginTop="10dp"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"/>
</RelativeLayout>
</ScrollView>
That's the code for search Fragment
#Override
public View onCreateView(#NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_inter_search, container, false);
searchView = view.findViewById(R.id.InterSearchView);
rv = view.findViewById(R.id.BySearch_Recycler);
rv.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
#Override
public void onViewCreated(#NotNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
searchView = view.findViewById(R.id.InterSearchView);
rv = view.findViewById(R.id.BySearch_Recycler);
rv.setLayoutManager(new LinearLayoutManager(getActivity()));
dbHandler = new DBHandler(requireContext());
myDB = dbHandler.getWritableDatabase();
q1 = "SELECT DISTINCT Book FROM Interpretation_Books";
c1 = myDB.rawQuery(q1, null);
if (c1 != null && c1.getCount() > 0) {
while (c1.moveToNext()) {
Book.add(c1.getString(0));
}
}
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
searchView.setVisibility(View.GONE);
search_query = query;
q2 = "SELECT Verse, Tashkeel_text, Sura_no, NoTashkeel_text FROM ayat WHERE NoTashkeel_text Like '%" + query + "%'";
c2 = myDB.rawQuery(q2, null);
if (c2 != null && c2.getCount() > 0) {
while (c2.moveToNext()) {
BySearchAya_Number.add(c2.getString(0));
BySearchAya_Text.add(c2.getString(1));
BySearchSura_Number.add(c2.getString(2));
BySearchNewAya_Text.add(c2.getString(3));
}
}
for (int i = 0; i < BySearchSura_Number.size(); i++) {
q3 = "SELECT Sura_ArName FROM Sura_Pics WHERE Sura_Id =" + BySearchSura_Number.get(i);
c3 = myDB.rawQuery(q3, null);
if (c3 != null && c3.getCount() > 0) {
while (c3.moveToNext()) {
BySearchSura_Name.add(c3.getString(0));
}
}
}
for (int i = 0; i < BySearchAya_Number.size(); i++) {
interSearchItems.add(new CustomSearch(BySearchAya_Number.get(i), BySearchSura_Name.get(i), BySearchAya_Text.get(i), BySearchNewAya_Text.get(i)));
}
rv.setAdapter(new RecyclerViewAdapter(interSearchItems));
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
private final TextView mAya_Number;
private final TextView mSura_Name;
private final TextView mAya_Text;
private final TextView mBook1, mBook2, mBook3, mBook4, mBook5, mBook6, mSearch;
public RecyclerViewHolder(LayoutInflater inflater, ViewGroup container){
super(inflater.inflate(R.layout.new_interpretation_search_by_search, container, false));
mAya_Number = itemView.findViewById(R.id.Aya_Number);
mSura_Name = itemView.findViewById(R.id.Sura_Name);
mAya_Text = itemView.findViewById(R.id.Ayah_Text);
mBook1 = itemView.findViewById(R.id.Book1Title_Search);
mBook2 = itemView.findViewById(R.id.Book2Title_Search);
mBook3 = itemView.findViewById(R.id.Book3Title_Search);
mBook4 = itemView.findViewById(R.id.Book4Title_Search);
mBook5 = itemView.findViewById(R.id.Book5Title_Search);
mBook6 = itemView.findViewById(R.id.Book6Title_Search);
mSearch = itemView.findViewById(R.id.Search_Query);
}
}
private class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
List<CustomSearch> mList;
public RecyclerViewAdapter(List<CustomSearch> mList) {
this.mList = mList;
}
#NonNull
#NotNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NotNull ViewGroup parent, int viewType) {
dbHandler = new DBHandler(getContext());
LayoutInflater inflater = LayoutInflater.from(getActivity());
return new RecyclerViewHolder(inflater, parent);
}
#SuppressLint("Range")
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
CustomSearch interSearchItem = mList.get(position);
holder.mAya_Number.setText(interSearchItem.getAya_Number());
holder.mSura_Name.setText(interSearchItem.getSura_Name());
holder.mAya_Text.setText(interSearchItem.getAya_Text());
holder.mBook1.setText(Book.get(0));
holder.mBook2.setText(Book.get(1));
holder.mBook3.setText(Book.get(2));
holder.mBook4.setText(Book.get(3));
holder.mBook5.setText(Book.get(4));
holder.mBook6.setText(Book.get(5));
holder.mSearch.setText(interSearchItem.getAya_Without_Tashkeel());
holder.mBook1.setOnClickListener(v -> {
Bundle bundle = new Bundle();
bundle.putString("Sura_Name", interSearchItem.getSura_Name());
bundle.putString("Book_Name", Book.get(0));
bundle.putString("Aya_No_Tashkeel", interSearchItem.getAya_Without_Tashkeel());
Fragment interSearch = new NewInterSearch_BySearch();
interSearch.setArguments(bundle);
fm = Objects.requireNonNull(requireActivity()).getSupportFragmentManager();
ft = fm.beginTransaction();
ft.add(R.id.Search_BySearch_Frag, interSearch)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commit();
});
holder.mBook2.setOnClickListener(v -> {
Bundle bundle = new Bundle();
bundle.putString("Sura_Name", interSearchItem.getSura_Name());
bundle.putString("Book_Name", Book.get(1));
bundle.putString("Aya_No_Tashkeel", interSearchItem.getAya_Without_Tashkeel());
Fragment interSearch = new NewInterSearch_BySearch();
interSearch.setArguments(bundle);
fm = Objects.requireNonNull(requireActivity()).getSupportFragmentManager();
ft = fm.beginTransaction();
ft.add(R.id.Search_BySearch_Frag, interSearch)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commit();
});
holder.mBook3.setOnClickListener(v -> {
Bundle bundle = new Bundle();
bundle.putString("Sura_Name", interSearchItem.getSura_Name());
bundle.putString("Book_Name", Book.get(2));
bundle.putString("Aya_No_Tashkeel", interSearchItem.getAya_Without_Tashkeel());
Fragment interSearch = new NewInterSearch_BySearch();
interSearch.setArguments(bundle);
fm = Objects.requireNonNull(requireActivity()).getSupportFragmentManager();
ft = fm.beginTransaction();
ft.add(R.id.Search_BySearch_Frag, interSearch)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commit();
});
holder.mBook4.setOnClickListener(v -> {
Bundle bundle = new Bundle();
bundle.putString("Sura_Name", interSearchItem.getSura_Name());
bundle.putString("Book_Name", Book.get(3));
bundle.putString("Aya_No_Tashkeel", interSearchItem.getAya_Without_Tashkeel());
Fragment interSearch = new NewInterSearch_BySearch();
interSearch.setArguments(bundle);
fm = Objects.requireNonNull(requireActivity()).getSupportFragmentManager();
ft = fm.beginTransaction();
ft.add(R.id.Search_BySearch_Frag, interSearch)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commit();
});
holder.mBook5.setOnClickListener(v -> {
Bundle bundle = new Bundle();
bundle.putString("Sura_Name", interSearchItem.getSura_Name());
bundle.putString("Book_Name", Book.get(4));
bundle.putString("Aya_No_Tashkeel", interSearchItem.getAya_Without_Tashkeel());
Fragment interSearch = new NewInterSearch_BySearch();
interSearch.setArguments(bundle);
fm = Objects.requireNonNull(requireActivity()).getSupportFragmentManager();
ft = fm.beginTransaction();
ft.add(R.id.Search_BySearch_Frag, interSearch)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commit();
});
holder.mBook6.setOnClickListener(v -> {
Bundle bundle = new Bundle();
bundle.putString("Sura_Name", interSearchItem.getSura_Name());
bundle.putString("Book_Name", Book.get(5));
bundle.putString("Aya_No_Tashkeel", interSearchItem.getAya_Without_Tashkeel());
Fragment interSearch = new NewInterSearch_BySearch();
interSearch.setArguments(bundle);
fm = Objects.requireNonNull(requireActivity()).getSupportFragmentManager();
ft = fm.beginTransaction();
ft.add(R.id.Search_BySearch_Frag, interSearch)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commit();
});
}
#Override
public int getItemCount() {
return mList.size();
}
}
That's the code for fragment contains web view displaying search
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_inter_search__by_search, container, false);
dbHandler = new DBHandler(requireContext());
myDB= dbHandler.getWritableDatabase();
assert getArguments() != null;
sura_name = getArguments().getString("Sura_Name");
book_name = getArguments().getString("Book_Name");
aya_without_tashkeel = getArguments().getString("Aya_No_Tashkeel");
webView = view.findViewById(R.id.webv);
PreviousB = view.findViewById(R.id.LQPButt);
NextB = view.findViewById(R.id.LQNButt);
q1 = "SELECT UrlLink FROM Interpretation_Books WHERE Book LIKE '%" + book_name + "%' AND Tasneef LIKE '%" + sura_name + "%' AND Bab_NoTashkeel LIKE '%" + aya_without_tashkeel + "%'";
c1 = myDB.rawQuery(q1, null);
if (c1 != null && c1.getCount() > 0) {
while (c1.moveToNext()) {
Url = c1.getString(0);
}
}
webView.loadUrl(Url);

Related

Working with application in Java using maps

I have trouble with my Java application. I'm writing a program that connects to public transport API and perform some operations, which includes showing map of Warsaw with bus stops. I want to add an EventHandler function that allows to tap on a bus stop on the map, which will result in showing a box with some informations about this bus stop. How can I do such a thing?
My application so far:
Main.java:
package gui;
import api.Api;
import com.gluonhq.charm.down.ServiceFactory;
import com.gluonhq.charm.down.Services;
import com.gluonhq.charm.down.plugins.StorageService;
import com.gluonhq.maps.MapPoint;
import com.gluonhq.maps.MapView;
import com.gluonhq.maps.demo.PoiLayer;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import java.io.File;
import java.util.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class Main extends Application{
private ContentType currentContent = ContentType.SCHEDULE;
private HashMap<ContentType, Pane> contentPaneMap;
private HBox buttonBox;
private Stage stage;
private Theme theme;
private final int height = 500;
private final int width = 800;
private final ToggleGroup menuButtonToggle = new ToggleGroup();
private String selectedStopId;
#Override
public void start(Stage primaryStage) {
this.stage = primaryStage;
theme = Theme.DARK;
buttonBox = new HBox();
buttonBox.getChildren().addAll(getMenuButtons());
initContentPanes();
getContentPaneAndResetStage();
primaryStage.show();
}
private void getContentPaneAndResetStage(){
Pane contentPane = contentPaneMap.get(currentContent);
VBox rootPane = new VBox();
rootPane.getChildren().addAll(buttonBox, contentPane);
Scene scene = new Scene(rootPane, width, height);
scene.getStylesheets().add(theme.cssFile);
stage.setScene(scene);
}
private List<ToggleButton> getMenuButtons(){
List<ToggleButton> buttonList = new ArrayList<>();
for(ContentType contentType:ContentType.values()){
ToggleButton button = new ToggleButton(contentType.buttonText);
button.setPrefWidth((double) width/4);
button.setOnAction(e -> {
Main.this.currentContent = contentType;
getContentPaneAndResetStage();
});
buttonList.add(button);
button.setToggleGroup(Main.this.menuButtonToggle);
}
return buttonList;
}
private void initContentPanes(){
contentPaneMap = new HashMap<>();
Api.saveLocalisationToCache();
contentPaneMap.put(ContentType.MAP, getMapPane());
contentPaneMap.put(ContentType.SCHEDULE, getSchedulePane());
contentPaneMap.put(ContentType.ROUTE, getRoutePane());
contentPaneMap.put(ContentType.SETTINGS, getSettingsPane());
}
private Pane getSchedulePane(){
VBox schedulePane = new VBox();
Label stopNameLabel = new Label("Nazwa przystanku: ");
stopNameLabel.setPadding(new Insets(5));
TextField stopName = new TextField();
stopName.setOnAction(e -> {
List<String> stopId = Api.getId(stopName.getText());
selectedStopId = null;
schedulePane.getChildren().remove(1);
schedulePane.getChildren().add(getContentForSchedulePane(stopId, stopName.getText()));
});
schedulePane.getChildren().add(new HBox(stopNameLabel, stopName));
if (selectedStopId == null) schedulePane.getChildren().add(new Pane(new Label("Nie znaleziono przystanku")));
else schedulePane.getChildren().add(new Label(selectedStopId));
return schedulePane;
}
private Pane getContentForSchedulePane(List<String> stopId, String stopName){
if (stopId.size() == 0) return new Pane(new Label("Nie znaleziono przystanku"));
if (stopId.size() == 1) {
String stop1id = stopId.get(0);
Label stopNameLabel = new Label("Przystanek " + stopName.toUpperCase() + " (id " + stop1id + ")");
stopNameLabel.setPadding(new Insets(5));
VBox newContentPane = new VBox(stopNameLabel);
ChoiceBox<String> busStopNr = new ChoiceBox<>(
FXCollections.observableArrayList(List.of(new String[]{"01", "02"})));
busStopNr.setValue("01");
ChoiceBox<String> lineChoice = new ChoiceBox<>(
FXCollections.observableArrayList(Api.getLines(stop1id, busStopNr.getValue())));
Label times = new Label();
lineChoice.setOnAction(
e -> times.setText(Api.getTimes(stop1id, busStopNr.getValue(), lineChoice.getValue()).toString()));
busStopNr.setOnAction(
e -> lineChoice.setItems(
FXCollections.observableArrayList(Api.getLines(stop1id, busStopNr.getValue()))));
newContentPane.getChildren().addAll(
new HBox(new Label("Nr słupka: "), busStopNr),
new HBox(new Label("Nr linii: "), lineChoice),
times);
return newContentPane;
}
GridPane newButtonPane = new GridPane();
int i = 1; int j = 0;
for (String id:stopId) {
Button b = new Button(id);
b.setOnAction(event -> {
selectedStopId = b.getText();
contentPaneMap.get(ContentType.SCHEDULE).getChildren().remove(1);
contentPaneMap.get(ContentType.SCHEDULE).getChildren()
.add(getContentForSchedulePane(Collections.singletonList(b.getText()), stopName));
});
((GridPane) newButtonPane).add(b, i, j);
i = (i+1)%4+1; j = i==1?j+1:j;
}
return newButtonPane;
}
private Pane getRoutePane(){return new VBox(new Circle(20, Color.BLUE));}
private Pane getMapPane(){
MapView mapView = new MapView();
PoiLayer poiLayer = new PoiLayer();
List<Map<String, String>> pointList = Api.getLocalization();
for (Map<String, String> stop: pointList){
MapPoint point = new MapPoint(Double.parseDouble(stop.get("szer_geo")), Double.parseDouble(stop.get("dlug_geo")));
poiLayer.addPoint(point, new Circle(3, Color.RED));
}
mapView.setCenter(new MapPoint(52.230926, 21.006701));
mapView.setZoom(13);
mapView.addLayer(poiLayer);
return new StackPane(mapView);
}
public void getInfo(){
}
private Pane getSettingsPane(){
GridPane settingsPane = new GridPane();
ChoiceBox<Theme> themeChoiceBox = new ChoiceBox<>(FXCollections.observableArrayList(Theme.values()));
themeChoiceBox.setOnAction(e -> {
Main.this.theme = themeChoiceBox.getValue();
getContentPaneAndResetStage();
});
Label themeLabel = new Label("Motyw: ");
themeLabel.setPadding(new Insets(5));
settingsPane.add(themeLabel, 1, 1);
settingsPane.add(themeChoiceBox, 2, 1);
settingsPane.setHgap(10);
settingsPane.setVgap(10);
settingsPane.setGridLinesVisible(false);
return settingsPane;
}
#Override
public void init() {
System.setProperty("javafx.platform", "Desktop");
System.setProperty("http.agent", "Gluon Mobile/1.0.1");
StorageService storageService = new StorageService() {
#Override
public Optional<File> getPrivateStorage() {
return Optional.of(new File(System.getProperty("user.home")));
}
#Override
public Optional<File> getPublicStorage(String s) {
return getPrivateStorage();
}
#Override
public boolean isExternalStorageWritable() {
return getPrivateStorage().isPresent() && getPrivateStorage().get().canWrite();
}
#Override
public boolean isExternalStorageReadable() {
return getPrivateStorage().isPresent() && getPrivateStorage().get().canRead();
}
};
ServiceFactory<StorageService> storageServiceServiceFactory = new ServiceFactory<>() {
#Override
public Class<StorageService> getServiceType() {
return StorageService.class;
}
#Override
public Optional<StorageService> getInstance() {
return Optional.of(storageService);
}
};
Services.registerServiceFactory(storageServiceServiceFactory);
}
}
api.java:
package api;
import javafx.application.Platform;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Api {
private static final String baseUrl = "https://api.um.warszawa.pl/api/action/";
private static final String apikey = "95904037-5fdc-48d5-bd7f-c9f8d0b28947";
private static final String pathToLocalisationCache = "./.cache/stop-localisation.json";
private static HttpURLConnection getConnection(String urlString){
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
assert url != null;
connection = (HttpURLConnection)url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
//Współrzędne przystanków
public static List<Map<String,String>> getLocalization() {
File cacheFile = new File(pathToLocalisationCache);
String data;
if(!cacheFile.exists()){
String url = baseUrl+"dbstore_get?id=ab75c33d-3a26-4342-b36a-6e5fef0a3ac3&apikey="+apikey;
HttpURLConnection connection = Api.setParameters(getConnection(url));
data = Api.readData(connection);
} else{
data = readLocalisationFromCache();
}
List<Map<String,String>> list = new ArrayList<>();
assert data != null;
JSONObject obj = new JSONObject(data);
JSONArray arr = obj.getJSONArray("result");
for(int j=0; j<arr.length();j++){
JSONObject obj1 = arr.getJSONObject(j);
JSONArray arr1 = obj1.getJSONArray("values");
Map<String, String> map = new HashMap<>();
for(int i = 0; i < arr1.length();i++){
String value = arr1.getJSONObject(i).getString("value");
String key = arr1.getJSONObject(i).getString("key");
map.put(key, value);
}
list.add(map);
}
return list;
}
public static void saveLocalisationToCache(){
File file = new File(pathToLocalisationCache);
if (file.exists()) return;
try{
boolean fileCreated = true;
if (!file.getParentFile().exists()) fileCreated = file.getParentFile().mkdir();
if (!fileCreated) throw new IOException("Unable to create cache directory");
fileCreated = file.createNewFile();
if (!fileCreated) throw new IOException("Unable to create file");
String url = baseUrl+"dbstore_get?id=ab75c33d-3a26-4342-b36a-6e5fef0a3ac3&apikey="+apikey;
HttpURLConnection connection = setParameters(getConnection(url));
InputStreamReader in = new InputStreamReader(new BufferedInputStream(connection.getInputStream()), StandardCharsets.UTF_8.newDecoder());
OutputStreamWriter out = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(file)), StandardCharsets.UTF_8.newEncoder());
in.transferTo(out);
in.close(); out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String readLocalisationFromCache(){
try{
BufferedReader reader = new BufferedReader(new FileReader(pathToLocalisationCache));
StringBuilder dataSB = new StringBuilder();
reader.lines().forEach(dataSB::append);
reader.close();
return dataSB.toString();
} catch (IOException e){e.printStackTrace();}
return null;
}
//id przystanku po nazwie
public static List<String> getId(String n) {
StringBuilder name = new StringBuilder();
try {
String[] testStrings = {n};
for (String s : testStrings) {
String encodedString = URLEncoder.encode(s, StandardCharsets.UTF_8);
name.append(encodedString);
}
} catch(Exception e){e.printStackTrace();}
String url = baseUrl+"dbtimetable_get?id=b27f4c17-5c50-4a5b-89dd-236b282bc499&name="+name+"&apikey="+apikey;
HttpURLConnection connection = Api.setParameters(getConnection(url));
String data = Api.readData(connection);
assert data != null;
JSONObject json = new JSONObject(data);
Pattern integerPattern = Pattern.compile("-?\\d+");
Matcher matcher = integerPattern.matcher(json.toString());
List<String> linesList = new ArrayList<>();
while (matcher.find()) {
linesList.add(matcher.group());
}
return linesList;
}
// Zwraca liste linii dla konkretnego przystanku i nr slupka
public static List<String> getLines(String idPrzystanku, String nrSlupka) {
String url = baseUrl+"dbtimetable_get?id=88cd555f-6f31-43ca-9de4-66c479ad5942&busstopId="+
idPrzystanku+"&busstopNr="+nrSlupka+"&apikey="+apikey;
HttpURLConnection connection = Api.setParameters(getConnection(url));
String data = Api.readData(connection);
assert data != null;
JSONObject json = new JSONObject(data);
Pattern integerPattern = Pattern.compile("-?\\d+");
Matcher matcher = integerPattern.matcher(json.toString());
List<String> linesList = new ArrayList<>();
while (matcher.find()) {
linesList.add(matcher.group());
}
return linesList;
}
//Zwraca listę czas dla danego przystanku i linii
public static List<String> getTimes(String idPrzystanku, String nrSlupka, String line) {
String url = baseUrl+"dbtimetable_get?id=e923fa0e-d96c-43f9-ae6e-60518c9f3238&busstopId="+
idPrzystanku+"&busstopNr="+nrSlupka+"&line="+line+"&apikey="+apikey;
HttpURLConnection connection = Api.setParameters(getConnection(url));
String data = Api.readData(connection);
List<String> times = new ArrayList<>();
assert data != null;
JSONObject obj = new JSONObject(data);
JSONArray arr = obj.getJSONArray("result");
for(int j=0; j<arr.length();j++){
JSONObject obj1 = arr.getJSONObject(j);
JSONArray arr1 = obj1.getJSONArray("values");
JSONObject obj2 = arr1.getJSONObject(5);
times.add(obj2.getString("value"));
}
return times;
}
//Odczytuje dane
public static String readData(HttpURLConnection connection) {
InputStream inStream;
try {
inStream = new BufferedInputStream(connection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
return null;
}
Scanner in = new Scanner(inStream, StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
while (in.hasNext()) {
sb.append(in.next());
}
return sb.toString();
}
//Ustala parametry połączenia
public static HttpURLConnection setParameters(HttpURLConnection
connection) {
try {
connection.setRequestMethod("GET");
connection.setDoInput(true);
} catch (ProtocolException e) {
e.printStackTrace();
}
connection.setRequestProperty("Authorization", "Token " + apikey);
try {
if (connection.getResponseCode() != 200) {
System.out.println("Response code: "
+ connection.getResponseCode() + " " + connection.getResponseMessage());
Platform.exit(); // ze względu na javafx
System.exit(0);
}
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
}
I have no idea how to do it and I will be very grateful if someone will help me.
Based on my work experience on map libraries with JavaFX, I can share an approach you can take here. You can simply add a Mouse click event handler on the MapView and in that event you can catch the coordinates/Point where the user clicks on the screen. Then you can compare that point clicked by the user with one of the location Map points you want your user to click and see if it matches (by checking a distance between the user click position and the map coordinate of the bus stop). I have applied this approach in a different map library but similar can be applied here with some tweaks and adjustments.
List<Map<String, String>> pointList = Api.getLocalization();
mapView.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
Point2D clickedMapCoordinates = mapView.screenToLocal(new Point2D(mouseEvent.getX(), mouseEvent.getY()));
for (Map<String, String> stop: pointList){
MapPoint stopPoint = new MapPoint(Double.parseDouble(stop.get("szer_geo")), Double.parseDouble(stop.get("dlug_geo")));
Point2D mapStopPoint = new Point2D(stopPoint.getLongitude(), stopPoint.getLatitude());
// if user clicked on map near the position(lat,lng) of a stop
// then trigger the logic, you can change the distance threshold value according to your need
if(mapStopPoint.distance(clickedMapCoordinates) < 0.0001)
{
// perform your logic here about the stop point point...
}
}
}
});
Another approach which I suppose you can take is put a click event handler on the Circle object for the bus stop point and then check if the user's clicked circle matches the coordinates of a bus stop point.
Circle circle = new Circle(3, Color.RED);
circle.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
if(mouseEvent.getSource() instanceof Circle)
{
Circle clickedCircle = (Circle) mouseEvent.getSource();
Point2D clickedPoint = mapView.screenToLocal(clickedCircle.getCenterX(), clickedCircle.getCenterY())
for (Map<String, String> stop: pointList){
MapPoint point = new MapPoint(Double.parseDouble(stop.get("szer_geo")), Double.parseDouble(stop.get("dlug_geo")));
if(clickedPoint.getX() == point.getLongitude() && clickedPoint.getY() == point.getLatitude())
{
// this is the clicked map point (bus stop point)
// perform your logic here
}
}
}
}
});
If the second approach doesn't work, try debugging and checking the clicked point and bus stop point coordinates values and adjust them. Hope this helps you in some way.

Restored ImageView after app close and restart

How to restore an ImageView picked from gallery after close and restart the app. I am using SharedPreferences. To save the state of the URI after the app is closed, however it is not working the image is not set again any help would be appreciate.
public class test extends AppCompatActivity {
private static int RESULT_LOAD_IMAGE = 1;
ImageButton buttonLoadImage;
private static int RESULT_LOAD_IMG = 1;
String imgDecodableString;
public String getImagePathFetch;
ImageView imgView;
public String keyImage = "myImage";
public SharedPreferences sharedPrefEnter, sharedPrefGet;
Intent galleryIntent;
Uri selectedImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity_layout);
imgView = (ImageView) findViewById(R.id.imageView1);
sharedPrefGet = PreferenceManager.getDefaultSharedPreferences(this);
getImagePathFetch = sharedPrefGet.getString(keyImage, "");
if (!getImagePathFetch.equals("")) {
// tToast("OnCreate Path=" + getImagePathFetch);
Uri uri;
uri = Uri.parse(getImagePathFetch);
imgView.setImageURI(uri);
}
buttonLoadImage = (ImageButton) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddImage(view);
}
});
}
public void AddImage(View view) {
galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
// Get the Image from data
selectedImage = data.getData();
sharedPrefEnter = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPrefEnter.edit();
editor.putString(keyImage, selectedImage.toString());
editor.commit();
Uri uri = Uri.parse(selectedImage.toString());
imgView.setImageURI(uri);
}
}
}
// get the path of the image
sharedPrefGet = PreferenceManager.getDefaultSharedPreferences(this);
getImagePathFetch = sharedPrefGet.getString(keyImage, "");
if (!getImagePathFetch.equals("")) {
// tToast("OnCreate Path = " + getImagePathFetch); //TESTING
// parse path from toString to uri
uriImage = Uri.parse(getImagePathFetch);
// explicitly check for the permission at runtime since API 23
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
// Permission not granted
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
WRITE_EXTERNAL_STORAGE);
} else // Permission granted
{
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(uriImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
Bitmap imageResized = getResizedBitmap(yourSelectedImage, 480, 480); // resized
// Image
imgView.setImageBitmap(imageResized);
} // end if
}
//Check permission result.
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case WRITE_EXTERNAL_STORAGE:
if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(uriImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
Bitmap imageResized = getResizedBitmap(yourSelectedImage, 480, 480); // resized
// Image
imgView.setImageBitmap(imageResized);
}
break;
default:
break;
}
}

javafx button.onclick() not working

i am having a problem when i click on the button it doesn t work.
actually for the moment i am just asking that the button execute a system.out.println() just for the test. the name of the button is btndetailUser
listRechercheUser.setCellFactory(new Callback<ListView<User>, ListCell<User>>() {
#Override
public ListCell<User> call(ListView<User> p) {
ListCell<User> cell;
cell = new ListCell<User>() {
#Override
protected void updateItem(User user, boolean bln) {
super.updateItem(user, bln);
if (user != null) {
ImageView img;
String mm=user.getPath().trim();
if (mm.equals("fusee.png")){
img = new ImageView(new Image("mto/cr/images/"+mm));}
else{
img = new ImageView(new Image("mto/cr/images/mains-fonds.png"));
}
VBox vb = new VBox(10);
HBox hb = new HBox(20);
VBox vb1 = new VBox(20);
VBox vb3= new VBox(20);
vb1.getChildren().add(new Label(" "));
hb.setStyle("-fx-border-color: #C8C8C8 ;");
vb.setAlignment(Pos.CENTER);
VBox vb2 = new VBox(30);
vb.setAlignment(Pos.CENTER);
vb2.setAlignment(Pos.BASELINE_LEFT);
vb3.setAlignment(Pos.CENTER_RIGHT);
Label id = new Label(user.getId()+"id firas:");
Label username = new Label(user.getUsername()+" username firas:");
Label nom = new Label(user.getNom()+"nom firas:");
Label prenom = new Label(user.getPrenom()+"prenom firas:");
Button btndetailUser = new Button();
btndetailUser.setId("btndetailUser");
btndetailUser.setText("btndetailUser "+user.getId());
Image imageAccesProjet = new Image("mto/cr/images/enter.png");
ImageView enterIV= new ImageView(imageAccesProjet);
enterIV.setFitHeight(10);
enterIV.setFitWidth(10);
btndetailUser.setGraphic(enterIV);
btndetailUser.getStyleClass().add("buttonLogin");
System.out.println(btndetailUser.getText());
btndetailUser.setOnMouseClicked(
(MouseEvent event2) ->
System.out.println("firas"));
btndetailUser.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println(".handle()");
}
});
vb.getChildren().addAll(new Label(" "), img, new Label(" "),username);
vb2.getChildren().addAll(nom, prenom);
vb3.getChildren().addAll(btndetailUser);
hb.getChildren().addAll(vb1, vb, vb2,vb3);
setGraphic(hb);
}
}
};
return cell;
}
});
try something like,
btndetailUser.setOnAction(e -> {
System.out.println("freetext")
});

refresh label during a foreach loop

I'm asking for your help.
I'm developing an application in JavaFX who "scan" Mp3 files to get ID3tag.
Here is my problem. I did a foreach loop of a list for every .mp3 found but I'd like to increment a label which inform the progression of the list.
Here is my code
private ArrayList checkMp3File(ArrayList<String> lsMp3file, String sDir) throws UnsupportedTagException, InvalidDataException, IOException
{
this.currentData = 1;
int size = lsMp3file.size();
ArrayList<DataSong> lsds = new ArrayList<>();
for(String mp3file : lsMp3file)
{
this.labelUpdate.setText(this.current++ + " of " + " size");
DataSong ds = new DataSong();
Mp3File mp3 = new Mp3File(mp3file);
ds.setLenghtOfMp3inSec(mp3.getLengthInSeconds());
ds.setBitRateOfMp3(mp3.getBitrate());
ds.setSampleRate(mp3.getSampleRate());
ds.setVbrOrCbr(mp3.isVbr());
}
Actually, when the loop progress my window interface is completely freeze.
And only when the loop is finished, the label updated.
Someone can explain why ?
I already thank you for your answers.
EDIT :
Here is my fully code
public class LaunchOption extends Pane {
private final HBox launchAndSend = new HBox();
private final HBox browseAndField = new HBox();
private final HBox jsonAndAdvance = new HBox();
private ArrayList<DataSong> lsWithData = new ArrayList<>();
private String sendJson;
private File selectedDirectory;
private User user;
private int currentData;
private final ProgressIndicator pi = new ProgressIndicator(0);
private final VBox containerElement = new VBox();
private final TextArea displayJson = new TextArea();
private final TextField pathDir = new TextField();
private final TextField nbrOfData = new TextField();
private final Button btnScan = new Button();
private final Button btnSend = new Button();
private final Button btnCheckJson = new Button();
private final Button btnDirectoryBrowser = new Button();
private final Label nbMp3 = new Label();
public Label listAdvance = new Label();
private final Stage home;
public LaunchOption(Stage home){
this.home = home;
configureBtnCheckJson();
configureBtnScan();
configureBtnSend();
configureLabelMp3();
configureBtnDirectoryBrowser();
configureTextAreaDisplayJson();
configureTextFieldPathDir();
configureTextFieldNbDataMp3();
configureHBoxlaunchSend();
configureHBoxBrowseAndField();
configureHBoxJsonAndAdvance();
configureContainer();
this.getChildren().addAll(containerElement,launchAndSend);
}
private void configureLabelMp3()
{
nbMp3.setText("MP3");
}
private void configureBtnScan(){
btnScan.setText("Scan");
btnScan.setOnAction(event->{
ArrayList<String> Mp3FileData;
Mp3FileData = mapFilesMp3(selectedDirectory.getAbsolutePath());
System.out.println("ListSize = " + Mp3FileData.size());
nbrOfData.setText(String.valueOf(Mp3FileData.size()));
try {
lsWithData = checkMp3File(Mp3FileData, selectedDirectory.getAbsolutePath());
} catch (UnsupportedTagException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidDataException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
}
pi.setProgress(1);
});
}
private void configureBtnDirectoryBrowser(){
btnDirectoryBrowser.setText("Browse ...");
btnDirectoryBrowser.getStyleClass().add("round-red");
btnDirectoryBrowser.setOnAction(event-> {
DirectoryChooser dc = new DirectoryChooser();
selectedDirectory = dc.showDialog(home);
pi.setProgress(0.35);
if(selectedDirectory == null)
{
pathDir.setText("No directory selected");
}
else
{
pathDir.setText(selectedDirectory.getAbsolutePath());
String Text = pathDir.getText();
System.out.println(Text.toString());
}
});
}
private static String regexMp3()
{
return "^.*\\.(mp3)$";
}
private ArrayList mapFilesMp3(String sDir){
ArrayList<String> ls = new ArrayList<>();
printFnames(sDir,ls);
return ls;
}
private static void printFnames(String sDir, ArrayList<String> ls)
{
File[] faFiles = new File(sDir).listFiles();
for(File file : faFiles)
{
if(file.getName().matches(regexMp3()))
{
// System.out.println(file.getAbsolutePath());
ls.add(file.getAbsolutePath());
}
if(file.isDirectory())
{
printFnames(file.getAbsolutePath(), ls);
}
}
}
private ArrayList checkMp3File(ArrayList<String> lsMp3file, String sDir) throws UnsupportedTagException, InvalidDataException, IOException
{
this.currentData = 1;
int size = lsMp3file.size();
ArrayList<DataSong> lsds = new ArrayList<>();
for(String mp3file : lsMp3file)
{
System.out.println(this.currentData++);
DataSong ds = new DataSong();
Mp3File mp3 = new Mp3File(mp3file);
ds.setLenghtOfMp3inSec(mp3.getLengthInSeconds());
ds.setBitRateOfMp3(mp3.getBitrate());
ds.setSampleRate(mp3.getSampleRate());
ds.setVbrOrCbr(mp3.isVbr());
if(mp3 != null){
ds.setAbsoluteLocation(mp3.getFilename());
ds.setLocation(removeSDir(mp3.getFilename(), sDir));
if(mp3.hasId3v2Tag())
{
ID3v2 id3v2Tag = mp3.getId3v2Tag();
if(!(id3v2Tag.getArtist() == null))
{
ds.setArtist(id3v2Tag.getAlbumArtist());
}
if(!(id3v2Tag.getAlbum() == null))
{
ds.setAlbum((id3v2Tag.getAlbum()));
}
if(!(id3v2Tag.getTitle() == null))
{
ds.setTitle(id3v2Tag.getTitle());
}
if(!(id3v2Tag.getTrack() == null))
{
ds.setTrackOnAlbum(id3v2Tag.getTrack());
}
if(!(id3v2Tag.getYear() == null) && !(id3v2Tag.getYear().isEmpty()))
{
ds.setYearReleased(id3v2Tag.getYear());
}
if(!(id3v2Tag.getGenreDescription() == null))
{
ds.setGenre(id3v2Tag.getGenreDescription());
}
if(!(id3v2Tag.getComposer() == null))
{
ds.setComposer(id3v2Tag.getComposer());
}
if(!(id3v2Tag.getPublisher() == null))
{
ds.setPublisher(id3v2Tag.getPublisher());
}
if(!(id3v2Tag.getOriginalArtist() == null))
{
ds.setOriginArtist(id3v2Tag.getOriginalArtist());
}
if(!(id3v2Tag.getAlbumArtist() == null))
{
ds.setAlbumArtString(id3v2Tag.getAlbumArtist());
}
if(!(id3v2Tag.getCopyright() == null))
{
ds.setCopyright(id3v2Tag.getCopyright());
}
if(!(id3v2Tag.getUrl() == null))
{
ds.setUrl(id3v2Tag.getUrl());
}
}
}
lsds.add(ds);
}
return lsds;
}
I presume that what I should do is to make my checkMp3File method into a Task method which will do a background thread ?
There is not enough code to be sure but I think you are probably calling your method on the JavaFX application thread which then blocks your UI.
You should read the documentation about concurrency in JavaFX.
https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/concurrency.htm

get value of checked checkbox created dynamically

in this i m fetching data from database i.e. question and answer and accordingly numbers of answer in the database equals to number of checked box created dynamically and i want that the when the user checked the checked box the value of that checked box must me save in sqlite database
public class Multiselect extends Fragment
{
TextView ques;
DefaultHttpClient httpclient;
HttpPost httppost;
HttpResponse httpResponse;
HttpEntity httpEntity;
HttpResponse response;
HttpEntity entity;
InputStream is = null;
String result = null;
StringBuilder sb=null;
BufferedReader reader;
JSONArray jArray;
String line;
String question;
String answer;
int questionno;
int i;
View view;
Context context;
int id=1;
CheckBox checkboxbutton;
final CheckBox[] checkboxbuttons = new CheckBox[50];
LinearLayout l;
//DatabaseMultiselect db;
String text;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.multiselect, container, false);
l=(LinearLayout)view.findViewById(R.id.l1);
/*String l1=l.toString();
String strtext=getArguments().getString("next");
Log.e("str",strtext);*/
StrictMode.enableDefaults();
ques=(TextView)view.findViewById(R.id.quesmultiselect);
//db=new DatabaseMultiselect(getActivity());
// db.open();
getMultiselect();
getAnswer(container);
Log.e("id",""+id);
Log.e("count",""+l.getChildCount());
return view;
}
void getMultiselect()
{
try
{
httpclient=new DefaultHttpClient();
// httppost= new HttpPost("http://10.0.2.2/multiselectandroid.php");
httpResponse = httpclient.execute(httppost);
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
ques.setText("error!!");
}
//convert response to string
try
{
reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
try
{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
questionno=json_data.getInt("question_no");
question=json_data.getString("question");
Log.e("question",question);
//s=s+""+question;
}
ques.setText(question);
}
catch(JSONException excep)
{
excep.printStackTrace();
//Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_LONG).show();
}
catch (ParseException excep)
{
excep.printStackTrace();
}
}
void getAnswer(ViewGroup container)
{
try
{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2/multiselectanswer.php?questionno="+questionno);
httpResponse = httpclient.execute(httppost);
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
ques.setText("error!!");
}
//convert response to string
try
{
reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
//pairing data
try
{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
answer=json_data.getString("answer");
checkboxbuttons[i] = new CheckBox(container.getContext());
checkboxbuttons[i].setId(id);
l.addView(checkboxbuttons[i]);
checkboxbuttons[i].setText(answer);
checkboxbuttons[i].setTextColor(Color.RED);
int rid=checkboxbuttons[i].getId();
Log.e("rid",""+rid);
id++;
}
/* if(id.getCheckedRadioButton==true)
{
String selected=chk;
Log.e("select",selected);
}*/
}
catch(JSONException excep)
{
excep.printStackTrace();
//Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_LONG).show();
}
catch (ParseException excep)
{
excep.printStackTrace();
}
}
}
public class Multiselect extends Fragment
{
//Declaring variables
TextView ques;
TextView condition;
TextView sectionidtext;
TextView instructions;
String instructionset;
int question_no;
String question1;
String surveyName;
String selectedQues;
String username;
int min_answers;
int max_answers;
int id=1;
DatabaseHandler db;
String rating=null;
View view;
final CheckBox[] answercheckbox = new CheckBox[50];
LinearLayout answersettinglayout;
String answertext;
int count=0;
String limit;
String sectionids;
String date=null;
String time=null;
String tablename="multiselect";
String input_answer=null;
String userid;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Getting Question number,user name,survey name,questionnaire name and user id value
Bundle mulitselectBundle=getArguments();
question_no=mulitselectBundle.getInt("questionnum");
surveyName=mulitselectBundle.getString("surveyname");
selectedQues=mulitselectBundle.getString("quesname");
username=mulitselectBundle.getString("username");
userid=mulitselectBundle.getString("userid");
Log.e("mulitselect"," "+question_no);
Log.e("mulitselect",surveyName);
Log.e("mulitselect",selectedQues);
Log.e("mulitselect",username);
Log.e("mulitselect",userid);
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.multiselect, container, false);
//Getting id of Linear Layout for answers
answersettinglayout=(LinearLayout)view.findViewById(R.id.answersetting);
//Getting id of text view for question
ques=(TextView)view.findViewById(R.id.quesmultiselect);
//Getting id of textview for conditions
condition=(TextView)view.findViewById(R.id.conditionmulti);
//Getting id of textview for section id
sectionidtext=(TextView)view.findViewById(R.id.sectionidmultiselect);
//Getting id of text view for instructions display
instructions=(TextView)view.findViewById(R.id.instructionmultiselect);
//Create object of database
db=new DatabaseHandler(getActivity());
//Function call
retrieveQuestion();
getAnswer(container);
getcheckedCheckBoxes();
return view;
}
void retrieveQuestion()
{
//Open database
db.open();
Log.e("inside","retrieve question");
//Fetching value of question and section id
Cursor questioncursor=db.getQuestion(username,surveyName,selectedQues,question_no);
int length=questioncursor.getCount();
Log.e("length",""+length);
//Getting question and section id
if(questioncursor.moveToFirst())
{
//Getting column number
int indexquestion=questioncursor.getColumnIndex("question");
Log.e("index",""+indexquestion);
//Getting value of question and section id
question1= questioncursor.getString(indexquestion);
sectionids=questioncursor.getString(questioncursor.getColumnIndex("ques_id"));
//Setting question
ques.setText(question1);
Log.e("question",question1);
//Setting section id
sectionidtext.setText("Q."+sectionids);
}
//Closing cursor
questioncursor.close();
}
void getAnswer(ViewGroup container)
{
//Open database
db.open();
Log.e("inside","answer question");
//Fetching answers
Cursor answergettingcursor=db. getAnswer(username,surveyName,selectedQues,question_no);
//Declaring variable
int i=0;
//Getting answer value
while(answergettingcursor.moveToPosition(i))
{
//Getting column number
int indexanswer=answergettingcursor.getColumnIndex("answer");
//creating check boxes
answercheckbox[i] = new CheckBox(container.getContext());
//Setting id of check boxes
answercheckbox[i].setId(id);
//Adding check boxes in layout
answersettinglayout.addView(answercheckbox[i]);
//Setting answer value
answercheckbox[i].setText(answergettingcursor.getString(indexanswer));
//Setting text color
answercheckbox[i].setTextColor(Color.RED);
int rid=answercheckbox[i].getId();
Log.e("rid",""+rid);
//Incrementing value
id++;
i++;
}
//Closing cursor
answergettingcursor.close();
}
void getcheckedCheckBoxes()
{
Log.e("id",""+id);
Log.e("count",""+answersettinglayout.getChildCount());
//Fetching value of minimum and maximum characters
Cursor checkcondition=db.getmultiselecttabledata(username, surveyName, selectedQues, question_no);
//For Conditions
if(checkcondition.moveToFirst())
{
//Getting column number
int indexmin_answers=checkcondition.getColumnIndex("min_answers");
int indexmax_answers=checkcondition.getColumnIndex("max_answers");
Log.e("indexanswer",""+indexmin_answers);
Log.e("indexanswer1",""+indexmax_answers);
//Getting value of minimum and maximum characters and instructions
min_answers=checkcondition.getInt(indexmin_answers);
max_answers=checkcondition.getInt(indexmax_answers);
instructionset=checkcondition.getString(checkcondition.getColumnIndex("instructions"));
Log.e("texttableview",""+min_answers);
Log.e("texttableview",""+max_answers);
//Setting value of instructions
instructions.setText(instructionset);
//For answers
for(int k=0;k<answersettinglayout.getChildCount();k++)
{
//Whether check box checked or not
answercheckbox[k].setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//If check box checked
if(((CheckBox) v).isChecked())
{
//Incrementing value of count
count++;
Log.e("count",""+count);
//Getting value of checked check box
answertext=((CheckBox) v).getText().toString();
Log.e("checkbox",""+answertext);
//Checking min and max character conditions
if(count>=min_answers)
{
if(count>max_answers)
{
//Setting text
condition.setText("Selected answers exceeds maximum length");
//Setting text color
condition.setTextColor(Color.RED);
//Setting value of limit
limit="max";
}
else
{
//Setting text
condition.setText("");
//Setting value of limit
limit="proper";
}
}
else
{
//Setting text
condition.setText("Please select more answers");
//Setting text color
condition.setTextColor(Color.RED);
//Setting value of limit
limit="min";
}
//Inserting answers
db.insertAnswer(userid,username,surveyName,selectedQues,question_no,question1,answertext,rating,input_answer,limit,date,time,sectionids,tablename);
}
//if unchecked check box
else
{
//Decreasing count value
count--;
Log.e("count",""+count);
//Getting value of checked check box
answertext=((CheckBox) v).getText().toString();
Log.e("checkboxdelete",""+answertext);
//Deleting unchecked check box value
db.deleteQuesMultiselect(userid,username, surveyName, selectedQues, question_no,answertext);
//Checking min and max character conditions
if(count>=min_answers)
{
if(count>max_answers)
{
//Setting text
condition.setText("Selected answers exceeds maximum length");
//Setting text color
condition.setTextColor(Color.RED);
}
else
{
//Setting text
condition.setText("");
}
}
else
{
//Setting text
condition.setText("Please select more answers");
//Setting text color
condition.setTextColor(Color.RED);
}
}
}
});
}
//Closing cursor
checkcondition.close();
}
}
}

Resources