im trying to parse url generated by Bootstrap`s Bootpage.js which looks like
https://example.com/#page-2
but JSOUP cant parse it and showing main url.
how to get normal link from Bootpage or how to make JSOUP to parse it.
Parsing code:
Jsoup.connect("https://example.com/#page-2").followRedirects(true).get();
(See UPDATE below, first/accepted solution didn't met the android requirement, but is left for reference.)
Desktop Solution
HtmlUnit doesn't seem able to handle this site (often the case, lately). So I don't have a plain java solution either, but you could use PhantomJS: download the binary for your os, create a script file, start the process from within your java code and parse the output with a dom parser like jsoup.
Script file (here called simple.js):
var page = require('webpage').create();
var fs = require('fs');
var system = require('system');
var url = "";
var fileName = "output";
// first parameter: url
// second parameter: filename for output
console.log("args length: " + system.args.length);
if (system.args.length > 1) {
url=system.args[1];
}
if (system.args.length > 2){
fileName=system.args[2];
}
if(url===""){
phantom.exit();
}
page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36';
page.settings.loadImages = false;
page.open(url, function(status) {
console.log("Status: " + status);
if(status === "success") {
var path = fileName+'.html';
fs.write(path, page.content, 'w');
}
phantom.exit();
});
Java code (example to get title and cover-url):
try {
//change path to phantomjs binary and your script file
String outputFileName = "srulad";
String phantomJSPath = "phantomjs" + File.separator + "bin" + File.separator + "phantomjs";
String scriptFile = "simple.js";
String urlParameter = "http://srulad.com/#page-2";
new File(outputFileName+".html").delete();
Process process = Runtime.getRuntime().exec(phantomJSPath + " " + scriptFile + " " + urlParameter + " " + outputFileName);
process.waitFor();
Document doc = Jsoup.parse(new File(outputFileName + ".html"),"UTF-8"); // output.html is created by phantom.js, same path as page.js
Elements elements = doc.select("#list_page-2 > div");
for (Element element : elements) {
System.out.println(element.select("div.l-description.float-left > div:nth-child(1) > a").first().attr("title"));
System.out.println(element.select("div.l-image.float-left > a > img.lazy").first().attr("data-original"));
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
Output:
სიყვარული და მოწყალება / Love & Mercy
http://srulad.com/assets/uploads/42410_Love_and_Mercy.jpg
მუზა / The Muse
http://srulad.com/assets/uploads/43164_large_qRzsimNz0eDyFLFJcbVLIxlqii.jpg
...
UPDATE
Parsing of websites with javascript based dynamic content in Android is possible using WebView and jsoup.
The following example app uses a javascript enabled WebView to render a Javascript dependent website. With a JavascriptInterface the html source is returned, parsed with jsoup and as a proof of concept the titles and the urls to the cover-images are used to populate a ListView. The buttons decrement or increment the page number triggering an update of the ListView. Note: tested on an Android 5.1.1/API 22 device.
add internet permission to your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/page_down"
android:id="#+id/buttonDown"
android:layout_weight="0.5" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/page_up"
android:id="#+id/buttonUp"
android:layout_weight="0.5" />
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/listView"
android:layout_gravity="bottom"
android:layout_weight="0.5" />
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private final Handler uiHandler = new Handler();
private ArrayAdapter<String> adapter;
private ArrayList<String> entries = new ArrayList<>();
private ProgressDialog progressDialog;
private class JSHtmlInterface {
#android.webkit.JavascriptInterface
public void showHTML(String html) {
final String htmlContent = html;
uiHandler.post(
new Runnable() {
#Override
public void run() {
Document doc = Jsoup.parse(htmlContent);
Elements elements = doc.select("#online_movies > div > div");
entries.clear();
for (Element element : elements) {
String title = element.select("div.l-description.float-left > div:nth-child(1) > a").first().attr("title");
String imgUrl = element.select("div.l-image.float-left > a > img.lazy").first().attr("data-original");
entries.add(title + "\n" + imgUrl);
}
adapter.notifyDataSetChanged();
}
}
);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, entries);
listView.setAdapter(adapter);
progressDialog = ProgressDialog.show(this, "Loading","Please wait...", true);
progressDialog.setCancelable(false);
try {
final WebView browser = new WebView(this);
browser.setVisibility(View.INVISIBLE);
browser.setLayerType(View.LAYER_TYPE_NONE,null);
browser.getSettings().setJavaScriptEnabled(true);
browser.getSettings().setBlockNetworkImage(true);
browser.getSettings().setDomStorageEnabled(false);
browser.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
browser.getSettings().setLoadsImagesAutomatically(false);
browser.getSettings().setGeolocationEnabled(false);
browser.getSettings().setSupportZoom(false);
browser.addJavascriptInterface(new JSHtmlInterface(), "JSBridge");
browser.setWebViewClient(
new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressDialog.show();
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
browser.loadUrl("javascript:window.JSBridge.showHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
progressDialog.dismiss();
}
}
);
findViewById(R.id.buttonDown).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uiHandler.post(new Runnable() {
#Override
public void run() {
int page = Integer.parseInt(browser.getUrl().split("-")[1]);
int newPage = page > 1 ? page-1 : 1;
browser.loadUrl("http://srulad.com/#page-" + newPage);
browser.loadUrl(browser.getUrl()); // not sure why this is needed, but doesn't update without it on my device
if(getSupportActionBar()!=null) getSupportActionBar().setTitle(browser.getUrl());
}
});
}
});
findViewById(R.id.buttonUp).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uiHandler.post(new Runnable() {
#Override
public void run() {
int page = Integer.parseInt(browser.getUrl().split("-")[1]);
int newPage = page+1;
browser.loadUrl("http://srulad.com/#page-" + newPage);
browser.loadUrl(browser.getUrl()); // not sure why this is needed, but doesn't update without it on my device
if(getSupportActionBar()!=null) getSupportActionBar().setTitle(browser.getUrl());
}
});
}
});
browser.loadUrl("http://srulad.com/#page-1");
if(getSupportActionBar()!=null) getSupportActionBar().setTitle(browser.getUrl());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
It's been days of researching and I cannot figure out a way to do it.
Here is the link of the library on Github. Library
public class PDFViewActivity1 extends AppCompatActivity {
LinearLayout root;
EditText etPdfUrl;
Button btnDownload;
PDFPagerAdapter adapter;
String id;
ArrayList<String> topicLink;
File file;
String filePath;
PDFViewPager pdfViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
setContentView(R.layout.activity_p_d_f_view);
root = (LinearLayout) findViewById(R.id.remote_pdf_root);
final Context ctx = this;
Intent intent = getIntent();
String str = intent.getStringExtra("filePath");
str = str; // This contains the path of the PDF on my device
Log.i("filePathInString", str);
pdfViewPager = new PDFViewPager(ctx, str);
pdfViewPager.setId(R.id.pdfViewPager);
pdfViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
adapter = new PDFPagerAdapter(ctx, str);
pdfViewPager.setAdapter(adapter);
root.removeAllViewsInLayout();
root.addView(pdfViewPager,
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
}
#Override
protected void onDestroy() {
super.onDestroy();
((PDFPagerAdapter) pdfViewPager.getAdapter()).close();
}
}
The PDF renders perfectly form my device but I cannot see the page numbers, title , total pages of the PDF when the PDF is loaded.
This is my XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/remote_pdf_root"
android:orientation="vertical"
android:background="#FFFFFF"
tools:context=".PDFViewActivity1"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<es.voghdev.pdfviewpager.library.PDFViewPager
android:id="#+id/pdfViewPager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
What do I do when the page is scrolled, I cannot figure out a thing , I tried a lot of methods of the PDFAdapter but I an unsuccessful :( How can I do the task ?
RelativeLayout remotePdfRoot = findViewById(R.id.remote_pdf_root);
remotePDFViewPager = new RemotePDFViewPager(this, downloadFileUrlConnection, url, listener);
remotePDFViewPager.setId(R.id.pdfViewPager);
//after file loading success
PDFPagerAdapter adapter = new PDFPagerAdapter(this, FileUtil.extractFileNameFromURL(url));
remotePDFViewPager.setAdapter(adapter);
updateLayout();
private void updateLayout() {
remotePdfRoot.removeAllViewsInLayout();
remotePdfRoot.addView(remotePDFViewPager, LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
}
I preview pdf this way and there will be a pagenumber.
You can use https://github.com/barteksc/AndroidPdfViewer library for this and you can get the page count by
`vpPdf.fromAsset("sample.pdf").onError {
Log.i(TAG, "${it.localizedMessage}")
it.printStackTrace()
}.onPageError { _, t ->
t.printStackTrace()
}.enableSwipe(true).swipeHorizontal(true).onPageChange { page, pageCount ->
//here page count is count of page user currently is viewing.
}.load()`
I had to use this lib at work and it is working perfectly fine!!
The above code is from kotlin but you can convert it to java i guess,If you are not able to convert it the kindly comment so i will help you with that too!!.
I'm working on a new Android Java program which brings two variables (String title and String imageUrl) then adds buttons named as the String (title).
When the user click on a button the application must load the image from the url in String (imageUrl).
The problem which I face is that none of the load images methodes worked with me!!
Although my project has no errors at all!!
This is my code:
public void start(String res) {
try {
JSONArray jarray = new JSONArray(jsonString);
for (int k = 0; k < jarray.length(); k++) {
JSONObject obj = jarray.getJSONObject(k);
Button btn = new Button(this);
btn.setText(obj.getString("title"));
final String link = obj.getString("link");
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openImage(link);
}
});
space.addView(btn);
dialog.dismiss();
}
} catch(Exception e) {
}
}
public void openImage(final String urk) {
dialog = ProgressDialog.show(this, "", "loading...", true);
new Thread(new Runnable() {
public void run() {
nextstepload(urk);
}
});
}
public void nextstepload(final String urk) {
try {
ImageView im = findViewById(R.id.img);
URL url = new URL(urk);
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
im.setImageBitmap(image);
dialog.dismiss();
} catch(IOException e) {
System.out.println(e);
}
}
And my Xml form is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/displayer">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/img"/>
</LinearLayout>
</LinearLayout>
Notice:
I read the previous writings about this subject on StackOverFlow but none of them helps me enough! I may need a code suitable for my project especially.
Thanks very much
Give it a try to Glide.
https://github.com/bumptech/glide
You can load images like this:
Glide
.with(context)
.load(YOUR URL HERE - AS STRING)
.placeholder(R.drawable.loading_spinner) // if you want some placeholder, it comes here
.into(myImageView); // The imageview reference.
You just forgot to Thread.start()
new Thread(new Runnable() {
public void run() {
nextstepload(urk);
}
}).start();
A Thread object itself does nothing. You must .start() it after instantiated.
I am trying to display response json in android HTML Webview,while clicking the button it will invoke the Activity and loads the asset URL but load() returns null as the responseJsonObject,because before the completion of getData() load() returns responseJsonObject as null.By setting break points and debugging the code step by step it's giving the expected result,I understood it's because of asynchronous call,don't have clear picture of how to handle this kind of invocation.
Anyone please guide me to handle this invocation?.
Note:I have used thread also like,
#JavascriptInterface
public JSONObject load() throws JSONException {
Log.d("RESPONSE>>", "WEBCONNECTOR");
Runnable delay = new Runnable() {
#Override
public void run() {
try {
response = getData();//response also declared as global variable
} catch (Exception e) {
e.printStackTrace();
}
}
};
if (response != null)
return responseJsonObject;
else {
return new JSONObject("{'Message':'No Data Found!.'}");
}
}
Activity.java
public class Activity extends AppCompatActivity {
private JSONObject responseJsonObject = null;
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_response_display);
final WebView webView=(WebView)findViewById(R.id.webView);
webView.setWebClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
String webConnector = "webConnector";
String toaster = "toaster";
webView.addJavascriptInterface(this, webConnector);
webView.addJavascriptInterface(this, toaster);
String folder_path = "file:/android_asset/";
String fileName = "sample.html";
String file = folder_path + fileName;
webView.loadUrl(file);
}
#JavascriptInterface
public JSONObject load(){
getData();
return responseJsonObject;
}
#JavascriptInterface
public void checkData(JSONObject data) {
Toast.makeText(this, "hello" + data.toString(), Toast.LENGTH_LONG).show();
}
public void getData(){
//REST SERVICE INVOCATION
responseJsonObject=result.asJSONObject();
}
}
activity_response_display.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/webView">
</WebView>
</LinearLayout>
Sample.html
<html>
<head>
<script type="text/javascript">
function loader(){
var responseJSON=window.webConnector.load();
toaster.checkData(responseJSON);
document.getElementById("hello").innerHTML=responseJSON;
}
</script>
</head>
<body onload="loader()">
<p id="hello">result:</p>
</body>
</html>
I'm new to the java programming language and I'm trying to build an app. The app has to make a list of worked hours that have been saved in an MySQL database. I found an example app, that helped me retrieving the data from the database and putting it in a ListView.
But now we get to my problem. I want to put separators in the listview.
Now, the date of the worked hours is in every item of the ListView. I want the date only above the first item.
I've searched the internet for a way to do this, but it didn't help me.
This it the code that gets the data and puts it in a ListView:
public class AllUrenActivity extends ListActivity {
String url_all_uren;
String ip;
String proid;
String uid = MainScreenActivity.uid;
String datum;
String datum1;
ImageView btntoevoegen;
// Progress Dialog
private ProgressDialog pDialog;
TextView tvDatum;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>>urenList;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_UREN = "uren";
private static final String TAG_TRID = "trid";
private static final String TAG_PROID = "proid";
private static final String TAG_WERKZAAMHEID = "werkzaamheid";
private static final String TAG_TIJD = "tijd";
private static final String TAG_DATUM = "datum";
// products JSONArray
JSONArray uren = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_uren);
SharedPreferences settings = getSharedPreferences("databaseIP", 0);
ip = settings.getString("ip", "").toString();
url_all_uren = ("http://"+ip+"/android_connect/get_all_uren.php");
// Hashmap for ListView
urenList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllUren().execute();
// Get listview
ListView lv = getListView();
// on selecting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String proid = ((TextView) view.findViewById(R.id.tvProid)).getText()
.toString();
String werkzaamheid = ((TextView) view.findViewById(R.id.tvWerkzaamheid)).getText()
.toString();
String trid = ((TextView) view.findViewById(R.id.tvTrid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
AllProjectsActivity.class);
// sending pid to next activity
in.putExtra(TAG_PROID, proid);
in.putExtra(TAG_TRID, trid);
in.putExtra(TAG_WERKZAAMHEID, werkzaamheid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllUren extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllUrenActivity.this);
pDialog.setMessage("Uren laden...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uid", uid));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_uren, "GET", params);
// Check your log cat for JSON reponse
Log.d("Uren: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
uren = json.getJSONArray(TAG_UREN);
// looping through All Products
for (int i = 0; i < uren.length(); i++) {
JSONObject c = uren.getJSONObject(i);
// Storing each json item in variable
String trid = c.getString(TAG_TRID);
String proid = c.getString(TAG_PROID);
String werkzaamheid = c.getString(TAG_WERKZAAMHEID);
String datum = c.getString(TAG_DATUM);
String tijd = c.getString(TAG_TIJD);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_TRID, trid);
map.put(TAG_WERKZAAMHEID, werkzaamheid);
map.put(TAG_PROID, proid);
map.put(TAG_TIJD, tijd);
map.put(TAG_DATUM, datum);
// adding HashList to ArrayList
urenList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllUrenActivity.this, urenList,
R.layout.list_uren, new String[] { TAG_TRID, TAG_PROID, TAG_WERKZAAMHEID, TAG_TIJD, TAG_DATUM},
new int[] { R.id.tvTrid, R.id.tvProid, R.id.tvWerkzaamheid, R.id.tvTijd, R.id.tvDatum });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
list_uren.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/tvTrid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<!-- Name Label -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/tvDatum"
android:layout_width="269dp"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingLeft="6dip"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="17sp"
android:visibility="visible" />
<ImageView
android:id="#+id/toevoegen"
android:layout_width="25dp"
android:layout_height="25dp"
android:src="#android:drawable/ic_menu_add" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/tvTijd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="6dip"
android:text="8:00-12:00"
android:textSize="17sp"
android:textStyle="bold"
android:visibility="visible" />
<TextView
android:id="#+id/tvProid"
android:layout_width="138dp"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:paddingLeft="6dip"
android:text="Project"
android:textSize="17sp" />
</LinearLayout>
<TextView
android:id="#+id/tvWerkzaamheid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="6dip"
android:paddingTop="6dip"
android:text="Werkzaamheid"
android:textSize="17sp" />
</LinearLayout>
all_uren.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
What is the best way to get the date separators? Thank you.
Add this at the end of list_uren.xml before closing the LinearLayout
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#666666" />
You can change the background to whatever you want.
Here is my json output sample:
{"podcast":[{"link":"rtsp:\\live.xxx.ro:554\vod\_definst_\mp4:05\rfm_00.mp4","name":"Recording 1"}
For parsing the json code i use this:
private static final String TAG_LINK = "link";
private static final String TAG_NAME = "name";
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
products = json.getJSONArray(TAG_PRODUCTS);
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String link = c.getString(TAG_LINK);
String name = c.getString(TAG_NAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_LINK, link);
map.put(TAG_NAME, name);
productsList.add(map);
}
} else {
}
} 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(
PodCast.this, productsList,
R.layout.list_item, new String[] {
TAG_NAME, TAG_LINK },
new int[] { R.id.link, R.id.name });
setListAdapter(adapter);
}
});
For the layout this is the code of the link view:
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:autoLink="web"
android:textColor="#fff"
android:textColorLink="#fff"
android:textStyle="bold"/>
All works well...but in the link view i get the whole link rtsp://live.xxx.ro...etc and i would like to be something like this: NAME So i would have the name and when i click it to open the specified link. Can you guys please help me figure it out how?
Simple...
String href = String.format(" %s ", map.get(TAG_LINK), map.get(TAG_NAME));
textV.setText(Html.fromHTML(href))
Or if you have a link as a resource string; just make sure that the reserved HTML characters aren't converted to HTML entities.
An example that would parse incorrectly:
<string name="a_link"><a href="http://www.google.com">click here</a></string>
To fix it, edit strings.xml manually and convert HTML entities to characters they represent,
so that the above becomes:
<string name="a_link">click here</string>
And it should work.
You need to set a function setOnItemClickListener() and inside it declare something like this:
Uri uri = Uri.parse( "http://www.google.com" );
startActivity( new Intent( Intent.ACTION_VIEW, uri ) );