error when setting an onclick to a listview/json - java

I'm getting a json exception when I try to run my code.
The problem happens on the onclick listener. I'm trying to have the application go to the article of the rss feed on click
Here is the main activity
public class Blocku extends ListActivity {
private RssListAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<JSONObject> jobs = new ArrayList<JSONObject>();
try {
jobs = BlockuReader.getLatestRssFeed();
} catch (Exception e) {
Log.e("RSS ERROR", "Error loading RSS Feed Stream >> " + e.getMessage() + " //" + e.toString());
}
adapter = new RssListAdapter(this,jobs);
setListAdapter(adapter);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String link = null;
try {
String url = Article.getUrl().toString();
link = adapter.getItem(position).getString(url).toString();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(link));
startActivity(i);
} catch (JSONException e) {
Context context = getApplicationContext();
CharSequence text = "error";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
e.printStackTrace();
}
}
}
here is the adapter:
public class RssListAdapter extends ArrayAdapter<JSONObject> {
public RssListAdapter(Activity activity, List<JSONObject> imageAndTexts) {
super(activity, 0, imageAndTexts);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Activity activity = (Activity) getContext();
LayoutInflater inflater = activity.getLayoutInflater();
// Inflate the views from XML
View rowView = inflater.inflate(R.layout.image_text_layout, null);
JSONObject jsonImageText = getItem(position);
//////////////////////////////////////////////////////////////////////////////////////////////////////
//The next section we update at runtime the text - as provided by the JSON from our REST call
////////////////////////////////////////////////////////////////////////////////////////////////////
TextView textView = (TextView) rowView.findViewById(R.id.job_text);
try {
Spanned text = (Spanned)jsonImageText.get("text");
textView.setText(text);
} catch (JSONException e) {
textView.setText("JSON Exception");
}
return rowView;
}
}
and the article class
public class Article {
private long articleId;
private long feedId;
private String title;
private String description;
private String pubDate;
private static URL url;
private String encodedContent;
private static String link;
/**
* #return the articleId
*/
public long getArticleId() {
return articleId;
}
/**
* #param articleId the articleId to set
*/
public void setArticleId(long articleId) {
this.articleId = articleId;
}
/**
* #return the feedId
*/
public long getFeedId() {
return feedId;
}
/**
* #param feedId the feedId to set
*/
public void setFeedId(long feedId) {
this.feedId = feedId;
}
/**
* #return the title
*/
public String getTitle() {
return title;
}
/**
* #param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
/**
* #return the url
*/
public static URL getUrl() {
return url;
}
/**
* #param url the url to set
*/
public void setUrl(URL url) {
Article.url = url;
}
/**
* #param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* #return the description
*/
public String getDescription() {
return description;
}
/**
* #param pubDate the pubDate to set
*/
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
/**
* #return the pubDate
*/
public String getPubDate() {
return pubDate;
}
/**
* #param encodedContent the encodedContent to set
*/
public void setEncodedContent(String encodedContent) {
this.encodedContent = encodedContent;
}
/**
* #return the encodedContent
*/
public String getEncodedContent() {
return encodedContent;
}
}

JSONException is usually thrown when there are issues with parsing. Check how you are parsing the JSON. this says that you are trying to get a value for a key named "then it lists the site i want"

Related

Insert and Fetch Data from Microsoft Azure Using Android.Getting Error

I am working with Microsoft Azure Cloud Database, inserting data from Android Application.
i referred below mentioned link code,for insert and fetch data from azure using my android App. its Works fine.
Problem:
I have added two more columns in Azure database. I am not able to interact that columns using demo code.its little complicated for me.
Please help me,how to add few more columns in android code,Insert and Fetching data from cloud Database.
Link i referred
ToDoActivity.java
public class ToDoActivity extends Activity {
/**
* Mobile Service Client reference
*/
private MobileServiceClient mClient;
/**
* Mobile Service Table used to access data
*/
private MobileServiceTable<ToDoItem> mToDoTable;
//Offline Sync
/**
* Mobile Service Table used to access and Sync data
*/
//private MobileServiceSyncTable<ToDoItem> mToDoTable;
/**
* Adapter to sync the items list with the view
*/
private ToDoItemAdapter mAdapter;
/**
* EditText containing the "New To Do" text
*/
private EditText mTextNewToDo;
/**
* Progress spinner to use for table operations
*/
private ProgressBar mProgressBar;
/**
* Initializes the activity
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
mProgressBar = (ProgressBar) findViewById(R.id.loadingProgressBar);
// Initialize the progress bar
mProgressBar.setVisibility(ProgressBar.GONE);
try {
// Create the Mobile Service Client instance, using the provided
// Mobile Service URL and key
mClient = new MobileServiceClient(
"https://newapk.azure-mobile.net/",
"****************************",
this).withFilter(new ProgressFilter());
// Get the Mobile Service Table instance to use
mToDoTable = mClient.getTable(ToDoItem.class);
// Offline Sync
//mToDoTable = mClient.getSyncTable("ToDoItem", ToDoItem.class);
//Init local storage
initLocalStore().get();
mTextNewToDo = (EditText) findViewById(R.id.textNewToDo);
// Create an adapter to bind the items with the view
mAdapter = new ToDoItemAdapter(this, R.layout.row_list_to_do);
ListView listViewToDo = (ListView) findViewById(R.id.listViewToDo);
listViewToDo.setAdapter(mAdapter);
// Load the items from the Mobile Service
refreshItemsFromTable();
} catch (MalformedURLException e) {
createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
} catch (Exception e){
createAndShowDialog(e, "Error");
}
}
/**
* Initializes the activity menu
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/**
* Select an option from the menu
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_refresh) {
refreshItemsFromTable();
}
return true;
}
/**
* Mark an item as completed
*
* #param item
* The item to mark
*/
public void checkItem(final ToDoItem item) {
if (mClient == null) {
return;
}
// Set the item as completed and update it in the table
item.setComplete(true);
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
checkItemInTable(item);
runOnUiThread(new Runnable() {
#Override
public void run() {
if (item.isComplete()) {
mAdapter.remove(item);
}
}
});
} catch (final Exception e) {
createAndShowDialogFromTask(e, "Error");
}
return null;
}
};
runAsyncTask(task);
}
/**
* Mark an item as completed in the Mobile Service Table
*
* #param item
* The item to mark
*/
public void checkItemInTable(ToDoItem item) throws ExecutionException, InterruptedException {
mToDoTable.update(item).get();
}
/**
* Add a new item
*
* #param view
* The view that originated the call
*/
public void addItem(View view) {
if (mClient == null) {
return;
}
// Create a new item
final ToDoItem item = new ToDoItem();
item.setText(mTextNewToDo.getText().toString());
item.setComplete(false);
// Insert the new item
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
final ToDoItem entity = addItemInTable(item);
runOnUiThread(new Runnable() {
#Override
public void run() {
if(!entity.isComplete()){
mAdapter.add(entity);
}
}
});
} catch (final Exception e) {
createAndShowDialogFromTask(e, "Error");
}
return null;
}
};
runAsyncTask(task);
mTextNewToDo.setText("");
}
/**
* Add an item to the Mobile Service Table
*
* #param item
* The item to Add
*/
public ToDoItem addItemInTable(ToDoItem item) throws ExecutionException, InterruptedException {
ToDoItem entity = mToDoTable.insert(item).get();
return entity;
}
/**
* Refresh the list with the items in the Table
*/
private void refreshItemsFromTable() {
// Get the items that weren't marked as completed and add them in the
// adapter
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
final List<ToDoItem> results = refreshItemsFromMobileServiceTable();
//Offline Sync
//final List<ToDoItem> results = refreshItemsFromMobileServiceTableSyncTable();
runOnUiThread(new Runnable() {
#Override
public void run() {
mAdapter.clear();
for (ToDoItem item : results) {
mAdapter.add(item);
}
}
});
} catch (final Exception e){
createAndShowDialogFromTask(e, "Error");
}
return null;
}
};
runAsyncTask(task);
}
/**
* Refresh the list with the items in the Mobile Service Table
*/
private List<ToDoItem> refreshItemsFromMobileServiceTable() throws ExecutionException, InterruptedException {
return mToDoTable.where().field("complete").
eq(val(false)).execute().get();
}
//Offline Sync
/**
* Refresh the list with the items in the Mobile Service Sync Table
*/
/*private List<ToDoItem> refreshItemsFromMobileServiceTableSyncTable() throws ExecutionException, InterruptedException {
//sync the data
sync().get();
Query query = QueryOperations.field("complete").
eq(val(false));
return mToDoTable.read(query).get();
}*/
/**
* Initialize local storage
* #return
* #throws MobileServiceLocalStoreException
* #throws ExecutionException
* #throws InterruptedException
*/
private AsyncTask<Void, Void, Void> initLocalStore() throws MobileServiceLocalStoreException, ExecutionException, InterruptedException {
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
MobileServiceSyncContext syncContext = mClient.getSyncContext();
if (syncContext.isInitialized())
return null;
SQLiteLocalStore localStore = new SQLiteLocalStore(mClient.getContext(), "OfflineStore", null, 1);
Map<String, ColumnDataType> tableDefinition = new HashMap<String, ColumnDataType>();
tableDefinition.put("id", ColumnDataType.String);
tableDefinition.put("text", ColumnDataType.String);
tableDefinition.put("complete", ColumnDataType.Boolean);
localStore.defineTable("ToDoItem", tableDefinition);
SimpleSyncHandler handler = new SimpleSyncHandler();
syncContext.initialize(localStore, handler).get();
} catch (final Exception e) {
createAndShowDialogFromTask(e, "Error");
}
return null;
}
};
return runAsyncTask(task);
}
//Offline Sync
/**
* Sync the current context and the Mobile Service Sync Table
* #return
*/
/*
private AsyncTask<Void, Void, Void> sync() {
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
MobileServiceSyncContext syncContext = mClient.getSyncContext();
syncContext.push().get();
mToDoTable.pull(null).get();
} catch (final Exception e) {
createAndShowDialogFromTask(e, "Error");
}
return null;
}
};
return runAsyncTask(task);
}
*/
/**
* Creates a dialog and shows it
*
* #param exception
* The exception to show in the dialog
* #param title
* The dialog title
*/
private void createAndShowDialogFromTask(final Exception exception, String title) {
runOnUiThread(new Runnable() {
#Override
public void run() {
createAndShowDialog(exception, "Error");
}
});
}
/**
* Creates a dialog and shows it
*
* #param exception
* The exception to show in the dialog
* #param title
* The dialog title
*/
private void createAndShowDialog(Exception exception, String title) {
Throwable ex = exception;
if(exception.getCause() != null){
ex = exception.getCause();
}
createAndShowDialog(ex.getMessage(), title);
}
/**
* Creates a dialog and shows it
*
* #param message
* The dialog message
* #param title
* The dialog title
*/
private void createAndShowDialog(final String message, final String title) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message);
builder.setTitle(title);
builder.create().show();
}
/**
* Run an ASync task on the corresponding executor
* #param task
* #return
*/
private AsyncTask<Void, Void, Void> runAsyncTask(AsyncTask<Void, Void, Void> task) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
return task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
return task.execute();
}
}
private class ProgressFilter implements ServiceFilter {
#Override
public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilterCallback) {
final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create();
runOnUiThread(new Runnable() {
#Override
public void run() {
if (mProgressBar != null) mProgressBar.setVisibility(ProgressBar.VISIBLE);
}
});
ListenableFuture<ServiceFilterResponse> future = nextServiceFilterCallback.onNext(request);
Futures.addCallback(future, new FutureCallback<ServiceFilterResponse>() {
#Override
public void onFailure(Throwable e) {
resultFuture.setException(e);
}
#Override
public void onSuccess(ServiceFilterResponse response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (mProgressBar != null) mProgressBar.setVisibility(ProgressBar.GONE);
}
});
resultFuture.set(response);
}
});
return resultFuture;
}
}
}
ToDoItemAdapter.java
public class ToDoItemAdapter extends ArrayAdapter<ToDoItem> {
/**
* Adapter context
*/
Context mContext;
/**
* Adapter View layout
*/
int mLayoutResourceId;
public ToDoItemAdapter(Context context, int layoutResourceId) {
super(context, layoutResourceId);
mContext = context;
mLayoutResourceId = layoutResourceId;
}
/**
* Returns the view for a specific item on the list
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
final ToDoItem currentItem = getItem(position);
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(mLayoutResourceId, parent, false);
}
row.setTag(currentItem);
final CheckBox checkBox = (CheckBox) row.findViewById(R.id.checkToDoItem);
checkBox.setText(currentItem.getText());
checkBox.setChecked(false);
checkBox.setEnabled(true);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (checkBox.isChecked()) {
checkBox.setEnabled(false);
if (mContext instanceof ToDoActivity) {
ToDoActivity activity = (ToDoActivity) mContext;
activity.checkItem(currentItem);
}
}
}
});
return row;
}
}
ToDoItem.java
public class ToDoItem {
/**
* Item text
*/
#com.google.gson.annotations.SerializedName("text")
private String mText;
/**
* Item Id
*/
#com.google.gson.annotations.SerializedName("id")
private String mId;
/**
* Indicates if the item is completed
*/
#com.google.gson.annotations.SerializedName("complete")
private boolean mComplete;
/**
* ToDoItem constructor
*/
public ToDoItem() {
}
#Override
public String toString() {
return getText();
}
/**
* Initializes a new ToDoItem
*
* #param text
* The item text
* #param id
* The item id
*/
public ToDoItem(String text, String id) {
this.setText(text);
this.setId(id);
}
/**
* Returns the item text
*/
public String getText() {
return mText;
}
/**
* Sets the item text
*
* #param text
* text to set
*/
public final void setText(String text) {
mText = text;
}
/**
* Returns the item id
*/
public String getId() {
return mId;
}
/**
* Sets the item id
*
* #param id
* id to set
*/
public final void setId(String id) {
mId = id;
}
/**
* Indicates if the item is marked as completed
*/
public boolean isComplete() {
return mComplete;
}
/**
* Marks the item as completed or incompleted
*/
public void setComplete(boolean complete) {
mComplete = complete;
}
#Override
public boolean equals(Object o) {
return o instanceof ToDoItem && ((ToDoItem) o).mId == mId;
}
}
There are a documents https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-how-to-use-client-library/ that clearly explained how to use the android clinet library to interact with Azure Database for various operations.
I think you can refer to these sample in the document to write own code to implement your needs.
Any other concern, please feel free to let me know.
You have to make changes in your ToDoItem.java
It is the class which corresponds to the table in database.
whenever you make changes to the table in azure.
In ur case, when u are adding new columns to table in azure, say newcol1 and newcol2, You have to add
#com.google.gson.annotations.SerializedName("newcol1")
private boolean newColumnOne;
to your ToDoItem.java file. Only then u could have access to new columns in ToDoActivity.java
public void addItem(View view) {
if (mClient == null) {
return;
}
// Create a new item
final ToDoItem item = new ToDoItem();
item.setText(mTextNewToDo.getText().toString());
item.setComplete(false);
item.setNewColumnOne("dataabc");
item.setNewColumnTwo("dataxyz");
// Insert the new item
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
final ToDoItem entity = addItemInTable(item);
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!entity.isComplete()) {
mAdapter.add(entity);
}
}
});
} catch (final Exception e) {
createAndShowDialogFromTask(e, "Error 3rd");
}
return null;
}
};
runAsyncTask(task);
mTextNewToDo.setText("");
}
just add data through setNewColumnOne(); as i did.
rest of the code should be same.
P.S. dont forget to create getter setter and constructor for TodoItem.Java

From Json To ViewPager

I'm trying to pass data from a json file to a viewpager. I have followed most of the advice previously given to me here but it returns blank, without even crashing.
The four files involved in this:
1. The main fragment:
public class FashionFeed extends Fragment {
ViewPager viewPager;
PagerAdapter adapter;
ThePagerAdapter newdapter;
public static final String URL =
"http://celebirious.com/bey/data/space.json";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_whats_hot, null);
// Locate the ViewPager in viewpager_main.xml
viewPager = (ViewPager) v.findViewById(R.id.pager);
viewPager.setClipToPadding(false);
viewPager.setPadding(4, 0, 4, 0);
int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20 * 2, getResources().getDisplayMetrics());
viewPager.setPageMargin(-margin);
new SimpleTask().execute(URL);
return v;
}
private class SimpleTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// Create Show ProgressBar
}
protected String doInBackground(String... urls) {
String result = "";
try {
HttpGet httpGet = new HttpGet(urls[0]);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
InputStream inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader
(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
result += line;
}
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return result;
}
protected void onPostExecute(String jsonString) {
showData(jsonString);
}
}
private void showData(String jsonString) {
Gson gson = new Gson();
Style style = gson.fromJson(jsonString, Style.class);
List<Space> space = style.getSpace();
newdapter = new ThePagerAdapter(getActivity(), space);
viewPager.setAdapter(newdapter);
}
}
The Adapter extending the Pager:
public class ThePagerAdapter extends PagerAdapter {
List<Space> list;
LayoutInflater inflater;
Context context;
#Override
public int getCount() {
return list.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
public ThePagerAdapter(Context context,List<Space> list) {
this.list = list;
this.context = context; // red as well
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
// Declare Variables
TextView txtrank;
TextView txtcountry;
TextView txtpopulation;
ImageView imgflag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.styledeets, container,
false);
// Locate the TextViews in viewpager_item.xml
txtrank = (TextView) itemView.findViewById(R.id.date);
txtcountry = (TextView) itemView.findViewById(R.id.where);
txtpopulation = (TextView) itemView.findViewById(R.id.info);
// Capture position and set to the TextViews
txtrank.setText(list.get(position).getName());
txtcountry.setText(list.get(position).getDates());
txtpopulation.setText(list.get(position).getInfo());
String url = (list.get(position).getAvatarUrl());
imgflag = (ImageView) itemView.findViewById(R.id.photo);
Picasso.with(context)
.load(url)
.placeholder(R.mipmap.ic_launcher)
.error(R.drawable.ic_launcher_gmail)
.fit()
.tag(context)
.into(imgflag);
// Locate the ImageView in viewpager_item.xml
// Capture position and set to the ImageView
//imgflag.setImageResource(flag[position]);
// Add viewpager_item.xml to ViewPager
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((RelativeLayout) object);
}
}
Gson data retreived from jsonschema2pojo.org:
Space.java
public class Space {
#Expose
private String name;
#Expose
private String dates;
#Expose
private String type;
#Expose
private String social;
#Expose
private String info;
#SerializedName("avatar_url")
#Expose
private String avatarUrl;
/**
*
* #return
* The name
*/
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* #return
* The dates
*/
public String getDates() {
return dates;
}
/**
*
* #param dates
* The dates
*/
public void setDates(String dates) {
this.dates = dates;
}
/**
*
* #return
* The type
*/
public String getType() {
return type;
}
/**
*
* #param type
* The type
*/
public void setType(String type) {
this.type = type;
}
/**
*
* #return
* The social
*/
public String getSocial() {
return social;
}
/**
*
* #param social
* The social
*/
public void setSocial(String social) {
this.social = social;
}
/**
*
* #return
* The info
*/
public String getInfo() {
return info;
}
/**
*
* #param info
* The info
*/
public void setInfo(String info) {
this.info = info;
}
/**
*
* #return
* The avatarUrl
*/
public String getAvatarUrl() {
return avatarUrl;
}
/**
*
* #param avatarUrl
* The avatar_url
*/
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
Lastly, Style.java
public class Style {
#Expose
private List<Space> space = new ArrayList<Space>();
/**
*
* #return
* The space
*/
public List<Space> getSpace() {
return space;
}
/**
*
* #param space
* The space
*/
public void setSpace(List<Space> space) {
this.space = space;
}
}
All the xml data is properly linked 'cause this all works when it is retrieving data locally. What could be wrong?
I figured this out !!!!! How silly of me.
Was
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
should have been:
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}

Android: Exception Unmarshalling unknown type

I have to pass a ArrayList from one activity to another activity. So I use
intent.putParcelableArrayListExtra("Items",sendinglist);
And I get the sendinglist through
ArrayList<GeoItem> revd = new ArrayList<GeoItem>();
Bundle b = getIntent().getExtras();
if (b != null)
revd = b.getParcelableArrayList("Items");
Log.i("Element details",revd.get(0).getLatitude()+"");// Error
But i cant access the GeoItem object in that list.
UPDATE the class based on the answers...
My GeoItem class is
public class GeoItem implements Parcelable, Serializable {
/** id of item. */
protected long id_;
/** item location in GeoPoint. */
// protected GeoPoint location_;
/** selection state flag. true if selected. */
protected boolean isSelected_;
protected int latitude;
protected int longitude;
protected String incident_no;
protected String title;
protected String date;
protected String address;
/**
* #param id
* item id.
* #param latitudeE6
* latitude of the item in microdegrees (degrees * 1E6).
* #param longitudeE6
* longitude of the item in microdegrees (degrees * 1E6).
*/
public GeoItem(long id, int latitudeE6, int longitudeE6, String inc_no,
String tlt, String dates, String addr) {
id_ = id;
// location_ = new GeoPoint(latitudeE6, longitudeE6);
isSelected_ = false;
incident_no = inc_no;
title = tlt;
date = dates;
address = addr;
latitude=latitudeE6;
longitude=longitudeE6;
}
public long getId_() {
return id_;
}
public void setId_(long id_) {
this.id_ = id_;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public void setIncident_no(String incident_no) {
this.incident_no = incident_no;
}
public int getLatitude() {
return latitude;
}
public void setLatitude(int latitude) {
this.latitude = latitude;
}
public int getLongitude() {
return longitude;
}
public void setLongitude(int longitude) {
this.longitude = longitude;
}
/**
* #param src
* source GeoItem
*/
public GeoItem(GeoItem src) {
id_ = src.id_;
// location_ = new
// GeoPoint(src.location_.getLatitudeE6(),src.location_.getLongitudeE6());
isSelected_ = src.isSelected_;
}
/**
* #param src
* source Parcel
*/
public GeoItem(Parcel src) {
id_ = src.readLong();
// location_ = new GeoPoint(src.readInt(), src.readInt());
isSelected_ = src.readInt() == 0 ? false : true;
address = src.readString();
date = src.readString();
}
/* describeContents */
public int describeContents() {
return 0;
}
/**
* getId
*
* #return id of the item.
*/
public long getId() {
return id_;
}
public String getIncident_no() {
return incident_no;
}
/**
* setId
*
* #param id
* of the item.
*/
public void setId(long id) {
id_ = id;
;
}
/**
* getLocation
*
* #return GeoPoint of the item.
*
* public GeoPoint getLocation() { return location_; }
*/
/**
* isSelected
*
* #return true if the item is in selected state.
*/
public boolean isSelected() {
return isSelected_;
}
/**
* setSelect
*
* #param flg
* flag to be set.
*/
public void setSelect(boolean flg) {
isSelected_ = flg;
}
/**
* Parcelable.Creator
*/
public static final Parcelable.Creator<GeoItem> CREATOR = new Parcelable.Creator<GeoItem>() {
public GeoItem createFromParcel(Parcel in) {
return new GeoItem(in);
}
public GeoItem[] newArray(int size) {
return new GeoItem[size];
}
};
/**
* writeToParcel
*
* #param parcel
* Parcel to be written.
* #param flags
* flag.
*/
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeLong(id_);
parcel.writeString(address);
parcel.writeString(date);
parcel.writeInt(latitude);
parcel.writeInt(longitude);
int flg = isSelected_ ? 1 : 0;
parcel.writeInt(flg);
}
}
Please provide me the best way...
GeoPoint is not a Parceable therefore it can be marshalled. You may want to save the data somehow without GeoPoint or extend GeoPoint so it implements Parceable
**To pass an arraylist of Category to another activity,**
intent i = new Intent(_av.getContext(), ItemList.class);
Bundle b = new Bundle();
b.putParcelableArrayList("categories", categories);
b.putInt("index", _index);
i.putExtras(b);
startActivityForResult(i, ITEM_LIST);
**To retrieve the data,**
Bundle b = this.getIntent().getExtras();
ArrayList<Category> cats = b.getParcelableArrayList("categories");
int index = b.getInt("index");
My actual task is to send the list of GeoItems object through intent. Also My GeoItems class is serializable . Obviously list of serializable object is also serialibale So I used,
Intent listview = new Intent(context, ReportList.class);
Bundle send = new Bundle();
send.putSerializable("Items", (Serializable) items);
listview.putExtras(send);
context.startActivity(listview);
where items is a list of GeoIems objects
And in receiving activity,
Bundle b = this.getIntent().getExtras();
if (b != null) {
data = (List<GeoItem>) b.getSerializable("Items");
}
where data is a list of GeoIems objects
Without using Parceable interface, now i can set my list of serializable objects through intent to next activity

how to onclick for jsonobject/listview feed item?

I'm trying to follow this tutorial http://automateddeveloper.blogspot.com/2011/05/android-rss-reader-20.html
I'm using eclipse and developing for android 2.0
here is the problem
*I cant figure out how to set an onclick listener or something similar to each article
*I'm trying to make it go to the website the article is from onclick
public class Utezone extends ListActivity {
private RssListAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<JSONObject> jobs = new ArrayList<JSONObject>();
try {
jobs = RssReader.getLatestRssFeed();
} catch (Exception e) {
Log.e("RSS ERROR", "Error loading RSS Feed Stream >> " + e.getMessage() + " //" + e.toString());
}
adapter = new RssListAdapter(this,jobs);
setListAdapter(adapter);
}
}
public class RssListAdapter extends ArrayAdapter<JSONObject> {
public RssListAdapter(Activity activity, List<JSONObject> imageAndTexts) {
super(activity, 0, imageAndTexts);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Activity activity = (Activity) getContext();
LayoutInflater inflater = activity.getLayoutInflater();
// Inflate the views from XML
View rowView = inflater.inflate(R.layout.image_text_layout, null);
JSONObject jsonImageText = getItem(position);
//////////////////////////////////////////////////////////////////////////////////////////////////////
//The next section we update at runtime the text - as provided by the JSON from our REST call
////////////////////////////////////////////////////////////////////////////////////////////////////
TextView textView = (TextView) rowView.findViewById(R.id.job_text);
try {
Spanned text = (Spanned)jsonImageText.get("text");
textView.setText(text);
} catch (JSONException e) {
textView.setText("JSON Exception");
}
return rowView;
}
}
public class RssReader {
private final static String BOLD_OPEN = "<B>";
private final static String BOLD_CLOSE = "</B>";
private final static String BREAK = "<BR>";
private final static String ITALIC_OPEN = "<I>";
private final static String ITALIC_CLOSE = "</I>";
private final static String SMALL_OPEN = "<SMALL>";
private final static String SMALL_CLOSE = "</SMALL>";
/**
* This method defines a feed URL and then calles our SAX Handler to read the article list
* from the stream
*
* #return List<JSONObject> - suitable for the List View activity
*/
public static List<JSONObject> getLatestRssFeed(){
String feed = "thefeedurl";
RSSHandler rh = new RSSHandler();
List<Article> articles = rh.getLatestArticles(feed);
Log.e("RSS ERROR", "Number of articles " + articles.size());
return fillData(articles);
}
/**
* This method takes a list of Article objects and converts them in to the
* correct JSON format so the info can be processed by our list view
*
* #param articles - list<Article>
* #return List<JSONObject> - suitable for the List View activity
*/
private static List<JSONObject> fillData(List<Article> articles) {
List<JSONObject> items = new ArrayList<JSONObject>();
for (Article article : articles) {
JSONObject current = new JSONObject();
try {
buildJsonObject(article, current);
} catch (JSONException e) {
Log.e("RSS ERROR", "Error creating JSON Object from RSS feed");
}
items.add(current);
}
return items;
}
/**
* This method takes a single Article Object and converts it in to a single JSON object
* including some additional HTML formating so they can be displayed nicely
*
* #param article
* #param current
* #throws JSONException
*/
private static void buildJsonObject(Article article, JSONObject current) throws JSONException {
String title = article.getTitle();
String description = article.getDescription();
String date = article.getPubDate();
StringBuffer sb = new StringBuffer();
sb.append(BOLD_OPEN).append(title).append(BOLD_CLOSE);
sb.append(BREAK);
sb.append(description);
sb.append(BREAK);
sb.append(SMALL_OPEN).append(ITALIC_OPEN).append(date).append(ITALIC_CLOSE).append(SMALL_CLOSE);
current.put("text", Html.fromHtml(sb.toString()));
}
}
Since the activity extends ListActivity you can simply do:
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//do something
}
A onclicklistener is bound to a listview. call getListView() and set it to a ListView ivar. On that ivar implement an OnItemClickListener by calling the method setOnItemClickListener();
ListView lw = getListView();
lw.setOnItemClickListener(new OnItemClickListener({
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {}
}));

Isolating a link in RSS Feed

I am new to programming so please go easy on me, I have been messing around with a simple RSS Reader, trying to get the link to the artice to open in a webview when the user clicks on the article.
I have found the string that controls and stores the link but when I try to print the link in the toast the link appears but with the whole article publishing date ect... how can I get the link to print on it own and what commands do I need to use to pass the link to the webview once I have isolated it, here is some of the code I have
RSSActivity
public class RssActivity extends ListActivity {
private RssListAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<JSONObject> jobs = new ArrayList<JSONObject>();
try {
jobs = RssReader.getLatestRssFeed();
} catch (Exception e) {
Log.e("RSS ERROR", "Error loading RSS Feed Stream >> " + e.getMessage() + " //" + e.toString());
}
adapter = new RssListAdapter(this,jobs);
setListAdapter(adapter);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
Object o = this.getListAdapter().getItem(position);
adapter.getItem(position).toString();
String link = o.toString();
Toast.makeText(this, "You selected: " + link, Toast.LENGTH_LONG)
.show();
}
}
Article.class
public class Article {
private long articleId;
private long feedId;
private String title;
private String description;
private String pubDate;
private URL url;
private String encodedContent;
private String link;
public void setArticleId(long articleId) {
this.articleId = articleId;
}
/**
* #return the feedId
*/
public long getFeedId() {
return feedId;
}
/**
* #param feedId the feedId to set
*/
public void setFeedId(long feedId) {
this.feedId = feedId;
}
public String getLink() {
return link;
}
/**
* #param title the title to set
*/
public void setLink(String link) {
this.link = link;
}
/**
* #return the title
*/
public String getTitle() {
return title;
}
/**
* #param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
/**
* #return the url
*/
public URL getUrl() {
return url;
}
/**
* #param url the url to set
*/
public void setUrl(URL url) {
this.url = url;
}
/**
* #param description the description to set
*/
public void setDescription(String description) {
this.description = description;
//parse description for any image or video links
if (description.contains("<img ")){
String img = description.substring(description.indexOf("<img "));
String cleanUp = img.substring(0, img.indexOf(">")+1);
int indexOf = img.indexOf("'");
if (indexOf==-1){
}
this.description = this.description.replace(cleanUp, "");
}
}
/**
* #return the description
*/
public String getDescription() {
return description;
}
/**
* #param pubDate the pubDate to set
*/
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
/**
* #return the pubDate
*/
public String getPubDate() {
return pubDate;
}
/**
* #param encodedContent the encodedContent to set
*/
public void setEncodedContent(String encodedContent) {
this.encodedContent = encodedContent;
}
/**
* #return the encodedContent
*/
public String getEncodedContent() {
return encodedContent;
}
}
RSS Handler
public class RSSHandler extends DefaultHandler {
// Feed and Article objects to use for temporary storage
private Article currentArticle = new Article();
private List<Article> articleList = new ArrayList<Article>();
// Number of articles added so far
private int articlesAdded = 0;
// Number of articles to download
private static final int ARTICLES_LIMIT = 15;
//Current characters being accumulated
StringBuffer chars = new StringBuffer();
public void startElement(String uri, String localName, String qName, Attributes atts) {
chars = new StringBuffer();
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equalsIgnoreCase("title"))
{
Log.d("LOGGING RSS XML", "Setting article title: " + chars.toString());
currentArticle.setTitle(chars.toString());
}
else if (localName.equalsIgnoreCase("description"))
{
Log.d("LOGGING RSS XML", "Setting article description: " + chars.toString());
currentArticle.setDescription(chars.toString());
}
else if (localName.equalsIgnoreCase("pubDate"))
{
Log.d("LOGGING RSS XML", "Setting article published date: " + chars.toString());
currentArticle.setPubDate(chars.toString());
}
else if (localName.equalsIgnoreCase("encoded"))
{
Log.d("LOGGING RSS XML", "Setting article content: " + chars.toString());
currentArticle.setEncodedContent(chars.toString());
}
else if (localName.equalsIgnoreCase("item"))
{
}
else if (localName.equalsIgnoreCase("link"))
{
Log.d("LOGGING RSS XML", "Setting article link: " + chars.toString());
currentArticle.setLink(chars.toString());
try {
Log.d("LOGGING RSS XML", "Setting article link url: " + chars.toString());
currentArticle.setUrl(new URL(chars.toString()));
} catch (MalformedURLException e) {
Log.e("RSA Error", e.getMessage());
}
}
// Check if looking for article, and if article is complete
if (localName.equalsIgnoreCase("item")) {
articleList.add(currentArticle);
currentArticle = new Article();
// Lets check if we've hit our limit on number of articles
articlesAdded++;
if (articlesAdded >= ARTICLES_LIMIT)
{
throw new SAXException();
}
}
}
public void characters(char ch[], int start, int length) {
chars.append(new String(ch, start, length));
}
public List<Article> getLatestArticles(String feedUrl) {
URL url = null;
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
url = new URL(feedUrl);
xr.setContentHandler(this);
xr.parse(new InputSource(url.openStream()));
} catch (IOException e) {
Log.e("RSS Handler IO", e.getMessage() + " >> " + e.toString());
} catch (SAXException e) {
Log.e("RSS Handler SAX", e.toString());
} catch (ParserConfigurationException e) {
Log.e("RSS Handler Parser Config", e.toString());
}
return articleList;
}
}
public class RssReader {
private final static String BOLD_OPEN = "<B>";
private final static String BOLD_CLOSE = "</B>";
private final static String BREAK = "<BR>";
private final static String ITALIC_OPEN = "<I>";
private final static String ITALIC_CLOSE = "</I>";
private final static String SMALL_OPEN = "<SMALL>";
private final static String SMALL_CLOSE = "</SMALL>";
private final static String WEB_LINK = "<A>";
private final static String WEB_CLOSE = "<A/";
public static List<JSONObject> getLatestRssFeed(){
String feed = "http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/eng_prem/rss.xml";
RSSHandler rh = new RSSHandler();
List<Article> articles = rh.getLatestArticles(feed);
Log.e("RSS ERROR", "Number of articles " + articles.size());
return fillData(articles);
}
private static List<JSONObject> fillData(List<Article> articles) {
List<JSONObject> items = new ArrayList<JSONObject>();
for (Article article : articles) {
JSONObject current = new JSONObject();
try {
buildJsonObject(article, current);
} catch (JSONException e) {
Log.e("RSS ERROR", "Error creating JSON Object from RSS feed");
}
items.add(current);
}
return items;
}
private static void buildJsonObject(Article article, JSONObject current) throws JSONException {
String link = article.getLink();
String title = article.getTitle();
String description = article.getDescription();
String date = article.getPubDate();
StringBuffer sb = new StringBuffer();
sb.append(BOLD_OPEN).append(title).append(BOLD_CLOSE);
sb.append(BREAK);
sb.append(description);
sb.append(BREAK);
sb.append(SMALL_OPEN).append(ITALIC_OPEN).append(date).append(ITALIC_CLOSE).append(SMALL_CLOSE);
sb.append(BREAK);
sb.append(BREAK);
sb.append(BOLD_OPEN).append(WEB_LINK).append(link).append(BOLD_CLOSE).append(WEB_CLOSE);
current.put("link", link);
current.put("text", Html.fromHtml(sb.toString()));
}
}
RssListAdapter
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class RssListAdapter extends ArrayAdapter<JSONObject> {
public RssListAdapter(Activity activity, List<JSONObject> imageAndTexts) {
super(activity, 0, imageAndTexts);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Activity activity = (Activity) getContext();
LayoutInflater inflater = activity.getLayoutInflater();
// Inflate the views from XML
View rowView = inflater.inflate(R.layout.image_text_layout, null);
JSONObject jsonImageText = getItem(position);
//////////////////////////////////////////////////////////////////////////////////////////////////////
//The next section we update at runtime the text - as provided by the JSON from our REST call
////////////////////////////////////////////////////////////////////////////////////////////////////
TextView textView = (TextView) rowView.findViewById(R.id.job_text);
try {
Spanned text = (Spanned)jsonImageText.get("text");
textView.setText(text);
} catch (JSONException e) {
textView.setText("JSON Exception");
}
return rowView;
}
}
Open URL in default browser
Open URL with Android
If you have the URL or URI object at one point, probably one of the explanations in the links above will get you on your way.
--
Edit:
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
Object o = this.getListAdapter().getItem(position);
adapter.getItem(position).toString();
String link = o.toString();
Toast.makeText(this, "You selected: " + link, Toast.LENGTH_LONG)
.show();
}
Guessing this is the code to show the link but if you don't supply us what the getListAdapter() method etc do then I'm afraid it's hard to help you out.
Try this
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
JSONObject o = (JSONObject) this.getListAdapter().getItem(position);
adapter.getItem(position).toString();
String link = o.getString("NameOfLinkInJsonObject");
Toast.makeText(this, "You selected: " + link, Toast.LENGTH_LONG)
.show();
mMyWebView.loadUrl(link);
}
Be aware that you need to fix "NameOfLinkInJsonObject".
In your activity add a field like so
private WebView mMyWebView;
In your onCreate method add a
mMyWebView = (WebView) findViewById(R.id.webViewId);
You will have to change the R.id.webViewId to the appropriate id for your web view.

Categories

Resources