I have shown on a 10-key layout dynamically created, now I need to retrieve the ID of the button pressed to release the necessary procedure. Here the code.
Button Btn;
Toast msg;
RelativeLayout rl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
Btn = (Button) findViewById( R.id.Btntu );
for (int i = 0; i < 10; i++) {
Btn = new Button(this);
Btn.setText("Número: " + i);
Btn.setGravity(Gravity.CENTER);
Btn.setId(i);
rl = new RelativeLayout(this);
RelativeLayout.LayoutParams parametros = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
Btn.setLayoutParams(parametros);
rl.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT)
);
rl.addView(Btn);
ll.addView(rl);
}
I need the function to retrieve the ID of the button pressed.
Thank you all.
:o)
Have you tried getId() ?
http://developer.android.com/reference/android/view/View.html#getId%28%29
for (int i = 0; i < 10; i++) {
Btn = new Button(this);
Btn.setText("Número: " + i);
Btn.setGravity(Gravity.CENTER);
Btn.setId(i);
Btn.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
Log.d("Button", "ID clicked: " + Btn.getId());
// Or even
Log.d("View", "ID clicked: " + v.getId());
}
});
(...)
}
Related
I'm using Xamarin.Forms.Map and I want to show pins on my map with already expanded window message(without click on them). Something like screenshot. By default window message show only after I clicked on them. How can I do this?
I did a test based on this sample:sample
The thing I do is override the GetViewForAnnotation method.
I add a subview and set it's position based on pin's position.
Here is relative code:
[assembly:ExportRenderer(typeof(CustomMap),typeof(CustomMapRenderer))]
namespace My_Forms_Test3.iOS
{
public class CustomMapRenderer:MapRenderer
{
UIView customPinView;
List<CustomPin> customPins;
protected override void OnElementChanged(ElementChangedEventArgs<View> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
var nativeMap = Control as MKMapView;
nativeMap.GetViewForAnnotation = null;
nativeMap.CalloutAccessoryControlTapped -= OnCallourAccessoryControlTapped;
nativeMap.DidSelectAnnotationView -= OnDidSelect;
nativeMap.DidDeselectAnnotationView -= OnDidDeSelect;
}
if (e.NewElement != null)
{
var formsMap = (CustomMap)e.NewElement;
var nativeMap = Control as MKMapView;
customPins = formsMap.CustomPins;
nativeMap.GetViewForAnnotation = GetViewForAnnotation;
nativeMap.CalloutAccessoryControlTapped += OnCallourAccessoryControlTapped;
nativeMap.DidSelectAnnotationView += OnDidSelect;
nativeMap.DidDeselectAnnotationView += OnDidDeSelect;
}
}
private void OnDidDeSelect(object sender, MKAnnotationViewEventArgs e)
{
if (!e.View.Selected)
{
customPinView.RemoveFromSuperview();
customPinView.Dispose();
customPinView = null;
}
}
private void OnDidSelect(object sender, MKAnnotationViewEventArgs e)
{
throw new NotImplementedException();
}
private void OnCallourAccessoryControlTapped(object sender, MKMapViewAccessoryTappedEventArgs e)
{
throw new NotImplementedException();
}
protected override MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
{
MKAnnotationView annotationView = null;
if (annotation is MKUserLocation)
return null;
var customPin = GetCustomPin(annotation as MKPointAnnotation);
if (customPin == null)
{
throw new Exception("not found");
}
annotationView = mapView.DequeueReusableAnnotation(customPin.Name);
if (annotationView == null)
{
annotationView = new CustomMKAnnotationView(annotation, customPin.Name);
annotationView.Image = UIImage.FromFile("pin.png");
annotationView.CalloutOffset = new CGPoint(0, 0);
annotationView.LeftCalloutAccessoryView = new UIImageView(UIImage.FromFile("monkey.png"));
annotationView.RightCalloutAccessoryView = UIButton.FromType(UIButtonType.DetailDisclosure);
((CustomMKAnnotationView)annotationView).Name = customPin.Name;
customPinView = new UIView();
var Label = new UILabel();
Label.Text = "Samsung";
Label.Frame=new CGRect(annotationView.GetFrame().X+35,annotationView.GetFrame().Y,100,50);
var Label2 = new UILabel();
Label2.Text = "20:20";
Label2.Frame = new CGRect(annotationView.GetFrame().X + 35, annotationView.GetFrame().Y+20, 100, 50);
customPinView.Frame= new CGRect(annotationView.GetFrame().X+40, annotationView.GetFrame().Y-20, 100, 50);
customPinView.AddSubview(Label);
customPinView.AddSubview(Label2);
Label.BaselineAdjustment = UIBaselineAdjustment.AlignBaselines;
customPinView.BackgroundColor = UIColor.White;
customPinView.Layer.CornerRadius = 5;
customPinView.Alpha = (nfloat)0.8;
customPinView.Layer.MasksToBounds = true;
annotationView.AddSubview(customPinView);
}
annotationView.CanShowCallout = true;
return annotationView;
}
CustomPin GetCustomPin(MKPointAnnotation annotation)
{
var position = new Position(annotation.Coordinate.Latitude, annotation.Coordinate.Longitude);
foreach (var pin in customPins)
{
if (pin.Position == position)
{ return pin; }
}
return null;
}}
result:
I am working on a windows forms project. Theres a button which generates new textboxes.
TextBox txtbox = new TextBox();
this.positionY += 40;
txtbox.Location = new System.Drawing.Point(this.positionX, this.positionY);
this.Controls.Add(txtbox);
How can I get the input from these generated textboxes?
Can someone help me?
Best regards
JuRi-2020
You must create an array of text boxes and then access them as array items.
I hope the following code helps.
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int positionX = 10;
int positionY = 0;
TextBox[] txtboxes = new TextBox[3];
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < txtboxes.Length; i++)
{
this.positionY += 40;
txtboxes[i] = new TextBox();
txtboxes[i].Location = new System.Drawing.Point(this.positionX, this.positionY);
this.Controls.Add(txtboxes[i]);
}
}
private void button1_Click(object sender, EventArgs e)
{
string str = "";
for(int i=0; i<txtboxes.Length;i++)
str += txtboxes[i].Text + "\n";
MessageBox.Show(str);
}
}
}
I tried to add Buttons in to an Hbox i wanna grab the index when a button clicked
here is what i have done.
HBox gp = new HBox(10);
gp.setPadding(new Insets(3));
for (int i = 0; i < 20; i++) {
JFXButton jb = new JFXButton("Number " + i);
jb.setStyle("-fx-background-color: rgb(230, 126, 34)");
jb.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("index no?");
}
});
jb.setMinWidth(100);
jb.setMinHeight(50);
gp.getChildren().add(jb);
}
gp.prefWidthProperty().bind(topscroll.widthProperty());
topscroll.setContent(gp);
gp.prefWidthProperty().bind(topscroll.widthProperty());
topscroll.setContent(gp);
any suggestion to achieve that?
You can just copy the index into a final variable:
for (int i = 0; i < 20; i++) {
JFXButton jb = new JFXButton("Number " + i);
jb.setStyle("-fx-background-color: rgb(230, 126, 34)");
int index = i ;
jb.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("index no: " + index);
}
});
jb.setMinWidth(100);
jb.setMinHeight(50);
gp.getChildren().add(jb);
}
Note you can get the button directly (in case that is all you need) without creating another variable:
for (int i = 0; i < 20; i++) {
JFXButton jb = new JFXButton("Number " + i);
jb.setStyle("-fx-background-color: rgb(230, 126, 34)");
jb.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Click on "+jb.getText());
}
});
jb.setMinWidth(100);
jb.setMinHeight(50);
gp.getChildren().add(jb);
}
In one of the apps I'm working on I require the use of custom map pins and I've followed the guide on Xamarin https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/custom-renderer/map/customized-pin/ as well as borrowed their sample code to try and make my own example.
It works to a degree in such that the info window is actually updated to the custom layout but the map pin never changes.
My CustomMapRenderer:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Android.Content;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using Android.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Maps.Android;
using WorkingWithMaps.Droid.Renderers;
using WorkingWithMaps;
[assembly: ExportRenderer(typeof(CustomMap), typeof(CustomMapRenderer))]
namespace WorkingWithMaps.Droid.Renderers
{
public class CustomMapRenderer : MapRenderer, GoogleMap.IInfoWindowAdapter, IOnMapReadyCallback
{
GoogleMap map;
List<CustomPin> customPins;
bool isDrawn;
protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Map> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
map.InfoWindowClick -= OnInfoWindowClick;
}
if (e.NewElement != null)
{
var formsMap = (CustomMap)e.NewElement;
customPins = formsMap.CustomPins;
((MapView)Control).GetMapAsync(this);
}
}
void IOnMapReadyCallback.OnMapReady(GoogleMap googleMap)
{
map = googleMap;
map.SetInfoWindowAdapter(this);
map.InfoWindowClick += OnInfoWindowClick;
this.NativeMap = googleMap;
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName.Equals("VisibleRegion") && !isDrawn)
{
map.Clear();
foreach (var pin in customPins)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Pin.Position.Latitude, pin.Pin.Position.Longitude));
marker.SetTitle(pin.Pin.Label);
marker.SetSnippet(pin.Pin.Address);
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pin));
map.AddMarker(marker);
}
isDrawn = true;
}
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
if (changed)
{
isDrawn = false;
}
}
void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
{
var customPin = GetCustomPin(e.Marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (!string.IsNullOrWhiteSpace(customPin.Url))
{
var url = Android.Net.Uri.Parse(customPin.Url);
var intent = new Intent(Intent.ActionView, url);
intent.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
}
}
public Android.Views.View GetInfoContents(Marker marker)
{
var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
if (inflater != null)
{
Android.Views.View view;
var customPin = GetCustomPin(marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (customPin.Id == "Xamarin")
{
view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
}
else
{
view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
}
var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);
if (infoTitle != null)
{
infoTitle.Text = marker.Title;
}
if (infoSubtitle != null)
{
infoSubtitle.Text = marker.Snippet;
}
return view;
}
return null;
}
public Android.Views.View GetInfoWindow(Marker marker)
{
return null;
}
CustomPin GetCustomPin(Marker annotation)
{
var position = new Position(annotation.Position.Latitude, annotation.Position.Longitude);
foreach (var pin in customPins)
{
if (pin.Pin.Position == position)
{
return pin;
}
}
return null;
}
}
}
and my map page, also heavily borrowed from Xamarin's working with maps guide
using Plugin.Geolocator;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Xaml;
namespace WorkingWithMaps
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainPage : ContentPage
{
CustomMap map;
Geocoder geoCoder;
String navAdd;
public MainPage()
{
InitializeComponent();
var maplocator = CrossGeolocator.Current;
maplocator.DesiredAccuracy = 1;
geoCoder = new Geocoder();
map = new CustomMap
{
HeightRequest = 100,
WidthRequest = 960,
VerticalOptions = LayoutOptions.FillAndExpand,
IsShowingUser = true
};
map.MapType = MapType.Street;
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(55.237208, 10.479160), Distance.FromMeters(500)));
map.IsShowingUser = true;
var street = new Button { Text = "Street" };
var hybrid = new Button { Text = "Hybrid" };
var satellite = new Button { Text = "Satellite" };
street.Clicked += HandleClickedAsync;
hybrid.Clicked += HandleClickedAsync;
//satellite.Clicked += OnReverseGeocodeButtonClicked;
var segments = new StackLayout
{
Spacing = 30,
HorizontalOptions = LayoutOptions.CenterAndExpand,
Orientation = StackOrientation.Horizontal,
Children = { street, hybrid, satellite }
};
Content = new StackLayout
{
HorizontalOptions = LayoutOptions.Center,
Children = { map, segments }
};
Device.BeginInvokeOnMainThread(async () =>
{
try
{
//var currentpos = await maplocator.GetPositionAsync(1000);
//map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(currentpos.Latitude, currentpos.Longitude), Distance.FromMeters(500)));
if (!maplocator.IsListening)
{
await maplocator.StartListeningAsync(1000, 50, true);
}
}
catch (Exception ex)
{
Debug.WriteLine("Fail" + ex);
}
});
var pin = new CustomPin
{
Pin = new Pin
{
Type = PinType.Place,
Position = new Position(55.240121, 10.469895),
Label = "Testing Pins"
}
};
map.CustomPins = new List<CustomPin> { pin };
map.Pins.Add(pin.Pin);
map.PropertyChanged += (sender, e) =>
{
Debug.WriteLine(e.PropertyName + " just changed!");
if (e.PropertyName == "VisibleRegion" && map.VisibleRegion != null)
CalculateBoundingCoordinates(map.VisibleRegion);
};
maplocator.PositionChanged += (sender, e) =>
{
var position = e.Position;
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(position.Latitude, position.Longitude), Distance.FromKilometers(2)));
};
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
//async void OnReverseGeocodeButtonClicked(object sender, EventArgs e)
//{
// var possibleAddresses = await geoCoder.GetAddressesForPositionAsync(pin.Position);
// navAdd += possibleAddresses.ElementAt(0) + "\n";
// switch (Device.OS)
// {
// case TargetPlatform.iOS:
// Device.OpenUri(new Uri(string.Format("http://maps.apple.com/?q={0}", WebUtility.UrlEncode(navAdd))));
// break;
// case TargetPlatform.Android:
// Device.OpenUri(new Uri(string.Format("geo:0,0?q={0}", WebUtility.UrlEncode(navAdd))));
// break;
// case TargetPlatform.Windows:
// case TargetPlatform.WinPhone:
// Device.OpenUri(new Uri(string.Format("bingmaps:?where={0}", Uri.EscapeDataString(navAdd))));
// break;
// }
//}
void HandleClickedAsync(object sender, EventArgs e)
{
var b = sender as Button;
switch (b.Text)
{
case "Street":
map.MapType = MapType.Street;
break;
case "Hybrid":
map.MapType = MapType.Hybrid;
break;
case "Satellite":
map.MapType = MapType.Satellite;
break;
}
}
static void CalculateBoundingCoordinates(MapSpan region)
{
var center = region.Center;
var halfheightDegrees = region.LatitudeDegrees / 2;
var halfwidthDegrees = region.LongitudeDegrees / 2;
var left = center.Longitude - halfwidthDegrees;
var right = center.Longitude + halfwidthDegrees;
var top = center.Latitude + halfheightDegrees;
var bottom = center.Latitude - halfheightDegrees;
if (left < -180) left = 180 + (180 + left);
if (right > 180) right = (right - 180) - 180;
Debug.WriteLine("Bounding box:");
Debug.WriteLine(" " + top);
Debug.WriteLine(" " + left + " " + right);
Debug.WriteLine(" " + bottom);
}
}
}
On top of the mentioned issue the implementation has also caused IsShowingUser = True to no longer function as well as
var currentpos = await maplocator.GetPositionAsync(1000);
to throw an exception.
Github repository: https://github.com/Mortp/CustomMapPinsXamarin
First of all I would like to provide 2 links that helped me to understand the problem. Thank you guys.
Xamarin.Forms.Maps 2.3.4 custom MapRenderer disables everything and https://forums.xamarin.com/discussion/92565/android-ionmapreadycallback-forms-2-3-4
Latest Xamarin Maps broke OnElementPropertyChanged with VisibleRegion. They defined that MapRenderer now implements IOnMapReadyCallback and that broke somehow OnElementPropertyChanged (I didn't investigate how and why). As you can see in link I provided there are 2 methods you can go. To keep your renderer implementing IOnMapReadyCallback or not. When I kept IOnMapReadyCallback I started to get 2 pins - one of top another - our custom pin and regular pin. I didn't dig more how that happens and removed IOnMapReadyCallback. After that things became really simple because if you let Xamarin handle it and create NativeMap you can remove some code and make renderer simpler.
Before I post the code I also want to mention that when I fixed it the app started crashing with OutOfMemory exception and I found out that your pin image is 2000 pixels width. I changed it to 40. Below is the code:
public class CustomMapRenderer : MapRenderer, GoogleMap.IInfoWindowAdapter//, IOnMapReadyCallback
{
bool isDrawn;
protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Map> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
NativeMap.InfoWindowClick -= OnInfoWindowClick;
}
}
bool isMapReady;
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (!isMapReady && (NativeMap != null))
{
NativeMap.SetInfoWindowAdapter(this);
NativeMap.InfoWindowClick += OnInfoWindowClick;
isMapReady = true;
}
if (e.PropertyName.Equals("VisibleRegion") && !isDrawn)
{
NativeMap.Clear();
foreach (var pin in ((CustomMap)Element).CustomPins)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Pin.Position.Latitude, pin.Pin.Position.Longitude));
marker.SetTitle(pin.Pin.Label);
marker.SetSnippet(pin.Pin.Address);
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pin));
NativeMap.AddMarker(marker);
}
isDrawn = true;
}
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
if (changed)
{
isDrawn = false;
}
}
void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
{
var customPin = GetCustomPin(e.Marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (!string.IsNullOrWhiteSpace(customPin.Url))
{
var url = Android.Net.Uri.Parse(customPin.Url);
var intent = new Intent(Intent.ActionView, url);
intent.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
}
}
public Android.Views.View GetInfoContents(Marker marker)
{
var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
if (inflater != null)
{
Android.Views.View view;
var customPin = GetCustomPin(marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (customPin.Id == "Xamarin")
{
view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
}
else
{
view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
}
var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);
if (infoTitle != null)
{
infoTitle.Text = marker.Title;
}
if (infoSubtitle != null)
{
infoSubtitle.Text = marker.Snippet;
}
return view;
}
return null;
}
public Android.Views.View GetInfoWindow(Marker marker)
{
return null;
}
CustomPin GetCustomPin(Marker annotation)
{
var position = new Position(annotation.Position.Latitude, annotation.Position.Longitude);
foreach (var pin in ((CustomMap)Element).CustomPins)
{
if (pin.Pin.Position == position)
{
return pin;
}
}
return null;
}
}
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();
}
}
}