Use one instance of class in multiple Fragments - java

What is the best way to use one instance of a Class in multiple Fragments? (or just a method of it)
In my Application I have a Class RangeFetcher which downloads an XML-file and parses it into a model class Item. RangeFetcher holds an ArrayList<Item> items containing the whole XML-file parsed into instances of the model.
I'm creating the Fragment ShopFragment from my starting activity ShopMainViewScreen. In this Fragment I instantiate a RangeFetcher. Since this is a pretty expensive operation in terms of data volume and computing, I would like to pass this instance of RangeFetcher to the other three Fragments I have.
This method getItems is basically all I need in the fragments.
public class RangeFetcher extends AsyncTask {
ArrayList <Item> items = new ArrayList();
//filling the List...
public ArrayList <Item> getItems() {
return items;
}
}
What i took into consideration up to now:
I thought about using a bundle and passing the ArrayList in the arguments to pass the instance from one Fragment to another, but that feels kinda clunky. Could this cause trouble regarding the back-stack?
making the method getItems static? I think it would be feasible since the RangeFetcher will always produce exactly the same output for all the fragments. (am I missing something here?)
Do you have any other suggestions on how to access this instance from multiple fragments?
RangeFetcher Class
package com.XXX;
import android.os.AsyncTask;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
//I know using a switch statement would probably be more fitting here.
//Furthermore I didn't know how to wait for the background task to
//finish so i just introduced a boolean "processing". When this boolean
//is set to false, i continue with my tasks on the fragments.
//So feel free to suggest some improvements to my code ^^
public class RangeFetcher extends AsyncTask {
URL url;
ArrayList < Item > items = new ArrayList();
boolean processing = false;
Item i;
protected Object doInBackground(Object[] objects) {
processing = true;
try {
url = new URL("XXXX");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
boolean priceSet = false;
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
i = new Item();
} else if (xpp.getName().equalsIgnoreCase("g:id")) {
if (insideItem)
i.setmID(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem)
i.setmTitle(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("description")) {
if (insideItem)
i.setmDescription(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("g:product_type")) {
if (insideItem) {
String fullCategory = xpp.nextText();
if (fullCategory.contains(" ")) {
fullCategory = fullCategory.substring(0, fullCategory.indexOf(" "));
}
i.setmProductType(fullCategory);
}
} else if (xpp.getName().equalsIgnoreCase("g:image_link")) {
if (insideItem)
i.setmPictureLink(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("g:condition")) {
if (insideItem)
i.setmCondition(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("g:availability")) {
if (insideItem)
i.setmAvailability(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("g:price") && priceSet == false) {
if (insideItem)
i.setmPrice(xpp.nextText());
priceSet = true;
} else if (xpp.getName().equalsIgnoreCase("g:brand")) {
if (insideItem)
i.setmBrand(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("g:mpn")) {
if (insideItem)
i.setmMpn(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("g:country")) {
if (insideItem)
i.setmShippingCountry(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("g:service")) {
if (insideItem)
i.setmService(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("g:price")) {
if (insideItem)
i.setmShippingCosts(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("g:pubDate")) {
if (insideItem)
i.setMpubDate(xpp.nextText());
}
} else if (eventType == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")) {
insideItem = false;
items.add(i);
priceSet = false;
}
eventType = xpp.next(); //move to next element
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
processing = false;
return items;
}
private InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
public ArrayList < Item > getItems() {
while (processing == true) {}
return items;
}
public Boolean processing() {
return processing;
}
}

Related

Common method for null check

I want to create a common method which will check for null on primary keys of database tables.
I have two type of datatype
String
Date
Want to create a common function which will take parameters on the run time and check for null.
Table 1:
private boolean checkForNullEntries(Table1 table1) {
if (StringUtil.isNullOrEmpty(table1.getName())) {
return true;
} else if (table1.getLastUpdateTime() == null) {
return true;
}
return false;
}
public checkIfPrimaryKeyIsNull(Table1 table1) {
boolean nullValueFound = checkForNullEntries(table1);
if (nullValueFound) {
//skip db operation
} else {
// save to DB
}
}
Table 2:
private boolean checkForNullEntries(Table2 table2) {
if (table2.getTimeSlot == null) {
return true;
} else if (table2.getDate() == null) {
return true;
}
return false;
}
public checkIfPrimaryKeyIsNull(Table2 table2) {
boolean nullValueFound = checkForNullEntries(table2);
if (nullValueFound){
//skip db operation
} else {
// save to DB
}
}
I want to create a common method for both the tables. Any suggestion experts
Using a Map, you should be able to pass any table to the functions, regardless of the data type you wanna test, and then establish each test case in a different 'if', as follows:
private static boolean checkForNullEntries(Map<String, Table> map) {
if(map.get("String") != null) {
if (StringUtil.isNullOrEmpty(map.get("String").getName())) {
return true;
} else if (map.get("String").getLastUpdateTime() == null) {
return true;
}
return false;
}
if(map.get("Date") != null) {
if (map.get("Date").getTimeSlot == null) {
return true;
} else if (map.get("Date").getDate() == null) {
return true;
}
return false;
}
return false;
}
Then you can call the function like this:
Map<String, Table> map = new HashMap<>();
map.put("Date", table2);
boolean result = checkForNullEntries(map);

Convert BufferedReader To InputStream

I just finished writing a bunch of code that works fine when reading from internal resource :))))
try {
SeriesDataXMLPullParserHandler seriesDataXmlPullParserHandler = new SeriesDataXMLPullParserHandler();
entries = seriesDataXmlPullParserHandler.parse(getAssets().open("series_box.xml"));
} catch (IOException e) {
e.printStackTrace();
Log.d("errorOpeningSeries", e.getMessage());
}
Collections.sort(entries, new Comparator<Entry>() {
#Override
public int compare(Entry entryOne, Entry entryTwo) {
return (entryOne.getSeriesName().compareTo(entryTwo.getSeriesName()));
}
});
listView.setAdapter(new MyAdapter(this, R.id.details_SeriesName, entries));
"SeriesDataXMLPullParserHandler" class parse data from xml file that uses InputStream as argument
here is "SeriesDataXMLPullParserHandler" class
public class SeriesDataXMLPullParserHandler {
List<Entry> entries;
private Entry entry;
private String text;
public SeriesDataXMLPullParserHandler() {
entries = new ArrayList<>();
}
public List<Entry> getEntries() {
return entries;
}
public List<Entry> parse(InputStream inputStream) {
XmlPullParserFactory xmlPullParserFactory = null;
XmlPullParser xmlPullParser = null;
try {
xmlPullParserFactory = XmlPullParserFactory.newInstance();
xmlPullParserFactory.setNamespaceAware(true);
xmlPullParser = xmlPullParserFactory.newPullParser();
xmlPullParser.setInput(inputStream, null);
int eventType = xmlPullParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String tagname = xmlPullParser.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if (tagname.equalsIgnoreCase("series")) {
entry = new Entry();
}
break;
case XmlPullParser.TEXT:
text = xmlPullParser.getText();
break;
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase("series")) {
entries.add(entry);
} else if (tagname.equalsIgnoreCase("id")) {
entry.setId(text);
} else if (tagname.equalsIgnoreCase("Actors")) {
entry.setActors(text);
}else if (tagname.equalsIgnoreCase("Genre")) {
entry.setGenre(text);
} else if (tagname.equalsIgnoreCase("IMDB_ID")) {
entry.setImdb_id(text);
} else if (tagname.equalsIgnoreCase("Language")) {
entry.setLanguage(text);
} else if (tagname.equalsIgnoreCase("Network")) {
entry.setNetwork(text);
} else if (tagname.equalsIgnoreCase("NetworkID")) {
entry.setNetwork_id(text);
} else if (tagname.equalsIgnoreCase("Overview")) {
entry.setOverview(text);
} else if (tagname.equalsIgnoreCase("SeriesID")) {
entry.setSeriesId(text);
} else if (tagname.equalsIgnoreCase("SeriesName")) {
entry.setSeriesName(text);
}
break;
default:
break;
}
eventType = xmlPullParser.next();
}
} catch (XmlPullParserException | IOException e) {
e.printStackTrace();
}
return entries;
}
}
but the problem is when I want to get data from server, it comes in "InputStreamReader" type
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
the question is how do I change the type of "BufferedReader" to "InputStream" for parsing data???
or the best way to do such a thing ???
sorry for bad english :)

How to catch a context within a class correctly?

I'm in a paser of a Webservice. With it, I picked up the dice and already gave Set In each of them (is working agreement). However, in time to insert the same in the database it displays the following error (null):
Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference
The db needs a Context, but I can not in class because there extends an Activity or otherwise to the use of getBaseContext, getAplication among others ..
*parser:
public class WSParserSetValoresBD {
private String text;
public BDProgramacaoGetterSetter programacaoGetterSetter;
boolean tabela = false;
int contadorLinhas = 0;
private Context ctx;
public WSParserSetValoresBD(Context contextP){
this.ctx=contextP; // I've checked here and not be null, it's all right
}
BDProgramacaoBancoDao inserir = new BDProgramacaoBancoDao(ctx);
public void parse(InputStream is) {
XmlPullParserFactory factory = null;
XmlPullParser parser = null;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
parser = factory.newPullParser();
parser.setInput(is, null);
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT ) {
String tagname = parser.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if(tagname.equalsIgnoreCase("Table")){
tabela = true;
programacaoGetterSetter = new BDProgramacaoGetterSetter();
contadorLinhas++;
}
else if (tagname.equalsIgnoreCase("DATA") || tagname.equalsIgnoreCase("ROTA") || tagname.equalsIgnoreCase("IWERK")
|| tagname.equalsIgnoreCase("AUFNR")|| tagname.equalsIgnoreCase("VORNR")|| tagname.equalsIgnoreCase("POINT")
|| tagname.equalsIgnoreCase("SEQUENCIA")|| tagname.equalsIgnoreCase("STATUS_PONTO")|| tagname.equalsIgnoreCase("FREQUENCIA")
|| tagname.equalsIgnoreCase("PSORT")|| tagname.equalsIgnoreCase("PTTXT")|| tagname.equalsIgnoreCase("EQUNR")
|| tagname.equalsIgnoreCase("EQKTX")|| tagname.equalsIgnoreCase("TPLNR")|| tagname.equalsIgnoreCase("PLTXT")
|| tagname.equalsIgnoreCase("SIST_LUBRIFIC")|| tagname.equalsIgnoreCase("REF_LUBRIFIC")|| tagname.equalsIgnoreCase("COD_LUBRIFIC")
|| tagname.equalsIgnoreCase("VOL_LUBRIFICCL")|| tagname.equalsIgnoreCase("QTD_CONSUMO")|| tagname.equalsIgnoreCase("DESCR_ROTA")
|| tagname.equalsIgnoreCase("ID_PROGRAMACAO")|| tagname.equalsIgnoreCase("GRUPO")|| tagname.equalsIgnoreCase("OBSERVACAO")
|| tagname.equalsIgnoreCase("ATIVI")|| tagname.equalsIgnoreCase("ARBPL")|| tagname.equalsIgnoreCase("ITEM_INSPEC")
|| tagname.equalsIgnoreCase("VOL_LUBRIFCKG")|| tagname.equalsIgnoreCase("NRO_BOMBADAS")|| tagname.equalsIgnoreCase("LIMITE_INF")
|| tagname.equalsIgnoreCase("LIMITE_SUP")|| tagname.equalsIgnoreCase("IDATE_ITIME")|| tagname.equalsIgnoreCase("VLR_MED")
|| tagname.equalsIgnoreCase("COD_VALOR")|| tagname.equalsIgnoreCase("TEXTO_OBS")|| tagname.equalsIgnoreCase("MATRIC")
|| tagname.equalsIgnoreCase("ATIVI")|| tagname.equalsIgnoreCase("STATUS_PROC")|| tagname.equalsIgnoreCase("MENSAGEM")
|| tagname.equalsIgnoreCase("COL_NUMERIC")){
}
break;
case XmlPullParser.TEXT:
text = parser.getText();
break;
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase("DATA")) {
programacaoGetterSetter.setData(text);
} else if(tagname.equalsIgnoreCase("ROTA")){
programacaoGetterSetter.setRota(text);
} else if (tagname.equalsIgnoreCase("IWERK")) {
programacaoGetterSetter.setIwerk(text);
} else if (tagname.equalsIgnoreCase("AUFNR")) {
programacaoGetterSetter.setAufnr(text);
} else if (tagname.equalsIgnoreCase("VORNR")) {
programacaoGetterSetter.setVornr(text);
} else if (tagname.equalsIgnoreCase("POINT")) {
programacaoGetterSetter.setPoint(text);
} else if (tagname.equalsIgnoreCase("SEQUENCIA")) {
programacaoGetterSetter.setSequencia(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("STATUS_PONTO")) {
programacaoGetterSetter.setStatus_proc(text);
} else if (tagname.equalsIgnoreCase("FREQUENCIA")) {
programacaoGetterSetter.setFrequencia(text);
} else if (tagname.equalsIgnoreCase("PSORT")) {
programacaoGetterSetter.setPsort(text);
} else if (tagname.equalsIgnoreCase("PTTXT")) {
programacaoGetterSetter.setPttxt(text);
} else if (tagname.equalsIgnoreCase("EQUNR")) {
programacaoGetterSetter.setEqunr(text);
} else if (tagname.equalsIgnoreCase("EQKTX")) {
programacaoGetterSetter.setEqktx(text);
} else if (tagname.equalsIgnoreCase("TPLNR")) {
programacaoGetterSetter.setTplnr(text);
} else if (tagname.equalsIgnoreCase("PLTXT")) {
programacaoGetterSetter.setPltxt(text);
} else if (tagname.equalsIgnoreCase("SIST_LUBRIFIC")) {
programacaoGetterSetter.setSist_lubrific(text);
} else if (tagname.equalsIgnoreCase("REF_LUBRIFIC")) {
programacaoGetterSetter.setRef_lubrific(text);
} else if (tagname.equalsIgnoreCase("COD_LUBRIFIC")) {
programacaoGetterSetter.setCod_lubrific(text);
} else if (tagname.equalsIgnoreCase("VOL_LUBRIFICCL")) {
programacaoGetterSetter.setVol_lubrificcl(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("QTD_CONSUMO")) {
programacaoGetterSetter.setQtd_consumo(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("DESCR_ROTA")) {
programacaoGetterSetter.setDescr_rota(text);
} else if (tagname.equalsIgnoreCase("ID_PROGRAMACAO")) {
programacaoGetterSetter.setId_programacao(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("GRUPO")) {
programacaoGetterSetter.setGrupo(text);
} else if (tagname.equalsIgnoreCase("OBSERVACAO")) {
programacaoGetterSetter.setObservacao(text);
} else if (tagname.equalsIgnoreCase("ATIVI")) {
programacaoGetterSetter.setAtivi(text);
} else if (tagname.equalsIgnoreCase("ARBPL")) {
programacaoGetterSetter.setArbpl(text);
} else if (tagname.equalsIgnoreCase("ITEM_INSPEC")) {
programacaoGetterSetter.setItem_inspec(text);
} else if (tagname.equalsIgnoreCase("VOL_LUBRIFCKG")) {
programacaoGetterSetter.setVol_lubrifickg(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("NRO_BOMBADAS")) {
programacaoGetterSetter.setNro_bombadas(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("LIMITE_INF")) {
programacaoGetterSetter.setLimite_inf(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("LIMITE_SUP")) {
programacaoGetterSetter.setlimite_sup(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("IDATE_ITIME")) {
programacaoGetterSetter.setIdate_itime(text);
} else if (tagname.equalsIgnoreCase("VLR_MED")) {
programacaoGetterSetter.setVlr_med(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("COD_VALOR")) {
programacaoGetterSetter.setCod_valor(text);
} else if (tagname.equalsIgnoreCase("TEXTO_OBS")) {
programacaoGetterSetter.setTexto_obs(text);
} else if (tagname.equalsIgnoreCase("MATRIC")) {
programacaoGetterSetter.setMatric(text);
} else if (tagname.equalsIgnoreCase("ATIVI")) {
programacaoGetterSetter.setAtivi(text);
} else if (tagname.equalsIgnoreCase("STATUS_PROC")) {
programacaoGetterSetter.setStatus_proc(text);
} else if (tagname.equalsIgnoreCase("MENSAGEM")) {
programacaoGetterSetter.setMensagem(text);
} else if (tagname.equalsIgnoreCase("COL_NUMERIC")) {
programacaoGetterSetter.setCol_numeric(Integer.parseInt(text));
} else if (tagname.equalsIgnoreCase("Table")){
if (programacaoGetterSetter != null && inserir != null){
inserir.open(); // HERE IS THE ERROR; database_prog is null
inserir.inserirDados(programacaoGetterSetter);
}
}
break;
default:
break;
}
eventType = parser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
*database
public class BDProgramacaoBancoDao {
private SQLiteDatabase database_prog;
public void open () throws SQLDataException{
database_prog = sqliteOpenHelper_prog.getWritableDatabase();
}
private BDProgramacaoCustomSQLiteOpenHelper sqliteOpenHelper_prog;
public BDProgramacaoBancoDao(Context context) {
sqliteOpenHelper_prog = new BDProgramacaoCustomSQLiteOpenHelper(context);
}
public String insertDados(BDProgramacaoGetterSetter dadosProg) {
ContentValues valores = new ContentValues();
long resultado;
//valores.put(sqliteOpenHelper_prog.COLUMN_ID,dadosProg.getId()); ID eh auto increment
valores.put(sqliteOpenHelper_prog.COLUMN_ARBPL, dadosProg.getArbpl());
valores.put(sqliteOpenHelper_prog.COLUMN_ATIVI, dadosProg.getAtivi());
valores.put(sqliteOpenHelper_prog.COLUMN_AUFNR, dadosProg.getAufnr());
valores.put(sqliteOpenHelper_prog.COLUMN_COD_LUBRIFIC, dadosProg.getCod_lubrific());
valores.put(sqliteOpenHelper_prog.COLUMN_COD_VALOR, dadosProg.getCod_valor());
valores.put(sqliteOpenHelper_prog.COLUMN_DATA, dadosProg.getData()); // no banco esta como integer
valores.put(sqliteOpenHelper_prog.COLUMN_COL_NUMERIC, dadosProg.getCol_numeric());
valores.put(sqliteOpenHelper_prog.COLUMN_DESCR_ROTA, dadosProg.getDescr_rota());
valores.put(sqliteOpenHelper_prog.COLUMN_EQKTX, dadosProg.getEqktx());
valores.put(sqliteOpenHelper_prog.COLUMN_EQUNR, dadosProg.getEqunr());
valores.put(sqliteOpenHelper_prog.COLUMN_FREQUENCIA, dadosProg.getFrequencia());
valores.put(sqliteOpenHelper_prog.COLUMN_GRUPO, dadosProg.getGrupo());
valores.put(sqliteOpenHelper_prog.COLUMN_IDATE_ITIME, dadosProg.getIdate_itime());
valores.put(sqliteOpenHelper_prog.COLUMN_ITEM_INSPEC, dadosProg.getIdate_itime());
valores.put(sqliteOpenHelper_prog.COLUMN_IWERK, dadosProg.getIwerk());
valores.put(sqliteOpenHelper_prog.COLUMN_LIMITE_SUP, dadosProg.getlimite_sup());
valores.put(sqliteOpenHelper_prog.COLUMN_LIMITE_INF, dadosProg.getLimite_inf());
valores.put(sqliteOpenHelper_prog.COLUMN_MATRIC, dadosProg.getMatric());
valores.put(sqliteOpenHelper_prog.COLUMN_MENSAGEM, dadosProg.getMensagem());
valores.put(sqliteOpenHelper_prog.COLUMN_NRO_BOMBADAS, dadosProg.getNro_bombadas());
valores.put(sqliteOpenHelper_prog.COLUMN_OBSERVACAO, dadosProg.getObservacao());
valores.put(sqliteOpenHelper_prog.COLUMN_PLTXT, dadosProg.getPltxt());
valores.put(sqliteOpenHelper_prog.COLUMN_POINT, dadosProg.getPoint());
valores.put(sqliteOpenHelper_prog.COLUMN_PSORT, dadosProg.getPsort());
valores.put(sqliteOpenHelper_prog.COLUMN_PTTXT, dadosProg.getPttxt());
valores.put(sqliteOpenHelper_prog.COLUMN_QTD_CONSUMO, dadosProg.getQtd_consumo());
valores.put(sqliteOpenHelper_prog.COLUMN_TEXTO_OBS, dadosProg.getTexto_obs());
valores.put(sqliteOpenHelper_prog.COLUMN_TPLNR, dadosProg.getTplnr());
valores.put(sqliteOpenHelper_prog.COLUMN_VLR_MED, dadosProg.getVlr_med());
valores.put(sqliteOpenHelper_prog.COLUMN_VOL_LUBRIFCCL, dadosProg.getVol_lubrificcl());
valores.put(sqliteOpenHelper_prog.COLUMN_VOL_LUBRIFCKG, dadosProg.getVol_lubrifickg());
valores.put(sqliteOpenHelper_prog.COLUMN_VORNR, dadosProg.getVornr());
valores.put(sqliteOpenHelper_prog.COLUMN_REF_LUBRIFIC, dadosProg.getRef_lubrific());
valores.put(sqliteOpenHelper_prog.COLUMN_ROTA, dadosProg.getRota());
valores.put(sqliteOpenHelper_prog.COLUMN_SEQUENCIA, dadosProg.getSequencia());
valores.put(sqliteOpenHelper_prog.COLUMN_SIST_LUBRIFIC, dadosProg.getSist_lubrific());
valores.put(sqliteOpenHelper_prog.COLUMN_STATUS_PONTO, dadosProg.getStatus_ponto());
valores.put(sqliteOpenHelper_prog.COLUMN_STATUS_PROC, dadosProg.getStatus_proc());
valores.put(sqliteOpenHelper_prog.COLUMN_ID_PROGRAMACAO, dadosProg.getId_programacao());
resultado = database_prog.insert(BDProgramacaoCustomSQLiteOpenHelper.TABLE_PROGRAMACAO, null, valores);
database_prog.close();
if (resultado ==-1) return "Erro ao inserir registro";
else return "Registro Inserido com sucesso";
}
}
For some reason, the database_prog is null
*WSParserSetValoresBD in activity Opcoes_BaixarRotas (button "Yes" do AlertDialog):
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// nova query para o novo WS com as variaveis
final Runnable gravandoDados = new Runnable() {
public void run() {
getTodosDados(rota, atividade, responsavel, dataSelecionada);
if (WSResultadoTodosDados != null) {
InputStream isTodosDados = new ByteArrayInputStream(WSResultadoTodosDados.getBytes());
// call class
WSParserSetValoresBD parserTodosDados = new WSParserSetValoresBD(Opcoes_BaixarRotas.this.getApplicationContext());
parserTodosDados.parse(isTodosDados);
}
};
Thread queryTodosDados = new Thread(gravandoDados);
queryTodosDados.start();
}
Member variables are initialized before the constructor is invoked. Move the new BDProgramacaoBancoDao(ctx) initialization to your constructor where ctx is non-null.

XML parsing converting string to int

I made a string that contains part of xml that I am working on.
There are some integers in that file and I can not covert them from String to int. I try with getAttributeValue(0) but it didn`t work. So I was wondering if someone may have a solution for my problem. Thanks
import android.os.AsyncTask;
import android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URL;
class ReadXMLFile extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
Log.d("beginning: ", "Pocetak");
//TODO - Call getFeeds Method to populate feeds list & return true/false depending on result of operation
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
String xmldata = <cenovnik>
<cenovnikStavkaList>
<id>12195432</id>
<izlaznaStanica>100</izlaznaStanica>
<kategorijaVozila>0</kategorijaVozila>
<ulaznaStanica>100</ulaznaStanica>
</cenovnikStavkaList>
<cenovnikStavkaList>
<id>12197782</id>
<izlaznaStanica>100</izlaznaStanica>
<kategorijaVozila>1</kategorijaVozila>
<ulaznaStanica>100</ulaznaStanica>
</cenovnikStavkaList>
xpp.setInput(new StringReader( xmldata ));
Log.d("step1a", "string");
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String tagname = xpp.getName();
if(eventType == XmlPullParser.START_DOCUMENT) {
Log.d("Step 2a: ","Start document");
} else if(eventType == XmlPullParser.START_TAG) {
Log.d("Step 2b: ", "Start tag " + xpp.getName());
if(xpp.getName().equals("cenovnikStavkaList")){
String testid = xpp.getAttributeValue(null, "id");
Log.d("Step 2d - ID: ", testid);
}
} else if(eventType == XmlPullParser.END_TAG) {
} else if(eventType == XmlPullParser.TEXT) {
Log.d("Step 2d: ", xpp.getText());
}
eventType = xpp.next();
}
Log.d("Step 2e: ", "End document");
Log.d("Step 2: ", "radi");
return true;
} catch (Exception e) {
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
if(result){
Log.d("END TEST","done");
}
}
public static InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
}
The numbers are inside leaf tags, like <id>12195432</id>.
The XML parsing events needs states, keeping data in variables.
Officially you could have several TEXTs inside two tags, hence:
StringBuilder text;
} else if(eventType == XmlPullParser.START_TAG) {
text = new StringBuilder();
} else if(eventType == XmlPullParser.TEXT) {
if (text != null) {
text.append(xpp.getText());
}
} else if(eventType == XmlPullParser.END_TAG) {
if (text != null) {
String s = text.toString();
try {
int n = Integer.parseInt(s);
// do something with number n
} catch (NumberFormatException e) {
// No number
}
text = null;
}
}
Create a new field cenovnikStavkaList with itself a field id for every same named tag, and do
cenovnikStavkaList.id = n;
and on END_TAG add it to a list.

Android sax parser error while getting html data

Hi Am trying to parse the data from xml which contains the html data using sax parser the data in xml is like below
but while parsing am getting the data between details tag as different strings, not getting as single string which contains full html data between dtails tag.
can anyone help me out please how can i resolve this.
<details>
<html> <b>Animal Care BTEC Level 1</b>
<hr style="height:0.03em;width:18em;border:1px ;border-style:dotted;margin-left:0; color:white"
/>
<body>
<e>Course Length: 1 year</e>
<br />
<e>Fees: Free for 16-18 year olds</e>
<br />
<e>Course Code: B332</e>
<br />
<br />
<body> <b> Overview:</b>
<hr style="height:0.03em;width:18em;border:1px ;border-style:dotted;margin-left:0 ;color:white"
/>
<p>The course provides a basic introduction to working with animals. A practical
approach allows student to develop animal handling skills along side personal
and social development. Student will have access to a wide range of animals
to enable them to develop skills and confidence. Each week practical work
will include time spent on the animal unit, the farm and at the equine
centre to enable students to develop practical ability in all three areas.</p>
</body>
</html>
</details>
package com.bb.mypotential;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class SaxHandler extends DefaultHandler {
public static Courseobj courseobj;
public static Subject subjectobj;
public boolean courseidb = false;
public boolean coursesubjectb = false;
public boolean coursetitleb = false;
public boolean subjectidb = false;
public boolean subjectnameb = false;
public boolean subjectcodeb = false;
public boolean subjectdetailsb = false;
public boolean entryRequirementb = false;
public boolean courseContentb = false;
public boolean futhuroptionsb = false;
public boolean additionalInfob = false;
public boolean fundingInfob = false;
public boolean assignmethodb = false;
public String currentvalue = null;
public ArrayList<Subject> subarr = null;
String TAG = getClass().getSimpleName();
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if (localName.equals("Courses")) {
MainListActivity.value = new ArrayList<Courseobj>();
}
if (localName.equals("Course")) {
courseobj = new Courseobj();
subarr = new ArrayList<Subject>();
String courseid = attributes.getValue(0);// getValue("ID");
courseobj.setCOURSE_ID(courseid);
courseidb = true;
} else if (localName.equalsIgnoreCase("title")) {
coursetitleb = true;
} else if (localName.equals("subject")) {
subjectobj = new Subject();
String subid = attributes.getValue(0);
subjectobj.setSUB_ID(subid);
subjectidb = true;
} else if (localName.equals("name")) {
subjectnameb = true;
} else if (localName.equals("code")) {
subjectcodeb = true;
} else if (localName.equals("details")) {
subjectdetailsb = true;
} else if (localName.equals("entryRequirement")) {
entryRequirementb = true;
} else if (localName.equals("courseContent")) {
courseContentb = true;
} else if (localName.equals("assignmentMethods")) {
assignmethodb = true;
} else if (localName.equals("furtherOptions")) {
futhuroptionsb = true;
} else if (localName.equals("additionalInformation")) {
additionalInfob = true;
} else if (localName.equals("fundingInformation")) {
fundingInfob = true;
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
currentvalue = new String(ch, start, length);
if (coursetitleb) {
courseobj.setTitle(currentvalue);
} else if (subjectnameb) {
subjectobj.setName(currentvalue);
} else if (subjectcodeb) {
subjectobj.setCode(currentvalue);
} else if (subjectdetailsb) {
subjectobj.setDetails(currentvalue);
} else if (entryRequirementb) {
subjectobj.setEntryRequirement(currentvalue);
} else if (courseContentb) {
subjectobj.setCourseContent(currentvalue);
} else if (assignmethodb) {
subjectobj.setCourseContent(currentvalue);
} else if (futhuroptionsb) {
subjectobj.setFuthuroptions(currentvalue);
} else if (additionalInfob) {
subjectobj.setAdditionalInfo(currentvalue);
} else if (fundingInfob) {
subjectobj.setFundingInfo(currentvalue);
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
if (localName.equalsIgnoreCase("Course")) {
courseobj.setSubject(subarr);
MainListActivity.value.add(courseobj);
courseidb = false;
} else if (localName.equalsIgnoreCase("title")) {
coursetitleb = false;
} else if (localName.equals("subject")) {
subarr.add(subjectobj);
subjectidb = false;
} else if (localName.equals("name")) {
subjectnameb = false;
} else if (localName.equals("code")) {
subjectcodeb = false;
} else if (localName.equals("details")) {
subjectdetailsb = false;
} else if (localName.equals("entryRequirement")) {
entryRequirementb = false;
} else if (localName.equals("courseContent")) {
courseContentb = false;
} else if (localName.equals("assignmentMethods")) {
assignmethodb = false;
} else if (localName.equals("furtherOptions")) {
futhuroptionsb = false;
} else if (localName.equals("additionalInformation")) {
additionalInfob = false;
} else if (localName.equals("fundingInformation")) {
fundingInfob = false;
}
}
}

Categories

Resources