Android FileOutputStream FileInputStream issue - android

I have set up a activity on my app that creates a new high score then saves it and allows it to be reloaded and display through FileOutputStream and FileInputStream logic. I have been testing the app on my phone and when loading the high score back I am getting 0 returned. I believe this is because there are zero bytes within the file.
Heres all my code:
public class Course extends ActionBarActivity {
String chosenCourseValue = "";
int courseNum;
String listPars = "";
String listHoles = "";
String courseImage = "";
int[] scoreNum = new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int totalScoreNum = 0;
String collected = "test string";
public void upButtonOnClick(View imageButton)
{
int textViewId = getResources().getIdentifier((String) imageButton.getTag(), "id", getPackageName());
TextView score = (TextView) findViewById(textViewId);
totalScoreNum++;
if (score.getId() == R.id.score1)
{
scoreNum[0]++;
score.setText(String.valueOf(scoreNum[0]));
}
if (score.getId() == R.id.score2)
{
scoreNum[1]++;
score.setText(String.valueOf(scoreNum[1]));
}
if (score.getId() == R.id.score3)
{
scoreNum[2]++;
score.setText(String.valueOf(scoreNum[2]));
}
if (score.getId() == R.id.score4)
{
scoreNum[3]++;
score.setText(String.valueOf(scoreNum[3]));
}
if (score.getId() == R.id.score5)
{
scoreNum[4]++;
score.setText(String.valueOf(scoreNum[4]));
}
if (score.getId() == R.id.score6)
{
scoreNum[5]++;
score.setText(String.valueOf(scoreNum[5]));
}
if (score.getId() == R.id.score7)
{
scoreNum[6]++;
score.setText(String.valueOf(scoreNum[6]));
}
if (score.getId() == R.id.score8)
{
scoreNum[7]++;
score.setText(String.valueOf(scoreNum[7]));
}
if (score.getId() == R.id.score9)
{
scoreNum[8]++;
score.setText(String.valueOf(scoreNum[8]));
}
if (score.getId() == R.id.score10)
{
scoreNum[9]++;
score.setText(String.valueOf(scoreNum[9]));
}
if (score.getId() == R.id.score11)
{
scoreNum[10]++;
score.setText(String.valueOf(scoreNum[10]));
}
if (score.getId() == R.id.score12)
{
scoreNum[11]++;
score.setText(String.valueOf(scoreNum[11]));
}
if (score.getId() == R.id.score13)
{
scoreNum[12]++;
score.setText(String.valueOf(scoreNum[12]));
}
if (score.getId() == R.id.score14)
{
scoreNum[13]++;
score.setText(String.valueOf(scoreNum[13]));
}
if (score.getId() == R.id.score15)
{
scoreNum[14]++;
score.setText(String.valueOf(scoreNum[14]));
}
if (score.getId() == R.id.score16)
{
scoreNum[15]++;
score.setText(String.valueOf(scoreNum[15]));
}
if (score.getId() == R.id.score17)
{
scoreNum[16]++;
score.setText(String.valueOf(scoreNum[16]));
}
if (score.getId() == R.id.score18)
{
scoreNum[17]++;
score.setText(String.valueOf(scoreNum[17]));
}
}
public void downButtonOnClick(View imageButton)
{
int textViewId = getResources().getIdentifier((String) imageButton.getTag(), "id", getPackageName());
TextView score = (TextView) findViewById(textViewId);
totalScoreNum--;
if (score.getId() == R.id.score1)
{
scoreNum[0]--;
score.setText(String.valueOf(scoreNum[0]));
}
if (score.getId() == R.id.score2)
{
scoreNum[1]--;
score.setText(String.valueOf(scoreNum[1]));
}
if (score.getId() == R.id.score3)
{
scoreNum[2]--;
score.setText(String.valueOf(scoreNum[2]));
}
if (score.getId() == R.id.score4)
{
scoreNum[3]--;
score.setText(String.valueOf(scoreNum[3]));
}
if (score.getId() == R.id.score5)
{
scoreNum[4]--;
score.setText(String.valueOf(scoreNum[4]));
}
if (score.getId() == R.id.score6)
{
scoreNum[5]--;
score.setText(String.valueOf(scoreNum[5]));
}
if (score.getId() == R.id.score7)
{
scoreNum[6]--;
score.setText(String.valueOf(scoreNum[6]));
}
if (score.getId() == R.id.score8)
{
scoreNum[7]--;
score.setText(String.valueOf(scoreNum[7]));
}
if (score.getId() == R.id.score9)
{
scoreNum[8]--;
score.setText(String.valueOf(scoreNum[8]));
}
if (score.getId() == R.id.score10)
{
scoreNum[9]--;
score.setText(String.valueOf(scoreNum[9]));
}
if (score.getId() == R.id.score11)
{
scoreNum[10]--;
score.setText(String.valueOf(scoreNum[10]));
}
if (score.getId() == R.id.score12)
{
scoreNum[11]--;
score.setText(String.valueOf(scoreNum[11]));
}
if (score.getId() == R.id.score13)
{
scoreNum[12]--;
score.setText(String.valueOf(scoreNum[12]));
}
if (score.getId() == R.id.score14)
{
scoreNum[13]--;
score.setText(String.valueOf(scoreNum[13]));
}
if (score.getId() == R.id.score15)
{
scoreNum[14]--;
score.setText(String.valueOf(scoreNum[14]));
}
if (score.getId() == R.id.score16)
{
scoreNum[15]--;
score.setText(String.valueOf(scoreNum[15]));
}
if (score.getId() == R.id.score17)
{
scoreNum[16]--;
score.setText(String.valueOf(scoreNum[16]));
}
if (score.getId() == R.id.score18)
{
scoreNum[17]--;
score.setText(String.valueOf(scoreNum[17]));
}
}
class AsyncAPI extends AsyncTask<Void, Void, String>
{
#Override
protected String doInBackground(Void... arg0)
{
String JSONString = null;
try
{
//hard coded url API from website
String urlString = "http://webthree.ict.op.ac.nz/murraas1/golf.html";
//converting url string to object then sending (same as pressing return)
URL URLObject = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) URLObject.openConnection();
connection.connect();
//if it doesnt return 200 no data received. (use if statement to check in future)
int responseCode = connection.getResponseCode();
//getting inputstream from the sent object and setting up bufferreader
InputStream inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//reading the input
String responseString;
StringBuilder stringBuilder = new StringBuilder();
while ((responseString = bufferedReader.readLine()) != null)
{
stringBuilder = stringBuilder.append(responseString);
}
//getting string from stringbuilder and converting to a json string
JSONString = stringBuilder.toString();
}
catch (Exception e){e.printStackTrace();}
return JSONString;
}
protected void onPostExecute(String fetchedString)
{
String selectedCourse = "";
String totalPar = "";
if (chosenCourseValue.equals("Chisholm"))
{
courseNum = 0;
courseImage = "chisolm";
}
if (chosenCourseValue.equals("St Clair"))
{
courseNum = 1;
courseImage = "stclair";
}
if (chosenCourseValue.equals("Balmacewen"))
{
courseNum = 2;
courseImage = "balmacewen";
}
if (chosenCourseValue.equals("Taieri"))
{
courseNum = 3;
courseImage = "taieri";
}
if (chosenCourseValue.equals("Island Park"))
{
courseNum = 4;
courseImage = "islandpark";
}
try {
JSONObject root = new JSONObject(fetchedString);
JSONArray courseArray = root.getJSONArray("courses");
JSONObject courseInfo = courseArray.getJSONObject(courseNum);
selectedCourse = (courseInfo.getString("name"));
totalPar = (courseInfo.getString("course par"));
JSONArray parsInfo = courseInfo.getJSONArray("pars");
for(int i = 0; i < parsInfo.length(); i++)
{
JSONObject parsNum = parsInfo.getJSONObject(i);
listPars += ("Par " + parsNum.getString("par") + ",");
}
JSONArray holesInfo = courseInfo.getJSONArray("pars");
for(int i = 0; i < holesInfo.length(); i++)
{
JSONObject holeNum = holesInfo.getJSONObject(i);
listHoles += (holeNum.getString("hole") + ",");
}
}
catch (JSONException e) {
e.printStackTrace();
}
//Convert Pars and Holes text into usable array
String[] listParsArray = listPars.split(",");
String[] listHolesArray = listHoles.split(",");
//dumping Name into textview
TextView tv = (TextView) findViewById(R.id.courseName);
tv.setText(selectedCourse);
//dumping Total Par into textview
TextView tv1 = (TextView) findViewById(R.id.totalPar);
tv1.setText(totalPar);
//dumping Pars into textview
int[] parViewIDs = new int[] {R.id.hole1Par, R.id.hole2Par, R.id.hole3Par, R.id.hole4Par, R.id.hole5Par, R.id.hole6Par, R.id.hole7Par, R.id.hole8Par, R.id.hole9Par, R.id.hole10Par, R.id.hole11Par, R.id.hole12Par, R.id.hole13Par, R.id.hole14Par, R.id.hole15Par, R.id.hole16Par, R.id.hole17Par, R.id.hole18Par,};
for(int i = 0; i < 18; i++) {
TextView tv2 = (TextView) findViewById(parViewIDs[i]);
tv2.setText(listParsArray[i]);
}
//dumping Holes into textview
int[] holeViewIDs = new int[] {R.id.hole1, R.id.hole2, R.id.hole3, R.id.hole4, R.id.hole5, R.id.hole6, R.id.hole7, R.id.hole8, R.id.hole9, R.id.hole10, R.id.hole11, R.id.hole12, R.id.hole13, R.id.hole14, R.id.hole15, R.id.hole16, R.id.hole17, R.id.hole18,};
for(int i = 0; i < 18; i++)
{
TextView tv3 = (TextView) findViewById(holeViewIDs[i]);
tv3.setText(listHolesArray[i]);
}
int[] images = {R.drawable.chisholm, R.drawable.stclair, R.drawable.balmacewen, R.drawable.taieri, R.drawable.islandpark};
ImageView i = (ImageView) findViewById(R.id.courseImage);
i.setImageResource(images[courseNum]);
}
}
private void updateTextView() {
TextView tv3 = (TextView) findViewById(R.id.totalScore);
tv3.setText(String.valueOf(totalScoreNum));
}
public class SaveData implements View.OnClickListener
{
//String totalScoreString = String.valueOf(totalScoreNum);
#Override
public void onClick(View v) {
try {
FileOutputStream fou = openFileOutput("scoreFile.txt", Context.MODE_PRIVATE);
fou.write(totalScoreNum);
fou.close();
// Toast Confirm
Toast.makeText(Course.this, "Success", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void loadData()
{
FileInputStream fis = null;
try {
fis = openFileInput("scoreFile.txt");
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
collected = new String(dataArray);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public class LoadData implements View.OnClickListener
{
#Override
public void onClick(View v) {
TextView tv7 = (TextView) findViewById(R.id.returnScore);
tv7.setText(collected);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course);
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateTextView();
}
});
}
} catch (InterruptedException e) {
}
}
};
loadData();
t.start();
Button SaveDataBtn = (Button)findViewById(R.id.saveScore);
SaveData handler = new SaveData();
SaveDataBtn.setOnClickListener (handler);
Button LoadDataBtn = (Button)findViewById(R.id.loadScore);
LoadData handler1 = new LoadData();
LoadDataBtn.setOnClickListener (handler1);
Bundle extras = getIntent().getExtras();
if (extras != null) {
chosenCourseValue = extras.getString("passedChosenCourse");
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
AsyncAPI APIThread = new AsyncAPI();
APIThread.execute();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Heres the FileOutputStream FileInputStream where i believe the problem lies:
public class SaveData implements View.OnClickListener
{
//String totalScoreString = String.valueOf(totalScoreNum);
#Override
public void onClick(View v) {
try {
FileOutputStream fou = openFileOutput("scoreFile.txt", Context.MODE_PRIVATE);
fou.write(totalScoreNum);
fou.close();
// Toast Confirm
Toast.makeText(Course.this, "Success", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void loadData()
{
FileInputStream fis = null;
try {
fis = openFileInput("scoreFile.txt");
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
collected = new String(dataArray);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
When first running the app loading back the score will return the string "test string" which it was initially populated with, but once a actual score is loaded and saved it will return "0". Any help or explanation would be appreciated!

Have you tried supplying a full path for the input and output stream?
For example "/sdcard/Downloads/myapp/scoreFile.txt"
Also don't hardcode the path, use Environment.getExternalStorageDirectory(), I think this will return a File object or string path equal to "/sdcard/"
Don't forgot to add permissions for the external read and write

Related

code which one should I change to throw button and instantly displays my listview without having to click a button

code which one should I change to throw button and instantly displays my listview without having to click a button
public class MainActivity extends AppCompatActivity {
Button btnLoadFeed; <<<<<------------- Which should I remove associated with this code?
TextView textViewFeedUrl;
ListView listViewFeed;
List<FeedItem> listFeedItems;
ListAdapter adapterFeed;
String myFeed = "http://temfilm.blogspot.co.id/feeds/posts/default?alt=json";
//String myFeed = "http://arduino-er.blogspot.com/feeds/posts/default?alt=json";
//String myFeed = "http://helloraspberrypi.blogspot.com/feeds/posts/default?alt=json";
//String myFeed = "http://photo-er.blogspot.com/feeds/posts/default?alt=json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLoadFeed = (Button)findViewById(R.id.loadfeed);
textViewFeedUrl = (TextView)findViewById(R.id.feedurl);
setContentView(R.layout.layout_feed);
listViewFeed = (ListView)findViewById(R.id.listviewfeed);
listFeedItems = new ArrayList<>();
adapterFeed = new ArrayAdapter<FeedItem>(
this, android.R.layout.simple_list_item_1, listFeedItems);
listViewFeed.setAdapter(adapterFeed);
btnLoadFeed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textViewFeedUrl.setText(myFeed);
new JsonTask(listFeedItems, listViewFeed).execute(myFeed);
}
});
}
/*
JsonTask:
AsyncTask to download and parse JSON Feed of blogspot in background
*/
private class JsonTask extends AsyncTask<String, FeedItem, String> {
List<FeedItem> jsonTaskList;
ListView jsonTaskListView;
public JsonTask(List<FeedItem> targetList, ListView targetListView) {
super();
jsonTaskList = targetList;
jsonTaskListView = targetListView;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
jsonTaskList.clear();
jsonTaskListView.invalidateViews();
}
#Override
protected String doInBackground(String... params) {
try {
final String queryResult = sendQuery(params[0]);
parseQueryResult(queryResult);
} catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
eString,
Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
final String eString = e.toString();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
eString,
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onProgressUpdate(FeedItem... values) {
FeedItem newItem = values[0];
jsonTaskList.add(newItem);
jsonTaskListView.invalidateViews();
}
private String sendQuery(String query) throws IOException {
String queryReturn = "";
URL queryURL = new URL(query);
HttpURLConnection httpURLConnection = (HttpURLConnection)queryURL.openConnection();
if(httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader inputStreamReader =
new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader, 8192);
String line = null;
while((line = bufferedReader.readLine()) != null){
queryReturn += line;
}
bufferedReader.close();
}
return queryReturn;
}
private void parseQueryResult(String json) throws JSONException {
JSONObject jsonObject = new JSONObject(json);
final JSONObject jsonObject_feed = jsonObject.getJSONObject("feed");
final JSONArray jsonArray_entry = jsonObject_feed.getJSONArray("entry");
runOnUiThread(new Runnable() {
#Override
public void run() {
if(jsonArray_entry == null){
Toast.makeText(MainActivity.this,
"jsonArray_entry == null",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,
String.valueOf(jsonArray_entry.length()),
Toast.LENGTH_LONG).show();
for(int i=0; i<jsonArray_entry.length(); i++){
try {
JSONObject thisEntry = (JSONObject) jsonArray_entry.get(i);
JSONObject thisEntryTitle = thisEntry.getJSONObject("title");
String thisEntryTitleString = thisEntryTitle.getString("$t");
JSONArray jsonArray_EntryLink = thisEntry.getJSONArray("link");
//search for the link element with rel="alternate"
//I assume it's one and only one element with rel="alternate",
//and its href hold the link to the page
for(int j=0; j<jsonArray_EntryLink.length(); j++){
JSONObject thisLink = (JSONObject) jsonArray_EntryLink.get(j);
try{
String thisLinkRel = thisLink.getString("rel");
if(thisLinkRel.equals("alternate")){
try{
String thisLinkHref = thisLink.getString("href");
FeedItem thisElement = new FeedItem(
thisEntryTitleString.toString(),
thisLinkHref);
publishProgress(thisElement);
break;
}catch (JSONException e){
//no such mapping exists
}
}
}catch (JSONException e){
//no such mapping exists
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
});
}
}
}

Show data on Listview is duplication

I'm doing a app can update data every 1 minutes, data will from database mysql on server to show on listview of my app android. My problem is when show data the first is ok but when show data the second on listview, data of the first and the second is duplication.Can you help me!
Source code:
public class Hoadon extends Activity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> al1 = new ArrayList<String>();
ArrayList<String> al2 = new ArrayList<String>();
ArrayList<String> al3 = new ArrayList<String>();
ArrayList<String> al1a = new ArrayList<String>();
String date;
String name;
String address;
String url;
String code;
int responseCode;
private String IDinvoice;
private TimerTask mTimerTask;
private Timer t=new Timer();
private final Handler handler=new Handler();
private ListView listview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hoadon);
int currentOrientation = getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
try {
URL url = new URL("http://longvansolution.tk/monthlytarget.php");
URLConnection connection = url.openConnection();
connection.setConnectTimeout(2000);
HttpURLConnection httpConnection = (HttpURLConnection) connection;
responseCode = httpConnection.getResponseCode();
} catch (Exception e) {
}
try {
if (isNetworkAvailable() == true
//&& responseCode == HttpURLConnection.HTTP_OK
) {
//new LoadData().execute();
al.clear();
al1.clear();
al2.clear();
al3.clear();
al1a.clear();
doTimerTask();
} else {
AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setMessage("No Internet Connection available!!!");
ad.show();
}
} catch (Exception e) {
}
Bundle extras = getIntent().getExtras();
if (extras != null) {
IDinvoice = extras.getString("IDinvoice");
}
}
public void doTimerTask(){
mTimerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
new LoadData().execute();
Log.d("TIMER", "TimerTask run");
}
});
}};
// public void schedule (TimerTask task, long delay, long period)
t.schedule(mTimerTask, 500, 10000); //
}
#Override
public void onBackPressed() {
//do something with bitmap
}
private class LoadData extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
// can use UI thread here
protected void onPreExecute() {
this.progressDialog = ProgressDialog.show(
Hoadon.this, "", " Loading...");
}
#Override
protected void onPostExecute(final Void unused) {
this.progressDialog.dismiss();
try {
listview = (ListView) findViewById(R.id.listView1);
this.progressDialog.dismiss();
listview.setAdapter(new DataAdapter(Hoadon.this,
al.toArray(new String[al.size()]), al1a
.toArray(new String[al1a.size()]), al1
.toArray(new String[al1.size()]), al2
.toArray(new String[al2.size()])));
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String t = al3.get(position);
Intent i = new Intent(Hoadon.this,
Signature.class);
i.putExtra("url", t);
startActivity(i);
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// HTTP post
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(
"http://longvansolution.tk/monthlytarget.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
// buffered reader
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 80);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
date = json_data.getString("date");
address = json_data.getString("address");
name = json_data.getString("name");
url = json_data.getString("url");
code = json_data.getString("code");
al.add(date);
al1a.add(code);
al1.add(name);
al2.add(address);
al3.add(url);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
} catch (ParseException e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
return null;
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null, otherwise check
// if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
// Log.i("net status:", "Online...!!!");
return true;
}
// Log.i("net status:", "offline...!!!");
return false;
}
}
Source DataAdapter
public class DataAdapter extends BaseAdapter {
Context mContext;
private LayoutInflater mInflater;
String[] date;
String[] code;
String[] address;
String[] name;
public DataAdapter(Context c, String[] date,String[] code, String[] name, String[] address) {
this.date = date;
this.code=code;
this.name = name;
this.address = address;
mContext = c;
mInflater = LayoutInflater.from(c);
}
public void clearData() {
// clear the data
Arrays.fill(date, null);
Arrays.fill(code, null);
Arrays.fill(address, null);
Arrays.fill(name, null);
}
public int getCount() {
return date.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.customgrid, parent, false);
holder = new ViewHolder();
holder.date = (TextView) convertView.findViewById(R.id.date);
holder.code=(TextView)convertView.findViewById(R.id.mahd);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.address = (TextView) convertView.findViewById(R.id.address);
if (position == 0) {
convertView.setTag(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
holder.date.setText(date[position]);
holder.code.setText(code[position]);
holder.name.setText(name[position]);
holder.address.setText(address[position]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return convertView;
}
static class ViewHolder {
TextView date,code;
TextView name, address;
}
}
you should clear your arralist every LoadData task.
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
al.clear();
al1.clear();
al2.clear();
al3.clear();
al1a.clear();
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
date = json_data.getString("date");
address = json_data.getString("address");
name = json_data.getString("name");
url = json_data.getString("url");
code = json_data.getString("code");
al.add(date);
al1a.add(code);
al1.add(name);
al2.add(address);
al3.add(url);
}

Exception in AsyncTask downloading image

Refer my question on IllegalStateException in AsyncTask.
I am invoked the following AsyncTask from onPostExecute() of this task(Referred in this link).
public class SaveImageAsync extends AsyncTask<Context, Integer, String> {
private Bitmap bitmap = null;
private ArrayList<String> imageUrls = null;
private ArrayList<ImageView> imageViews = null;
int index = 0;
public SaveImageAsync(ArrayList<ImageView> imageViews,
ArrayList<String> imageUrls) {
this.imageUrls = imageUrls;
this.imageViews = imageViews;
}
#Override
protected String doInBackground(Context... params) {
boolean bRC;
String imageName, imageLocalPath, imageURL;
try {
for (int i = 0; i < imageUrls.size(); i++) {
imageURL = imageUrls.get(i);
String[] strSplittedImagePath = imageURL
.split("/");
if ((strSplittedImagePath != null)
&& (strSplittedImagePath.length >= 1)) {
imageName = strSplittedImagePath[(strSplittedImagePath.length - 1)];
} else {
imageName = imageURL;
}
imageLocalPath = path + imageName;
bRC = doesFileExists(imageLocalPath);
if (bRC == false) {
getImageFromServer(CommonSettings.mSTstrBaseURL
+ imageURL, imageLocalPath);
}
try {
bitmap = BitmapFactory
.decodeFile(imageLocalPath);
} catch (Exception e) {
}
if (bitmap == null) {
try {
new File(imageLocalPath).delete();
} catch (Exception e1) {
}
getImageFromServer(CommonSettings.mSTstrBaseURL
+ imageURL, imageLocalPath);
bitmap = BitmapFactory
.decodeFile(imageLocalPath);
}
Thread.sleep(300);
publishProgress();
}
} catch (InterruptedException e) {
e.printStackTrace();
Log.w(LOG_TAG,
"Got InterruptedException inside AsyncTask SaveImageAsync : "
+ e);
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
ImageView imageView = imageViews.get(index);
while (imageView == null) {
index = index + 1;
imageView = imageViews.get(index);
}
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setImageBitmap(bitmap);
index = index + 1;
//bitmap.recycle();
}
public boolean getImageFromServer(String url, String localPath) {
boolean bReturn = false;
File objNewFile;
try {
objNewFile = new File(localPath);
if (!objNewFile.exists()) {
objNewFile.createNewFile();
}
BufferedInputStream objBufferedInput = new BufferedInputStream(
new java.net.URL(url).openStream());
FileOutputStream objFileOutput = new FileOutputStream(objNewFile);
BufferedOutputStream objBufferOutput = new BufferedOutputStream(
objFileOutput, 1024);
byte[] data = new byte[1024];
int x = 0;
while ((x = objBufferedInput.read(data, 0, 1024)) >= 0) {
objBufferOutput.write(data, 0, x);
}
objFileOutput.flush();
objBufferOutput.flush();
objFileOutput.close();
objBufferOutput.close();
objBufferedInput.close();
bReturn = true;
} catch (IOException e) {
} catch (Exception ex) {
}
return bReturn;
}
}
When pressing back button and loading this task it throws OutOfMemoryException at decodeFile(). Why this happen and how to fix this?
Thanks

Android 3.0 Honeycomb problem in parsing RSS feed

I am trying to parse rss feed in honeycomb 3.0 but it gives error as follows.
ERROR/AndroidNews::PullFeedParser(444): android.os.NetworkOnMainThreadException
I tried same code in android lower version it works but it doesn't work in Honeycomb.
Please suggest some help
This is in main activity
try{
FeedParser parser = new XmlPullFeedParser(feedUrl);
messages = parser.parse();
titles = new ArrayList<String>(messages.size());
String description ="";//= new ArrayList<String>(messages.size());
for (Message msg : messages){
description = msg.getDescription().toString();
Log.v("Desc", description);
titles.add(description);
}
} catch (Throwable t){
Log.e("AndroidNews",t.getMessage(),t);
}
I am using XmlPullFeedParser which extends BaseFeedParser
public class XmlPullFeedParser extends BaseFeedParser {
public XmlPullFeedParser(String feedUrl) {
super(feedUrl);
}
public List<Message> parse() {
List<Message> messages = null;
XmlPullParser parser = Xml.newPullParser();
try {
// auto-detect the encoding from the stream
parser.setInput(this.getInputStream(), null);
int eventType = parser.getEventType();
Message currentMessage = null;
boolean done = false;
while (eventType != XmlPullParser.END_DOCUMENT && !done){
String name = null;
switch (eventType){
case XmlPullParser.START_DOCUMENT:
messages = new ArrayList<Message>();
break;
case XmlPullParser.START_TAG:
name = parser.getName();
if (name.equalsIgnoreCase(ITEM)){
currentMessage = new Message();
} else if (currentMessage != null){
if (name.equalsIgnoreCase(LINK)){
currentMessage.setLink(parser.nextText());
} else if (name.equalsIgnoreCase(DESCRIPTION)){
currentMessage.setDescription(parser.nextText());
} else if (name.equalsIgnoreCase(PUB_DATE)){
currentMessage.setDate(parser.nextText());
} else if (name.equalsIgnoreCase(TITLE)){
currentMessage.setTitle(parser.nextText());
}
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
if (name.equalsIgnoreCase(ITEM) && currentMessage != null){
messages.add(currentMessage);
} else if (name.equalsIgnoreCase(CHANNEL)){
done = true;
}
break;
}
eventType = parser.next();
}
} catch (Exception e) {
Log.e("AndroidNews::PullFeedParser", e.getMessage(), e);
throw new RuntimeException(e);
}
return messages;
}
}
This is BaseFeedParser:
public class BaseFeedParser implements FeedParser {
// names of the XML tags
static final String CHANNEL = "channel";
static final String PUB_DATE = "pubDate";
static final String DESCRIPTION = "description";
static final String LINK = "link";
static final String TITLE = "title";
static final String ITEM = "item";
static final String BODY = "body";
private final URL feedUrl;
protected BaseFeedParser(String feedUrl){
try {
this.feedUrl = new URL(feedUrl);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
protected InputStream getInputStream() {
try {
return feedUrl.openConnection().getInputStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public List<Message> parse() {
// TODO Auto-generated method stub
return null;
}
}
This is FeedParser:
public interface FeedParser {
List<Message> parse();
}
This is message class:
public class Message implements Comparable<Message>{
static SimpleDateFormat FORMATTER =
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
private String title;
private URL link;
private String description;
private Date date;
private String body;
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
public void setTitle(String title) {
this.title = title.trim();
}
// getters and setters omitted for brevity
public URL getLink() {
return link;
}
public void setLink(String link) {
try {
this.link = new URL(link);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description.trim();
}
public String getDate() {
return FORMATTER.format(this.date);
}
public void setDate(String date) {
// pad the date if necessary
while (!date.endsWith("00")){
date += "0";
}
try {
this.date = FORMATTER.parse(date.trim());
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
public Message copy(){
Message copy = new Message();
copy.title = title;
copy.link = link;
copy.description = description;
copy.date = date;
copy.body = body;
return copy;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Title: ");
sb.append(title);
sb.append("Body: ");
sb.append(body);
sb.append('\n');
sb.append("Date: ");
sb.append(this.getDate());
sb.append('\n');
sb.append("Link: ");
sb.append(link);
sb.append('\n');
sb.append("Description: ");
sb.append(description);
return sb.toString();
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result
+ ((description == null) ? 0 : description.hashCode());
result = prime * result + ((link == null) ? 0 : link.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Message other = (Message) obj;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (link == null) {
if (other.link != null)
return false;
} else if (!link.equals(other.link))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title)){
return false;
} else if (!body.equals(other.body))
return false;
return true;
}
public int compareTo(Message another) {
if (another == null) return 1;
// sort descending, most recent first
return another.date.compareTo(date);
}
}
The error message here pretty much tells you what is going on -- you are trying to access the network on tthe main thread. You really shouldn't do that on any version of android, because it can (read: will) cause your UI to hang while the connection is processing.
There are ways to turn the error off, but I won't get into tthem: you shouodnt do it.
instead, you want to do this work in aa background thread and post a minimal handler back to the UI thread. I don't have an example handy (on my tablet now) but let me know if you cannot find one.
..edit..
OK, here's a simple example. This requires an activity with a text view (id "text") and, of course, INTERNET permissions. Let me know if you have any questions!
public class MainActivity extends Activity {
private TextView mTextView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.text);
// start our call in a new thread
(new Thread(new Runnable() {
#Override
public void run() {
fetchPage();
}
})).start();
}
private void fetchPage() {
try {
URL url = new URL("http://stackoverflow.com/feeds");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
bos.write(buffer, 0, len1);
}
bos.close();
is.close();
// Remember, all UI things must occur back on the UI thread!
final String text = bos.toString();
this.runOnUiThread(new Runnable() {
#Override
public void run() {
mTextView.setText(text);
}
});
} catch (final IOException ioe) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, ioe.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
thanks,
--randy

How to Build a RSS reader for Android?

I am new to android and i am trying to build a RSS reader for Android. I have built all the classes and XML files but its not giving the required output. Its just showing the message
No RSS feed available.
Please can some one suggest what should i do.
Here is the code which i took from the tutorial and tried to manipulate-
public final String RSSFEEDOFCHOICE = "http://blog.01synergy.com/feed/";
public final String tag = "RSSReader";
private RSSFeed feed = null;
/** Called when the activity is first created. */
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
// go get our feed!
feed = getFeed(RSSFEEDOFCHOICE);
// display UI
UpdateDisplay();
}
private RSSFeed getFeed(String urlToRssFeed)
{
try
{
// setup the url
URL url = new URL(urlToRssFeed);
// create the factory
SAXParserFactory factory = SAXParserFactory.newInstance();
// create a parser
SAXParser parser = factory.newSAXParser();
// create the reader (scanner)
XMLReader xmlreader = parser.getXMLReader();
// instantiate our handler
RSSHandler theRssHandler = new RSSHandler();
// assign our handler
xmlreader.setContentHandler(theRssHandler);
// get our data via the url class
InputSource is = new InputSource(url.openStream());
// perform the synchronous parse
xmlreader.parse(is);
// get the results - should be a fully populated RSSFeed instance, or null on error
return theRssHandler.getFeed();
}
catch (Exception ee)
{
// if we have a problem, simply return null
return null;
}
}
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
menu.add(0,0,0, "Choose RSS Feed");
menu.add(0,1,0, "Refresh");
Log.i(tag,"onCreateOptionsMenu");
return true;
}
public boolean onOptionsItemSelected(Menu item){
switch (((View) item).getId()) {
case 0:
Log.i(tag,"Set RSS Feed");
return true;
case 1:
Log.i(tag,"Refreshing RSS Feed");
return true;
}
return false;
}
private void UpdateDisplay()
{
TextView feedtitle = (TextView) findViewById(R.id.feedtitle);
TextView feedpubdate = (TextView) findViewById(R.id.feedpubdate);
ListView itemlist = (ListView) findViewById(R.id.itemlist);
if (feed == null)
{
feedtitle.setText("No RSS Feed Available");
return;
}
feedtitle.setText(feed.getTitle());
feedpubdate.setText(feed.getPubDate());
ArrayAdapter<RSSItem> adapter = new ArrayAdapter<RSSItem>(this,android.R.layout.simple_list_item_1,feed.getAllItems());
itemlist.setAdapter(adapter);
itemlist.setOnItemClickListener(this);
itemlist.setSelection(0);
}
public void onItemClick(AdapterView parent, View v, int position, long id)
{
Log.i(tag,"item clicked! [" + feed.getItem(position).getTitle() + "]");
Intent itemintent = new Intent(this,ShowDescription.class);
Bundle b = new Bundle();
b.putString("title", feed.getItem(position).getTitle());
b.putString("description", feed.getItem(position).getDescription());
b.putString("link", feed.getItem(position).getLink());
b.putString("pubdate", feed.getItem(position).getPubDate());
itemintent.putExtra("android.intent.extra.INTENT", b);
startSubActivity(itemintent,0);
}
private void startSubActivity(Intent itemintent, int i) {
// TODO Auto-generated method stub
}
}
This is my first approach to RSS Reader, It's no so dynamic and has boilerplate code but worked well for myself.
Usage:
RssParser parser = new RssParser(feedUrl);
Log.i("LOG", "Description: " + parser.getItem(3).description); //4th item's description
Class:
package com.uncocoder.course.app.feed_reader;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class RssParser extends DefaultHandler {
private StringBuilder content;
private boolean inChannel;
private boolean inImage;
private boolean inItem;
private ArrayList<Item> items = new ArrayList<Item>();
private Channel channel = new Channel();
private Item lastItem;
public RssParser(String url) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
URL sourceUrl = new URL(url);
xr.setContentHandler(this);
xr.parse(new InputSource(sourceUrl.openStream()));
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public class Item {
public String title;
public String description;
public String link;
public String category;
public String pubDate;
public String guid;
}
public class Channel {
public String title;
public String description;
public String link;
public String lastBuildDate;
public String generator;
public String imageUrl;
public String imageTitle;
public String imageLink;
public String imageWidth;
public String imageHeight;
public String imageDescription;
public String language;
public String copyright;
public String pubDate;
public String category;
public String ttl;
}
#Override
public void startDocument() throws SAXException {
Log.i("LOG", "StartDocument");
}
#Override
public void endDocument() throws SAXException {
Log.i("LOG", "EndDocument");
}
#Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if (localName.equalsIgnoreCase("image")) {
inImage = true;
}
if (localName.equalsIgnoreCase("channel")) {
inChannel = true;
}
if (localName.equalsIgnoreCase("item")) {
lastItem = new Item();
items.add(lastItem);
inItem = true;
}
content = new StringBuilder();
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equalsIgnoreCase("image")) {
inImage = false;
}
if (localName.equalsIgnoreCase("channel")) {
inChannel = false;
}
if (localName.equalsIgnoreCase("item")) {
inItem = false;
}
if (localName.equalsIgnoreCase("title")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.title = content.toString();
} else if (inImage) {
channel.imageTitle = content.toString();
} else if (inChannel) {
channel.title = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("description")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.description = content.toString();
} else if (inImage) {
channel.imageDescription = content.toString();
} else if (inChannel) {
channel.description = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("link")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.link = content.toString();
} else if (inImage) {
channel.imageLink = content.toString();
} else if (inChannel) {
channel.link = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("category")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.category = content.toString();
} else if (inChannel) {
channel.category = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("pubDate")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.pubDate = content.toString();
} else if (inChannel) {
channel.pubDate = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("guid")) {
if (content == null) {
return;
}
lastItem.guid = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("url")) {
if (content == null) {
return;
}
channel.imageUrl = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("width")) {
if (content == null) {
return;
}
channel.imageWidth = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("height")) {
if (content == null) {
return;
}
channel.imageHeight = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("language")) {
if (content == null) {
return;
}
channel.language = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("copyright")) {
if (content == null) {
return;
}
channel.copyright = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("ttl")) {
if (content == null) {
return;
}
channel.ttl = content.toString();
content = null;
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (content == null) {
return;
}
content.append(ch, start, length);
}
public Item getItem(int index) {
return items.get(index);
}
}
Check following link, It's open source RSS reader for Android, You can download code for reference
http://code.google.com/p/android-rss/
There is a tutorial (including complete source code) on how to build an Android RSS reder here:
part 1 (complete application)
part 2 (application updated to parse image tags from desciption)
part 3 (application update with Android 3.0)
The tutorial uses SAX parser and includes a complete Android project that accesses an RSS feed and then displays the feed in a list view.
There still seems to be a lot of people interested in this - so if you are looking for an Android 3.0+ with fragments/async tasks etc, as well as complete application code, I have updated the posts again, and they can be found here!
You can download and check my project on google-play.
This project is about some turkish sport channels feeds. Lots of channels are in one application.
You can check source code of project on github.
Parse this type of Rss Feeds easily using XmlPullParser
public class RSSParser {
public static ArrayList<Pojo> getParserData(String Data){
try {
RSSXMLTag currentTag = null;
ArrayList<Pojo> postDataList = new ArrayList<>();
XmlPullParserFactory factory = XmlPullParserFactory
.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(Data));
int eventType = xpp.getEventType();
Pojo pdData = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(
"EEEE, DD MMM yyyy ");
while (eventType != XmlPullParser.END_DOCUMENT) {
int i = 0;
if (eventType == XmlPullParser.START_DOCUMENT) {
} else if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equals("item")) {
pdData = new Pojo();
currentTag = RSSXMLTag.IGNORETAG;
} else if (xpp.getName().equals("title")) {
currentTag = RSSXMLTag.TITLE;
} else if (xpp.getName().equals("link")) {
currentTag = RSSXMLTag.LINK;
} else if (xpp.getName().equals("pubDate")) {
currentTag = RSSXMLTag.DATE;
} else if (xpp.getName().equals("creator")) {
currentTag = RSSXMLTag.CREATOR;
} else if (xpp.getName().equals("category")) {
currentTag = RSSXMLTag.CATEGORY;
} else if (xpp.getName().equals("description")) {
currentTag = RSSXMLTag.DESCRIPTION;
}
} else if (eventType == XmlPullParser.END_TAG) {
if (xpp.getName().equals("item")) {
// format the data here, otherwise format data in
// Adapter
Date postDate = dateFormat.parse(pdData.postDate);
pdData.postDate = dateFormat.format(postDate);
postDataList.add(pdData);
} else {
currentTag = RSSXMLTag.IGNORETAG;
}
} else if (eventType == XmlPullParser.TEXT) {
String content = xpp.getText();
content = content.trim();
Log.d("debug", content);
if (pdData != null) {
switch (currentTag) {
case TITLE:
if (content.length() != 0) {
if (pdData.postTitle != null) {
pdData.postTitle += content;
} else {
pdData.postTitle = content;
}
}
break;
case LINK:
if (content.length() != 0) {
if (pdData.postLink != null) {
pdData.postLink += content;
} else {
pdData.postLink = content;
}
}
break;
case DATE:
if (content.length() != 0) {
if (pdData.postDate != null) {
pdData.postDate += content;
} else {
pdData.postDate = content;
}
}
break;
case CATEGORY:
if (content.length() != 0) {
if (pdData.postCategory != null) {
i = i + 1;
if (i == 1) {
pdData.postCategory = content;
}
} else {
i = i + 1;
if (i == 1) {
pdData.postCategory = content;
}
}
}
break;
case DESCRIPTION:
if (content.length() != 0) {
if (pdData.postDescription != null) {
String s = content;
String string = s.substring(s.indexOf("src=\"") + 5, s.indexOf("\" class=\""));
pdData.postDescription += string;
} else {
String s = content;
String string = s.substring(s.indexOf("src=\"") + 5, s.indexOf("\" class=\""));
pdData.postDescription = string;
}
}
break;
case CREATOR:
if (content.length() != 0) {
if (pdData.postCreator != null) {
pdData.postCreator += content;
} else {
pdData.postCreator = content;
}
}
break;
default:
break;
}
}
}
eventType = xpp.next();
}
return postDataList;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public enum RSSXMLTag {
IGNORETAG, TITLE, LINK, DATE,CREATOR,CATEGORY, DESCRIPTION;
}
public class Pojo {
public String getPostTitle() {
return postTitle;
}
public void setPostTitle(String postTitle) {
this.postTitle = postTitle;
}
public String getPostLink() {
return postLink;
}
public void setPostLink(String postLink) {
this.postLink = postLink;
}
public String getPostDate() {
return postDate;
}
public void setPostDate(String postDate) {
this.postDate = postDate;
}
public String getPostCategory() {
return postCategory;
}
public void setPostCategory(String postCategory) {
this.postCategory = postCategory;
}
public String getPostDescription() {
return postDescription;
}
public void setPostDescription(String postDescription) {
this.postDescription = postDescription;
}
public String getPostCreator() {
return postCreator;
}
public void setPostCreator(String postCreator) {
this.postCreator = postCreator;
}
public String postTitle;
public String postLink;
public String postDate;
public String postCategory;
public String postDescription;
public String postCreator;
}
}

Categories

Resources