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();
}
}
}
Related
In the program.cs the user is asked if he wanna read the data, if he types y then the method Doc.ReadDoc starts is there any proper way:
class Program
{
static void Main(string[] args)
{
do
{
var path = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path + #"\TestFile.txt";
Console.WriteLine("Do you want to read it? y/n");
string yesorno = Console.ReadLine();
if (yesorno=="y")
{
Console.Clear();
Doc.ReadDoc();
}
Console.WriteLine("Which type of vehicle");
string type = Console.ReadLine();
Console.WriteLine("how many tires");
int raeder = Convert.ToInt32( Console.ReadLine());
var Vehicle = new Used_Cars(type, raeder);
Doc.Write(Vehicle);
} while (true);
}
}
The Class with the methods (Read, Write):
public static List<string> ReadDoc()
{
var list = new List<string>();
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
try
{
using (StreamReader sr = new StreamReader(fileName))
{
Console.WriteLine("Data found");
string line;
Console.WriteLine(sr.ReadToEnd());
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("Data not found");
Console.WriteLine(e.Message);
list = null;
}
return list;
}
And the last Method is the Write method, is this a good code to save properties in a file? How could i stop the program with ESC or smth like that, so if the user presses ESC it should stop.
public static void Write(Used_Cars vehicle)
{
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
Console.WriteLine("Is it correct?");
Console.WriteLine("y/n");
string yeahorno= Console.ReadLine();
if (jaodernein == "y")
{
try
{
using (StreamWriter writer = new StreamWriter(fileName))
{
writer.WriteLine(vehicle.Vehicle);
writer.WriteLine(vehicle.Wheels);
Console.WriteLine();
}
}
catch (Exception exp)
{
Console.Write(exp.Message);
}
}
}
I am using SQLite Database to store some value/items from recyclerview which are coming from Firebase by long press. And in that recyclerview i am changing background of the values/items which are already stored in SQLite database. But problem is that when I long press on any item, it also colors every 21st item in recyclerview. and then colors any random item when scrolling back to top.
OnBindView
holder.Card.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
if (favDB.isFav(model.getUrl(), model.getName())) {
Toast.makeText(getContext(), "Already in Favorite", Toast.LENGTH_SHORT).show();
} else {
new FavDB(getContext()).addToFav(
model.getName(), model.getType(), model.getUrl(),
model.getBrowser(), model.getImage());
holder.Card.setCardBackgroundColor(R.color.Background);
Toast.makeText(getContext(), "Added to Favorite", Toast.LENGTH_SHORT).show();
}
return true;
}
});
if (favDB.isFav(model.getUrl(), model.getName())) {
try {
Toast.makeText(getContext(), "Coloring", Toast.LENGTH_SHORT).show();
holder.Card.setCardBackgroundColor(R.color.Background);
favDB.close();
}catch (Exception e){
Toast.makeText(getContext(), "Error : " + e, Toast.LENGTH_SHORT).show();
}
}
SQLite Helper
public void addToFav(String name, String type, String url, String browser, String image) {
SQLiteDatabase favDatabase = getReadableDatabase();
String favAdd =
String.format("INSERT INTO fav(name,url) VALUES('%s','%s');",
name, type, url, browser, image);
favDatabase.execSQL(favAdd);
favDatabase.close();
}
public boolean isFav(String url, String name) {
SQLiteDatabase favDatabase = getReadableDatabase();
String masterQuery = String.format("SELECT * FROM fav WHERE (url= '%s' AND name = '%s')",
url, name);
Cursor cursor = favDatabase.rawQuery(masterQuery, null);
if (cursor.getCount() <= 0) {
cursor.close();
return false;
}
cursor.close();
favDatabase.close();
return true;
}
How to restore an ImageView picked from gallery after close and restart the app. I am using SharedPreferences. To save the state of the URI after the app is closed, however it is not working the image is not set again any help would be appreciate.
public class test extends AppCompatActivity {
private static int RESULT_LOAD_IMAGE = 1;
ImageButton buttonLoadImage;
private static int RESULT_LOAD_IMG = 1;
String imgDecodableString;
public String getImagePathFetch;
ImageView imgView;
public String keyImage = "myImage";
public SharedPreferences sharedPrefEnter, sharedPrefGet;
Intent galleryIntent;
Uri selectedImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity_layout);
imgView = (ImageView) findViewById(R.id.imageView1);
sharedPrefGet = PreferenceManager.getDefaultSharedPreferences(this);
getImagePathFetch = sharedPrefGet.getString(keyImage, "");
if (!getImagePathFetch.equals("")) {
// tToast("OnCreate Path=" + getImagePathFetch);
Uri uri;
uri = Uri.parse(getImagePathFetch);
imgView.setImageURI(uri);
}
buttonLoadImage = (ImageButton) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddImage(view);
}
});
}
public void AddImage(View view) {
galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
// Get the Image from data
selectedImage = data.getData();
sharedPrefEnter = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPrefEnter.edit();
editor.putString(keyImage, selectedImage.toString());
editor.commit();
Uri uri = Uri.parse(selectedImage.toString());
imgView.setImageURI(uri);
}
}
}
// get the path of the image
sharedPrefGet = PreferenceManager.getDefaultSharedPreferences(this);
getImagePathFetch = sharedPrefGet.getString(keyImage, "");
if (!getImagePathFetch.equals("")) {
// tToast("OnCreate Path = " + getImagePathFetch); //TESTING
// parse path from toString to uri
uriImage = Uri.parse(getImagePathFetch);
// explicitly check for the permission at runtime since API 23
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
// Permission not granted
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
WRITE_EXTERNAL_STORAGE);
} else // Permission granted
{
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(uriImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
Bitmap imageResized = getResizedBitmap(yourSelectedImage, 480, 480); // resized
// Image
imgView.setImageBitmap(imageResized);
} // end if
}
//Check permission result.
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case WRITE_EXTERNAL_STORAGE:
if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(uriImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
Bitmap imageResized = getResizedBitmap(yourSelectedImage, 480, 480); // resized
// Image
imgView.setImageBitmap(imageResized);
}
break;
default:
break;
}
}
I'm asking for your help.
I'm developing an application in JavaFX who "scan" Mp3 files to get ID3tag.
Here is my problem. I did a foreach loop of a list for every .mp3 found but I'd like to increment a label which inform the progression of the list.
Here is my code
private ArrayList checkMp3File(ArrayList<String> lsMp3file, String sDir) throws UnsupportedTagException, InvalidDataException, IOException
{
this.currentData = 1;
int size = lsMp3file.size();
ArrayList<DataSong> lsds = new ArrayList<>();
for(String mp3file : lsMp3file)
{
this.labelUpdate.setText(this.current++ + " of " + " size");
DataSong ds = new DataSong();
Mp3File mp3 = new Mp3File(mp3file);
ds.setLenghtOfMp3inSec(mp3.getLengthInSeconds());
ds.setBitRateOfMp3(mp3.getBitrate());
ds.setSampleRate(mp3.getSampleRate());
ds.setVbrOrCbr(mp3.isVbr());
}
Actually, when the loop progress my window interface is completely freeze.
And only when the loop is finished, the label updated.
Someone can explain why ?
I already thank you for your answers.
EDIT :
Here is my fully code
public class LaunchOption extends Pane {
private final HBox launchAndSend = new HBox();
private final HBox browseAndField = new HBox();
private final HBox jsonAndAdvance = new HBox();
private ArrayList<DataSong> lsWithData = new ArrayList<>();
private String sendJson;
private File selectedDirectory;
private User user;
private int currentData;
private final ProgressIndicator pi = new ProgressIndicator(0);
private final VBox containerElement = new VBox();
private final TextArea displayJson = new TextArea();
private final TextField pathDir = new TextField();
private final TextField nbrOfData = new TextField();
private final Button btnScan = new Button();
private final Button btnSend = new Button();
private final Button btnCheckJson = new Button();
private final Button btnDirectoryBrowser = new Button();
private final Label nbMp3 = new Label();
public Label listAdvance = new Label();
private final Stage home;
public LaunchOption(Stage home){
this.home = home;
configureBtnCheckJson();
configureBtnScan();
configureBtnSend();
configureLabelMp3();
configureBtnDirectoryBrowser();
configureTextAreaDisplayJson();
configureTextFieldPathDir();
configureTextFieldNbDataMp3();
configureHBoxlaunchSend();
configureHBoxBrowseAndField();
configureHBoxJsonAndAdvance();
configureContainer();
this.getChildren().addAll(containerElement,launchAndSend);
}
private void configureLabelMp3()
{
nbMp3.setText("MP3");
}
private void configureBtnScan(){
btnScan.setText("Scan");
btnScan.setOnAction(event->{
ArrayList<String> Mp3FileData;
Mp3FileData = mapFilesMp3(selectedDirectory.getAbsolutePath());
System.out.println("ListSize = " + Mp3FileData.size());
nbrOfData.setText(String.valueOf(Mp3FileData.size()));
try {
lsWithData = checkMp3File(Mp3FileData, selectedDirectory.getAbsolutePath());
} catch (UnsupportedTagException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidDataException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
}
pi.setProgress(1);
});
}
private void configureBtnDirectoryBrowser(){
btnDirectoryBrowser.setText("Browse ...");
btnDirectoryBrowser.getStyleClass().add("round-red");
btnDirectoryBrowser.setOnAction(event-> {
DirectoryChooser dc = new DirectoryChooser();
selectedDirectory = dc.showDialog(home);
pi.setProgress(0.35);
if(selectedDirectory == null)
{
pathDir.setText("No directory selected");
}
else
{
pathDir.setText(selectedDirectory.getAbsolutePath());
String Text = pathDir.getText();
System.out.println(Text.toString());
}
});
}
private static String regexMp3()
{
return "^.*\\.(mp3)$";
}
private ArrayList mapFilesMp3(String sDir){
ArrayList<String> ls = new ArrayList<>();
printFnames(sDir,ls);
return ls;
}
private static void printFnames(String sDir, ArrayList<String> ls)
{
File[] faFiles = new File(sDir).listFiles();
for(File file : faFiles)
{
if(file.getName().matches(regexMp3()))
{
// System.out.println(file.getAbsolutePath());
ls.add(file.getAbsolutePath());
}
if(file.isDirectory())
{
printFnames(file.getAbsolutePath(), ls);
}
}
}
private ArrayList checkMp3File(ArrayList<String> lsMp3file, String sDir) throws UnsupportedTagException, InvalidDataException, IOException
{
this.currentData = 1;
int size = lsMp3file.size();
ArrayList<DataSong> lsds = new ArrayList<>();
for(String mp3file : lsMp3file)
{
System.out.println(this.currentData++);
DataSong ds = new DataSong();
Mp3File mp3 = new Mp3File(mp3file);
ds.setLenghtOfMp3inSec(mp3.getLengthInSeconds());
ds.setBitRateOfMp3(mp3.getBitrate());
ds.setSampleRate(mp3.getSampleRate());
ds.setVbrOrCbr(mp3.isVbr());
if(mp3 != null){
ds.setAbsoluteLocation(mp3.getFilename());
ds.setLocation(removeSDir(mp3.getFilename(), sDir));
if(mp3.hasId3v2Tag())
{
ID3v2 id3v2Tag = mp3.getId3v2Tag();
if(!(id3v2Tag.getArtist() == null))
{
ds.setArtist(id3v2Tag.getAlbumArtist());
}
if(!(id3v2Tag.getAlbum() == null))
{
ds.setAlbum((id3v2Tag.getAlbum()));
}
if(!(id3v2Tag.getTitle() == null))
{
ds.setTitle(id3v2Tag.getTitle());
}
if(!(id3v2Tag.getTrack() == null))
{
ds.setTrackOnAlbum(id3v2Tag.getTrack());
}
if(!(id3v2Tag.getYear() == null) && !(id3v2Tag.getYear().isEmpty()))
{
ds.setYearReleased(id3v2Tag.getYear());
}
if(!(id3v2Tag.getGenreDescription() == null))
{
ds.setGenre(id3v2Tag.getGenreDescription());
}
if(!(id3v2Tag.getComposer() == null))
{
ds.setComposer(id3v2Tag.getComposer());
}
if(!(id3v2Tag.getPublisher() == null))
{
ds.setPublisher(id3v2Tag.getPublisher());
}
if(!(id3v2Tag.getOriginalArtist() == null))
{
ds.setOriginArtist(id3v2Tag.getOriginalArtist());
}
if(!(id3v2Tag.getAlbumArtist() == null))
{
ds.setAlbumArtString(id3v2Tag.getAlbumArtist());
}
if(!(id3v2Tag.getCopyright() == null))
{
ds.setCopyright(id3v2Tag.getCopyright());
}
if(!(id3v2Tag.getUrl() == null))
{
ds.setUrl(id3v2Tag.getUrl());
}
}
}
lsds.add(ds);
}
return lsds;
}
I presume that what I should do is to make my checkMp3File method into a Task method which will do a background thread ?
There is not enough code to be sure but I think you are probably calling your method on the JavaFX application thread which then blocks your UI.
You should read the documentation about concurrency in JavaFX.
https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/concurrency.htm
I'm doing an app with Xamarin iOS.
I put a UITableView on XCode, so that when I click on a button, it retrieves from the database and slot it in. I'm able to put it onto a row, but couldn't figure it out how to have multiple rows of data in it. This is my partial code from which I'm able to display a row of data.
cmd.CommandType = CommandType.Text;
dr = cmd.ExecuteReader();
while (dr.Read())
{
var table = new UITableView(this.retrieveData.Frame);
string[] tableItems = new String[] {dr["admin_num"] + ", " + dr["name"]};
table.Source = new TableSource(tableItems);
Add (table);
}
You are creating a completely new TableView for each row in your data. Instead, you should loop through your data and create a data structure (List, array, etc) containing ALL of the data you want to display, and then pass that data to your TableView/Source.
cmd.CommandType = CommandType.Text;
dr = cmd.ExecuteReader();
// you will need a class mydata with Num and Name properties
List<mydata> data = new List<mydata>();
while (dr.Read())
{
data.Add(new mydata { Num = dr["admin_num"], Name = dr["name"] });
}
dr.Close();
var table = new UITableView(this.retrieveData.Frame);
table.Source = new TableSource(data);
Add (table);
What you need to do is this:
public List<DemoClass> getDemoClassList()
{
List<DemoClass> lstDemoClass;
DemoClass objDemoClass;
try
{
String strCommandText;
strCommandText = "SELECT * FROM DemoClass ";
command = new SqliteCommand(strCommandText, connection);
lstDemoClass = new List<DemoClass>();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
objDemoClass = new Homes(false);
objDemoClass.ID = Convert.ToInt32(reader[0]);
objDemoClass.Name = Convert.ToString(reader[1]);
lstDemoClass.Add(objDemoClass);
}
}
return lstDemoClass;
}
catch (Exception ex)
{
throw ex;
}
finally
{
command.Dispose();
command = null;
lstDemoClass = null;
objDemoClass = null;
}
}
public void BindList()
{
List<DemoClass> lstDemoClass = new List<DemoClass>();
DemoClass hm = new DemoClass();
lstDemoClass = (List<DemoClass>)hm.getDemoClassList();
TableViewDataSource tdatasource = new TableViewDataSource(this, lstDemoClass);
table.Hidden = false;
table.DataSource = tdatasource;
table.Delegate = new TableViewDelegate(this, table, lstDemoClass);
table.ReloadData();
}
The getDemoClassList() will give the retrieved list from SQLite table, and later you can bind the list to the table datasource.
UPDATE:
As per your request I have updated my comment with the code for datasource and its delegate classes.
Now in this same class you need to add the following subclasses:
#region TableDelegate
public class TableViewDelegate : UITableViewDelegate
{
private DemoPageViewController _Controller;
private List<DemoClass> lst;
public TableViewDelegate(DemoPageViewController controller ,UITableView tableView, List<DemoClass> tblList)
{
try
{
this._Controller = controller;
this.lst = tblList;
}
catch(Exception ex)
{
}
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
try
{
//This loads the activity spinner till the selection code is completed
_Controller._loadPop = new LoadingOverlay (new System.Drawing.RectangleF(0,0,_Controller.View.Frame.Width,_Controller.View.Frame.Height),"Loading...");
_Controller.View.Add ( _Controller._loadPop );
// spin up a new thread to do some long running work using StartNew
Task.Factory.StartNew (
// tasks allow you to use the lambda syntax to pass work
() => {
InvokeOnMainThread(delegate{
DemoClass f = lst[indexPath.Row];
//Add your code here, usually some navigation or showing a popup
});
}).ContinueWith(t => InvokeOnMainThread(() => {
//Hide the activity spinner
_Controller._loadPop.Hide();
}));
}
catch(Exception ex)
{
}
finally
{
}
}
}
#endregion
#region TableDataSource
private class TableViewDataSource : UITableViewDataSource
{
static NSString kCellIdentifier = new NSString("MyIdentifier");
private List<DemoClass> lst;
private DemoPageViewController controller;
public TableViewDataSource (DemoPageViewController controller ,List<DemoClass> tblLst)
{
this.controller = controller;
this.lst = tblLst;
}
public override int NumberOfSections (UITableView tableView)
{
return 1;
}
public override int RowsInSection (UITableView tableView, int section)
{
return lst.Count;
}
// Override to support conditional editing of the table view.
public override bool CanEditRow (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
{
// Return false if you do not want the specified item to be editable.
return false;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
try
{
UITableViewCell cell = tableView.DequeueReusableCell (kCellIdentifier);
if (cell == null)
{
cell = new UITableViewCell (UITableViewCellStyle.Subtitle, kCellIdentifier);
cell.Tag = Environment.TickCount;
}
DemoClass objDemo = lst[indexPath.Row];
cell.Accessory = UITableViewCellAccessory.DisclosureIndicator;
cell.ImageView.Image = UIImage.FromFile("Images/CameraImg.png");
cell.DetailTextLabel.Text = "Show some detail: " + objDemo.DemoDescription.ToString();
cell.TextLabel.Text = "Some Title: " + objDemo.DemoTitle.ToString();
return cell;
}
catch(Exception ex)
{
return null;
}
finally
{
}
}
}
#endregion
Hope it helps.