How do I access the default android style from code? - android-styles

I'm trying to write my own version of android.widget.SeekBar by modifying the android source code: I can't use a derived class because I want to override some behaviour using private member variables which aren't visible to a derived class.
SeekBar, like most widgets, is styled. I want to change the behaviour, but not the style, so I need to get the default style that android.widget.SeekBar uses. The version in the android sources gets its style with something like this:-
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.SeekBar, defStyleAttr, defStyleRes);
final drawable thumb = a.getDrawable(R.styleable.SeekBar_thumb);
...
a.recycle();
Well R.styleable isn't accessible in user code. The answer to How do I access an Android internal style attributes via derived classes? suggests replacing R.styleable.SeekBar with
new int[] { android.R.attr.seekBarStyle }, but omits the a.recycle(), which I suspect may be wrong. It also says that only one style attribute at a time can be accessed in this way. Presumably you need to recycle the TypedArray each time
However SeekBar has a whole lot of style attributes, and the only thing exported from r.attr is android.R.attr.seekBarStyle, which is a single integer How do I get at the individual style attributes?

You can get the values of default resources with some code like this:-
Resources res = getResources();
int defStyleAttr = res.getIdentifier(
"android:attr/seekBarStyle", "", "android");
int resId = res.getIdentifier(
"android:attr/thumb", "", "android");
TypedArray a = obtainStyledAttributes(
null, new int[] {resId}, defStyleAttr, 0);
final Drawable thumb = a.getDrawable(0);
a.recycle();
resId = res.getIdentifier(
"android:attr/thumbTint", "", "android");
a = obtainStyledAttributes(
null, new int[] {resId}, defStyleAttr, 0);
ColorStateList ThumbTintList = null;
ThumbTintList = a.getColorStateList(0);
a.recycle();
resId = res.getIdentifier(
"android:attr/progressDrawable", "", "android");
a = obtainStyledAttributes(
null, new int[] {resId}, defStyleAttr, 0);
final Drawable track = a.getDrawable(0);
a.recycle();
resId = res.getIdentifier(
"android:attr/progressTint", "", "android");
a = obtainStyledAttributes(
null, new int[] {resId}, defStyleAttr, 0);
ColorStateList progressTintList = null;
progressTintList = a.getColorStateList(0);
a.recycle();
resId = res.getIdentifier(
"android:attr/paddingLeft", "", "android");
a = obtainStyledAttributes(
null, new int[] {resId}, defStyleAttr, 0);
int paddingLeft = a.getInt(0, 0);
a.recycle();
resId = res.getIdentifier(
"android:attr/paddingTop", "", "android");
a = obtainStyledAttributes(
null, new int[] {resId}, defStyleAttr, 0);
int paddingTop = a.getInt(0, 0);
a.recycle();
resId = res.getIdentifier(
"android:attr/paddingRight", "", "android");
a = obtainStyledAttributes(
null, new int[] {resId}, defStyleAttr, 0);
int paddingRight = a.getInt(0, 0);
a.recycle();
resId = res.getIdentifier(
"android:attr/paddingBottom", "", "android");
a = obtainStyledAttributes(
null, new int[] {resId}, defStyleAttr, 0);
int paddingBottom = a.getInt(0, 0);
a.recycle();
getIdentifier is deprecated, but currently (4 January 2022) still works. Of course you need to know the names of the resources. These you can get from R.styleable by chopping off the initial class name and the underscore.
getResources and obtainStyledAttributes are member functions of Context, so if you aren't calling them from a class which inherits Context (Activities do, but widgets don't), you need a context. in front.
You can get the name for defStyleAttr by looking in the source code of the widget that you're replacing: it seems to be the name of the widget class with initial letter lower-cased and "Style" appended. If you're creating a completely new widget, 0 should do, but I haven't properly tested that.

Related

Duplicate Fields using itextsharp

I have this code to create TextFields
public void MssCreateTextField(byte[] ssPdf, RCRectangleRecord ssRectangle, string ssName, int ssFontSize, string ssValue, int ssPage, out byte[] ssPdfOut, bool ssIsMultiline) {
PdfReader reader = new PdfReader(ssPdf);
ssPdfOut = null;
var output = new MemoryStream();
var stamper = new PdfStamper(reader, output);
/*TextField tField = new TextField(stamper.Writer, new iTextSharp.text.Rectangle((float)ssRectangle.ssSTRectangle.ssllx, (float)ssRectangle.ssSTRectangle.sslly, (float)ssRectangle.ssSTRectangle.ssurx, (float)ssRectangle.ssSTRectangle.ssury), ssName);
if (ssValue!="")
tField.Text = ssValue;
if (ssIsMultiline)
tField.Options = TextField.MULTILINE;
tField.FontSize = ssFontSize;*/
PdfFormField tField = PdfFormField.CreateTextField(stamper.Writer, ssIsMultiline, false, 50);
tField.FieldName = ssName;
tField.SetWidget(new iTextSharp.text.Rectangle((float)ssRectangle.ssSTRectangle.ssllx, (float)ssRectangle.ssSTRectangle.sslly, (float)ssRectangle.ssSTRectangle.ssurx, (float)ssRectangle.ssSTRectangle.ssury), PdfAnnotation.HIGHLIGHT_TOGGLE);
stamper.FormFlattening = false;
stamper.AddAnnotation(tField, ssPage);
stamper.Close();
reader.Close();
ssPdfOut = output.ToArray();
}
As you can see i have some code commented as an alternative but the two different ways are producing the same result.
What i am trying to achieve is create two textfields with the same name to when editing one it edits the others two. This two codes do that (in the browsers and pdfescape site) excepting in the adobe acrobat reader. In the acrobat reader i get just the first field visible and the others hidden i dont know why...
If you want to add two text field visualizations which represent the same content, you have to add them as two widgets of the same field and not two distinct fields, e.g. like this:
public void CreateDoubleTextField(byte[] ssPdf, Rectangle ssRectangle1, Rectangle ssRectangle2, string ssName, int ssFontSize, string ssValue, int ssPage, out byte[] ssPdfOut, bool ssIsMultiline)
{
PdfReader reader = new PdfReader(ssPdf);
ssPdfOut = null;
var output = new MemoryStream();
var stamper = new PdfStamper(reader, output);
PdfFormField tField = PdfFormField.CreateTextField(stamper.Writer, ssIsMultiline, false, 50);
tField.FieldName = ssName;
PdfFormField widget1 = PdfFormField.CreateEmpty(stamper.Writer);
widget1.SetWidget(ssRectangle1, PdfAnnotation.HIGHLIGHT_TOGGLE);
PdfFormField widget2 = PdfFormField.CreateEmpty(stamper.Writer);
widget2.SetWidget(ssRectangle2, PdfAnnotation.HIGHLIGHT_TOGGLE);
tField.AddKid(widget1);
tField.AddKid(widget2);
stamper.FormFlattening = false;
stamper.AddAnnotation(tField, ssPage);
stamper.Close();
reader.Close();
ssPdfOut = output.ToArray();
}
(As I don't have that RCRectangleRecord, I use the iTextSharp Rectangle class as argument.)
This gives you two field visualizations in Adobe Acrobat Reader; after editing one of them and switching focus (e.g. clicking somewhere outside that visualization), the other visualization duplicates the content.
Now i have this and i can create two fields when the list has more than one Rectangle but for some reason i dont know how the two fields appears without the name!!
PdfReader reader = new PdfReader(ssPdf);
ssPdfOut = null;
var output = new MemoryStream();
var stamper = new PdfStamper(reader, output);
TextField tField;
if (ssRectangle.Count==1){
tField= new TextField(stamper.Writer, new iTextSharp.text.Rectangle((float)ssRectangle[0].ssSTRectangle.ssllx, (float)ssRectangle[0].ssSTRectangle.sslly, (float)ssRectangle[0].ssSTRectangle.ssurx, (float)ssRectangle[0].ssSTRectangle.ssury), ssName);
if (ssValue!="")
tField.Text = ssValue;
if (ssIsMultiline)
tField.Options = TextField.MULTILINE;
tField.FontSize = ssFontSize;
tField.FieldName = ssName;
stamper.AddAnnotation(tField.GetTextField(), ssPage);
}
else
{
PdfFormField PtField = PdfFormField.CreateTextField(stamper.Writer, ssIsMultiline, false, 250);
PtField.Name=ssName;
foreach (RCRectangleRecord item in ssRectangle)
{
/*
tField=new TextField(stamper.Writer, new iTextSharp.text.Rectangle((float)ssRectangle[0].ssSTRectangle.ssllx, (float)ssRectangle[0].ssSTRectangle.sslly, (float)ssRectangle[0].ssSTRectangle.ssurx, (float)ssRectangle[0].ssSTRectangle.ssury), ssName);
tField.FieldName = ssName;
PtField.AddKid(tField.GetTextField());*/
PdfFormField widget = PdfFormField.CreateEmpty(stamper.Writer);
widget.SetWidget(new Rectangle((float)item.ssSTRectangle.ssllx, (float)item.ssSTRectangle.sslly, (float)item.ssSTRectangle.ssurx, (float)item.ssSTRectangle.ssury), PdfAnnotation.HIGHLIGHT_TOGGLE);
widget.Name = ssName;
PtField.AddKid(widget);
}
stamper.AddAnnotation(PtField, ssPage);
}
stamper.FormFlattening = false;
stamper.Close();
reader.Close();
ssPdfOut = output.ToArray();

Java Swing won’t display

I’m getting an error for regarding a nullPointerException and my JavaSwing project won’t display as a result. I think I need to initialise the employeeInfoPanel to the JFrams on line 55 but I dont know how to do this. There could be other errors after that. Any info/tips would be greatly appreciated!
package employee;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class taxSystemDriver1 extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel homePanel, employeeInfoPanel, taxDetailsPanel, textInputPanel;
private JPanel ppsPanel, surnamePanel, firstnamePanel, dobPanel, salaryPanel, maritialStatusPanel,noIncomesPanel, noDependentChildrenPanel, noBIKPanel;
private JPanel buttonPanel, buttonPanelTop, buttonPanelBottom;
private JButton calculatorButton, recordsButton, addEmployeeButton, modifyEmployeeButton, deleteEmployeeButton, saveButton, backButton;
private JLabel comboLabel1, ppsLabel, surnameLabel, firstnameLabel, dobLabel, salaryLabel, maritialStatusLabel, noIncomesLabel, noDependentChildrenLabel, noBIKLabel;
private JLabel birthDayLabel, birthMonthLabel, birthYearLabel;
private JComboBox birthDayComboBox, birthMonthComboBox, birthYearComboBox, incomeComboBox;
private JRadioButton childrenRadioButton, maritialStatusRadioButton;
private JButton addEmployee, deleteEmployee, modifyEmployee, displayFirst, displayNext, displayLast, displayTaxDetails;
private JTextField ppsTF, surnameTF, firstnameTF, dobTF, salaryTF, maritialStatusTF, noIncomesTF, noDependentChildrenTF, noBIKTF;
private JTextArea statementTextArea;
private JScrollPane statementPane;
public taxSystemDriver1 (String title) {
super(title);
initComponents();
}
private void initComponents() {
setSize(300, 500);
setLocation(100, 100);
//construct components
//**************************************************************************
// HomePanel North
//**************************************************************************
//*********************************************
// EmployeeInfo Panel West
//*********************************************
// PPS NUMBER (TextField)
ppsPanel = new JPanel();
ppsLabel = new JLabel ("PPS Number: ");
ppsLabel.setHorizontalAlignment(SwingConstants.LEFT);
ppsTF = new JTextField (5);
ppsTF.setEditable(true);
ppsPanel.add(ppsLabel);
ppsPanel.add(ppsTF);
employeeInfoPanel.add(ppsPanel);
// SURNAME (TextField)
surnamePanel = new JPanel();
surnameLabel = new JLabel ("Employee Surname: ");
surnameLabel.setHorizontalAlignment(SwingConstants.LEFT);
surnameTF = new JTextField (5);
surnameTF.setEditable(true);
surnamePanel.add(surnameLabel);
surnamePanel.add(surnameTF);
employeeInfoPanel.add(surnamePanel);
// FIRST NAME (TextField)
firstnamePanel = new JPanel();
firstnameLabel = new JLabel ("Employee First Name: ");
firstnameLabel.setHorizontalAlignment(SwingConstants.LEFT);
firstnameTF = new JTextField (5);
firstnameTF.setEditable(true);
firstnamePanel.add(firstnameLabel);
firstnamePanel.add(firstnameTF);
employeeInfoPanel.add(firstnamePanel);
// DOB (ComboBox)
dobPanel = new JPanel();
dobPanel.add(new JLabel ("Employee Date of Birth: "));
String[] days = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15",
"16","17","18","19","20","21","22","23","24","25","26","27","28",
"29","30","31"};
birthDayComboBox = new JComboBox(days);
dobPanel.add(birthDayComboBox);
String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"};
birthMonthComboBox = new JComboBox(months);
dobPanel.add(birthMonthComboBox);
String[] years = {"1996", "1995", "1994", "1993", "1992", "1991", "1990", "1989", "1988", "1987", "1986", "1985", "1984",
"1983", "1982", "1981", "1980", "1979", "1978", "1977", "1976", "1975", "1974", "1973", "1972", "1971", "1970",
"1969", "1968", "1967", "1966", "1965", "1964", "1963", "1962", "1961", "1960", "1959", "1958", "1957", "1956",
"1955", "1954", "1953", "1952", "1951", "1950", "1949", "1948", "1947", "1946", "1945", "1944", "1943", "1942",
"1941", "1940"};
birthYearComboBox = new JComboBox (years);
dobPanel.add(birthYearComboBox);
employeeInfoPanel.add(dobPanel);
//*********************************************
// TaxDetails Panel East
//*********************************************
// SALARY (TextField)
salaryPanel = new JPanel();
salaryLabel = new JLabel ("Employee yearly salary: €");
salaryLabel.setHorizontalAlignment(SwingConstants.LEFT);
salaryTF = new JTextField (5);
salaryTF.setEditable(true);
salaryPanel.add(salaryLabel);
salaryPanel.add(salaryTF);
taxDetailsPanel.add(salaryPanel);
// MARITIAL STATUS (Radio Button)
final ButtonGroup maritialStatus = new ButtonGroup();
maritialStatusPanel = new JPanel();
maritialStatusPanel.add(new JLabel("Relationship Status: "));
maritialStatusRadioButton = new JRadioButton ("Single", true);
maritialStatusRadioButton.setActionCommand("Single");
maritialStatus.add(maritialStatusRadioButton);
maritialStatusPanel.add(maritialStatusRadioButton);
maritialStatusRadioButton = new JRadioButton ("In unmarried Relationship");
maritialStatusRadioButton.setActionCommand("In unmarried Relationship");
maritialStatus.add(maritialStatusRadioButton);
maritialStatusPanel.add(maritialStatusRadioButton);
maritialStatusRadioButton = new JRadioButton ("Married");
maritialStatusRadioButton.setActionCommand("Married");
maritialStatus.add(maritialStatusRadioButton);
maritialStatusPanel.add(maritialStatusRadioButton);
taxDetailsPanel.add(maritialStatusRadioButton);
// NUMBER OF INCOMES IN HOUSEHOLD (ComboBox)
noIncomesPanel = new JPanel();
noIncomesPanel.add(new JLabel("Number of Incomes in the Household"));
String[] income = {"1", "2"};
incomeComboBox = new JComboBox(income);
noIncomesPanel.add(incomeComboBox);
taxDetailsPanel.add(incomeComboBox);
// NUMBER OF INDEPENDENT CHILDREN (Radio Button)
final ButtonGroup childrenNumber = new ButtonGroup();
noDependentChildrenPanel = new JPanel();
noDependentChildrenPanel.add(new JLabel("Number of Dependent Children: "));
childrenRadioButton = new JRadioButton ("0", true);
childrenRadioButton.setActionCommand("0");
childrenNumber.add(childrenRadioButton);
noDependentChildrenPanel.add(childrenRadioButton);
childrenRadioButton = new JRadioButton ("1");
childrenRadioButton.setActionCommand("1");
childrenNumber.add(childrenRadioButton);
noDependentChildrenPanel.add(childrenRadioButton);
childrenRadioButton = new JRadioButton ("2");
childrenRadioButton.setActionCommand("2");
childrenNumber.add(childrenRadioButton);
noDependentChildrenPanel.add(childrenRadioButton);
childrenRadioButton = new JRadioButton ("3");
childrenRadioButton.setActionCommand("3");
childrenNumber.add(childrenRadioButton);
noDependentChildrenPanel.add(childrenRadioButton);
childrenRadioButton = new JRadioButton ("4");
childrenRadioButton.setActionCommand("4");
childrenNumber.add(childrenRadioButton);
noDependentChildrenPanel.add(childrenRadioButton);
childrenRadioButton = new JRadioButton ("5");
childrenRadioButton.setActionCommand("5");
childrenNumber.add(childrenRadioButton);
noDependentChildrenPanel.add(childrenRadioButton);
taxDetailsPanel.add(childrenRadioButton);
// AMOUNT OF BENEFIT IN KIND (TextField)
noBIKPanel = new JPanel();
noBIKLabel = new JLabel ("Amount of benefits in kind : €");
noBIKLabel.setHorizontalAlignment(SwingConstants.LEFT);
noBIKTF = new JTextField (5);
noBIKTF.setEditable(true);
noBIKPanel.add(noBIKLabel);
noBIKPanel.add(noBIKTF);
taxDetailsPanel.add(noBIKPanel);
Container content = getContentPane();
content.setLayout(new BorderLayout());
content.add(homePanel, BorderLayout.NORTH);
homePanel.setLayout(new BorderLayout());
homePanel.add(employeeInfoPanel, BorderLayout.WEST);
homePanel.add(taxDetailsPanel, BorderLayout.EAST);
//*****************************************************
// ButtonGroup Panel Center
//*****************************************************
addEmployeeButton = new JButton("Add Employee");
modifyEmployeeButton = new JButton("Modify Employee");
deleteEmployeeButton = new JButton("Delete Employee");
displayFirst = new JButton("Display First Employee");
displayNext = new JButton("Display Next Employee");
displayLast = new JButton("Display Last Employee");
displayTaxDetails = new JButton("Display Employee Tax Details");
content.add(buttonPanel, BorderLayout.CENTER);
buttonPanel.setLayout(new BorderLayout());
buttonPanel.add(buttonPanelTop, BorderLayout.NORTH);
buttonPanel.add(buttonPanelBottom, BorderLayout.SOUTH);
buttonPanelTop.setLayout(new FlowLayout());
buttonPanelTop.add(addEmployeeButton);
buttonPanelTop.add(modifyEmployeeButton);
buttonPanelTop.add(deleteEmployeeButton);
buttonPanelBottom.setLayout(new FlowLayout());
buttonPanelBottom.add(displayFirst);
buttonPanelBottom.add(displayLast);
buttonPanelBottom.add(displayNext);
buttonPanelBottom.add(displayTaxDetails);
}
/*employeeInfoPanel = new JPanel();
employeeInfoPanel.setLayout(new GridLayout(7, 1));
public static void main(String[] args)
{
JFrame taxFrame = new taxSystemDriver1("Tax and Revenue System");
taxFrame.setVisible(true);
Your are calling a method on an object that does not exist (employeeInfoPanel is an attribute which is never constructed or assigned before the #add(...) method call).
To initialize your employeeInfoPanel, a simple default construction:
employeeInfoPanel = new JPanel();

android - trying to create listview

i'm trying to write data from sqlite to a listview. the compiler doesn't show error, but when I run the app on my phone, it crashes. please help me
Cursor resultSet = db.rawQuery("Select * from weight_listview ORDER BY `id` DESC",null);
resultSet.moveToFirst();
String[] list = new String[] {};
String[] weighttolist={};
String[] datetolist={};
ArrayList<String> List=new ArrayList<String>();
ArrayList<String> List2=new ArrayList<String>();
resultSet.moveToFirst();
int x = 0;
while(resultSet.moveToNext()){
String data = resultSet.getString(resultSet.getColumnIndex("weight"));
String data2 = resultSet.getString(resultSet.getColumnIndex("date"));
String id = resultSet.getString(resultSet.getColumnIndex("ID"));
List.add(data + " " + data2);
x++;
}
final ListView listView = (ListView) findViewById(R.id.listView1);
if(List != null){
weighttolist=(String[])List.toArray(new String[0]);
String[] from = { "weight", "date" };
int[] to = { R.id.weight, R.id.date };
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,R.layout.row, resultSet, from, to);
listView.setAdapter(cursorAdapter);
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1, android.R.id.text1, weighttolist);
// ListView.setAdapter(adapter);
}
edit:
I successed to fix the problem but now I have another problem. I want that the listview will show 2 columns , not only 1 . I created fill row.xml , as you can see in the first code.
Cursor resultSet = db.rawQuery("Select * from weight_listview ORDER BY `id` DESC",null);
resultSet.moveToFirst();
String[] list = new String[] {};
String[] weighttolist={};
String[] datetolist={};
ArrayList<String> List=new ArrayList<String>();
ArrayList<String> List2=new ArrayList<String>();
resultSet.moveToFirst();
int x = 0;
while(resultSet.moveToNext()){
String data = resultSet.getString(resultSet.getColumnIndex("weight"));
String data2 = resultSet.getString(resultSet.getColumnIndex("date"));
List.add(data + " " + data2);
x++;
}
final ListView listView = (ListView) findViewById(R.id.listView1);
if(List != null){
weighttolist=(String[])List.toArray(new String[0]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, weighttolist);
listView.setAdapter(adapter);
}
Well without the exact error it is hard to see what is going wrong. Here is my guess you are using a SimpleAdapter who's constructor looks like this
SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
For your second parameter you are using a Cursor not a list, your from variable are keys so you need to use a hash map I believe
Comment out your code and try this
List<HashMap<String, String>> List = new ArrayList<HashMap<String, String>>();
int x = 0;
while(resultSet.moveToNext()){
HashMap<String, String> map = new HashMap<String, String>();
String weight = resultSet.getString(resultSet.getColumnIndex("weight"));
String date = resultSet.getString(resultSet.getColumnIndex("date"));
String id = resultSet.getString(resultSet.getColumnIndex("ID"));
map.put("weight", weight);
map.put("date", date);
List.add(map);
x++;
}
final ListView listView = (ListView) findViewById(R.id.listView1);
if(List != null){
weighttolist=(String[])List.toArray(new String[0]);
String[] from = { "weight", "date" };
int[] to = { R.id.weight, R.id.date };
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,R.layout.row, List, from, to);
listView.setAdapter(cursorAdapter);

android listview with item and sub item not working properly

I have a database which i select 2 strings one as an item other one is description.I am trying to map these 2 strings into a listview item-subitem layout. the following code is what i tried so far.
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
Map<String, String> datum = new HashMap<String, String>(2);
SimpleAdapter adapter = new SimpleAdapter(this, data,
android.R.layout.simple_list_item_2,
new String[] { "item","descr" },
new int[] { android.R.id.text1, android.R.id.text2 });
itemList.setAdapter(adapter);
Cursor cours = MainActivity.mydb.query("sub_menu", null, "cat_id = "
+ menuid + " AND sub_flag = 1", null, null, null, null);
if (cours.moveToFirst()) {
do {
datum.put("item", cours.getString(cours.getColumnIndex("sub_label")));
datum.put("descr", cours.getString(cours.getColumnIndex("sub_description")));
data.add(datum);
Log.d("testt", datum.toString());
adapter.notifyDataSetChanged();
} while (cours.moveToNext());
}
the problem now it will add 5 entries to the listview with the same values which are the last row selected form the database which is not what. any idea how to fix this ?
EDIT.
after experimenting with it i found that i was overwriting the object datum which end up having the save value for all the entries. the fix was as easy as moving the intializition line for datum into the loop. here is the final code
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
String[] from = new String[] { "rowid", "col_1" };
int[] to = new int[] { android.R.id.text1, android.R.id.text2 };
Cursor cours = MainActivity.mydb.query("sub_menu", null, "cat_id = "
+ menuid + " AND sub_flag = 1", null, null, null, null);
if (cours.moveToFirst()) {
do {
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("rowid",
cours.getString(cours.getColumnIndex("sub_label")));
datum.put("col_1", cours.getString(cours
.getColumnIndex("sub_description")));
data.add(datum);
} while (cours.moveToNext());
}
SimpleAdapter adapter = new SimpleAdapter(this, data,
android.R.layout.simple_list_item_2, from, to);
itemList.setAdapter(adapter);
make custom ListView and use CursorAdapter
Here is a good example will help you.

The barchart(jfreechart) is displayed as small icon on a composite in a view of Eclipse RCP plugin

The barchart is displayed as small icon on a composite of a view in Eclipse RCP plugin. The chart does not cover the entire composite which should be the actual case. what additional setting needs to be made in code to display the graph on entire composite
Following is the code for displaying the bargraph
final CategoryDataset dataset = createDataset();
final JFreeChart chart = createChart(dataset);
if(flag == false){
frame.dispose();
}
frame = new ChartComposite(barchartComposite,SWT.NONE,chart,true);
frame.setLayoutData(new GridData(GridData.FILL_BOTH));
frame.setChart(chart);
frame.forceRedraw();
frame.pack();
frame.setVisible(true);
flag= false;
The method createDataset() generates the data for the barchart and method createChart(dataset) generates the barchart.
THE COMPLETE SOURCE CODE FOR DISPLAY OF VIEW
public class BarChartDisplay extends ViewPart {
Text searchfield = null;
String path = SelectDataBase.path;
public static int error=0;
public static int info=0;
public static int critical=0;
public static int warning=0;
ChartComposite frame;
boolean flag=true;
public BarChartDisplay() {
}
#Override
public void createPartControl(Composite parent) {
//Composite A:
final Composite mainComposite = new Composite(parent, SWT.NONE);
GridData mainLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true);
mainLayoutData.horizontalSpan = 1;
mainComposite.setLayoutData(mainLayoutData);
GridLayout outerLayout = new GridLayout();
outerLayout.marginTop = 30;
outerLayout.marginLeft = 20;
outerLayout.marginRight = 20;
mainComposite.setLayout(new GridLayout(1, false));
//Composite B:
final Composite selectComposite = new Composite(mainComposite, SWT.NONE);
selectComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
selectComposite.setLayout(new GridLayout(4, false));
//Composite C:
final Composite barchartComposite = new Composite(mainComposite, SWT.NONE);
barchartComposite.setLayout(new GridLayout(1, false));
barchartComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
final CalendarCombo ccombo = new CalendarCombo(selectComposite, SWT.READ_ONLY | SWT.FLAT);
GridData layoutDataCal = new GridData(150, 40);
ccombo.computeSize(SWT.DEFAULT, SWT.DEFAULT);
ccombo.showCalendar();
ccombo.setLayoutData(layoutDataCal);
org.eclipse.swt.widgets.Button button = new org.eclipse.swt.widgets.Button(selectComposite, SWT.PUSH);
button.setText("Go");
button.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
switch (e.type) {
case SWT.Selection:
error = 0;
info = 0;
warning = 0;
critical = 0;
DB db = new DB();
Connection conn = null;
conn = db.ConnTable(path);
Statement statement;
try {
statement = conn.createStatement();
String query = null;
String textfielddata = ccombo.getDateAsString();
System.out.println(textfielddata);
query = "select priority from log where creation_date = '"+ textfielddata +"'";
System.out.println(query);
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
int prioritydata = rs.getInt("priority");
if (prioritydata == 1)
error++;
else if (prioritydata == 2)
info++;
else if (prioritydata == 3)
warning++;
else if (prioritydata == 4)
critical++;
}
} catch (SQLException er) {
er.printStackTrace();
}
final CategoryDataset dataset = createDataset();
final JFreeChart chart = createChart(dataset);
if(flag == false){
frame.dispose();
}
frame = new ChartComposite(barchartComposite,SWT.BORDER,chart,true);
frame.setLayoutData(new GridData(GridData.FILL_BOTH));
frame.setChart(chart);
frame.forceRedraw();
frame.pack();
frame.setVisible(true);
flag= false;
break;
}
}
});
}
/**
* Returns a sample dataset.
*
* #return The dataset.
*/
private CategoryDataset createDataset() {
// row keys...
final String series1 = "First";
// column keys...
final String category1 = "error";
final String category2 = "info";
final String category3 = "warning";
final String category4 = "critical";
// create the dataset...
final DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(error, series1, category1);
dataset.addValue(info, series1, category2);
dataset.addValue(warning, series1, category3);
dataset.addValue(critical, series1, category4);
return dataset;
}
/**
* Creates a sample chart.
*
* #param dataset the dataset.
*
* #return The chart.
*/
private JFreeChart createChart(final CategoryDataset dataset) {
// create the chart...
final JFreeChart chart = ChartFactory.createBarChart(
"Priority BarChart", // chart title
"priority", // domain axis label
"Value", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
true, // include legend
true, // tooltips?
false // URLs?
);
// NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
// set the background color for the chart...
chart.setBackgroundPaint(Color.white);
// get a reference to the plot for further customisation...
final CategoryPlot plot = chart.getCategoryPlot();
plot.setBackgroundPaint(Color.lightGray);
plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinePaint(Color.white);
// set the range axis to display integers only...
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
// disable bar outlines...
final BarRenderer renderer = (BarRenderer) plot.getRenderer();
renderer.setDrawBarOutline(false);
// set up gradient paints for series...
final GradientPaint gp0 = new GradientPaint(
0.0f, 0.0f, Color.blue,
0.0f, 0.0f, Color.lightGray
);
renderer.setSeriesPaint(0, gp0);
final CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setCategoryLabelPositions(
CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0)
);
// OPTIONAL CUSTOMISATION COMPLETED.
return chart;
}
#Override
public void setFocus() {
}
}
You have to modify the parent composite named barchartComposite.
parent.setLayout(new GridLayout(1, false));
parent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
final CategoryDataset dataset = createDataset();
final JFreeChart chart = createChart(dataset);
Composite barchartComposite = new Composite(parent, SWT.NONE);
barchartComposite.setLayout(new GridLayout(1, false));
barchartComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
ChartComposite frame = new ChartComposite(barchartComposite, SWT.BORDER,chart,true);
frame.setLayoutData(new GridData(GridData.FILL_BOTH));
You have to make sure that barchartcomposite grabs the wohle space of the parent composite. This can be achieved with GridLayout and GridData.
You can find a very useful tutorial about all SWT layouts here:
Understanding Layouts in SWT