Json returns empty in android - java

I created this class and I created my data in json. It seems that doesn't work and returns empty when I try to insert the data in a database sqLite. This is the class with the creation of the Json:
public class Corsa
{
public Corsa corsaData = null;
public int id = 0;
public String oraPartenza;
public String oraArrivo;
public String partenza;
public String arrivo;
public String codiceLinea;
public String codiceCorsa;
public String tipoCorsa;
public String linkDettaglio;
#Override
public String toString() {
return partenza + " / "+ oraPartenza + "\n" + arrivo + " / " +oraArrivo;
}
public Corsa() {
}
/** Json **/
public static Corsa LoadJson(String jsonStr)
{
Corsa corsaJson = new Corsa();
try
{
JSONObject jObj = new JSONObject(jsonStr);
corsaJson.oraPartenza = HtmlUtils.getJSonString(jObj, "oraPartenza");
corsaJson.oraArrivo = HtmlUtils.getJSonString(jObj, "oraArrivo");
corsaJson.partenza = HtmlUtils.getJSonString(jObj, "partenza");
corsaJson.arrivo = HtmlUtils.getJSonString(jObj, "arrivo");
corsaJson.linkDettaglio = HtmlUtils.getJSonString(jObj, "linkDettaglio");
corsaJson.codiceCorsa = HtmlUtils.getJSonString(jObj, "codiceCorsa");
corsaJson.codiceLinea = HtmlUtils.getJSonString(jObj, "codiceLinea");
}
catch (Exception e) { e.printStackTrace(); }
return corsaJson;
}
public static JSONObject CreateJSon(Corsa corsaJson)
{
JSONObject jObj = new JSONObject();
try
{
jObj.put("oraPartenza", corsaJson.oraPartenza);
jObj.put("oraArrivo", corsaJson.oraArrivo);
jObj.put("partenza", corsaJson.partenza);
jObj.put("arrivo", corsaJson.arrivo);
jObj.put("linkDettaglio", corsaJson.linkDettaglio);
jObj.put("codiceCorsa", corsaJson.codiceCorsa);
jObj.put("codiceLinea", corsaJson.codiceLinea);
} catch (Exception e) { e.printStackTrace(); }
return jObj;
}
}
This is the saved json:
public static void SaveCorsa(Context context, Corsa c)
{
DeleteCorsa(context, c);
SqlHelper dbHelper = null;
try {
dbHelper = new SqlHelper(context);
SQLiteDatabase database = dbHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put("CORSA_DATA", Corsa.CreateJSon(c.corsaData).toString());
database.insert(TABLE_PREFERITI, null, initialValues);
Log.d("Insert preferiti", initialValues.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dbHelper!=null) dbHelper.close();
}
}
and the logCat returns CORSA_DATA{}..So it is empty.. But it's strange beacause is created in the activity..Any idea what's wrong? Thanks

Related

How to parsing JSON from presenter and set to RecyclerView(Android)

I try to get xml data then I parse it to JSON, I use OkHttp as a connection. I managed to get data from LOG but I can't display it in my RecyclerView, when I LOG to adapter and the result is size 0
I set the response to the model and sharedpreference
The point of the problem is that I just don't understand how to take the response from the presenter then I set it to the adapter in the main Fragment.
public class ParentCategories {
#SerializedName("idkategori")
#Expose
private String idkategori;
#SerializedName("namakategori")
#Expose
private String namakategori;
#SerializedName("fileicon")
#Expose
private String fileicon;
#SerializedName("subkategori")
#Expose
private SubCategories subkategori;
public ParentCategories(Parcel in) {
this.idkategori = in.readString();
this.namakategori = in.readString();
this.fileicon = in.readString();
}
public ParentCategories() {
}
public String getIdkategori() {
return idkategori;
}
public void setIdkategori(String idkategori) {
this.idkategori = idkategori;
}
public String getNamakategori() {
return namakategori;
}
public void setNamakategori(String namakategori) {
this.namakategori = namakategori;
}
public String getFileicon() {
return fileicon;
}
public void setFileicon(String fileicon) {
this.fileicon = fileicon;
}
public SubCategories getSubkategori() {
return subkategori;
}
public void setSubkategori(SubCategories subkategori) {
this.subkategori = subkategori;
}
}
public class CategoriesPresenter {
....
public void onResponse(Call call, Response response) throws IOException {
String mMessage = response.body().string();
JSONObject jsonObj = null;
try {
jsonObj = XML.toJSONObject(mMessage);
JSONObject jsonObject = new JSONObject(jsonObj.toString());
JSONObject object = jsonObject.getJSONObject("posh");
String attr2 = object.getString("resultcode");
com.davestpay.apphdi.helper.Log.d("hasil", String.valueOf(object));
if (attr2.equalsIgnoreCase("0000")) {
String idAgen = object.getString("idagen");
int jumlahKategori = object.getInt("jumlahkategori");
JSONArray category = object.getJSONArray("kategori");
List<ParentCategories> parentCategories = new ArrayList<ParentCategories>();
for (int i = 0; i < category.length(); i++) {
ParentCategories categories = new ParentCategories();
JSONObject c = category.getJSONObject(i);
Log.d(TAG, "onResponseC: "+c);
String idKategori = c.getString("idkategori");
String namaKategori = c.getString("namakategori");
Log.d(TAG, "onResponseNamaKategori: "+namaKategori);
String fileIcon = c.getString("fileicon");
JSONObject subCategories = c.getJSONObject("subkategori");
JSONArray subCategory = subCategories.getJSONArray("kategori2");
Log.d(TAG, "onResponseSubCategories: "+subCategory);
for (int subCatPosition = 0; subCatPosition < subCategory.length(); subCatPosition++) {
SecondCategories secondCategories = new SecondCategories();
List<SecondCategories> listSecondCategories = new ArrayList<>();
JSONObject sc = subCategory.getJSONObject(subCatPosition);
String secIdKategori = sc.getString("idkategori");
String secNamaKategori = sc.getString("namakategori");
String secFileIcon = sc.getString("fileicon");
secondCategories.setIdkategori(secIdKategori);
secondCategories.setNamakategori(secNamaKategori);
secondCategories.setFileicon(secFileIcon);
listSecondCategories.add(secondCategories);
}
categories.setIdkategori(idKategori);
categories.setNamakategori(namaKategori);
categories.setFileicon(fileIcon);
parentCategories.add(categories);
Log.d(TAG, "onResponseFinalCategories: "+parentCategories);
}
iCategories.onSuccessCategories(parentCategories);
preferenceHelper.clear(PreferenceHelper.CATEGORIES);
preferenceHelper.putList(PreferenceHelper.CATEGORIES, parentCategories);
} else {
Log.d(TAG, "onResponse: ");
}
} catch (JSONException e) {
com.davestpay.apphdi.helper.Log.e("JSON exception", e.getMessage());
e.printStackTrace();
}
}
}
private void getInit() {
if (preferenceHelper != null) {
idAgen = preferenceHelper.getString(PreferenceHelper.ID_AGEN);
namaAgen = preferenceHelper.getString(PreferenceHelper.NAMA_AGEN);
password = preferenceHelper.getString(PreferenceHelper.PASSWORD);
categories = preferenceHelper.getList(PreferenceHelper.CATEGORIES, ParentCategories[].class);
}
authPresenter = new AuthPresenter(getContext());
presenter = new CategoriesPresenter();
presenter.setBaseView(this);
presenter.onCreate(getContext());
if (authPresenter.isLoggedIn()) {
// kategori.setText(categories.toString());
presenter.getCategories(idAgen, password, counter);
}
kategori = mView.findViewById(R.id.kategori);
categories = new ArrayList<>();
rvMain = mView.findViewById(R.id.rv_categories);
adapter = new CategoriesListViewAdapter(getContext(), categories);
layoutManager = new LinearLayoutManager(getdActivity());
adapter.notifyDataSetChanged();
rvMain.setLayoutManager(layoutManager);
rvMain.setAdapter(adapter);
}
This is the problem.
categories = new ArrayList<>();
Here, you are initialising categories to new ArrayList<>(); It is like you are creating a new arraylist.
Just remove this line.

Change locale in data base android development

How can I localize the database for the project in other languages ​​(for example en, ru, fr and others)
I have an already ready database in English, but I want to make the application multilingual and able to work with other databases depending on the device locale.
I've already seen a lot of forums on this issue, but in each of them it says that you need to get the current locale. But I can not understand where these codes should be attributed. My code is completely listed below.
public class DatabaseHelper extends OrmLiteSqliteOpenHelper
{
private static final String DATABASE_NAME = MuseumConfig.DATABASE_NAME;
private static final String DATABASE_PATH = "/data/data/" + CookbookApplication.getContext().getPackageName() + "/databases/";
private static final int DATABASE_VERSION = CookbookConfig.DATABASE_VERSION;
private static final String PREFS_KEY_DATABASE_VERSION = "database_version";
private Dao<CategoryModel, Long> mCategoryDao = null;
private Dao<AboutModel, Long> mRecipeDao = null;
private Dao<InformationModel, Long> mIngredientDao = null;
// singleton
private static DatabaseHelper instance;
public static synchronized DatabaseHelper getInstance()
{
if(instance==null) instance = new DatabaseHelper();
return instance;
}
private DatabaseHelper()
{
super(CookbookApplication.getContext(), DATABASE_PATH + DATABASE_NAME, null, DATABASE_VERSION);
if(!databaseExists() || DATABASE_VERSION>getVersion())
{
synchronized(this)
{
boolean success = copyPrepopulatedDatabase();
if(success)
{
setVersion(DATABASE_VERSION);
}
}
}
}
#Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource)
{
try
{
Logcat.d("DatabaseHelper.onCreate()");
//TableUtils.createTable(connectionSource, CategoryModel.class);
//TableUtils.createTable(connectionSource, RecipeModel.class);
//TableUtils.createTable(connectionSource, IngredientModel.class);
}
catch(android.database.SQLException e)
{
Logcat.e("DatabaseHelper.onCreate(): can't create database", e);
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion)
{
try
{
Logcat.d("DatabaseHelper.onUpgrade()");
}
catch(android.database.SQLException e)
{
Logcat.e("DatabaseHelper.onUpgrade(): can't upgrade database", e);
e.printStackTrace();
}
}
#Override
public void close()
{
super.close();
mCategoryDao = null;
mRecipeDao = null;
mIngredientDao = null;
}
public synchronized void clearDatabase()
{
try
{
Logcat.d("DatabaseHelper.clearDatabase()");
TableUtils.dropTable(getConnectionSource(), CategoryModel.class, true);
TableUtils.dropTable(getConnectionSource(), RecipeModel.class, true);
TableUtils.dropTable(getConnectionSource(), IngredientModel.class, true);
TableUtils.createTable(getConnectionSource(), CategoryModel.class);
TableUtils.createTable(getConnectionSource(), RecipeModel.class);
TableUtils.createTable(getConnectionSource(), IngredientModel.class);
}
catch(android.database.SQLException e)
{
Logcat.e("DatabaseHelper.clearDatabase(): can't clear database", e);
e.printStackTrace();
}
catch(java.sql.SQLException e)
{
Logcat.e("DatabaseHelper.clearDatabase(): can't clear database", e);
e.printStackTrace();
}
}
public synchronized Dao<CategoryModel, Long> getCategoryDao() throws java.sql.SQLException
{
if(mCategoryDao==null)
{
mCategoryDao = getDao(CategoryModel.class);
}
return mCategoryDao;
}
public synchronized Dao<RecipeModel, Long> getRecipeDao() throws java.sql.SQLException
{
if(mRecipeDao==null)
{
mRecipeDao = getDao(RecipeModel.class);
}
return mRecipeDao;
}
public synchronized Dao<IngredientModel, Long> getIngredientDao() throws java.sql.SQLException
{
if(mIngredientDao==null)
{
mIngredientDao = getDao(IngredientModel.class);
}
return mIngredientDao;
}
private boolean databaseExists()
{
File file = new File(DATABASE_PATH + DATABASE_NAME);
boolean exists = file.exists();
Logcat.d("DatabaseHelper.databaseExists(): " + exists);
return exists;
}
private boolean copyPrepopulatedDatabase()
{
String locale = java.util.Locale.getDefault().getDisplayName();
// copy database from assets
try
{
// create directories
File dir = new File(DATABASE_PATH);
dir.mkdirs();
// output file name
String outputFileName = DATABASE_PATH + DATABASE_NAME;
Logcat.d("DatabaseHelper.copyDatabase(): " + outputFileName);
// create streams
InputStream inputStream = CookbookApplication.getContext().getAssets().open(DATABASE_NAME);
OutputStream outputStream = new FileOutputStream(outputFileName);
// write input to output
byte[] buffer = new byte[1024];
int length;
while((length = inputStream.read(buffer))>0)
{
outputStream.write(buffer, 0, length);
}
// close streams
outputStream.flush();
outputStream.close();
inputStream.close();
return true;
}
catch(IOException e)
{
e.printStackTrace();
return false;
}
}
private int getVersion()
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(CookbookApplication.getContext());
return sharedPreferences.getInt(PREFS_KEY_DATABASE_VERSION, 0);
}
private void setVersion(int version)
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(CookbookApplication.getContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(PREFS_KEY_DATABASE_VERSION, version);
editor.commit();
}
}

get value from xml in method with specific parameters JAVA

I'm newbie in XML parsing and try to understand JAXB. Have the following task:
Implemented the following method, to got the személy object by id parameter,but it returns null:
public Személy getSzemélyById(String id) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Személy.class);
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
XMLReader xmlReader = spf.newSAXParser().getXMLReader();
InputSource inputSource;
inputSource = new InputSource(new FileReader("C:\\Users\\zbocskay.TS-EU\\Documents\\NetBeansProjects\\prt2014levzh\\people.xml"));
SAXSource source = new SAXSource(xmlReader, inputSource);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Személy személy = (Személy) unmarshaller.unmarshal(source);
System.out.println(személy.toString());
return new Személy(személy.getId(), személy.getVezetéknév(), személy.getKeresztnév(), személy.getÉletkor(), személy.getCím(), személy.státusz.DIÁK);
} catch (JAXBException e) {
} catch (FileNotFoundException | ParserConfigurationException ex) {
Logger.getLogger(SzemélyDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXNotRecognizedException ex) {
Logger.getLogger(SzemélyDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXNotSupportedException ex) {
Logger.getLogger(SzemélyDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(SzemélyDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
Here is Személy Class:
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Személy {
public enum Státusz {
FELNŐTT, DIÁK, NYUGDÍJAS, GYERMEK
}
#XmlElement
protected String id;
#XmlElement
protected String vezetéknév;
#XmlElement
protected String keresztnév;
protected Integer életkor;
#XmlElement
protected String cím;
protected Státusz státusz;
public Személy(String id) {
super();
this.id = id;
}
public void setÉletkor(Integer életkor) {
this.életkor = életkor;
}
public String getVezetéknév() {
return vezetéknév;
}
public void setVezetéknév(String vezetéknév) {
this.vezetéknév = vezetéknév;
}
public String getKeresztnév() {
return keresztnév;
}
public void setKeresztnév(String keresztnév) {
this.keresztnév = keresztnév;
}
public String getCím() {
return cím;
}
public void setCím(String cím) {
this.cím = cím;
}
public String getId() {
return id;
}
public Személy(String id, String vezetéknév, String keresztnév,
Integer életkor, String cím, Státusz státusz) {
this(id);
this.vezetéknév = vezetéknév;
this.keresztnév = keresztnév;
this.életkor = életkor;
this.cím = cím;
this.státusz = státusz;
}
public Személy(String id, String vezetéknév, String keresztnév,
String születésiDátum, String cím, String diákigazolványszám,
Státusz státusz) throws ParseException {
this(id);
this.vezetéknév = vezetéknév;
this.keresztnév = keresztnév;
this.életkor = meghatározÉletkort(születésiDátum);
this.cím = cím;
this.státusz = státusz;
}
public Integer getÉletkor() {
return életkor;
}
#Override
public String toString() {
return "Személy [id=" + id + ", vezetéknév=" + vezetéknév
+ ", keresztnév=" + keresztnév + ", életkor=" + életkor
+ ", cím=" + cím + ", státusz=" + státusz + "]";
}
}
And people.xml file with data:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE személyek SYSTEM "people.dtd">
<személyek>
<személy id="micimacko">
<vezetéknév>Mici</vezetéknév>
<keresztnév>Mackó</keresztnév>
<születésidátum>1921.08.21</születésidátum>
<cím>Százholdas Pagony</cím>
<fotó>http://upload.wikimedia.org/wikipedia/en/1/10/Winniethepooh.png
</fotó>
</személy>
</személyek>
Running in the main class by the following:
public static void main(String args[]) {
SzemélyDAO ddd = new SzemélyDAOImpl();
System.out.println(ddd.getSzemélyById("micimacko"));
}
Could anybody help me, what am I doing wrong?Thanks.
As the exception states you need to add a no-arg constructor to your Személy class. This means a constructor that doesn't take any parameters. Currently the class has a single constructor that takes a String. Adding the following would work:
private Személy() {
}

update data from jTable to database -null pointer exception error

Im trying to read values from my jTable1
private void jcmdOKActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
int colum=jTable1.getSelectedColumn();
int row=jTable1.getSelectedRow();
System.out.println("row of selected is "+row+"col is "+colum);
final String remark1 = (String) jTable1.getValueAt(row, 8);
final String remark2 = (String) jTable1.getValueAt(row, 9);
final String invoiceno = (String) jTable1.getValueAt(row, 11);
final String id=(String) jTable1.getValueAt(row, 12);
System.out.println(id + "id");
try{
Transaction t = new Transaction(s) {
public Object transact() throws BasicException {
System.out.println("try loop for update");
SentenceExec followinsert = new PreparedSentence(s
, "UPDATE FOLLOWUP SET REMARK1= ?, REMARK2=?, INVOICENO=? WHERE ID= ?"
, SerializerWriteParams.INSTANCE);
followinsert.exec(new DataParams() { public void writeValues() throws BasicException {
System.out.println("executing command");
setString(1, remark1);
setString(2, remark2);
setString(3, invoiceno);
setString(2, id);
//System.out.println(" after update line");
}});
return null;
}
};
t.execute(); //im getting null pointer exception here :(
}
catch (BasicException ex) {
Logger.getLogger(FollowUp.class.getName()).log(Level.SEVERE, null, ex);
}
}
i get this error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.openbravo.data.loader.Transaction.execute(Transaction.java:42)
at com.openbravo.pos.followup.FollowUp.jcmdOKActionPerformed(FollowUp.java:679)
at com.openbravo.pos.followup.FollowUp.access$300(FollowUp.java:66)
at com.openbravo.pos.followup.FollowUp$5.actionPerformed(FollowUp.java:193)
Transaction.java is
public abstract class Transaction<T> {
private Session s;
/** Creates a new instance of Transaction */
public Transaction(Session s) {
this.s = s;
}
public final T execute() throws BasicException {
if (s.isTransaction()) {
return transact();
} else {
try {
try {
s.begin();
T result = transact();
s.commit();
return result;
} catch (BasicException e) {
s.rollback();
throw e;
}
} catch (SQLException eSQL) {
throw new BasicException("Transaction error", eSQL);
}
}
}
protected abstract T transact() throws BasicException;
}

ArrayList becomes null while writing to file

My arraylist<"obj"> becomes null after trying to write to a file.
In WriteToFile class arraylist info becomes null after executing the last line
writer.write(info.get(i).getIpadd().toString()+"\n");
It works on the first instance when i am writing another list to file but does not when i run it the 2nd instance. I dun understand why its happening. Below is the whole code and the stack trace.
WriteToFile Class:
public class WriteToFile {
public WriteToFile(ArrayList<Information> info,String location)
{
FileWriter writer=null;
try
{
writer = new FileWriter(location);
System.out.println(info.size());
for(int i=0;i<info.size()-1;i++)
{
writer.write(info.get(i).getDate().toString()+",");
writer.write(info.get(i).getAccount().toString()+",");
writer.write(info.get(i).getStatus().toString()+",");
writer.write(info.get(i).getIpadd().toString()+"\n");
System.out.println(info.get(i).getAccount());
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e.getMessage());
}
finally
{
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
StackTrace:
java.lang.NullPointerException
at WriteToFile.<init>(WriteToFile.java:17)
at Gen_Report.<init>(Gen_Report.java:45)
at Gen_Report.main(Gen_Report.java:57)
main:
public class Gen_Report {
public Gen_Report()
{
// TODO Auto-generated constructor stub
//locate file and read all text from .log file to .csv
//file is found.so read text from it and extract all date/time, email add ,accepts and rejects,ip add, delete
Date date=new Date();
String[] dateTokens=date.toString().split(" ");
String dateString=dateTokens[2]+dateTokens[1]+dateTokens[5]+"_"+dateTokens[3].substring(0, 2)+dateTokens[3].substring(3,5)+dateTokens[3].substring(6, 8);
String logFileLocation = "/Users/gundu_87/Documents/workspace/GenFLRReport/";
ReaderFromLog rfl = new ReaderFromLog(logFileLocation+"radsecproxy.log");
//include duplicates
WriteToFile wtf = new WriteToFile(rfl.log,logFileLocation+dateString+"_FLRlogduplicates.txt");
//exclude duplicates
RemoveDuplicatesInList rdil = new RemoveDuplicatesInList(logFileLocation+dateString+"_FLRlogduplicates.txt");
for(int i=0;i<rdil.log.size();i++)
{
System.out.println(rdil.log.get(i).getAccount());
}
wtf = new WriteToFile(rdil.log,logFileLocation+dateString+"_FLRlog.txt");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Gen_Report gr= new Gen_Report();
}
}
Information class:
public class Information {
private String ipadd;
private String status;
private String account;
private String date;
public String getIpadd() {
return ipadd;
}
public void setIpadd(String ipadd) {
this.ipadd = ipadd;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
ReaderFromLog class
public class ReaderFromLog {
Scanner s1 = null;
String line=null;
ArrayList<Information> log;
public ReaderFromLog(String logFileLocation) {
// TODO Auto-generated constructor stub
File logFile = new File(logFileLocation);
if(!logFile.exists())
{
System.err.println("File not found");
System.exit(1);
}
else
{
try
{
s1 = new Scanner(new FileReader(logFile));
} catch (FileNotFoundException e)
{
System.err.print("File not found");
}
}
log=new ArrayList<Information>();
//store into a array
//exclude any repeats
do{
line=s1.nextLine();
Information newUser = new Information();
if(line.contains("Access-Accept for user"))
{
newUser.setStatus("Accept");
String[] sb=line.split(" ");
newUser.setAccount(sb[7]);
int idx_Ipadd = 0;
for(int i=0;i<sb.length;i++)
if (sb[i].contentEquals("to"))
idx_Ipadd=i;
newUser.setIpadd(sb[idx_Ipadd+1]+ " " + sb[idx_Ipadd+2]);
newUser.setDate(sb[0]+ " "+sb[1] + " " +sb[2]+" " + sb[3].substring(0, 4));
log.add(newUser);
}
else if(line.contains("Access-Reject for user"))
{
newUser.setStatus("Reject");
String[] sb=line.split(" ");
newUser.setAccount(sb[7]);
int idx_Ipadd = 0;
for(int i=0;i<sb.length;i++)
if (sb[i].contentEquals("to"))
idx_Ipadd=i;
newUser.setIpadd(sb[idx_Ipadd+1]+ " " + sb[idx_Ipadd+2]);
newUser.setDate(sb[0]+ " "+sb[1] + " " +sb[2]+" " + sb[3].substring(0, 4));
log.add(newUser);
}
}while(s1.hasNextLine());
}
}
RemoveDuplicate class:
public class RemoveDuplicatesInList {
Scanner s1 = null;
String line=null;
ArrayList<Information> log;
public RemoveDuplicatesInList(String duplicateFileLocation)
{
// TODO Auto-generated constructor stub
File logFile = new File(duplicateFileLocation);
if(!logFile.exists())
{
System.err.println("File not found");
System.exit(1);
}
else
{
try
{
s1 = new Scanner(new FileReader(logFile));
} catch (FileNotFoundException e)
{
System.err.print("File not found");
}
}
log=new ArrayList<Information>();
//store into a array
//exclude any repeats
do{
boolean sameAccount=false;
line=s1.nextLine();
Information newUser = new Information();
if(line.contains("Accept"))
{
newUser.setStatus("Accept");
String[] sb=line.split(",");
sameAccount=false;
for(int i=0;i<log.size();i++)
if(log.get(i).getAccount().contentEquals(sb[1]))
{
sameAccount=true;
break;
}
if(!sameAccount)
{
newUser.setAccount(sb[1]);
newUser.setIpadd(sb[3]);
newUser.setDate(sb[0]);
log.add(newUser);
}
}
else if(line.contains("Reject"))
{
newUser.setStatus("Reject");
String[] sb=line.split(",");
for(int i=0;i<log.size();i++)
if(log.get(i).getAccount().contentEquals(sb[1]))
{
sameAccount=true;
break;
}
if(!sameAccount)
{
newUser.setAccount(sb[1]);
newUser.setIpadd(sb[3]);
newUser.setDate(sb[0]);
log.add(newUser);
}
}
}while(s1.hasNextLine());
}
}
Check value of
info.get(i).getIpadd()
if value of this is null then .toString(0 will give you NullPointerException

Categories