This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I have a list of number of url and its name is listOfUrlSources,
I passed it inside class GenerateUrlImages the task of this class is to come out with a picture link and it works if you use it and pass a link to one site it gives out a picture link, but now I'm trying to pass more than one site for it and also give me links to photos I tried, but I didn't make it through a list.
//
for (int i = 0; i < sources.size(); i++) {
item = new GenerateImage(sources.get(i).getUrl());
// networkImagesLiveData.setValue(createLiveDataForLoadingImage(sources.get(i).getUrl()));
listOfUrlSources.add(item);
}
new GenerateUrlImages().execute(listOfUrlSources);
//---------
//
public class GenerateUrlImages extends AsyncTask<List<GenerateImage>, Void, List<GenerateImage>>{
public GenerateUrlImages(){
}
#Override
protected List<GenerateImage> doInBackground(List<GenerateImage>... arrayLists) {
List<String> result = new ArrayList<String>();
List<GenerateImage> passed = new ArrayList<GenerateImage>();
passed = arrayLists[0];
//get passed arraylist
//urlImages
String src="";
try {
org.jsoup.nodes.Document doc1;
Elements img2;
GenerateImage Item;
for(int i=0; i<passed.size(); i++) {
doc1 = Jsoup.connect(passed.get(i).getUrl()).get();
//Elements img = doc1.getElementsByTag("img");
img2 = doc1.getElementsByTag("meta");
for(Element element : img2) {
if("og:image".equals(element.attr("property"))) {
src = element.attr("content");
Item = new GenerateImage(src);
urlImages.add(Item);
}
}
for (int j = 0; j < urlImages.size(); j++) {
Log.d("getUrlImage:", "" + urlImages(j));
}
}
//InputStream in = new java.net.URL(src).openStream();
// bmp = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error :", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute(){
}
protected void onPostExecute(ArrayList<String> result){
}
}
In for loop you did a mistake
for (int j = 0; j < urlImages.size(); j++) {
Log.d("getUrlImage: ", "" + urlImages[j]); // add this line also
}
You have printed the Arraylist without index value using the ArraylistName.get(index) in your case Log.d("getUrlImage: ", "" + urlImages); it should be like Log.d("getUrlImage: ", "" + urlImages.get(j));
after this change in your code, you will be able to see the required result.
for (int j = 0; j < urlImages.size(); j++) {
Log.d("getUrlImage: ", "" + urlImages.get(j));
}
Related
I have an arraylist in which I have ESSID, BSSID, Strenght of access Point on first three indexes, and from Index 4 to 6 I have again ESSID, BSSID, Strength of another AccessPoint. I want to store this list in database like first three values save in one row of table. and next three values save in 2nd row of table.
String[] namesArr = new String[arrayList2.size()]; //conver arraylist to array
for (int j = 0; j < arrayList2.size(); j++){
namesArr[j] = arrayList2.get(j);
int length = namesArr[j].length();
for (int k = 0; k < length; k += 3) {
ssid = namesArr[k];
bssid = namesArr[k + 1];
rssid = namesArr[k + 2];
}
insertValues(this);
}
public void insertValues(View.OnClickListener view){
SendData send = new SendData(this);
send.execute(bssid,ssid,rssid);}
I have made a class to store this data in database that works fine.
public class SendData extends AsyncTask<String, Void, String> {
AlertDialog dialog;
Context context;
public SendData(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
dialog = new AlertDialog.Builder(context).create();
dialog.setTitle("Message");
}
#Override
protected void onPostExecute(String s) {
dialog.setMessage(s);
dialog.show();
}
#Override
protected String doInBackground(String... voids) {
String data = "";
String result = "";
String MAC = voids[0];
String Name = voids[1];
String Strength = voids[2];
String con_Str = "http://10.5.48.129/Webapi/accesspoints_data/create.php";
try{
URL url = new URL(con_Str);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
OutputStream out_Stream = http.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out_Stream, "UTF-8"));
JSONObject obj = new JSONObject();
try {
obj.put("BSSID", MAC);
obj.put("ESSID", Name);
obj.put("RSSID", Strength);
} catch (JSONException e) {
e.printStackTrace();
}
data = obj.toString();
writer.write(data);
writer.flush();
writer.close();
out_Stream.close();
InputStream in_Stream = http.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in_Stream, "ISO-8859-1"));
String line = "";
while ((line = reader.readLine()) != null)
{
result += line;
}
reader.close();
in_Stream.close();
http.disconnect();
return result;
} catch (MalformedURLException e){
result = e.getMessage();
} catch (IOException e){
result = e.getMessage();
}
return result;
}
}
SendData class is perfectly working but problem is with for loop.
I think this is result that you are expecting :
List<String> arrayList2 = new ArrayList<>();
arrayList2.add("1");
arrayList2.add("2");
arrayList2.add("3");
arrayList2.add("4");
arrayList2.add("5");
arrayList2.add("6");
arrayList2.add("6");
arrayList2.add("7");
arrayList2.add("8");
arrayList2.add("9");
arrayList2.add("10");
List<String[]> sarrayList = new ArrayList<>();
String[] arr = new String[3];
int i = 0;
for (int j = 0; j < arrayList2.size(); j++)
{
arr[i] = arrayList2.get(j);
i++;
if((j+1)%3==0)
{
sarrayList.add(arr);
i = 0;
arr = new String[3];
}
}
for(String [] sa:sarrayList)
{
for(String s:sa)
{
System.out.println(s);
}
System.out.println("=========");
}
This might not be the most efficient way of doing it. But it splits the ArrayList in to String arrays of length=3 and stores them in a new ArrayList named sarrayList
I would advise to use a datastructure to hold the record. See the code below this is a small example how you could do it
ArrayList<Record> records;
for (int i = 2; i < inputArrayList.size(); i = i + 3){
string ssid = namesArr.get(i - 2);
string bssid = namesArr.get(i - 1);
string rssid = namesArr.get(i);
records.add(new Record(ssid, bssid, rssid));
}
class Record{
string ssid;
string bssid;
string rssid;
// Constructor...
// Getter and setter to be implemented...
}
ok from what i understand you want to divide the arraylist each 3 elements thats how you do it with streams and it will return an a collection of arraylists each one has 3 elements
final int chunkSize = 3;
final AtomicInteger counter = new AtomicInteger();
//arrayList here us your array list
final Collection<List<String>> result = arrayList.stream()
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / chunkSize))
.values();
and mentioning supermar10 answer you code make a class to map the strings to it like that
class Record{
string ssid;
string bssid;
string rssid;
Record(String ssid,String bssid,String rssid){
this.ssid=ssid;
this.bssid=bssid;
this.rssid=rssid;
}
}
now you have a class to map to now save the records in a list of Record
create a a list in the main class
static List<Record> lists=new ArrayList<>();
then map the data like that
result.stream().forEach(nowList -> saveRecord(nowList));
and thats the save method
static void saveRecord(List<String> list){
lists.add(new Record(list.get(0),list.get(1),list.get(2)));
}
I have simplified it to one loop and also modified insertValues so that it takes 3 more parameters. This
int size = arrayList2.size();
for (int j = 0; j < size; j += 3) {
if (size - j < 3 ) {
break;
}
String ssid = arrayList2.get(j);
String bssid = arrayList2.get(j + 1);
String rssid = arrayList2.get(j + 2);
insertValues(this, ssid, bssid, rssid);
}
if one the other hand ssid and so on are class variables the inside of the loop can be changed to
ssid = arrayList2.get(j);
bssid = arrayList2.get(j + 1);
rssid = arrayList2.get(j + 2);
insertValues();
I am creating a function for an app where the user supplies some items and the app then the app gets prices from a database. These prices are put in a map , and after async task is complete , the permutation function starts. What it IS meant to do id to go through all permutations based on combinations which change based on input from the user.I am getting ava.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object referenceMy code is as follows:
latest.java
public class latest extends AppCompatActivity {
String major = "";
TextView textView;
public static Map<String,Map<String,Integer>> cart_names = new HashMap<>();
public static Map<String,Map<String,Integer>> cart_names2 = new HashMap<>();
ProgressDialog pd;
ArrayList<String> strhold = new ArrayList<String>();
Activity context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_latest);
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
textView = (TextView) findViewById(R.id.main_text);
context=this;
for (int s=0;s<Search_multiple.cart_records.size();s++){
strhold.add(Search_multiple.cart_records.get(s).getName());
}
if (strhold.size()>0) {
BackTask backTask = new BackTask();
backTask.execute(strhold);
}
}
#Override
public void onStart(){
super.onStart();
String arr[]={};
}
public void goto_main_confirm(View view) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
/* public static void setCart_records(Items item){
cart_records.add(item);
}*/
public void goto_cart_confirm(View view) {
Intent someintent = new Intent(this, CartActiviy.class);
startActivity(someintent);
}
private class BackTask extends AsyncTask<ArrayList<String>, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(context);
pd.setTitle("Retrieving data");
pd.setMessage("Please wait.");
pd.setCancelable(true);
pd.setIndeterminate(true);
pd.show();
}
protected Void doInBackground(ArrayList<String>... arg0) {
InputStream is = null;
String result = "";
try {
ArrayList<String> name = arg0[0];
String link = "http://chutte.co.nf/get_item_prices.php?";
for (int b = 0; b < name.size(); b++) {
link += "names[]" + "=" + name.get(b);
if (b != name.size() - 1) {
link += "&";
}
}
Log.e("ERROR", link);
URL url = new URL(link);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
is = urlConnection.getInputStream();
} catch (Exception e) {
if (pd != null)
pd.dismiss();
Log.e("ERROR", e.getMessage());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
is.close();
result = builder.toString();
} catch (Exception e) {
Log.e("ERROR", "Error converting result " + e.toString());
}
try {
result = result.substring(result.indexOf("["));
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Map<String, Integer> temmap = new HashMap<>();
String temname = jsonObject.getString("Name");
temmap.put("First", jsonObject.getInt("First"));
strhold.add("First");
temmap.put("Second", jsonObject.getInt("Second"));
strhold.add("Second");
temmap.put("Third", jsonObject.getInt("Third"));
strhold.add("Third");
Log.e("ERROR", temmap.get("First").toString());
cart_names.put(temname, temmap);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
if (pd != null) pd.dismiss();
Log.e("size", cart_names.size() + " ");
if (cart_names.size() == 0) {
textView.setText("Sorry, Error applying data \n" + "Please contact customer service........");
} else {
String[] strhold1 = new String[strhold.size()];
for (int i = 0; i < strhold.size(); i++) {
strhold1[i] = strhold.get(i);
}
Combination.printCombination(strhold1, strhold.size(), 2);
}
}
}
}
Combination.java
Public class Combination {
/* arr[] ---> Input Array
data[] ---> Temporary array to store current combination
start & end ---> Staring and Ending indexes in arr[]
index ---> Current index in data[]
r ---> Size of a combination to be printed */
public static ArrayList<String> finalmap = new ArrayList<>();
public static void combinationUtil(String arr[], String data[], int start,
int end, int index, int r)
{
// Current combination is ready to be printed, print it
if (index == r)
{
ArrayList<String> stringArrayList = new ArrayList<String>();
for (int j=0; j<r; j++)
stringArrayList.add(data[j]);
permute(stringArrayList,0);
return;
}
// replace index with all possible elements. The condition
// "end-i+1 >= r-index" makes sure that including one element
// at index will make a combination with remaining elements
// at remaining positions
for (int i=start; i<=end && end-i+1 >= r-index; i++)
{
data[index] = arr[i];
combinationUtil(arr, data, i+1, end, index+1, r);
}
}
// The main function that prints all combinations of size r
// in arr[] of size n. This function mainly uses combinationUtil()
public static void printCombination(String arr[], int n, int r)
{
// A temporary array to store all combination one by one
String data[]=new String[r];
for(int no = 0;no<arr.length;no++){
boolean decider = true;
for (Map.Entry<String,Map<String,Integer>> entry : latest.cart_names.entrySet()){
if(latest.cart_names.get(entry.getKey()).get(arr[no])==0){
decider=false;
}
}
if (finalmap.size()==0) {
if (decider) {
for (int rt = 0; rt < latest.cart_names.size(); rt++) {
finalmap.add(arr[no]);
}
}
}else{
if (decider) {
int sum1 = 0;
int sum2 = 0;
for (Map.Entry<String, Map<String, Integer>> entry : latest.cart_names.entrySet()) {
sum1 += latest.cart_names.get(entry.getKey()).get(finalmap);
sum2 += latest.cart_names.get(entry.getKey()).get(arr[no]);
}
if (sum2>sum1){
for (int rt = 0; rt < latest.cart_names.size(); rt++) {
finalmap.add(arr[no]);
}
}
}
}
}
// Print all combination using temprary array 'data[]'
combinationUtil(arr, data, 0, n-1, 0, r);
}
public static void permute(ArrayList<String> arr, int k){
for(int i = k; i < arr.size(); i++){
java.util.Collections.swap(arr, i, k);
/*int sum1 = 0;
int sum2 = 0;
int man = 0;
for (Map.Entry<String, Map<String, Integer>> entry : latest.cart_names.entrySet()) {
sum1 += latest.cart_names.get(entry.getKey()).get(finalmap);
sum2+=latest.cart_names.get(entry.getKey()).get(arr.get(man));
man++;
}
if (sum2>sum1){
for (int rt = 0; rt < latest.cart_names.size(); rt++) {
finalmap.add(arr.get(rt));
}
}*/
permute(arr, k+1);
java.util.Collections.swap(arr, k, i);
/* for (Map.Entry<String, Map<String, Integer>> entry : latest.cart_names.entrySet()) {
sum1 += latest.cart_names.get(entry.getKey()).get(finalmap);
sum2+=latest.cart_names.get(entry.getKey()).get(arr.get(man));
man++;
}
if (sum2>sum1){
for (int rt = 0; rt < latest.cart_names.size(); rt++) {
finalmap.add(arr.get(rt));
}
}
}
if (k == arr.size() -1){
for(int woman = 0;woman<finalmap.size();woman++) {
System.out.println(finalmap.get(woman));
}*/
}
}
}
Log
6-15 15:06:41.850 3538-3538/nf.co.riaah.chutte D/AndroidRuntime: Shutting down VM
--------- beginning of crash
06-15 15:06:41.850 3538-3538/nf.co.riaah.chutte E/AndroidRuntime: FATAL EXCEPTION: main
Process: nf.co.riaah.chutte, PID: 3538
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
at nf.co.riaah.chutte.Combination.printCombination(Combination.java:54)
at nf.co.riaah.chutte.latest$BackTask.onPostExecute(latest.java:173)
at nf.co.riaah.chutte.latest$BackTask.onPostExecute(latest.java:83)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:139)
at android.app.ActivityThread.main(ActivityThread.java:5298)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
06-15 15:06:41.851 3538-3538/nf.co.riaah.chutte D/AppTracker: App Event: crash
06-15 15:06:41.883 3538-3538/nf.co.riaah.chutte I/Process: Sending signal. PID: 3538 SIG: 9
06-15 15:06:43.255 3918-3918/nf.co.riaah.chutte D/ThreadedRenderer: mThreadGroupCpuId 2 mRenderThreadCpuId 2 affinity
Have a look at Combination.java line 54 wich seams to be if(latest.cart_names.get(entry.getKey()).get(arr[no])==0) (If I counted correctly) so the Integer in the Map seams to be null. I recommend so add some log-output or to debug to find out which entry exactly is the problem and than check if you need to add a bull-check or fix your data.
Maybe arr[no] is null.
I recommend to split the line and make some log-outputs to find the problem (or use a debugger)
To find the cause of the problem I would replace:
if(latest.cart_names.get(entry.getKey()).get(arr[no])==0)
to
System.err.println("no: "+no);
String arrayElement=arr[no];
System.err.println("arrayElement: "+arrayElement);
Map<String,Integer> outerMapValue = entry.getValue();
System.err.println("outerMapValue: "+outerMapValue);
if(outerMapValue.get(arrayElement)==0)
Remarks:
if(latest.cart_names.get(entry.getKey()) can be replaced with entry.getValue()
Map<String,Map<String,Integer>> Is not very easy to understand while reading the code. You may consider to introduce a type to wrap the inner Map<String,Integer>
I am working on a driving licence project on j2Me wich is including Tests like quizz , well and i am having a problem after parsing the questions and moving them into choiceGroups just like that :
if (questions.length > 0) {
for (int i = 0; i < questions.length; i++) {
ChoiceGroup reponses = new ChoiceGroup("Reponses" + i, Choice.EXCLUSIVE);
reponses.append(questions[i].getReponse1(), null);
reponses.append(questions[i].getReponse2(), null);
reponses.append(questions[i].getReponse3(), null);
pass.append(questions[i].getContenu());
pass.append(reponses);
}
}
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
}
disp.setCurrent(pass);
and the next step is the command who's controlling the choiceGroups to test them if they are like the true answer or not .
so i am blocked here .
if (c == valider) {
int result = 0;
for (int i = 0; i < pass.size(); i++) {
String ch = pass.get(i).getLabel();
System.out.println(ch);
}
}
I don't know how to get the choice from the choicegroup
any help
Actually, I am not sure what totally you want for:
This code will help you get selected items from choicegroup that i did long time before:
//get a selected array in choicegroup
private String[] choiceGroupSelected(ChoiceGroup cg) {
String selectedArray[] = new String[cg.size()];
int k = 0;
for (int i = 0; i < cg.size(); i++) {
if (cg.isSelected(i)) {
selectedArray[k] = cg.getString(i);
k++;
}
}
return selectedArray;
}
That function will help me get all selected items for deleting action below:
private void deleteSpecificItem() {
try {
String temp = null;
int index;
//get ChoiceGroup size
int numbers = cgTrip.size();
String selectedItems[] = choiceGroupSelected(cgTrip);
//
rs = services.RecordStoreManager.openRecordStoreByName("TripRS");
re = rs.enumerateRecords(null, null, true);
String[] tripList = new String[2];
for (int i = 0; i < numbers; i++) {
temp = selectedItems[i];
if (temp != null) {
while (re.hasNextElement()) {
try {
index = re.nextRecordId();
System.out.println("RecordID: " + index);
byte[] byteBuff = rs.getRecord(index);
String source = new String(byteBuff);
tripList = services.StringManager.getItems(source, ";", 2);
String strProcess = tripList[0] + "-" + tripList[1];
//inspect all of items in choicegroup and if they are selecting then compare with record
//If comparison is true then delete this record
if (temp.equals(strProcess)) {
System.out.println("Delete RecordID: " + index);
rs.deleteRecord(index);
re.keepUpdated(true);
break;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
}
}
try {
rs.closeRecordStore();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
rs = null;
re.destroy();
this.LoadTripItem();
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
}
}
I am trying to open a file by drag and drop onto JTextField but i always get the error.
Heres my code
public void drop(DropTargetDropEvent dtde) {
String str4=null;
try {
JTextArea comp = null;
if(Switchtab==2)
comp=textarea1;
if(Switchtab==3)
comp=textarea2;
if(Switchtab==4)
comp=textarea3;
if(Switchtab==1)
comp=textarea4;
// Ok, get the dropped object and try to figure out what it is
Transferable tr = dtde.getTransferable();
DataFlavor[] flavors = tr.getTransferDataFlavors();
for (int i = 0; i < flavors.length; i++) {
System.out.println("Possible flavor: "
+ flavors[i].getMimeType());
// Check for file lists specifically
if (flavors[i].isFlavorJavaFileListType()) {
// Great! Accept copy drops...
dtde.acceptDrop(DnDConstants.ACTION_COPY);
// comp.setText("Successful file list drop.\n\n");
// And add the list of file names to our text area
java.util.List list = (java.util.List) tr
.getTransferData(flavors[i]);
for (int j = 0; j < list.size(); j++) {
//wcomp.append(list.get(j) + "\n");
str4=list.get(j)+"\n";
}
// Replace '\' with '/'
file_pth = str4.replaceAll("\\\\","/" );
System.out.println(str4.replaceAll("\\\\","/" ));
//Open the file
try {
File f = new File(file_pth);
FileInputStream fobj = new FileInputStream(f);
int len = (int) f.length();
str4 = "";
for (int j = 0; j < len; j++) {
char str5 = (char) fobj.read();
str4 = str4 + str5;
}
comp.setText(str4);
setTitle(str4);
} catch (Exception e) {
System.out.println("Caught::" + e);
}
// If we made it this far, everything worked.
dtde.dropComplete(true);
return;
}
}
// Hmm, the user must not have dropped a file list
System.out.println("Drop failed: " + dtde);
dtde.rejectDrop();
} catch (Exception e) {
e.printStackTrace();
dtde.rejectDrop();
}
}
I even tried replacing backslash with double backslash and forward slash but still i get this error
Possible flavor: application/x-java-file-list; class=java.util.List
C:/kevin_java/file io/DemoIO.java
Caught::java.io.FileNotFoundException: C:\kevin_java\file io\DemoIO.java
(The filename, directory name, or volume label syntax is incorrect)
The output doesnt show the replaced string.
It shows the previous string with single backslash.
finally i got my answer.
Simple solution
java.util.List list = (java.util.List) tr
.getTransferData(flavors[i]);
for (int j = 0; j < list.size(); j++) {
str4=list.get(j).toString();
}
File f = new File(str4);
FileInputStream fobj = new FileInputStream(f);
...
...
..
Edit
From the javadoc for isFlavorJavaFileListType,
Returns true if the DataFlavor specified represents a list of file objects.
Therefor,
FileInputStream fobj = new FileInputStream(list.get(list.length()-1));
I have a program reading from a text file (currently 653 lines long) all separated by a comma. But when I go to save the file to a new location, it only saves 490 lines. It also seems that the last line in the newly created text file is cut in half. Any ideas on what might be the problem?
Here is the code that I used to open and sort the data in the list:
try {
scanner = new Scanner(file);
// Put the database into an array and
// Make sure each String array is 13 in length
while (scanner.hasNext()) {
line = scanner.nextLine();
word = line.split(",");
if (word.length < 13) {
String[] word2 = {"","","","","","","","","","","","",""};
for (int i = 0; i < word.length; i++) {
word2[i] = word[i];
}
dataBaseArray.add(word2);
}
else {
dataBaseArray.add(word);
}
}
}
catch (FileNotFoundException exc) {
JOptionPane.showMessageDialog(this, "File cannot be found.", "error finding file", JOptionPane.ERROR_MESSAGE);
}
// Splitting the database into vacant numbers/dead lines/vacant cubicles
for (int i = 0; i < dataBaseArray.size(); i++) {
if (dataBaseArray.get(i)[8].equals("VACANT")) {
vacantNums.add(dataBaseArray.get(i));
}
else if (dataBaseArray.get(i)[4].equals("DEAD")) {
deadLines.add(dataBaseArray.get(i));
}
else if (dataBaseArray.get(i)[6].equals("") && dataBaseArray.get(i)[7].equals("")) {
vacantCubs.add(dataBaseArray.get(i));
}
else if (dataBaseArray.get(i)[7].equals("")) {
people.add(dataBaseArray.get(i));
}
else {
people.add(dataBaseArray.get(i));
}
}
// Resetting the DB Array to put the values back in it
dataBaseArray = new ArrayList<>();
// Ordering the arrays I want them to appear in the list
// Orering the people to appear in alphabetical order
Collections.sort(people, new Comparator<String[]>() {
#Override
public int compare(String[] strings, String[] otherStrings) {
return strings[7].compareTo(otherStrings[7]);
}
});
// Put the people in the DB Array
for (int i = 0; i < people.size(); i++) {
dataBaseArray.add(people.get(i));
}
// Put the vacant numbers in the AB Array
for (int i = 0; i < vacantNums.size(); i++) {
dataBaseArray.add(vacantNums.get(i));
}
// Put the vacant cubicles in the AB Array
for (int i = 0; i < vacantCubs.size(); i++) {
dataBaseArray.add(vacantCubs.get(i));
}
// Put the dead lines in the AB Array
for (int i = 0; i < deadLines.size(); i++) {
dataBaseArray.add(deadLines.get(i));
}
list = new String[dataBaseArray.size()];
// Add the DB Array to the list
for (int i = 0; i < list.length; i++) {
if (dataBaseArray.get(i)[8].equals("VACANT")) {
list[i] = "VACANT";
}
else if (dataBaseArray.get(i)[4].equals("DEAD")) {
list[i] = "DEAD";
}
else if (dataBaseArray.get(i)[6].equals("") && dataBaseArray.get(i)[7].equals("")) {
list[i] = "Vacant Cubicle";
}
else if (dataBaseArray.get(i)[7].equals("")) {
list[i] = dataBaseArray.get(i)[6];
}
else {
list[i] = dataBaseArray.get(i)[7] + ", " + dataBaseArray.get(i)[6];
}
}
// Populate the list
lstAdvance.setListData(list);
Here is what I used to save the file:
try {
saveFile = new FileWriter("Save Location");
String newLine = System.getProperty("line.separator");
for (int i = 0; i < dataBaseArray.size(); i++) {
for (int j = 0; j < dataBaseArray.get(i).length; j++) {
saveFile.append(dataBaseArray.get(i)[j] + ",");
}
saveFile.append(newLine);
}
}
catch (IOException exc) {
JOptionPane.showMessageDialog(this,"error", "error", JOptionPane.ERROR_MESSAGE);
}
Writing to a file is buffered. You have to close() or flush() your writer (saveFile) at the end of writing.
Even better: you should do close() on your writer in the finally block.
Try it using the FileWriter and BufferedWriter....
File f = new File("Your_Path");
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
And yes..its very important to do bw.close() (Closing the Buffer)
See this question : Java FileWriter with append mode
The problem is that your FileWriter object needs to be "append mode" . Then, you append to the file with the "write" method rather than the "append" method. Use a finally catch clause to call "close" . You don't need to flush ( I dont think).