How to use textview as a html page? - android

So I have an Asynctask class with this codes and I just want to change the view of contents from text to html
private class JSONP extends AsyncTask<String, String, JSONObject>{
#Override
protected void onPreExecute() {
super.onPreExecute();
title=(TextView)findViewById(R.id.textView2);
content=(TextView)findViewById(R.id.txtcontent);
}
#Override
protected JSONObject doInBackground(String... arg0) {
JSONParser jp = new JSONParser();
JSONObject tempjo = jp.getjsonfromurl(url);
return tempjo;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
try {
news = result.getJSONArray(Tag_posts);
for(int i = 0;i<news.length();i++){
JSONObject c = news.getJSONObject(i);
String titles = c.getString(Tag_title);
String contents = c.getString(Tag_content);
HashMap<String, String> map = new HashMap<String, String>();
map.put(Tag_title, titles);
map.put(Tag_content, contents);
newslist.add(map);
ListAdapter list = new SimpleAdapter(MainActivity.this,
newslist,
R.layout.listv,
new String[] {Tag_title,Tag_content},
new int[]{R.id.textView2, R.id.txtcontent});
mylist.setAdapter(list);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
i know the method must be something like
textView.setText(Html.fromHtml(contents));
but i just don't know where to put this code? make another class or directly use it in my asynctask class

Related

feed xml to json using googleapi

I am using google api to convert feed xml to json, but when I use it on my android app it says that "03-10 22:32:08.045: E/log_tag(1456): Error parsing data org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject", this is part of my code where I am converting xml into json, can somebody help me? Thanks.
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(NoticiasMia.this);
// Set progressdialog title
//mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Actualizando...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&q=myfeedurl");
try {
// Locate the array name in JSON
if(jsonobject == null)
return null;
JSONObject subObjuno = jsonobject.getJSONObject("responseData");
JSONObject subObjdos = subObjuno.getJSONObject("feed");
jsonarray = subObjdos.getJSONArray("entries");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobjecttres = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("title", jsonobjecttres.getString("title"));
map.put("link", jsonobjecttres.getString("link"));
map.put("publishedDate", jsonobjecttres.getString("publishedDate"));
map.put("contentSnippet", jsonobjecttres.getString("contentSnippet"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
if(arraylist == null || arraylist.size() == 0){
new DownloadJSON().execute();
mProgressDialog.dismiss();
return;
}
// Locate the listview in listview_main.xml
listview = (ListView) NoticiasMia.this.findViewById(R.id.lista_faltas_cometidas);
// Pass the results into ListViewAdapter.java
adapter = new LazyAdapterNoticiasMias(NoticiasMia.this, arraylist, "fonts/Roboto-Thin.ttf", "fonts/Roboto-Medium.ttf");
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}

Old listview data will be clear and reset again new data when getdata button is clicked again in android

I'm fresher to android. I created android ListView using JSON WebService. I want old ListView data to be clear and reset again new data when getdata button is clicked again . Help me, thanks in advance.
setContentView(R.layout.activity_main);
CargoTracklist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.button1);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Status = (TextView)findViewById(R.id.textView2);
Id= (TextView)findViewById(R.id.textView1);
DateTime = (TextView)findViewById(R.id.textView3);
JobNo =(EditText)findViewById(R.id.editText1);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.clear();
params.add(new BasicNameValuePair("JobNo",JobNo.getText().toString()));
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url,params);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
if (JobNo.getText().toString().equals(""))
{
Toast.makeText(MainActivity.this, "You did not enter a JobNo", Toast.LENGTH_SHORT).show();
}
else {
// Getting JSON Array from URL
Cargo = json.getJSONArray(TAG_CargoTrack);
for(int i = 0; i < Cargo.length(); i++){
JSONObject c = Cargo.getJSONObject(i);
// Storing JSON item in a Variable
String Status = c.getString(TAG_Status);
String Id = c.getString(TAG_Id);
String DateTime = c.getString(TAG_DateTime); HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_Status, Status);
map.put(TAG_Id, Id);
map.put(TAG_DateTime, DateTime);
CargoTracklist.add(map);
list=(ListView)findViewById(R.id.listView1);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, CargoTracklist,
R.layout.listview,
new String[] { TAG_Status,TAG_Id, TAG_DateTime }, new int[] {
R.id.textView2,R.id.textView1, R.id.textView3});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+CargoTracklist.get(+position).get("Id"), Toast.LENGTH_SHORT).show();
}
});
Whenever you want to update your list clear the old data by
if(CargoTracklist != null){
CargoTracklist.clear();
// Add new Data to CargoTracklist
CargoTracklist.add("new data");
if(adapter != null){
adapter.notifyDataChaned();
}
}

How to execute Asynctask simultaneously

I have two asynctask in one class and i am having trouble in executing them at the same time.
Here is my scenario, my the user clicks the view january calendar button it will show up the events for the month of calendar and the comments for it. The events and comments are stored in mysql database so i have to fetch different url. I used asyctask to fetch the url. Whenever i call the other asynctask it cannot be resolved. help me out!
Here is my code:
package sscr.stag;
#SuppressLint("ShowToast")
public class Calendar extends ListActivity {
// All xml labels
TextView txtEvent;
// Progress Dialog
private ProgressDialog pDialog;
JSONArray user;
JSONObject hay;
private static final String CALENDAR_URL = "http://www.stagconnect.com/StagConnect/calendar/januaryCalendar.php";
private static final String COMMENT_URL = "http://www.stagconnect.com/StagConnect/calendar/januaryReadComment.php";
private static final String TAG_USER = "username";
private static final String TAG_MESSAGE = "message";
private static final String TAG_TIME = "time";
private static final String TAG_ARRAY = "posts";
private JSONArray mCalendar = null;
private ArrayList<HashMap<String, String>> mCommentList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendaradmin);
txtEvent = (TextView) findViewById(R.id.event);
new LoadCalendar().execute();
new LoadCommentCal().execute(); // error here, says cannot be resolved in this type
}
private class LoadCalendar extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Calendar.this);
pDialog.setMessage("Loading Calendar.. ");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
String json = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(CALENDAR_URL);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
json = EntityUtils.toString(resEntity);
Log.i("Profile JSON: ", json.toString());
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
pDialog.dismiss();
try
{
hay = new JSONObject(json);
JSONArray user = hay.getJSONArray("posts");
JSONObject jb= user.getJSONObject(0);
String event = jb.getString("activities");
txtEvent.setText(event);
}catch(Exception e)
{
e.printStackTrace();
}
}
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(COMMENT_URL);
try {
mCalendar = json.getJSONArray(TAG_ARRAY);
for (int i = 0; i < mCalendar.length(); i++) {
JSONObject c = mCalendar.getJSONObject(i);
String username = c.getString(TAG_USER);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_USER, username);
mCommentList.add(0, map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateList() {
ListAdapter adapter = new SimpleAdapter(Calendar.this, mCommentList,
R.layout.calendar_comment, new String[] { TAG_MESSAGE,
TAG_USER, TAG_TIME }, new int[] { R.id.message,
R.id.username, R.id.time });
setListAdapter(adapter);
ListView lv = getListView();
lv.scrollTo(0, 0);
}
public class LoadCommentCal extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Calendar.this);
pDialog.setMessage("Loading Comments...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(Void... args) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
}
Your second asynctask public class LoadCommentCal extends AsyncTask is inside the first asynctask!
You need to move it out of the first asynctask.
private class LoadCalendar extends AsyncTask<String, String, String> {
...
}
... other functions
private class LoadCommentCal extends AsyncTask<Void, Void, String> {
...
}
You are declaring lots of things inside the first AsyncTask I strongly reccomend to close your AsyncTask after the onPostExecute
#Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
pDialog.dismiss();
try
{
hay = new JSONObject(json);
JSONArray user = hay.getJSONArray("posts");
JSONObject jb= user.getJSONObject(0);
String event = jb.getString("activities");
txtEvent.setText(event);
}catch(Exception e)
{
e.printStackTrace();
}
}
}
and then removing one } at the end of the java file (and also reindent if you wish)

Fixed Tab + Swipe with ListView

I'm doing an app that has mutiple tab and for each tab has its own activity. after putting the code to load the list on one activity; still listview is not visible at all.
here is my code, somebody please help:
public class BillsActivity extends ListActivity {
private ProgressDialog pDialog;
String mUrl = BayadCenterConstants.BAYAD_URL_BILLERS;
JSONParsers jsonParser = new JSONParsers();
ArrayList<HashMap<String, String>> billerList;
JSONArray billers = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_child_bills);
/*
* Check network connection here
*/
billerList = new ArrayList<HashMap<String, String>>();
new LoadBillers().execute();
}
class LoadBillers extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(BillsActivity.this);
pDialog.setMessage("Downlaoding list ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
String json = jsonParser.getBillers(mUrl, params);
Log.d("Billers JSON: ", "> " + json);
try {
billers = new JSONArray(json);
if (billers != null) {
for (int i = 0; i < billers.length(); i++) {
JSONObject c = billers.getJSONObject(i);
String id = c.getString("bid");
String name = c.getString("name");
String status = c.getString("status");
String date_added = c.getString("date_added");
HashMap<String, String> map = new HashMap<String, String>();
map.put("bid", id);
map.put("name", name);
map.put("status", status);
map.put("date_added", date_added);
billerList.add(map);
}
}else{
Log.d("Billers: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
BillsActivity.this, billerList,
R.layout.tab_child_bills_list_row, new String[] { "bid", "name", "status",
"date_added" }, new int[] { R.id.txtBillerID, R.id.txtBillerName,
R.id.txtBillerStatus, R.id.txtBillerDateAdded });
setListAdapter(adapter);
}
});
}
}
this activity is just part of an activity that holds then in tab+swipe manner.
did i miss something with my code?

unable to display image in listview

I am unable to display images but the text is displayed.
I have modified the code from http://mobile.dzone.com/news/android-tutorial-how-parse to the code below.
I would prefer using SimpleAdapter only .Is it possible? As I have implemented the same code as below everywhere.
Or little modifications to the below code would be fine.
How do I display images?
public class MainActivity extends ListActivity {
ArrayList<HashMap<String, String>> mylist;
SimpleAdapter adapter;
ProgressDialog pd ;
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
mylist = new ArrayList<HashMap<String, String>>();
new loadingDisplayClass().execute();
}
public class loadingDisplayClass extends AsyncTask<String, Integer, String> {
protected void onPreExecute() {
pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Loading......");
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String url = "https://itunes.apple.com/us/rss/topalbums/limit=50/json";
JSONObject json = JSONfunctions.getJSONfromURL(url);
try {
JSONObject arr2 = json.getJSONObject("feed");
JSONArray arr = arr2.getJSONArray("entry");
for (int i = 0; i < arr.length(); i++) {
JSONObject e1 = arr.getJSONObject(i);
JSONArray jsar = e1.getJSONArray("im:image");
JSONObject jsname = e1.getJSONObject("im:name");
String name = jsname.getString("label");
JSONObject jso = e1.getJSONObject("im:artist");
String lbl = jso.getString("label");
JSONObject e12 = jsar.getJSONObject(0);
String icon = e12.getString("label");
HashMap<String, String> hashmapnew = new HashMap<String, String>();
hashmapnew.put("icons", icon);
hashmapnew.put("name", name);
hashmapnew.put("artist", lbl);
mylist.add(hashmapnew);
publishProgress(((int) ((i + 1 / (float) arr.length()) * 100)));
}
} catch (JSONException e) {
Toast.makeText(getBaseContext(),
"Network communication error!", 5).show();
}
adapter = new SimpleAdapter(getBaseContext(), mylist,
R.layout.list, new String[] {
"icons","name","artist" },
new int[] { R.id.image,R.id.name,R.id.artist });
return null;
}
protected void onProgressUpdate(Integer... integers) {
pd.incrementProgressBy(integers[0]);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
setListAdapter(adapter);
pd.dismiss();
lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
}
});
}
}
}
I am unable to display images but the text is displayed
Images won't display because you are just passing url to the SimpleAdapter.In order to show images you need to first download the images in the url returned above service .
You need to create a custom Adapter and display images by downloading them
Downloading each image and displaying image in imageView takes lot time and as the listview recycle views your images will always download when the list is scrolled. So what you need to do is to use -Universal-Image-Loader or Lazy List to provide automatic downloading and caching images.

Categories

Resources