Parsing xml data on Android - android

What I wanted to have is to collect all the results in an ArrayList and iterate in that arraylist and display the result but when I try to run the code below, it only return one element...
I have 3 classes...
public class XMLDataCollected {
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> vicinities = new ArrayList<String>();
ArrayList<String> types = new ArrayList<String>();
ArrayList<String> lats = new ArrayList<String>();
ArrayList<String> longs = new ArrayList<String>();
String name = null;
String vicinity = null;
String type = null;
String lat = null;
String longi = null;
public ArrayList<String> getName() {
return names;
}
public void setName(String name) {
this.names.add(name);
this.name = name;
Log.i("This is the name: ", name + "size: " + names.size());
}
public ArrayList<String> getVicinity() {
return vicinities;
}
public void setVicinity(String vicinity) {
this.vicinities.add(vicinity);
this.vicinity = vicinity;
Log.i("This is the vicinity: ", vicinity);
}
public ArrayList<String> getType() {
return types;
}
public void setType(String type) {
this.types.add(type);
this.type = type;
Log.i("This is the type: ", type);
}
public ArrayList<String> getLat() {
return lats;
}
public void setLat(String lat) {
this.lats.add(lat);
this.lat = lat;
Log.i("This is the latitude: ", lat);
}
public ArrayList<String> getLongi() {
return longs;
}
public void setLongi(String longi) {
this.longs.add(longi);
this.longi = longi;
Log.i("This is the longitude: ", longi);
}
public String populate(){
StringBuilder sb = new StringBuilder();
sb.append(getName());
sb.append(getVicinity());
sb.append(getType());
sb.append(getLat());
sb.append(getLongi());
return sb.toString();
}
2.
public class HandlingXMLStuff extends DefaultHandler {
String elementValue = null;
Boolean elementOn = false;
XMLDataCollected data;
public ArrayList<String> getData() {
return data.getName();
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
elementOn = true;
if (localName.equals("result")) {
data = new XMLDataCollected();
} else if (localName.equals("CD")) {
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
elementOn = false;
/**
* Sets the values after retrieving the values from the XML tags
* */
if (localName.equalsIgnoreCase("name"))
data.setName(elementValue);
else if (localName.equalsIgnoreCase("vicinity"))
data.setVicinity(elementValue);
else if (localName.equalsIgnoreCase("type"))
data.setType(elementValue);
else if (localName.equalsIgnoreCase("lat"))
data.setLat(elementValue);
else if (localName.equalsIgnoreCase("lng"))
data.setLongi(elementValue);
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
if (elementOn) {
elementValue = new String(ch, start, length);
elementOn = false;
}
}
}
3.
public class XMLParsingActivity extends Activity implements OnClickListener {
static final String baseURL = "http://www.google.com/ig/api?weather=";
static final String test = "";
TextView tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button bone = (Button) findViewById(R.id.btnone);
tv = (TextView) findViewById(R.id.tvWeather);
bone.setOnClickListener(this);
}
public String buildURL(int lat, int longi){
String url = "";
return url;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try{
URL website = new URL(test);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
HandlingXMLStuff doingWork = new HandlingXMLStuff();
XMLDataCollected xdc = new XMLDataCollected();
xr.setContentHandler(doingWork);
xr.parse(new InputSource(website.openStream()));
StringBuilder sb = new StringBuilder();
String name = null;
for(int index = 0; index < doingWork.getData().size(); index++){
sb.append(doingWork.getData().get(index));
Log.i("test","" + index);
}
// tv.setText("Name: " + name + "\n" + "Vicinity: " + vicinity + "\n" + "Type: " + type + "\n "
// + "Latitude: " + lat + "\n " + "Longitude: " + longi
// );
tv.setText("The size: " + sb);
}catch(Exception ex){
tv.setText("Error" + ex.toString());
}
}
}
This is the sample XML file...
<result>
<name>Zaaffran Restaurant - BBQ and GRILL, Darling Harbour</name>
<vicinity>Harbourside Centre 10 Darling Drive, Darling Harbour, Sydney</vicinity>
<type>restaurant</type>
<type>food</type>
<type>establishment</type>
<geometry>
<location>
<lat>-33.8719830</lat>
<lng>151.1990860</lng>
</location>
</geometry>
<rating>3.9</rating>
</result>
What I want to achieve here is to iterate in the result but the result arraylist has only one element...please help me...

This should help you
http://p-xr.com/android-tutorial-how-to-parseread-xml-data-into-android-listview/
EDIT Also I recommend using the generic LIST <T> instead of ArrayList<T> as follows
List<String> names = new ArrayList<String>();
....
....
for code optimization as the latter ArrayList<String> has memory occupancy. Its not a big issue but optimization is the fundamental step to check the magnitude of efficiency (with respect to time duration and memory) of a program.

Related

my table is full in class and empty in other

I'am a beginner in android and i use AndroidStudio
I have a problem
in have 2 class i my project in the first class "fetch compte" i fill my table "dataParsed" and i 'am certain that the table is fil
but in the second class MainActivity
I find that the table is empty
please help me
this is my code
public class fetchcompte extends AsyncTask<Void,Void,Void> {
String data = "";
String dat = "";
public static String[] dataParsed ;
String singleParsed ;
String dataParse = "";
String singleParse1 = "";
String singleParse2 = "";
String singleParse3 = "";
String singleParse4 = "";
String singleParse5 = "";
private RequestQueue mQueue, mQueu;
int nbcompte;
protected Void doInBackground(Void... voids) {
String S = jsonArray;
// singleParsed=new String[20];
dataParsed=new String[20];
try {
// String url2="http://recrutement.stb.com.tn:1010/PlateformeApi_Externe/api/ComptesClient/000001498675\n";
//String url2 = "http://10.1.11.168:8081/my/banks/10/accounts/10403082500589678844/transactions";
String url2 = "http://10.12.0.66:8081/api/ComptesClient/000001498675";
URL url = new URL(url2);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
nbcompte=JA.length();
for(int i =0 ;i<nbcompte; i++) {
JSONObject JO = (JSONObject) JA.get(i);
singleParsed = "fullname:" + JO.get("fullname");
singleParse1 = "accountnumber:" + JO.get("accountnumber");
singleParse2 = "rib:" + JO.get("rib");
singleParse3 = "iban:" + JO.get("iban");
singleParse4 = "name:" + JO.get("name");
singleParse5 = "balance:" + JO.get("balance");
dataParsed[i] = singleParsed + "\n" + singleParse1 + "\n" + singleParse2 + "\n" + singleParse3 + "\n" + singleParse4 + "\n" + singleParse5;
}
// dataParsed[i] =dataParsed[i] +singleParsed[i] +"\n" ;
// MainActivity.compte[i]=dataParsed[i];
// singleParsed[i] = "fullname:" + JO.get("fullname") + "\n"+
// "accountnumber:" + JO.get("accountnumber") + "\n"+
// "rib:" + JO.get("rib") + "\n"+
// "iban:" + JO.get("iban") + "\n"+
// "name:" + JO.get("name") + "\n"+
//"balance:" + JO.get("balance") + "\n";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
for(int i =0 ;i <2; i++) {
// MainActivity.data.setText(this.d[i]);
}
}
//Authorization Bearer
my MainActivity
import static com.example.saiid.listecompte.fetchcompte.dataParsed;
public class MainActivity extends AppCompatActivity {
Button click;
public static TextView data;
public static String jsonArray;
private RequestQueue mQueue;
ImageView imageView2;
public static TextView textView_type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mQueue = Volley.newRequestQueue(this);
click = (Button) findViewById(R.id.button_parse);
data = (TextView) findViewById(R.id.text_view_result);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.listeview);
CustomAdaptercompte customAdapter=new CustomAdaptercompte();
ListView listeview=(ListView) findViewById(R.id.liste);
listeview.setAdapter(customAdapter);
fetchcompte process = new fetchcompte();
process.execute();
}
});
}
public class CustomAdaptercompte extends BaseAdapter {
#Override
public int getCount() {
return 2;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View convertView, ViewGroup viewgrp) {
View view = getLayoutInflater().inflate(R.layout.customlayout,null);
imageView2 = (ImageView) view.findViewById(R.id.imageView2);
textView_type =(TextView) view.findViewById(R.id.textView_type);
imageView2.setImageResource(R.drawable.compte);
textView_type.setText(dataParsed[i]);
return view;
}
}
}
The mistake that you have made is that you assume that
import static com.example.saiid.listecompte.fetchcompte.dataParsed;
will automatically just be the dataParsed Variable you need. What that line does is that it gets the default value of dataParsed (from a default fetchcompte instance). Since you make another instance of a fetchcompte object [called process] (which you are using to populate its dataParsed variable) simply access the dataParsed variable of that instance.
So instead of using:
textView_type.setText(dataParsed[i]);
You can use:
textView_type.setText(process.dataParsed[i]);
But to do this you will need to somehow access the process variable in your adapter class.

Saving/Storeing an external image into SQLite Database

I have a book-App, where I scan a book with barcodescanner and retrieving the information from googlebooksapi.
At the moment I can save the general bookinfos, title, author, date, rating and shelf (where i want to display the book) in my SQLite database
Now I want to save the bookcover, which comes with the googleapi, too.
Can you tell me how I can save the image in my SQlite Database. By looking for solution I realized that I have to blob the image. but I dont know how.
Following my activties.
ScanActivity.java -> at the end of the code, I save the book data into sql db
public class ScanActivity extends AppCompatActivity implements OnClickListener {
private Button scanBtn, previewBtn, linkBtn, addBookBtn, librarybtn;
public TextView authorText, titleText, descriptionText, dateText, ratingCountText;
public EditText shelfText;
private LinearLayout starLayout;
private ImageView thumbView;
private ImageView[] starViews;
private Bitmap thumbImg;
public BookDBHelper bookDBHelper;
public SQLiteDatabase sqLiteDatabase1;
public Context context1 = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
//Fonts
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
Button myButtonViewScan = (Button) findViewById(R.id.scan_button);
myButtonViewScan.setTypeface(myTypeface);
TextView myWheretoSaveTextView = (TextView) findViewById(R.id.textView_wheretosave);
myWheretoSaveTextView.setTypeface(myTypeface);
//Scanbutton
scanBtn = (Button) findViewById(R.id.scan_button);
scanBtn.setOnClickListener(this);
//Preview Button
previewBtn = (Button) findViewById(R.id.preview_btn);
previewBtn.setVisibility(View.GONE);
previewBtn.setOnClickListener(this);
//Weblink Button
linkBtn = (Button) findViewById(R.id.link_btn);
linkBtn.setVisibility(View.GONE);
linkBtn.setOnClickListener(this);
/* //AddBookBtn
addBookBtn= (Button)findViewById(R.id.btn_savebook);
addBookBtn.setVisibility(View.GONE);
addBookBtn.setOnClickListener(this);
//LibraryButton
librarybtn = (Button) findViewById(R.id.btn_maps);
librarybtn.setVisibility(View.GONE);
librarybtn.setOnClickListener(this);
*/
authorText = (TextView) findViewById(R.id.book_author);
titleText = (TextView) findViewById(R.id.book_title);
descriptionText = (TextView) findViewById(R.id.book_description);
dateText = (TextView) findViewById(R.id.book_date);
starLayout = (LinearLayout) findViewById(R.id.star_layout);
ratingCountText = (TextView) findViewById(R.id.book_rating_count);
thumbView = (ImageView) findViewById(R.id.thumb);
shelfText = (EditText) findViewById(R.id.editText_wheretosave);
starViews = new ImageView[5];
for (int s = 0; s < starViews.length; s++) {
starViews[s] = new ImageView(this);
}
starViews = new ImageView[5];
for (int s = 0; s < starViews.length; s++) {
starViews[s] = new ImageView(this);
}
}
public void onClick(View v) {
if (v.getId() == R.id.scan_button) {
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
} else if (v.getId() == R.id.link_btn) {
//get the url tag
String tag = (String) v.getTag();
//launch the url
Intent webIntent = new Intent(Intent.ACTION_VIEW);
webIntent.setData(Uri.parse(tag));
startActivity(webIntent);
} else if (v.getId() == R.id.preview_btn) {
String tag = (String) v.getTag();
Intent intent = new Intent(this, EmbeddedBook.class);
intent.putExtra("isbn", tag);
startActivity(intent);
//launch preview
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve result of scanning - instantiate ZXing object
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
//check we have a valid result
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
//get format name of data scanned
String scanFormat = scanningResult.getFormatName();
previewBtn.setTag(scanContent);
if (scanContent != null && scanFormat != null && scanFormat.equalsIgnoreCase("EAN_13")) {
String bookSearchString = "https://www.googleapis.com/books/v1/volumes?" +
"q=isbn:" + scanContent + "&key=AIzaSyDminlOe8YitHijWd51n7-w2h8W1qb5PP0";
new GetBookInfo().execute(bookSearchString);
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"Not a valid scan!", Toast.LENGTH_SHORT);
toast.show();
}
Log.v("SCAN", "content: " + scanContent + " - format: " + scanFormat);
} else {
//invalid scan data or scan canceled
Toast toast = Toast.makeText(getApplicationContext(),
"No book scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
private class GetBookInfo extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... bookURLs) {
StringBuilder bookBuilder = new StringBuilder();
for (String bookSearchURL : bookURLs) {
HttpClient bookClient = new DefaultHttpClient();
try {
HttpGet bookGet = new HttpGet(bookSearchURL);
HttpResponse bookResponse = bookClient.execute(bookGet);
StatusLine bookSearchStatus = bookResponse.getStatusLine();
if (bookSearchStatus.getStatusCode() == 200) {
HttpEntity bookEntity = bookResponse.getEntity();
InputStream bookContent = bookEntity.getContent();
InputStreamReader bookInput = new InputStreamReader(bookContent);
BufferedReader bookReader = new BufferedReader(bookInput);
String lineIn;
while ((lineIn = bookReader.readLine()) != null) {
bookBuilder.append(lineIn);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return bookBuilder.toString();
}
protected void onPostExecute(String result) {
try {
previewBtn.setVisibility(View.VISIBLE);
JSONObject resultObject = new JSONObject(result);
JSONArray bookArray = resultObject.getJSONArray("items");
JSONObject bookObject = bookArray.getJSONObject(0);
JSONObject volumeObject = bookObject.getJSONObject("volumeInfo");
try {
titleText.setText(volumeObject.getString("title"));
} catch (JSONException jse) {
titleText.setText("");
jse.printStackTrace();
}
StringBuilder authorBuild = new StringBuilder("");
try {
JSONArray authorArray = volumeObject.getJSONArray("authors");
for (int a = 0; a < authorArray.length(); a++) {
if (a > 0) authorBuild.append(", ");
authorBuild.append(authorArray.getString(a));
}
authorText.setText(authorBuild.toString());
} catch (JSONException jse) {
authorText.setText("");
jse.printStackTrace();
}
try {
dateText.setText(volumeObject.getString("publishedDate"));
} catch (JSONException jse) {
dateText.setText("");
jse.printStackTrace();
}
try {
descriptionText.setText("DESCRIPTION: " + volumeObject.getString("description"));
} catch (JSONException jse) {
descriptionText.setText("");
jse.printStackTrace();
}
try {
double decNumStars = Double.parseDouble(volumeObject.getString("averageRating"));
int numStars = (int) decNumStars;
starLayout.setTag(numStars);
starLayout.removeAllViews();
for (int s = 0; s < numStars; s++) {
starViews[s].setImageResource(R.drawable.star);
starLayout.addView(starViews[s]);
}
} catch (JSONException jse) {
starLayout.removeAllViews();
jse.printStackTrace();
}
try {
ratingCountText.setText(volumeObject.getString("ratingsCount") + " ratings");
} catch (JSONException jse) {
ratingCountText.setText("");
jse.printStackTrace();
}
try {
boolean isEmbeddable = Boolean.parseBoolean
(bookObject.getJSONObject("accessInfo").getString("embeddable"));
if (isEmbeddable) previewBtn.setEnabled(true);
else previewBtn.setEnabled(false);
} catch (JSONException jse) {
previewBtn.setEnabled(false);
jse.printStackTrace();
}
try {
linkBtn.setTag(volumeObject.getString("infoLink"));
linkBtn.setVisibility(View.VISIBLE);
} catch (JSONException jse) {
linkBtn.setVisibility(View.GONE);
jse.printStackTrace();
}
try {
JSONObject imageInfo = volumeObject.getJSONObject("imageLinks");
new GetBookThumb().execute(imageInfo.getString("smallThumbnail"));
} catch (JSONException jse) {
thumbView.setImageBitmap(null);
jse.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
titleText.setText("NOT FOUND");
authorText.setText("");
descriptionText.setText("");
dateText.setText("");
starLayout.removeAllViews();
ratingCountText.setText("");
thumbView.setImageBitmap(null);
previewBtn.setVisibility(View.GONE);
shelfText.setText("");
}
}
}
private class GetBookThumb extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... thumbURLs) {
try {
URL thumbURL = new URL(thumbURLs[0]);
URLConnection thumbConn = thumbURL.openConnection();
thumbConn.connect();
InputStream thumbIn = thumbConn.getInputStream();
BufferedInputStream thumbBuff = new BufferedInputStream(thumbIn);
thumbImg = BitmapFactory.decodeStream(thumbBuff);
thumbBuff.close();
thumbIn.close();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
protected void onPostExecute(String result) {
thumbView.setImageBitmap(thumbImg);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void showMaps(View view) {
Intent intent = new Intent(this, MapsActivity.class);
startActivity(intent);
}
//HERE I SAVE THE RETRIEVED DATA
public void saveBook(View view) { //Click on save Book
String title = titleText.getText().toString();
String author = authorText.getText().toString();
String date = dateText.getText().toString();
String rating = ratingCountText.getText().toString();
String shelf = shelfText.getText().toString();
bookDBHelper = new BookDBHelper(context1);
sqLiteDatabase1 = bookDBHelper.getWritableDatabase();
bookDBHelper.addInformations(title, author, date, rating, shelf, sqLiteDatabase1);
Toast.makeText(getBaseContext(), "Data Saved", Toast.LENGTH_LONG).show();
bookDBHelper.close();
}
}
BookDBHelper.java
public class BookDBHelper extends SQLiteOpenHelper{
private static final String DATABASE_BOOKS_NAME = "BookINFO.DB";
private static final int DATABASE_BOOKS_VERS = 2;
private static final String CREATE_QUERY_BOOKS =
"CREATE TABLE "
+ BookContent.NewBookInfo.TABLE_NAME_BOOKS
+"("
+ BookContent.NewBookInfo.BOOK_ID + "INTEGER PRIMARY KEY, "
+ BookContent.NewBookInfo.BOOK_IMAGE +" BLOB, "
+ BookContent.NewBookInfo.BOOK_IMAGE_TAG +" TEXT, "
+ BookContent.NewBookInfo.BOOK_TITLE+" TEXT, "
+ BookContent.NewBookInfo.BOOK_AUTHOR+" TEXT, "
+ BookContent.NewBookInfo.BOOK_DATE+" TEXT, "
+ BookContent.NewBookInfo.BOOK_RATING+" TEXT, "
+ BookContent.NewBookInfo.BOOK_SHELF+" TEXT);";
public BookDBHelper(Context context){
super(context, DATABASE_BOOKS_NAME, null, DATABASE_BOOKS_VERS);
Log.e("DATABASE OPERATIONS", " DATABASE CREATED");
}
#Override
public void onCreate(SQLiteDatabase bookdb) {
bookdb.execSQL(CREATE_QUERY_BOOKS);
Log.e("DATABASE OPERATIONS", " DATABASE CREATED");
}
#Override
public void onUpgrade(SQLiteDatabase bookdb, int oldVersion, int newVersion) {
bookdb.execSQL(" DROP TABLE IS EXISTS " + BookContent.NewBookInfo.TABLE_NAME_BOOKS);
onCreate(bookdb);
}
public void addInformations( String booktitle, String bookauthor, String bookdate, String bookrating, String bookshelf, SQLiteDatabase bookdb)
{
ContentValues contentValues = new ContentValues();
contentValues.put(BookContent.NewBookInfo.BOOK_TITLE, booktitle);
contentValues.put(BookContent.NewBookInfo.BOOK_AUTHOR, bookauthor);
contentValues.put(BookContent.NewBookInfo.BOOK_DATE, bookdate);
contentValues.put(BookContent.NewBookInfo.BOOK_RATING, bookrating);
contentValues.put(BookContent.NewBookInfo.BOOK_SHELF, bookshelf);
bookdb.insert(BookContent.NewBookInfo.TABLE_NAME_BOOKS, null, contentValues);
Log.e("DATABASE OPERATIONS", "ON ROW INSERTED");
}
public Cursor getInformations(SQLiteDatabase bookdb){
Cursor cursor2;
String[] projections = {
BookContent.NewBookInfo.BOOK_TITLE,
BookContent.NewBookInfo.BOOK_AUTHOR,
BookContent.NewBookInfo.BOOK_DATE,
BookContent.NewBookInfo.BOOK_RATING,
BookContent.NewBookInfo.BOOK_SHELF};
cursor2 = bookdb.query(BookContent.NewBookInfo.TABLE_NAME_BOOKS, projections,null, null, null, null, null);
return cursor2;
}
Afterwards the infos will be displayed in a liestview.
BookDataListActivity
public class BookDataListActivity extends Activity {
public ListView booklistView;
private EditText inputSearch = null;
public SQLiteDatabase sqLiteDatabaseBooks = null;
public BookDBHelper bookDBHelper;
public Cursor cursor2;
public BookListDataAdapter bookListDataAdapter;
public final static String EXTRA_MSG1 = "title";
public final static String EXTRA_MSG2 = "author";
public final static String EXTRA_MSG3 = "date";
public final static String EXTRA_MSG4 = "rating";
public final static String EXTRA_MSG5 = "shelf";
public TextView editTextBooktitle;
public TextView editTextBookauthor;
public TextView editTextBookdate;
public TextView editTextBookrating;
public TextView editTextBookshelf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.book_data_list_layout);
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
TextView myTextView = (TextView) findViewById(R.id.text_yourbooks);
myTextView.setTypeface(myTypeface);
booklistView = (ListView) findViewById(R.id.book_list_view);
inputSearch = (EditText) findViewById(R.id.search_bar);
bookListDataAdapter = new BookListDataAdapter(getApplicationContext(), R.layout.row_book_layout);
booklistView.setAdapter(bookListDataAdapter);
//onItemClickListener
booklistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), BookInfoActivity.class);
editTextBooktitle = (TextView) view.findViewById(R.id.text_book_title);
String book_title = editTextBooktitle.getText().toString();
intent.putExtra(EXTRA_MSG1, book_title);
editTextBookauthor = (TextView) view.findViewById(R.id.text_book_author);
String bookauthor = editTextBookauthor.getText().toString();
intent.putExtra(EXTRA_MSG2, bookauthor);
editTextBookdate = (TextView) view.findViewById(R.id.text_book_date);
String bookdate = editTextBookdate.getText().toString();
intent.putExtra(EXTRA_MSG3, bookdate);
editTextBookrating = (TextView) view.findViewById(R.id.text_book_rating);
String bookrating = editTextBookrating.getText().toString();
intent.putExtra(EXTRA_MSG4, bookrating);
editTextBookshelf = (TextView) view.findViewById(R.id.text_book_shelf);
String bookshelf = editTextBookshelf.getText().toString();
intent.putExtra(EXTRA_MSG5, bookshelf);
startActivity(intent);
}
});
bookDBHelper = new BookDBHelper(getApplicationContext());
sqLiteDatabaseBooks = bookDBHelper.getReadableDatabase();
cursor2 = bookDBHelper.getInformations(sqLiteDatabaseBooks);
if (cursor2.moveToFirst()) {
do {
String booktitle, bookauthor, bookdate, bookrating, bookshelf;
booktitle = cursor2.getString(0);
bookauthor = cursor2.getString(1);
bookdate = cursor2.getString(2);
bookrating = cursor2.getString(3);
bookshelf = cursor2.getString(4);
BookDataProvider bookDataProvider = new BookDataProvider(booktitle, bookauthor, bookdate, bookrating, bookshelf);
bookListDataAdapter.add(bookDataProvider);
} while (cursor2.moveToNext());
}
}
}
And I think you will need the DataAdapter
DataListDataAdapter
public class BookListDataAdapter extends ArrayAdapter implements Filterable{
List booklist = new ArrayList();
public SQLiteDatabase sqLiteDatabaseBooks;
public BookListDataAdapter(Context context,int resource) {
super(context, resource);
}
static class BookLayoutHandler {
TextView BOOKTITLE, BOOKAUTHOR, BOOKDATE, BOOKRATING, BOOKSHELF;
}
#Override
public void add (Object object){
super.add(object);
booklist.add(object);
}
#Override
public int getCount() {
return booklist.size();
}
#Override
public Object getItem(int position) {
return booklist.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row1= convertView;
BookLayoutHandler bookLayoutHandler;
if(row1 == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row1 = layoutInflater.inflate(R.layout.row_book_layout, parent, false);
bookLayoutHandler = new BookLayoutHandler();
bookLayoutHandler.BOOKTITLE = (TextView) row1.findViewById(R.id.text_book_title);
bookLayoutHandler.BOOKAUTHOR = (TextView) row1.findViewById(R.id.text_book_author);
bookLayoutHandler.BOOKDATE = (TextView) row1.findViewById(R.id.text_book_date);
bookLayoutHandler.BOOKRATING = (TextView) row1.findViewById(R.id.text_book_rating);
bookLayoutHandler.BOOKSHELF = (TextView) row1.findViewById(R.id.text_book_shelf);
row1.setTag(bookLayoutHandler);
}else{
bookLayoutHandler = (BookLayoutHandler) row1.getTag();
}
BookDataProvider bookDataProvider = (BookDataProvider) this.getItem(position);
bookLayoutHandler.BOOKTITLE.setText(bookDataProvider.getBooktitle());
bookLayoutHandler.BOOKAUTHOR.setText(bookDataProvider.getBookauthor());
bookLayoutHandler.BOOKDATE.setText(bookDataProvider.getBookdate());
bookLayoutHandler.BOOKRATING.setText(bookDataProvider.getBookrating());
bookLayoutHandler.BOOKSHELF.setText(bookDataProvider.getBookshelf());
return row1;
}
BookDataProvider:
public class BookDataProvider {
private Bitmap bookimage;
private String booktitle;
private String bookauthor;
private String bookdate;
private String bookrating;
private String bookshelf;
public Bitmap getBookimage() {
return bookimage;
}
public void setBookimage(Bitmap bookimage) {
this.bookimage = bookimage;
}
public String getBooktitle() {
return booktitle;
}
public void setBooktitle(String booktitle) {
this.booktitle = booktitle;
}
public String getBookauthor() {
return bookauthor;
}
public void setBookauthor(String bookauthor) {
this.bookauthor = bookauthor;
}
public String getBookdate() {
return bookdate;
}
public void setBookdate(String bookdate) {
this.bookdate = bookdate;
}
public String getBookrating() {
return bookrating;
}
public void setBookrating(String bookrating) {
this.bookrating = bookrating;
}
public String getBookshelf() {
return bookshelf;
}
public void setBookshelf(String bookshelf) {
this.bookshelf = bookshelf;
}
public BookDataProvider ( Bitmap bookimage, String booktitle, String bookauthor, String bookdate, String bookrating, String bookshelf)
{
this.bookimage = bookimage;
this.booktitle = booktitle;
this.bookauthor = bookauthor;
this.bookdate = bookdate;
this.bookrating = bookrating;
this.bookshelf = bookshelf;
}
}
BookContent
public class BookContent {
public static abstract class NewBookInfo{ //Tabllenspalten deklaration
public static final String BOOK_IMAGE = "book_image";
public static final String BOOK_IMAGE_TAG ="image_tag";
public static final String BOOK_TITLE = "book_title";
public static final String BOOK_AUTHOR = "book_author";
public static final String BOOK_DATE = "book_date";
public static final String BOOK_RATING = "book_rating";
public static final String BOOK_SHELF = "book_shelf";
public static final String TABLE_NAME_BOOKS = "book_info";
public static final String BOOK_ID = "_id";
}
}
If I get your question right, you need to convert your image to a blob.
Well, blob is a byte array, so the following code would help you to convert your Bitmap to a byte[]
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, thumbImg);
byte[] blob = stream.toByteArray();
You can also get the whole implementation from another question here:
how to store Image as blob in Sqlite & how to retrieve it?
EDIT:
Of course, you have to edit your BookDBHelper.addInformations function and add one additional parameter for your image:
public void addInformations( String booktitle, String bookauthor, String bookdate, String bookrating, String bookshelf, byte[] image, SQLiteDatabase bookdb)
{
ContentValues contentValues = new ContentValues();
contentValues.put(BookContent.NewBookInfo.BOOK_TITLE, booktitle);
contentValues.put(BookContent.NewBookInfo.BOOK_AUTHOR, bookauthor);
contentValues.put(BookContent.NewBookInfo.BOOK_DATE, bookdate);
contentValues.put(BookContent.NewBookInfo.BOOK_RATING, bookrating);
contentValues.put(BookContent.NewBookInfo.BOOK_SHELF, bookshelf);
contentValues.put(YOUR_IMAGE_CONSTANT, image);
bookdb.insert(BookContent.NewBookInfo.TABLE_NAME_BOOKS, null, contentValues);
Log.e("DATABASE OPERATIONS", "ON ROW INSERTED");
}
Now you can save your Book through ScanActivity.saveBook:
public void saveBook(View view) { //Click on save Book
// ...
BitmapDrawable bitmapDrawable = (BitmapDrawable) thumbView.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] blob = stream.toByteArray();
sqLiteDatabase1 = bookDBHelper.getWritableDatabase();
bookDBHelper.addInformations(title, author, date, rating, shelf, blob, sqLiteDatabase1);
Toast.makeText(getBaseContext(), "Data Saved", Toast.LENGTH_LONG).show();
bookDBHelper.close();
}

Android: sort by date in the JSON data

I am new to Android. I'm trying to sort by the date in the JSON data, but nothing works. I'm not even getting an error. I've tried so many different ways, but its not working.
I did a lot of searching but could not figure out how to implement this. How can I sort this by the days column? Thank you in advance.
Here's my code
public class ParseJSONTask extends AsyncTask< Void , Void , Void > {
public Handler handler = new Handler();
public Activity act = null;
private static String TAG_SERVICES = "services";
private static String TAG_ID = "id";
private static String TAG_COMMAND = "command";
private static String TAG_DAYS = "days";
private static String TAG_HOURS = "hours";
private static String TAG_OSMS = "osms";
private static String TAG_ISMS = "isms";
private static String TAG_TIMEOUT = "timeout";
public String SMS_SENT = "SMS Gönderildi";
public String SMS_DELIVERED = "SMS İletildi";
public String serviceString = "";
ArrayList<ServiceData> services;
#Override
public void onPreExecute() {
super.onPreExecute();
services = new ArrayList<ServiceData>();
}
#Override
public Void doInBackground(Void... params) {
WebServiceHandler webServiceHandler = new WebServiceHandler();
String JsonStr = webServiceHandler.getJSONData("http://jsonblob.com/55e34310e4b01190df36e861");
try {
JSONObject jsonObject = new JSONObject(JsonStr);
final JSONArray contactsJSON = jsonObject.getJSONArray(TAG_SERVICES);
for (int i = 0; i < contactsJSON.length(); i++) {
ServiceData aServiceData = new ServiceData();
//json parse istedimiz veriyi kullanabiliriz.
JSONObject serviceObject = contactsJSON.getJSONObject(i);
aServiceData.id = serviceObject.getString(TAG_ID);
aServiceData.command = serviceObject.getString(TAG_COMMAND);
aServiceData.days = serviceObject.getString(TAG_DAYS);
aServiceData.hours = serviceObject.getString(TAG_HOURS);
aServiceData.osms = serviceObject.getString(TAG_OSMS);
aServiceData.isms = serviceObject.getString(TAG_ISMS);
aServiceData.timeout = serviceObject.getString(TAG_TIMEOUT);
String input = aServiceData.days + " " + aServiceData.hours;
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(input);
long milliseconds = date.getTime();
final long millisecondsFromNow = milliseconds - (new Date()).getTime();
aServiceData.milliseconds = milliseconds;
services.add(aServiceData);
if(millisecondsFromNow > 0) {
new DateSendSMS().onCreate(aServiceData.days, aServiceData.hours, aServiceData.osms, aServiceData.command);
Thread.sleep(Integer.parseInt(aServiceData.timeout) * 60000);
}
//Timeout aşağı kısımda sürelendirilecek
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
String serviceString = "";
for (ServiceData aServiceData:services){
serviceString+=aServiceData.toString();
}
Collections.sort(services, new Comparator<ServiceData>() {
#Override
public int compare(ServiceData t1, ServiceData t2) {
return t1.milliseconds <= t2.milliseconds ? -1 : 1;
}
});
// here is sorted data
for (ServiceData aServiceData : services) {
// move DateSendSMS here. above you can add additional logic about millis
new DateSendSMS().onCreate(aServiceData.days, aServiceData.hours, aServiceData.osms, aServiceData.command);
Log.d("+++++", aServiceData.toString());
}
}
}
ServiceData Class:
public static class ServiceData {
public long milliseconds;
public String id = "";
public String command = "";
public String days = "";
public String hours = "";
public String osms = "";
public String isms = "";
public String timeout = "";
#Override
public String toString() {
return id + ", " + command + ", " + days + ", " + hours + ", " + osms + ", " + isms
+ ", " + timeout + "\n \n ";
}
}
Add time field to ServiceData class
ServiceDate {
...
long milliseconds;
...
}
Fill this field in for loop:
long milliseconds = date.getTime();
aServiceData.milliseconds = milliseconds;
Sort services in onPostExecute
Collections.sort(services, new Comparator<ServiceData>() {
#Override
public int compare(ServiceData t1, ServiceData t2) {
return t1.milliseconds <= t2.milliseconds ? -1 : 1;
}
});
I am not sure you can directly sort Json Data (I dont know weather there is a library that will actually do it - if so go for it). I Suggest you to put all the ServiceData into a collection (Which you do at the moment) and then Sort it.
You can write your own sorting algorithm or you can use a Java Collections library to do the sorting by implimention Comparable on your ServiceData class or using a Comparable and them you can use Colletions.sort() to sort your list.
Here is a good tutorial.

Trying to put a search functionality in my application

Hi, guys! First of all, I'm newbie! I'm trying to create a search functionality (Search BY CITY) in my application. But something is wrong! It don't work!
The error message is: 'The method filter(String) is undefined for the type BinderData'
adapter.filter(text);
Could someone help me in details? I included the "TextWatcher" function in my main activity (WeatherActivity).
This is my code:
WeatherActivity
public class WeatherActivity extends Activity {
// XML node keys
static final String KEY_TAG = "weatherdata"; // parent node
static final String KEY_ID = "id";
static final String KEY_CITY = "city";
static final String KEY_TEMP_C = "tempc";
static final String KEY_TEMP_F = "tempf";
static final String KEY_CONDN = "condition";
static final String KEY_SPEED = "windspeed";
static final String KEY_ICON = "icon";
EditText editsearch;
// List items
ListView list;
BinderData adapter = null;
List<HashMap<String,String>> weatherDataCollection;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (getAssets().open("weatherdata.xml"));
weatherDataCollection = new ArrayList<HashMap<String,String>>();
// normalize text representation
doc.getDocumentElement ().normalize ();
NodeList weatherList = doc.getElementsByTagName("weatherdata");
HashMap<String,String> map = null;
for (int i = 0; i < weatherList.getLength(); i++) {
map = new HashMap<String,String>();
Node firstWeatherNode = weatherList.item(i);
if(firstWeatherNode.getNodeType() == Node.ELEMENT_NODE){
Element firstWeatherElement = (Element)firstWeatherNode;
//-------
NodeList idList = firstWeatherElement.getElementsByTagName(KEY_ID);
Element firstIdElement = (Element)idList.item(0);
NodeList textIdList = firstIdElement.getChildNodes();
//--id
map.put(KEY_ID, ((Node)textIdList.item(0)).getNodeValue().trim());
//2.-------
NodeList cityList = firstWeatherElement.getElementsByTagName(KEY_CITY);
Element firstCityElement = (Element)cityList.item(0);
NodeList textCityList = firstCityElement.getChildNodes();
//--city
map.put(KEY_CITY, ((Node)textCityList.item(0)).getNodeValue().trim());
//3.-------
NodeList tempList = firstWeatherElement.getElementsByTagName(KEY_TEMP_C);
Element firstTempElement = (Element)tempList.item(0);
NodeList textTempList = firstTempElement.getChildNodes();
//--city
map.put(KEY_TEMP_C, ((Node)textTempList.item(0)).getNodeValue().trim());
//4.-------
NodeList condList = firstWeatherElement.getElementsByTagName(KEY_CONDN);
Element firstCondElement = (Element)condList.item(0);
NodeList textCondList = firstCondElement.getChildNodes();
//--city
map.put(KEY_CONDN, ((Node)textCondList.item(0)).getNodeValue().trim());
//5.-------
NodeList speedList = firstWeatherElement.getElementsByTagName(KEY_SPEED);
Element firstSpeedElement = (Element)speedList.item(0);
NodeList textSpeedList = firstSpeedElement.getChildNodes();
//--city
map.put(KEY_SPEED, ((Node)textSpeedList.item(0)).getNodeValue().trim());
//6.-------
NodeList iconList = firstWeatherElement.getElementsByTagName(KEY_ICON);
Element firstIconElement = (Element)iconList.item(0);
NodeList textIconList = firstIconElement.getChildNodes();
//--city
map.put(KEY_ICON, ((Node)textIconList.item(0)).getNodeValue().trim());
//Add to the Arraylist
weatherDataCollection.add(map);
}
}
BinderData bindingData = new BinderData(this,weatherDataCollection);
list = (ListView) findViewById(R.id.list);
adapter = new BinderData(WeatherActivity.this,
weatherDataCollection);
editsearch = (EditText) findViewById(R.id.search);
editsearch.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString()
.toLowerCase(Locale.getDefault());
adapter.filter(text);
}
});
Log.i("BEFORE", "<<------------- Before SetAdapter-------------->>");
list.setAdapter(bindingData);
Log.i("AFTER", "<<------------- After SetAdapter-------------->>");
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent();
i.setClass(WeatherActivity.this, SampleActivity.class);
// parameters
i.putExtra("position", String.valueOf(position + 1));
/* selected item parameters
* 1. City name
* 2. Weather
* 3. Wind speed
* 4. Temperature
* 5. Weather icon
*/
i.putExtra("city", weatherDataCollection.get(position).get(KEY_CITY));
i.putExtra("weather", weatherDataCollection.get(position).get(KEY_CONDN));
i.putExtra("windspeed", weatherDataCollection.get(position).get(KEY_SPEED));
i.putExtra("temperature", weatherDataCollection.get(position).get(KEY_TEMP_C));
i.putExtra("icon", weatherDataCollection.get(position).get(KEY_ICON));
// start the sample activity
startActivity(i);
}
});
}
catch (IOException ex) {
Log.e("Error", ex.getMessage());
}
catch (Exception ex) {
Log.e("Error", "Loading exception");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
BlinderData
public class BinderData extends BaseAdapter {
// XML node keys
static final String KEY_TAG = "weatherdata"; // parent node
static final String KEY_ID = "id";
static final String KEY_CITY = "city";
static final String KEY_TEMP_C = "tempc";
static final String KEY_TEMP_F = "tempf";
static final String KEY_CONDN = "condition";
static final String KEY_SPEED = "windspeed";
static final String KEY_ICON = "icon";
LayoutInflater inflater;
ImageView thumb_image;
List<HashMap<String,String>> weatherDataCollection;
ViewHolder holder;
public BinderData() {
// TODO Auto-generated constructor stub
}
public BinderData(Activity act, List<HashMap<String,String>> map) {
this.weatherDataCollection = map;
inflater = (LayoutInflater) act
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
// TODO Auto-generated method stub
// return idlist.size();
return weatherDataCollection.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null){
vi = inflater.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.tvCity = (TextView)vi.findViewById(R.id.tvCity); // city name
holder.tvWeather = (TextView)vi.findViewById(R.id.tvCondition); // city weather overview
holder.tvTemperature = (TextView)vi.findViewById(R.id.tvTemp); // city temperature
holder.tvWeatherImage =(ImageView)vi.findViewById(R.id.list_image); // thumb image
vi.setTag(holder);
}
else{
holder = (ViewHolder)vi.getTag();
}
// Setting all values in listview
holder.tvCity.setText(weatherDataCollection.get(position).get(KEY_CITY));
holder.tvWeather.setText(weatherDataCollection.get(position).get(KEY_CONDN));
holder.tvTemperature.setText(weatherDataCollection.get(position).get(KEY_TEMP_C));
//Setting an image
String uri = "drawable/"+ weatherDataCollection.get(position).get(KEY_ICON);
int imageResource = vi.getContext().getApplicationContext().getResources().getIdentifier(uri, null, vi.getContext().getApplicationContext().getPackageName());
Drawable image = vi.getContext().getResources().getDrawable(imageResource);
holder.tvWeatherImage.setImageDrawable(image);
return vi;
}
/*
*
* */
static class ViewHolder{
TextView tvCity;
TextView tvTemperature;
TextView tvWeather;
ImageView tvWeatherImage;
}
}
SampleActivity
public class SampleActivity extends Activity {
String position = "1";
String city = "";
String weather = "";
String temperature = "";
String windSpeed = "";
String iconfile = "";
ImageButton imgWeatherIcon;
TextView tvcity;
TextView tvtemp;
TextView tvwindspeed;
TextView tvCondition;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detailpage);
try {
//handle for the UI elements
imgWeatherIcon = (ImageButton) findViewById(R.id.imageButtonAlpha);
//Text fields
tvcity = (TextView) findViewById(R.id.textViewCity);
tvtemp = (TextView) findViewById(R.id.textViewTemperature);
tvwindspeed = (TextView) findViewById(R.id.textViewWindSpeed);
tvCondition = (TextView) findViewById(R.id.textViewCondition);
// Get position to display
Intent i = getIntent();
this.position = i.getStringExtra("position");
this.city = i.getStringExtra("city");
this.weather= i.getStringExtra("weather");
this.temperature = i.getStringExtra("temperature");
this.windSpeed = i.getStringExtra("windspeed");
this.iconfile = i.getStringExtra("icon");
String uri = "drawable/"+ "d" + iconfile;
int imageBtnResource = getResources().getIdentifier(uri, null, getPackageName());
Drawable dimgbutton = getResources().getDrawable(imageBtnResource);
//text elements
tvcity.setText(city);
tvtemp.setText(temperature);
tvwindspeed.setText(windSpeed);
tvCondition.setText(weather);
//thumb_image.setImageDrawable(image);
imgWeatherIcon.setImageDrawable(dimgbutton);
}
catch (Exception ex) {
Log.e("Error", "Loading exception");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
XParser
public class XParser extends DefaultHandler {
ArrayList<String> idlist = new ArrayList<String>();
ArrayList<String> citylist = new ArrayList<String>();
ArrayList<String> condilist = new ArrayList<String>();
ArrayList<String> templist = new ArrayList<String>();
ArrayList<String> speedlist = new ArrayList<String>();
ArrayList<String> iconlist = new ArrayList<String>();
//temp variable to store the data chunk read while parsing
private String tempStore = null;
public XParser() {
// TODO Auto-generated constructor stub
}
/*
* Clears the tempStore variable on every start of the element
* notification
*
* */
public void startElement (String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if (localName.equalsIgnoreCase("id")) {
tempStore = "";
} else if (localName.equalsIgnoreCase("city")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("tempc")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("condition")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("windspeed")) {
tempStore = "";
}
else if (localName.equalsIgnoreCase("icon")) {
tempStore = "";
}
else {
tempStore = "";
}
}
/*
* updates the value of the tempStore variable into
* corresponding list on receiving end of the element
* notification
* */
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if (localName.equalsIgnoreCase("id")) {
idlist.add(tempStore);
}
else if (localName.equalsIgnoreCase("city")) {
citylist.add(tempStore);
}
else if (localName.equalsIgnoreCase("tempc")) {
templist.add(tempStore);
}
else if (localName.equalsIgnoreCase("condition")) {
condilist.add(tempStore);
}
else if (localName.equalsIgnoreCase("windspeed")) {
speedlist.add(tempStore);
}
else if (localName.equalsIgnoreCase("icon")) {
iconlist.add(tempStore);
}
tempStore = "";
}
/*
* adds the incoming data chunk of character data to the
* temp data variable - tempStore
*
* */
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
tempStore += new String(ch, start, length);
}
}``
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

How to retrieve RSS FEED from Yahoo weather

I've tried to retrieve RSS data from Yahho weather ,however my code couldn't work.
May I know what's wrong with it?
The Url that I've use is http://weather.yahooapis.com/forecastrss?w=1062617&u=c.
I'm a newbie in programming, Kindly seek your advice to it.
Thanks
the below are my coding.
CXActivity.java
public class CXActivity extends Activity {
/** Called when the activity is first created. */
ListView listview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RestClient rc = new RestClient();
//the account key might not work. Please insert your own set.
ArrayList<Weather> list1 = rc.getPlaces("", "");
int index = 3;
String[] listArray = new String[list1.size()];
StringBuilder sb = new StringBuilder();
int counter = 0;
for(int i = 1; i<list1.size(); i++)
{
sb.append("\n\nEntry #: " + i);
sb.append("\n" + "Title: \""+ list1.get(i).getTitle() + "\"");
sb.append("\n" + "Publish Date: \""+ list1.get(i).getPubDate() +"\"");
sb.append("\n" + "Condition: \""+ list1.get(i).getCondition()+"\"");
sb.append("\n" + "Forecast: \""+ list1.get(i).getForecast()+"\"");
listArray[counter] = sb.toString();
counter++;
sb.delete(0, sb.capacity());
}
listview=(ListView)findViewById(R.id.ListView01);
listview.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , listArray));
}
}
RestClient.java
public class RestClient
{
ArrayList weatherList;
//This is the function responsible to pull data from web service.
public ArrayList<Weather> getPlaces(String accountKey, String uniqueId)
{
weatherList = new ArrayList<Weather>();
try {
URL _url = new URL("http://weather.yahooapis.com/forecastrss?w=1062617&u=c");
URLConnection _urlConn = _url.openConnection();
_urlConn.addRequestProperty("AccountKey", accountKey);
_urlConn.addRequestProperty("UniqueUserID", uniqueId);
BufferedReader br = new BufferedReader(new InputStreamReader(_urlConn.getInputStream()));
String line = null;
StringBuilder strBuilder = new StringBuilder();
while ((line = br.readLine()) != null) {
strBuilder.append(line);
System.out.println(line);
}
String[] IProperties = strBuilder.toString().split("<m:properties>");
for (String str : IProperties)
{
Weather weather = new Weather();
weather.setTitle(Utils.getStringBetween(str, "<title>", "</<title>>"));
weather.setPubDate(Utils.getStringBetween(str, "<pubDate>", "</pubDate>"));
weather.setCondition(Utils.getStringBetween(str, "<yweather:condition>", "</yweather:condition>"));
weather.setForecast(Utils.getStringBetween(str, "<yweather:forecast>", "</yweather:forecast>"));
weatherList.add(weather);
}
}
catch (MalformedURLException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
catch (Exception ex)
{
ex.printStackTrace();
}
return weatherList;
}
//This is a helper function to get specific traffic data structure
public Weather getPlacesAtIndex(ArrayList<Weather> list, int index)
{
if(list.size() <= index) return null;
return list.get(index);
}
}
Utils.java
public class Utils {
//This functions get the xml data between the xml elements
public static String getStringBetween(String src, String start, String end)
{
StringBuilder sb = new StringBuilder();
int startIdx = src.indexOf(start) + start.length();
int endIdx = src.indexOf(end);
while(startIdx < endIdx)
{
sb.append("" + String.valueOf(src.charAt(startIdx)));
startIdx++;
}
return sb.toString();
}
}
weather.java
public class Weather {
String Title;
String PubDate;
String Condition;
String Forecast;
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getPubDate() {
return PubDate;
}
public void setPubDate(String pubDate) {
PubDate = pubDate;
}
public String getCondition() {
return Condition;
}
public void setCondition(String condition) {
Condition = condition;
}
public String getForecast() {
return Forecast;
}
public void setForecast(String forecast) {
Forecast = forecast;
}
}
Please change your activity code.
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
ListView listview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RestClient rc = new RestClient();
// the account key might not work. Please insert your own set.
ArrayList<Weather> list1 = rc.getPlaces("", "");
int index = 3;
String[] listArray = new String[list1.size()];
StringBuilder sb = new StringBuilder();
int counter = 0;
Log.e("N", "listArray::" + list1.size());
for (int i = 0; i < list1.size(); i++) {
sb.append("\n\nEntry #: " + i);
sb.append("\n" + "Title: \"" + list1.get(i).getTitle() + "\"");
sb.append("\n" + "Publish Date: \"" + list1.get(i).getPubDate()
+ "\"");
sb.append("\n" + "Condition: \"" + list1.get(i).getCondition()
+ "\"");
sb.append("\n" + "Forecast: \"" + list1.get(i).getForecast() + "\"");
listArray[counter] = sb.toString();
counter++;
sb.delete(0, sb.capacity());
}
Log.e("N", "listArray::" + listArray.length);
listview = (ListView) findViewById(R.id.listView);
listview.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listArray));
}
}

Categories

Resources