android json add hyperlink to text - java

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 ) );

Related

Can not load data to ListView in Activity

I'm using json to load data in Activity class with content following as:
My Activity class:
public class CategoryCarActivity extends ListActivity {
ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
ArrayList<Category> carsList = new ArrayList<Category>();
JSONArray manufacturers = null;
String manufacturer_id, manufacturer_name;
private static final String URL_MANUFACTURERS = "MyURL";
// ALL JSON node names
private static final String TAG_CARS = "cars";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_MANUFACTURER = "name";
private static final String TAG_PRICE = "price";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(CategoryCarActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
Intent i = getIntent();
manufacturer_id = i.getStringExtra("id");
carsList = new ArrayList<Category>();
// Loading tracks in Background Thread
new LoadTracks().execute();
// get listview
ListView lv = getListView();
/**
* Listview on item click listener
* SingleTrackActivity will be lauched by passing manufacturer id, car id
* */
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
// On selecting single track get car information
Intent i = new Intent(getApplicationContext(), DetailListCarActivity.class);
// to get car information
// both manufacturer id and car is needed
String manufacturer_id = ((TextView) view.findViewById(R.id.manufacturer_id)).getText().toString();
String car_id = ((TextView) view.findViewById(R.id.car_id)).getText().toString();
Toast.makeText(getApplicationContext(), "Manufacturer Id: " + manufacturer_id + ", Car Id: " + car_id, Toast.LENGTH_SHORT).show();
i.putExtra("manufacturer_id", manufacturer_id);
i.putExtra("car_id", car_id);
startActivity(i);
}
});
}
/**
* Background Async Task to Load all tracks under one album
* */
class LoadTracks extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CategoryCarActivity.this);
pDialog.setMessage("Loading selected car ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting tracks json and parsing
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// post album id as GET parameter
params.add(new BasicNameValuePair(TAG_ID, manufacturer_id));
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_MANUFACTURERS, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Category List JSON: ", json);
try {
JSONObject jObj = new JSONObject(json);
if (jObj != null) {
String manufacturer_id = jObj.getString(TAG_ID);
manufacturer_name = jObj.getString(TAG_MANUFACTURER);
manufacturers = jObj.getJSONArray(TAG_CARS);
if (manufacturers != null) {
// looping through All cars
for (int i = 0; i < manufacturers.length(); i++) {
JSONObject c = manufacturers.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
// track no - increment i value
String track_no = String.valueOf(i + 1);
String name = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
// creating new HashMap
// HashMap<String, String> map = new HashMap<String, String>();
Category category = new Category();
category.setManufacturer_id(manufacturer_id);
category.setId(id);
category.setName(name);
category.setPrice(price);
// adding each child node to HashMap key => value
/*
map.put("manufacturer_id", manufacturer_id); // note here
map.put(TAG_ID, car_id);
map.put("track_no", track_no + ".");
map.put(TAG_NAME, name);
map.put(TAG_PRICE, price);
*/
// adding HashList to ArrayList
// carsList.add(map);
carsList.add(category);
}
} else {
Log.d("Manufacturers: ", "null");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
pDialog.dismiss();
ListAdapter adapter = new ArrayAdapter<Category>(
CategoryCarActivity.this, // the context
R.layout.list_item_categorys, // Simple list item - will toString() your data
carsList // The arraylist
);
// updating listview
setListAdapter(adapter);
}
}
}
list_item_categorys.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/manufacturer_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<!-- Song id / Hidden by default -->
<TextView
android:id="#+id/car_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="#+id/track_no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="15dip"
android:paddingLeft="5dip"
android:paddingTop="15dip"
android:textColor="#000000"
android:textSize="16dip"
android:layout_alignParentLeft="true"/>
<TextView
android:id="#+id/manufacturer_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="15dip"
android:paddingLeft="5dip"
android:paddingTop="15dip"
android:textColor="#000000"
android:textSize="16dip"
android:layout_toRightOf="#+id/track_no"/>
<TextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:paddingLeft="3dip"
android:paddingRight="6dip"
android:textColor="#9ed321" />
I have debugged and check Logcat and see that data has loaded and everything normal, but don't know why data can not load to ListView
updated
Logcat:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.totoroads.android.app, PID: 4697
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:393)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:369)
How to fix this problem?? thank you
You're not providing your list to the list view. You need to add your list to your list view with an adapter. This tutorial should help walk you through the process. http://www.vogella.com/tutorials/AndroidListView/article.html
In your postExecute of your asyncTask you can than call adapter.notifyDataSetChanged(). And your view will update with the new list content.
This code looks really similar... maybe copy the rest of it?
You need an Adapter for your data.
protected void onPostExecute(String result) {
// dismiss the dialog after getting all tracks
pDialog.dismiss();
ListAdapter adapter = new ArrayAdapter<Category>(
CategoryCarActivity.this, // the context
android.R.layout.simple_list_item_1, // Simple list item - will toString() your data
carList // The arraylist
);
// updating listview
setListAdapter(adapter);
}
You can also make a subclass of ArrayAdapter<Category> if you really want to customize a layout.
Adding to Ben's answer, you need to set the list to the listview adapter after the asynctask completes its background functionality i.e in onPostExecute() method of the asynctask.
Need to set the list view as suggested by Ben in onPostExecute().
ListView listView = (ListView) findViewById(R.id.your_list_view_id);
listView.getAdapter().notifyDataSetChanged();

unable to retrieve complete webpage using jsoup, possible fix? [duplicate]

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();
}
}
}

How do I make separators for a ListView with a SimpleAdapter

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.

How to use intent to call the method of next activity in android

What i am doing now is--> i'm getting data from the webservice in one activity and displaying the entire data in a listview. i added just a search functinality on the presented listview itself.
My requirement is --> i should have a search button in the first activity. When it is clicked, should show the related result in second activity, to do this added putExtras in the intent like this intent.putExtra("search", searchBox); that is the second activities search function keyword. but still m not getting the searched output.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
final EditText searchBox=(EditText) findViewById(R.id.search);
final ListView list=(ListView)findViewById(android.R.id.list);
//get the LayoutInflater for inflating the customomView
//this will be used in the custom adapter
inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
final JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
posts = json.getJSONArray(KEY_POSTS);
// looping through all song nodes <song>
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// to remove all <P> </p> and <br /> and replace with ""
content = content.replace("<br />", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
//authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
String url = null;
String slug = null;
try {
JSONArray atta = c.getJSONArray("attachments");
for(int j = 0; j < atta.length(); j++){
JSONObject d = atta.getJSONObject(j);
slug = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
url = thumbnail.getString(KEY_URL);
}
} catch (Exception e) {
e.printStackTrace();
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug);
map.put(KEY_URL, url);
// System.out.println("the map is title "+map.get("title"));
//title2.add(map.get("title"));
// adding HashList to ArrayList
songsList.add(map);
}
}catch (JSONException e) {
e.printStackTrace();
}
//searchResults=OriginalValues initially
searchResults=new ArrayList<HashMap<String, String>>(songsList);
// Getting adapter by passing json data ArrayList
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
//get the text in the EditText
searchString=searchBox.getText().toString();
textLength=searchString.length();
searchResults.clear();
for(int i=0;i<songsList.size();i++)
{
playerName=songsList.get(i).get("title").toString();
System.out.println("player name "+playerName);
if(textLength<=playerName.length()){
//compare the String in EditText with Names in the ArrayList
if(searchString.equalsIgnoreCase(playerName.substring(0,textLength))){
searchResults.add(songsList.get(i));
System.out.println("the array list is "+songsList.get(i));
adapter=new LazyAdapter(Home.this, searchResults);
list.setAdapter(adapter);
}
}
Intents are for activity and not methods inside them , So you cannot use it to call any specific method however you can use extras to figure out what you want to do \
like after when you get extras from Intent you can ,
if extras has "search" value
then do something about it

Fatal exception caused by android.os.NetworkOnMainThreadException

As I am a beginner to Android programming, I was trying to run some tutorials, but upon running the programs( the source code is available here: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ ) I got an error.
The program is supposed to read in data from a website and process it, but I think there is something wrong with the networking part.
I am fully aware there have been similar questions here on SO, yet I had no clue how to solve it, perhaps anyone could give solutions which I also can understand.
Strange NetworkOnMainThreadException in Android app?
This is a questions which was asked earlier and is identical to my problem, but I had no clue what they are trying to say there, i.e. "To fix you just need to move any thing that is touching the network to its own thread." makes no sense to me whatsoever..
Can anyone please shed some light on this?
Use an AsyncTask to move your network operation off of the main/ui thread and onto a background/worker thread.
Expanding on the example from the tutorial, wrap the JSON stuff inside of an anonymous AsyncTask:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new AsyncTask<Void, Void, JSONObject>() {
protected JSONObject doInBackground(Void... args) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
return jParser.getJSONFromUrl(url);
}
protected void onPostExecute(JSONObject json) {
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
}
}.execute((Void) null);
}

Categories

Resources