Hi am new to android and would like some help. So in my app I am fetching data from an xml file on a server and storing it in a database. I manually checked the database and all went well. Now when I am trying to read the data from the connectToDB() method in ActivityTwo class I see no data on the screen but when I read the data from the offlineDatabase() in the same class, I see the data perfectly on the screen. I am completely baffled by this situation. Any help would be immensely appreciated. BTW: connectToDB() is called when the user is online and offlineDatabase() is called when the user is offline.
ActivityTwo.java
public class ActivityTwo extends Activity {
private ArrayList<String> eventsList = new ArrayList<String>();
private HandleXML handleXML;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.events);
if(netCheckPls() == false) {
new AlertDialog.Builder(this)
.setTitle("Internet Connection")
.setMessage("Not connected to the Internet!")
.setCancelable(true)
.setPositiveButton(R.string.ok, null)
.show();
offlineDatabase();
} else {
connectToDB();
}
}
@Override
public void onDestroy() {
//eventsData.close();
}
public void offlineDatabase() {
DBHelper dHelper = new DBHelper(this);
eventsList = dHelper.getAllEvents();
addMoreRows();
}
public void connectToDB() {
handleXML = new HandleXML(this, "http://eamplesite/example.xml");
handleXML.fetchXML();
//while(handleXML.parsingComplete);
//;
eventsList = handleXML.arrayList();
addMoreRows();
//offlineDatabase();
}
public void addMoreRows() {
TableLayout tl = (TableLayout)findViewById(R.id.linearLayout);
for(int i = 0; i < eventsList.size(); i++) {
TableRow row = new TableRow(this);
TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(lp);
TextView tv = new TextView(this);
tv.setTextColor(Color.parseColor("#FFFFFF"));
tv.setText((String)eventsList.get(i));
row.addView(tv);
tl.addView(row);
}
}
public boolean netCheckPls() {
Context ctx = this;
ConnectivityManager connec = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
// Check if wifi or mobile network is available or not. If any of them is
// available or connected then it will return true, otherwise false;
return wifi.isConnected() || mobile.isConnected();
}
}
HandleXML.java
public class HandleXML extends Activity {
private String title = "title";
private String link = "link";
private String description = "description";
private DBHelper dbHelper;
private ArrayList<String> titles = new ArrayList<String>();
private ArrayList<String> links = new ArrayList<String>();
private ArrayList<String> descriptions = new ArrayList<String>();
private String urlString = null;
private XmlPullParserFactory xmlFactoryObject;
public volatile boolean parsingComplete = true;
public HandleXML(Context context, String url){
context.deleteDatabase("EventsDB.db");
dbHelper = new DBHelper(context);
this.urlString = url;
}
public ArrayList<String> arrayList() {
return dbHelper.getAllEvents();
}
public String getTheTitle(){
return title;
}
public String getLink(){
return link;
}
public String getDescription(){
return description;
}
public void parseXMLAndStoreIt(XmlPullParser myParser) {
int event;
String text=null;
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name=myParser.getName();
switch (event){
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
if(name.equals("title")){
title = text;
titles.add(text);
}
else if(name.equals("guid")){
link = text;
links.add(text);
}
else if(name.equals("description")){
description = text;
descriptions.add(text);
}
else{
}
break;
}
event = myParser.next();
}
parsingComplete = false;
//dbHelper.insertEvents(title, description, link);
addToDB();
} catch (Exception e) {
e.printStackTrace();
}
}
public void addToDB() {
for(int i = 0; i < titles.size(); i++) {
dbHelper.insertEvents(titles.get(i), descriptions.get(i), links.get(i));
}
}
public void fetchXML(){
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
myparser.setInput(stream, null);
parseXMLAndStoreIt(myparser);
stream.close();
} catch (Exception e) {
}
}
});
thread.start();
}
}
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "EventsDB.db";
public static final String EVENTS_TITLE = "title";
public static final String EVENTS_DESCRIPTION = "decription";
public static final String EVENTS_LINK = "link";
public static final String EVENTS_TABLE_NAME = "events";
public static final String EVENTS_COLUMN_NAME = "title";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "name";
public static final String CONTACTS_COLUMN_EMAIL = "email";
public static final String CONTACTS_COLUMN_STREET = "street";
public static final String CONTACTS_COLUMN_CITY = "place";
public static final String CONTACTS_COLUMN_PHONE = "phone";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table events " +
"(id integer primary key, title text, description text, link text)"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS events");
onCreate(db);
}
public boolean insertEvents (String title, String description, String link)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("title", title);
contentValues.put("description", description);
contentValues.put("link", link);
db.insert("events", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from events where id=" + id + "", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, EVENTS_TABLE_NAME);
return numRows;
}
public boolean updateEvents (Integer id, String title, String description, String link)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("title", title);
contentValues.put("description", description);
contentValues.put("link", link);
db.update("events", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
/*public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}*/
public ArrayList getAllEvents()
{
ArrayList array_list = new ArrayList();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from events", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(EVENTS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
events.xml
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:background="@drawable/bg2">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/linearLayout"
android:orientation="vertical">
</TableLayout>
</ScrollView>
</LinearLayout>
FYI the reason I want to delete the database, when the user comes online, is that I want to prevent similar data being added to the database (which I found was happening). Again would greatly appreciate some light on this matter. Thank You!
No comments:
Post a Comment