display a list of blob - list

i have some blobs in my database ,actually i can retrie just one and display it in ImageView and i would like to retire several and give the choice to the user like if he just click at the same button
the image of ImageView change
here is my main class:
there is my mainclass:
package com.example.autretest;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton imagebutton=(ImageButton)findViewById(R.id.imageButton1);
addListenerOnButton();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void addListenerOnButton() {
final ImageView imageview=(ImageView)findViewById(R.id.imageView1);
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Bitmap bm = null;
List<Bitmap> listbitmap=null;
SQLiteAdapter mySQLiteAdapter =new SQLiteAdapter(getApplicationContext());
mySQLiteAdapter.openToRead();
listbitmap=mySQLiteAdapter.queueAllphoto();
int location=2;
while (location<listbitmap.size()){
imageview.setImageBitmap(listbitmap.get(location));
}
location++;
mySQLiteAdapter.close();
//Bitmap bmp = BitmapFactory.decodeByteArray(content,0,content.length);
//image = new BitmapDrawable(BitmapFactory.decodeByteArray(content, 0, content.length));
Toast.makeText(MainActivity.this,
"ImageButton is clicked!", Toast.LENGTH_SHORT).show();
}
});
}
}
then you've got the otherclass SqliteAdapter:
package com.example.autretest;
import java.sql.Blob;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class SQLiteAdapter {
public static final String MYDATABASE_NAME = "mydatabase";
public static final String MYDATABASE_TABLE_APP = "ma_table";
public static final String MYDATABASE_TABLE_photo = "pictures";
public static final String MYDATABASE_TABLE_plan = "plan";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_CONTENT = "Content";
public static final String KEY_CONTENT_ID = "Content_PK";
public static final String KEY_CONTENT_ID_photo = "Content_PK_photo";
public static final String KEY_CONTENT_ID_plan = "Content_PK_plan";
public static final String KEY_CONTENT_photo = "Content_photo";
public static final String KEY_CONTENT_plan = "Content_plan";
//create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
"create table " + MYDATABASE_TABLE_APP + " ("
+ KEY_CONTENT + " text not null)"+
"create table " + MYDATABASE_TABLE_photo + " ("+ KEY_CONTENT_photo + " blob not null)"+" " +
"("+ KEY_CONTENT_ID_photo + " INTEGER not null);" +" ("+ KEY_CONTENT_ID + " INTEGER not null) "+
"create table " + MYDATABASE_TABLE_plan + " ("+ KEY_CONTENT_plan + " INTEGER not null)";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
int s=0;
byte[]app_image=null;
public SQLiteAdapter(Context c){
context = c;
}
#SuppressWarnings("null")
public void DropDB() {
SQLiteDatabase db = null;
//On peut faire ce qu'on veut ici moi j'ai décidé de supprimer la table et de la recréer
//comme ça lorsque je change la version les id repartent de 0
db.execSQL("DROP DATABASE " + MYDATABASE_NAME + ";");
}
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public Bitmap getIcone(){
String[] columns = new String[]{KEY_CONTENT_photo};
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
byte[]image_bytes=null;
Cursor rslt=null;
rslt=sqLiteDatabase.query(MYDATABASE_TABLE_photo,columns, null, null, null, null, null);
if(rslt.getCount()!=0){
rslt.moveToFirst();
image_bytes=rslt.getBlob(rslt.getColumnIndex(KEY_CONTENT_photo));
Bitmap bmp=BitmapFactory.decodeByteArray(image_bytes, 0, image_bytes.length);
return bmp;
}
else {
return null;
}
}
public String queueAll(){
String[] columns = new String[]{KEY_CONTENT};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE_APP, columns,
null, null, null, null, null);
String result = "";
int index_CONTENT = cursor.getColumnIndex(KEY_CONTENT);
for(cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()){
result = result + cursor.getString(index_CONTENT) + "\n";
}
return result;
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close(){
sqLiteHelper.close();
}
public long insert(String content){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_CONTENT, content);
return sqLiteDatabase.insert(MYDATABASE_TABLE_APP, null, contentValues);
}
public long insertphoto(byte[] iconebyte){
// "create table " + MYDATABASE_TABLE_APP + " ("+ KEY_CONTENT + " text not null)" +
//" ("+ KEY_CONTENT_ID + " INTEGER not null);"+" ("+ KEY_CONTENT_plan + " INTEGER not null)"+
// String sql="Insert into MYDATABASE_TABLE_APP_photo(KEY_CONTENT_ID_photo,KEY_CONTENT_ID,KEY_CONTENT_photo) values(?,?,?)";
//executeSql
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_CONTENT_photo, iconebyte);
return sqLiteDatabase.insert(MYDATABASE_TABLE_photo, null, contentValues);
}
public int deleteAll(){
return sqLiteDatabase.delete(MYDATABASE_TABLE_APP, null, null);
}
public int deleteAllphoto(){
return sqLiteDatabase.delete(MYDATABASE_TABLE_photo, null, null);
}
#SuppressWarnings("null")
public List<Bitmap> queueAllphoto(){
Bitmap bitmap;
String[] columns = new String[]{KEY_CONTENT_photo};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE_photo, columns,
null, null, null, null, null);
byte[] result = null;
List<Bitmap> listbitmap=null;
int index_CONTENT = cursor.getColumnIndex(KEY_CONTENT_photo);
for(cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()){
result = cursor.getBlob(index_CONTENT) ;
}
bitmap=BitmapFactory.decodeByteArray(result , 0, result.length);
listbitmap.add(bitmap);
return listbitmap;
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
//db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}

the first thing to know is the number of blobs that need to be shown then after that i created the same number of buttons where i just "setBackgroundRessource"!
here is an example but the images are not blobs but drawables but the idea is the same
except that you need to convert the blob in a bytearray
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
Button btn = new Button(getBaseContext());
btn.setId(k1);
final int id_ = btn.getId();
LinearLayout linear = (LinearLayout) findViewById(R.id.linearscroll);
linear.addView(btn, params);
final Button btn1 = ((Button) findViewById(id_));
btn1.setBackgroundResource(matable[k1]);
matable is just an array of all my drawable

Related

Which regex to validate JavaFX Textfield for decimal number in scientific notation

Using as a starting point the DecimalField class found on this site, I wrote the following:
import javafx.scene.control.TextField;
import java.util.regex.Pattern;
public class DecimalField extends TextField {
public Boolean rate, positive, integer;
Pattern decimalPattern;
DecimalField(Boolean rate, Boolean positive) {
this.rate = rate;
this.positive = positive;
decimalPattern = Pattern.compile ("[-+]?[0-9]*(\\.[0-9]*)?");
// decimalPattern = Pattern.compile("[-+]?(\\b[0-9]+(\\.[0-9]*)?|\\.[0-9]+)([eE][-+]?[0-9]+\\b)?");
if (rate) {
decimalPattern = Pattern.compile ("[-+]?[0-9]*(\\.[0-9]*)?[%]?");
} else if (positive) {
decimalPattern = Pattern.compile ("[1-9][0-9]*(\\.[0-9]*)?");
}
}
#Override
public void replaceText(int start, int end, String text) {
if (validate (start, text)) {
super.replaceText (start, end, text);
}
}
#Override
public void replaceSelection(String text) {
if (validate (Integer.MAX_VALUE, text)) {
super.replaceSelection (text);
}
}
private boolean validate(int start, String text) {
String currentText = (getText ().isEmpty ()) ? "" : getText ();
if (start == 0) { //to handle "-1.1" or ".1" cases
return decimalPattern.matcher (text + currentText).matches ();
} else {
return decimalPattern.matcher (currentText + text).matches ();
}
}
}
Depending on the parameters sent to the constructor, this class can be used to restrict entries to a standard decimal number, to a positive only (i.e. > 0) decimal number, or to a number followed by the per-cent character.
It seems to work fine (a small test application is provided), but I wanted to also be able to specify a number in scientific notation such as 25.56e-5
I could not write the right regex pattern. A pattern such as "[0-9.eE+-]*" would limit the entry to acceptable characters but would not enforce the number syntax! Suggestions are welcome.
Here is the test program:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class DecimalFieldTest extends Application {
#Override
public void start(Stage primaryStage) {
// Boolean rate;
// rate = false; positive = true;
Label basicLbl = new Label("Basic Decimal");
DecimalField decimalField = new DecimalField (false, false);
Label rateLbl = new Label("Rate Decimal");
DecimalField rateDecimalField = new DecimalField (true, false);
Label positiveLbl = new Label("Positive Decimal");
DecimalField positiveDecimalField = new DecimalField (false, true);
Button clickMe = new Button ("Click Me");
clickMe.setOnAction (new EventHandler<ActionEvent> () {
#Override
public void handle(ActionEvent event) {
String s;
s = decimalField.getText ();
if (!s.isEmpty ()) getOut(s, false);
s = rateDecimalField.getText ();
if (!s.isEmpty ()) getOut(s, true);
s = positiveDecimalField.getText ();
if (!s.isEmpty ()) getOut(s, false);
}
});
decimalField.setOnAction (new EventHandler<ActionEvent> () {
#Override
public void handle(ActionEvent event) {
getOut(decimalField.getText (),false);
}
});
rateDecimalField.setOnAction (new EventHandler<ActionEvent> () {
#Override
public void handle(ActionEvent event) {
getOut(rateDecimalField.getText (),true);
}
});
positiveDecimalField.setOnAction (new EventHandler<ActionEvent> () {
#Override
public void handle(ActionEvent event) {
getOut(positiveDecimalField.getText (),false);
}
});
VBox root = new VBox (5, basicLbl, decimalField,
rateLbl, rateDecimalField, positiveLbl, positiveDecimalField, clickMe);
root.setAlignment (Pos.CENTER);
Scene scene = new Scene (root, 300, 250);
primaryStage.setScene (scene);
primaryStage.show ();
}
void getOut(String s, Boolean rate) {
// for rate : textField.getText().replaceAll("%","")
String ss = s.replaceAll ("%", "");
double value = Double.parseDouble (ss);
if (rate) {
System.out.println (String.format (ss + " <-> " + value) + "%");
} else {
System.out.println (String.format (ss + " <-> " + value));
}
}
public static void main(String[] args) {
launch (args);
}
}
You can use NumberTextField with BigDecimal and different number formats.
package control;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.geometry.Pos;
import javafx.scene.control.TextField;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.ParseException;
/**
* Number text field
*
* <p>
* Original source code from:
* https://dzone.com/articles/javafx-numbertextfield-and
*/
public class NumberTextField extends TextField {
private final NumberFormat numberFormat;
private ObjectProperty<BigDecimal> value = new SimpleObjectProperty<>();
public NumberTextField(NumberFormat numberFormat) {
this(BigDecimal.ZERO, numberFormat, 100);
}
public NumberTextField(NumberFormat numberFormat, double width) {
this(BigDecimal.ZERO, numberFormat, width);
}
/**
* Number field with properties.
*
* #param value decimal value
* #param numberFormat number format
* #param width min, max and pref width
*/
public NumberTextField(BigDecimal value, NumberFormat numberFormat, double width) {
super();
this.numberFormat = numberFormat;
setMinWidth(width);
setMaxWidth(width);
setPrefWidth(width);
initHandlers();
setValue(value);
setAlignment(Pos.BOTTOM_RIGHT);
}
public final BigDecimal getValue() {
return value.get();
}
public final void setValue(BigDecimal value) {
this.value.set(value);
}
public ObjectProperty<BigDecimal> valueProperty() {
return value;
}
private void initHandlers() {
// try to parse when focus is lost or RETURN is hit
setOnAction((ActionEvent arg0) -> {
parseAndFormatInput();
});
focusedProperty().addListener((ObservableValue<? extends Boolean> observable,
Boolean oldValue, Boolean newValue) -> {
if (!newValue) {
parseAndFormatInput();
}
});
// Set text in field if BigDecimal property is changed from outside.
valueProperty().addListener((ObservableValue<? extends BigDecimal> observable,
BigDecimal oldValue, BigDecimal newValue) -> {
setText(numberFormat.format(newValue));
});
}
/**
* Tries to parse the user input to a number according to the provided
* NumberFormat
*/
private void parseAndFormatInput() {
try {
String input = getText();
if (input == null || input.length() == 0) {
return;
}
Number parsedNumber = numberFormat.parse(input);
BigDecimal newValue = new BigDecimal(parsedNumber.toString());
setValue(newValue);
selectAll();
} catch (ParseException ex) {
// If parsing fails keep old number
setText(numberFormat.format(value.get()));
}
}
}
And as BigDecimalTextField:
NumberTextField bigDecimalField =
new NumberTextField(new DecimalFormat("#,###,###,##0.00"));

Java FX: Getting and editing an object from Observable List

I know about the method list.getSelectionModel().getSelectedItem(); and its index version, but heres my problem:
I have setup a List in my GUI which holds Objects of a class Person. In my GUI theres also Text Fields with the attributes of that class (Name,Street,Age etc).
What I did so far is implement a method clickList() which will fill the attribute fields with the data from the selected object in the listview. So the user can edit them from here and press another button which should then update those attributes.
I also setup so you can create a new object from the text form by doing this inside my "OK" Button inside my Controller:
ObservableList<Person> items = FXCollections.observableArrayList();
items.add(new Person(tf_vn.getText(), tf_nn.getText(),tf_strasse.getText(), tf_plz.getText(), tf_ort.getText(),genderChoice, sliderAge.getValue());
list.setItems(items);
However what im struggling with is the editing of the already existing Person. Can someone give me some pointers? I know I can get the selected object index but how do I work with it? Basicly I just need to find a way to do something like selectedObject.setAge(),selectedObject.setName() etc
I looked through all the getSelectionModel() methods but didnt find a solution, im sure there is a easy one....
Thanks in advance !
This way you can reach selectedObject's methods
ListView<Person> l = new ListView<>();
...
l.getSelectionModel().getSelectedItem().setFirstName("new name");
l.refresh();
a full example may look like;
package so;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class TableViewSample extends Application {
private TableView<Person> table = new TableView<Person>();
private final ObservableList<Person> data = FXCollections.observableArrayList(
new Person("Jacob", "Smith", "jacob.smith#example.com"),
new Person("Isabella", "Johnson", "isabella.johnson#example.com"),
new Person("Ethan", "Williams", "ethan.williams#example.com"),
new Person("Emma", "Jones", "emma.jones#example.com"),
new Person("Michael", "Brown", "michael.brown#example.com"));
final HBox hb = new HBox();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setTitle("Table View Sample");
stage.setWidth(450);
stage.setHeight(550);
final Label label = new Label("Address Book");
label.setFont(new Font("Arial", 20));
// table.setEditable(true);
TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));
TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
lastNameCol.setMinWidth(100);
lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));
TableColumn<Person, String> emailCol = new TableColumn<>("Email");
emailCol.setMinWidth(200);
emailCol.setCellValueFactory(new PropertyValueFactory<Person, String>("email"));
table.setItems(data);
table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
final TextField addFirstName = new TextField();
addFirstName.setPromptText("First Name");
addFirstName.setMaxWidth(firstNameCol.getPrefWidth());
final TextField addLastName = new TextField();
addLastName.setMaxWidth(lastNameCol.getPrefWidth());
addLastName.setPromptText("Last Name");
final TextField addEmail = new TextField();
addEmail.setMaxWidth(emailCol.getPrefWidth());
addEmail.setPromptText("Email");
final Button addButton = new Button("Add");
addButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
if (table.getSelectionModel().getSelectedItem() != null) {
table.getSelectionModel().getSelectedItem().setFirstName(addFirstName.getText());
table.getSelectionModel().getSelectedItem().setLastName(addLastName.getText());
table.getSelectionModel().getSelectedItem().setEmail(addEmail.getText());
table.refresh();
} else {
data.add(new Person(addFirstName.getText(), addLastName.getText(), addEmail.getText()));
addFirstName.clear();
addLastName.clear();
addEmail.clear();
}
}
});
table.getSelectionModel().selectedItemProperty().addListener((e, o, n) -> {
// addFirstName.clear();
// addLastName.clear();
// addEmail.clear();
if (n != null) {
addFirstName.setText(n.getFirstName());
addLastName.setText(n.getLastName());
addEmail.setText(n.getEmail());
addButton.setText("Edit");
}
else {
addButton.setText("Add");
}
});
hb.getChildren().addAll(addFirstName, addLastName, addEmail, addButton);
hb.setSpacing(3);
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(label, table, hb);
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
}
public static class Person {
private final SimpleStringProperty firstName;
private final SimpleStringProperty lastName;
private final SimpleStringProperty email;
private Person(String fName, String lName, String email) {
this.firstName = new SimpleStringProperty(fName);
this.lastName = new SimpleStringProperty(lName);
this.email = new SimpleStringProperty(email);
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String fName) {
firstName.set(fName);
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String fName) {
lastName.set(fName);
}
public String getEmail() {
return email.get();
}
public void setEmail(String fName) {
email.set(fName);
}
}
}

seek bar not working when playing mp3 song from server

In my app I am trying to play a media player from server along with a seek bar. When I tried to play the song from server, my app was working fine but the seek bar was not getting moved ! Also, The seekbar is not working....
It's not displaying MediaPlayer progress
also, It is playing multiple songs at the same time
solution needed for 2 bugs
Here is a screenshot of that app
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity2 extends AppCompatActivity {
private ArrayList<SongInfo> _songs = new ArrayList<SongInfo>();
RecyclerView recyclerView;
SeekBar seekBar;
SongAdapter songAdapter;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
seekBar = (SeekBar) findViewById(R.id.seekBar);
SongInfo s = new SongInfo("Cheap Thrills", "sia", "http://176.126.236.250/33Mmt/music/hindi/movies/new/oh_my_god/Go-Go-Govinda_(webmusic.in).mp3");
_songs.add(s);
s = new SongInfo("Cheap Thrills", "sia", "http://176.126.236.250/33Mmt/music/hindi/movies/new/oh_my_god/Go-Go-Govinda_(webmusic.in).mp3");
_songs.add(s);
songAdapter = new SongAdapter(this, _songs);
recyclerView.setAdapter(songAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
linearLayoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(songAdapter);
songAdapter.setOnItemClickListener(new SongAdapter.OnItemClickListener() {
#Override
public void onItemClick(final Button b, View view, SongInfo obj, int position) {
try {
if (b.getText().toString().equals("stop")) {
b.setText("Play");
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}else {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(obj.getSongUrl());
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
b.setText("stop");
}
});
}
} catch (IOException e) {
}
}
});
}
}
this is my song adapter code -:
package com.a03.dip.kaliprasadbengalisongs;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
public class SongAdapter extends RecyclerView.Adapter<SongAdapter.SongHolder> {
ArrayList<SongInfo> _songs;
Context context;
OnItemClickListener mOnItemClickListener;
SongAdapter(Context context, ArrayList<SongInfo> songs) {
this.context = context;
this._songs = songs;
}
public interface OnItemClickListener {
void onItemClick(Button b ,View view, SongInfo obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
#Override
public SongHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View myView = LayoutInflater.from(context).inflate(R.layout.row_song,viewGroup,false);
return new SongHolder(myView);
}
#Override
public void onBindViewHolder(final SongHolder songHolder, final int i) {
final SongInfo c = _songs.get(i);
songHolder.songName.setText(_songs.get(i).songName());
songHolder.artistName.setText(_songs.get(i).artistName());
songHolder.btnAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(songHolder.btnAction,v, c, i);
}
}
});
}
#Override
public int getItemCount() {
return _songs.size();
}
public class SongHolder extends RecyclerView.ViewHolder {
TextView songName,artistName;
Button btnAction;
public SongHolder(View itemView) {
super(itemView);
songName = (TextView) itemView.findViewById(R.id.tvSongName);
artistName = (TextView) itemView.findViewById(R.id.tvArtistName);
btnAction = (Button) itemView.findViewById(R.id.btnPlay);
}
}
}
and here is songInfo class -----
package com.a03.dip.kaliprasadbengalisongs;
import android.media.MediaPlayer;
public class SongInfo {
public String songName ,artistName,songUrl;
public SongInfo() {
}
public SongInfo(String songName, String artistName, String songUrl) {
this.songName = songName;
this.artistName = artistName;
this.songUrl = songUrl;
}
public String songName() {
return songName;
}
public String artistName() {
return artistName;
}
public String getSongUrl() {
return songUrl;
}
}
you have to use seekbar listener on ur activity.
seekBar.setOnSeekBarChangeListener(new >SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int >progress,
boolean fromUser) {
if (fromUser) {
mPlayer.seekTo(progress);
}
}

JFreeChart is not updating ChartPanel, after reading data from serial port

I am trying to read some data from serial port and display the same using JFreeChart and ChartPanel.
After I click button 'Aquire' I get new set of data from serial port. For the first time when panel is getting displayed, the values read from serial port is displayed. After I click the button 'Aquire', the values are getting populated in variable 'dataset' but they are not getting refreshed on the graph. Where am I going wrong? please help. Thanks in advance.
import java.awt.BasicStroke;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import javax.swing.GroupLayout;
import javax.swing.JApplet;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartMouseEvent;
import org.jfree.chart.ChartMouseListener;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.annotations.XYLineAnnotation;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.event.ChartChangeEvent;
import org.jfree.chart.event.ChartChangeListener;
import org.jfree.chart.panel.CrosshairOverlay;
import org.jfree.chart.plot.Crosshair;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.RectangleEdge;
public class DisplayPanel extends JApplet implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
SimplePortComm spc;
JFreeChart xylineChart;
ChartPanel panel;
XYSeriesCollection dataset;
public static String sLLD;
public static String sULD;
Label lblTitle;
Label lblMax, lblMin, lblULD, lblLLD;
TextField txtMax, txtMin, txtULD, txtLLD;
Label lblInrangeCount;
TextField txtInrangeCount;
Button bAquire, bSave, bLoad, bQuit;
int i, nInRangeChannels;
private Crosshair xCrosshair;
private Crosshair yCrosshair;
double dULD,dLLD;
public DisplayPanel() {
dataset = new XYSeriesCollection();
spc = new SimplePortComm();
lblTitle = new Label("Data Aquisition System for MCA");
lblTitle.setPreferredSize(new Dimension(600, 20));
lblMax = new Label("Max:");
lblMin = new Label("Min:");
lblULD = new Label("ULD:");
lblLLD = new Label("LLD:");
lblInrangeCount = new Label("Count in Range:");
lblInrangeCount.setPreferredSize(new Dimension(60, 20));
txtMax = new TextField(10);
txtMax.setEditable(false);
txtMin = new TextField(10);
txtMin.setEditable(false);
txtULD = new TextField(10);
txtULD.setText("240.0");
txtLLD = new TextField(10);
txtLLD.setText("20.0");
txtInrangeCount = new TextField(10);
txtInrangeCount.setPreferredSize(new Dimension(60, 20));
txtInrangeCount.setEditable(false);
dULD = Double.parseDouble(txtULD.getText());
dLLD = Double.parseDouble(txtLLD.getText());
drawChart();
bAquire = new Button("Aquire");
bAquire.setPreferredSize(new Dimension(20, 60));
bAquire.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent aquire) {
//panel.setRefreshBuffer(true);
System.setSecurityManager(null);// with out this statement, set_ports() throws null pointer exception
spc.set_ports(dULD, dLLD);
dataset = SimplePortComm.dataset;
panel.repaint();
panel.updateUI();
System.out.print("Button: Aquire");
}
}
);
bSave = new Button("Save");
bSave.setPreferredSize(null);
bSave.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent save) {
System.out.print("Button: Save");
}
}
);
bLoad = new Button("Load");
bLoad.setPreferredSize(null);
bLoad.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent load) {
System.out.print("Button: Load");
sLLD = txtLLD.getText();
sULD = txtULD.getText();
txtInrangeCount.setText(Integer.toString(spc.getInRangeChannels()));
}
}
);
bQuit = new Button("Quit");
bQuit.setPreferredSize(new Dimension(10, 10));
bQuit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent quit) {
System.out.print("Button: Quit");
System.exit(0);
}
});
GroupLayout layout = new GroupLayout(getContentPane());
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(lblTitle)
.addComponent(panel)
.addGroup(layout.createSequentialGroup()
.addComponent(bAquire)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(lblMax)
.addComponent(lblMin))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(txtMax)
.addComponent(txtMin))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(lblULD)
.addComponent(lblLLD))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(txtULD)
.addComponent(txtLLD)))
.addGroup(layout.createSequentialGroup()
.addComponent(lblInrangeCount)
.addComponent(txtInrangeCount))
.addGroup(layout.createSequentialGroup()
.addComponent(bSave)
.addComponent(bLoad)
.addComponent(bQuit))
);
layout.setVerticalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addGroup(layout.createSequentialGroup()
.addComponent(lblTitle)))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addGroup(layout.createSequentialGroup()
.addComponent(panel)))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(bAquire))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(lblMax)
.addComponent(txtMax)
.addComponent(lblULD)
.addComponent(txtULD))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(lblMin)
.addComponent(txtMin)
.addComponent(lblLLD)
.addComponent(txtLLD))))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(lblInrangeCount)
.addComponent(txtInrangeCount))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(bSave)
.addComponent(bLoad)
.addComponent(bQuit))
);
getContentPane().setLayout(layout);
getContentPane().setEnabled(true);
getContentPane().setSize(1500, 1500);
}
public void drawChart()
{
System.setSecurityManager(null);// with out this statement, set_ports() throws null pointer exception
spc.set_ports(dULD, dLLD);
dataset = SimplePortComm.dataset;
xylineChart = ChartFactory.createXYLineChart(
"Data Aquired" ,
"Time" ,
"Amplitude" ,
dataset ,
PlotOrientation.VERTICAL ,
true , true , false);
panel = new ChartPanel(xylineChart, 650, 450, 180, 180, 800, 600, false, true, false, false, false, false);
//panel.setRefreshBuffer(true);
CrosshairOverlay crosshairOverlay = new CrosshairOverlay();
this.xCrosshair = new Crosshair(Double.NaN, Color.BLACK,
new BasicStroke(0f));
this.xCrosshair.setLabelVisible(true);
this.yCrosshair = new Crosshair(Double.NaN, Color.BLACK,
new BasicStroke(0f));
this.yCrosshair.setLabelVisible(true);
crosshairOverlay.addDomainCrosshair(xCrosshair);
crosshairOverlay.addRangeCrosshair(yCrosshair);
panel.addOverlay(crosshairOverlay);
panel.addChartMouseListener(new ChartMouseListener() {
#Override
public void chartMouseMoved(ChartMouseEvent event) {
Rectangle2D dataArea = panel.getScreenDataArea();
JFreeChart chart = event.getChart();
XYPlot plot = (XYPlot) chart.getPlot();
ValueAxis xAxis = plot.getDomainAxis();
double x = xAxis.java2DToValue(event.getTrigger().getX(), dataArea,
RectangleEdge.BOTTOM);
// make the crosshairs disappear if the mouse is out of range
if (!xAxis.getRange().contains(x)) {
x = Double.NaN;
}
double y = DatasetUtilities.findYValue(plot.getDataset(), 0, x);
xCrosshair.setValue(x);
yCrosshair.setValue(y);
}
#Override
public void chartMouseClicked(ChartMouseEvent event) {
Rectangle2D dataArea = panel.getScreenDataArea();
System.out.println("Mouse clicked on the graph");
XYPlot plot = (XYPlot) xylineChart.getPlot();
ValueAxis xAxis = plot.getDomainAxis();
double x = xAxis.java2DToValue(event.getTrigger().getX(), dataArea,
RectangleEdge.BOTTOM);
// make the crosshairs disappear if the mouse is out of range
if (!xAxis.getRange().contains(x)) {
x = Double.NaN;
}
double y = DatasetUtilities.findYValue(plot.getDataset(), 0, x);
System.out.println("Graph click: " + x + ":" + y);
xCrosshair.setValue(x);
yCrosshair.setValue(y);
XYItemRenderer renderer = plot.getRenderer();
renderer.removeAnnotations();
XYLineAnnotation mark = new XYLineAnnotation(x,0,x,250, new BasicStroke(), Color.BLACK);
renderer.addAnnotation(mark);
XYLineAnnotation low = new XYLineAnnotation(0.0f,dULD,400f,dULD, new BasicStroke(), Color.BLUE);
renderer.addAnnotation(low);
low.setToolTipText("low");
XYLineAnnotation high = new XYLineAnnotation(0.0f,dLLD,400f,dLLD, new BasicStroke(), Color.MAGENTA);
renderer.addAnnotation(high);
high.setToolTipText("high");
plot.setRenderer(renderer);
}
});
}
public void init()
{
setBackground(Color.WHITE);
System.setSecurityManager(null);
spc = new SimplePortComm();
}
public static void main(String args[])
{
DisplayPanel ds = new DisplayPanel();
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
I don't know how SimplePortComm works, but your ActionListener is replacing the dataset that was used to create the chart. It works the first time because the original dataset is the one that xylineChart is listening to; the chart doesn't know about the new dataset. You can tell the chart about the change by using plot.setDataset(dataset);
Your ActionListener is also blocking the event dispatch thread, so you might want to use a SwingWorker like they show here.

Sharing data between master and reduce

I need to perform aggregation using the results form all the reduce tasks. Basically the reduce task finds the sum and count and a value. I need to add all the sums and counts and find the final average.
I tried using conf.setInt in reduce. But when I try to access it from the main function it fails
class Main {
public static class MyReducer
extends Reducer<Text, Text,Text,IntWritable> {
public void reduce(Text key, Iterable<Text> values,
Context context
) throws IOException, InterruptedException {
int i = 0;
int fd = 0, fc = 0;
fd = context.getConfiguration().getInt("fd", -1);
fc = context.getConfiguration().getInt("fc", -1);
//when I check the value of fd, fc here they are fine. fc fd is shared across all reduce tasks and the updated value is seen by all reduce task. Only main function doesnt seem to have access to it.
}
}
public static void main(String[] args) throws Exception{
Configuration conf = new Configuration();
conf.setInt("fc", 5);
Job job = new Job(conf, "Flight Data");
job.setJarByClass(FlightData.class);
job.setMapperClass(TokenizerMapper.class);
job.setReducerClass(MyReducer.class);
job.setPartitionerClass(FirstPartitioner.class);
job.setGroupingComparatorClass(GroupComparator.class);
job.setSortComparatorClass(KeyComparator.class);
job.setNumReduceTasks(10);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(Text.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
flightCount = job.getConfiguration().getInt("fc", -1);
flightDelay = job.getConfiguration().getInt("fd", -1);
//here when I access fc, fd, I get back 5 & 5
System.out.println("Final " + flightCount +" " + flightDelay+ " " + flightDelay/flightCount);
}
Override the run() of the mapper and reducer using the new org.apache.hadoop.mapreduce API. In these methods you can emit the accumulated sum/count from each mapper or reducer.
Also you would need to limit the reducer count by 1 so as to get a global sum of all the sums generated by multiple mappers.
See the below code for more clarity:
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
public class AggregationExample extends Configured implements Tool {
/**
* This is Mapper.
*
*/
public static class MapJob extends Mapper<LongWritable, Text, Text, Text> {
private Text outputKey = new Text();
private Text outputValue = new Text();
private double sum;
#Override
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
try {
// say that you need to sum up the value part
sum+= Double.valueOf(value);
}
#Override
public void run(Context context) throws IOException, InterruptedException {
setup(context);
while (context.nextKeyValue()) {
map(context.getCurrentKey(), context.getCurrentValue(), context);
}
// emit out the sum per mapper
outputKey.set(sum);
context.write(outputKey, outputValue);// Notice that the outputValue is empty
cleanup(context);
}
}
/**
* This is Reducer.
*
*/
public static class ReduceJob extends Reducer<Text, Text, Text, Text> {
private Text outputKey = new Text();
private Text outputValue = new Text();
private double sum;
#Override
protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException,
InterruptedException {
// summation of values from each mapper
sum += Double.valueOf(key.toString());
}
#Override
public void run(Context context) throws IOException, InterruptedException {
setup(context);
while (context.nextKey()) {
reduce(context.getCurrentKey(), context.getValues(), context);
}
// emit out the global sums
outputKey.set(sum);
context.write(outputKey, outputValue);
cleanup(context);
}
}
#Override
public int run(String[] args) throws Exception {
try {
Configuration conf = getConf();
// output key and value separator is empty as in final output only
// key is emitted and value is empty
conf.set("mapred.textoutputformat.separator", "");
// Configuring mapred to have just one reducer as we need to find
// single sum values from all the inputs
conf.setInt("mapred.tasktracker.reduce.tasks.maximum", 1);
conf.setInt("mapred.reduce.tasks", 1);
Job job = new Job(conf);
job.setJarByClass(AggregationExample.class);
job.setJobName("Aggregation Example");
job.setMapperClass(MapJob.class);
job.setReducerClass(ReduceJob.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(Text.class);
FileInputFormat.setInputPaths(job, args[0]);
FileOutputFormat.setOutputPath(job, new Path(args[1]));
boolean success = job.waitForCompletion(true);
return success ? 0 : 1;
} catch (Exception e) {
e.printStackTrace();
return 1;
}
}
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.out
.println("Usage: AggregationExample <comma sparated list of input directories> <output dir>");
System.exit(-1);
}
int result = ToolRunner.run(new AggregationExample(), args);
System.exit(result);
}
}
You may very well map this approach to your problem.
Found the solution. I used counters
http://diveintodata.org/2011/03/15/an-example-of-hadoop-mapreduce-counter/
public class FlightData {
//enum for counters used by reducers
public static enum FlightCounters {
FLIGHT_COUNT,
FLIGHT_DELAY;
}
public static class MyReducer
extends Reducer<Text, Text,Text,IntWritable> {
public void reduce(Text key, Iterable<Text> values,
Context context
) throws IOException, InterruptedException {
delay1 = Float.parseFloat(origin[5]);
delay2 = Float.parseFloat(dest[5]);
context.getCounter(FlightCounters.FLIGHT_COUNT).increment(1);
context.getCounter(FlightCounters.FLIGHT_DELAY)
.increment((long) (delay1 + delay2));
}
}
public static void main(String[] args) throws Exception{
float flightCount, flightDelay;
job.waitForCompletion(true);
//get the final results updated in counter by all map and reduce tasks
flightCount = job.getCounters()
.findCounter(FlightCounters.FLIGHT_COUNT).getValue();
flightDelay = job.getCounters()
.findCounter(FlightCounters.FLIGHT_DELAY).getValue();
}
}