android:how to call method from hyperlink - android

I am trying to click a hyperlink and call method in android programming...
But the problem is , the link is not showing up and neither the method is getting called. How to achieve this result?
I am basically a javascript/jsp developer, this is my first android application , which i am learning. Accordingly i am trying to click link and call method with parameter....
Results looking like
Java code
private class CallAPI extends AsyncTask<String, String, String> {
private String Content;
#Override
protected String doInBackground(String... params) {
String urlString=params[0]; // URL to call
String resultToDisplay = "";
InputStream in = null;
emailVerificationResult result = null;
// HTTP Get
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
System.out.println("test");
BufferedReader reader = null;
// Get the server response
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (Exception e ) {
System.out.println(e.getMessage());
return e.getMessage();
}
/****************** Start Parse Response JSON Data *************/
String OutputData = "<center><b><u>Weight Training</u></b></center><br/><br/>";
JSONObject jsonResponse;
try {
/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
jsonResponse = new JSONObject(Content);
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonMainNode = jsonResponse.optJSONArray("articleList");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonMainNode.length();
for (int i = 0; i < lengthJsonArr; i++) {
/****** Get Object for each JSON node.***********/
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
/******* Fetch node values **********/
String name = jsonChildNode.optString("menu_name").toString();
String number = jsonChildNode.optString("id").toString();
String date_added = jsonChildNode.optString("parent_id").toString();
OutputData += " " +
String.format("<a onClick='verifyEmail("+number+","+date_added+")'><b>"+name+"<b> "+ number+" "+ date_added+"</a> ") +"<br/><br/>";
}
/****************** End Parse Response JSON Data *************/
/* Show Parsed Output on screen (activity) */
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
resultToDisplay =OutputData ;
return resultToDisplay;
}
// This is the method that is called when the submit button is clicked
public void verifyEmail(String m,String p) {
String urlString = apiURL + "mid=" + m + "&pid=" + p;
new CallAPI().execute(urlString);
}
protected void onPostExecute(String result) {
Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
intent.putExtra(EXTRA_MESSAGE, result);
startActivity(intent);
}
Update:
Instead of link, can i put a button and provide on click method and pass parameter to the method

(Thankfully) You cannot call a function using HTML tags in android. Instead try setting ClickableSpan on you you TextView to get the desired effect
SpannableString ss = new SpannableString("Click Me to do magic");
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View textView) {
doSomeMagic();
}
#Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
}
};
// apply the clickable span on "Click Me" part which is on index 0 -> 7
// 8 is used because it goes from a -> b-1
ss.setSpan(clickableSpan, 0, 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView textView = (TextView) findViewById(R.id.foo);
textView.setText(ss);

Related

How to retreive data from background thread to UI thread in aysnctask?

i have fetched data from my api but i don't know how to assign this fetched data to my adapter?
Issue:
how to set fetched data to array defined above?
how to set an adapter ?
public class FetchLists extends AsyncTask<>{
public List<MailChimpList> listTitles = new ArrayList<>();
#Override
protected List<MailChimpList> doInBackground(Integer... params) {
int count = params[0];
int offset = params[1];
String urlString = "https://us14.api.mailchimp.com/lists?apikey=efb918ee8791215bac4c8a3a8a77-us14"
urlString = urlString + "&count=" + count + "&offset=" + offset;
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line = reader.readLine();
String response = "";
while (line != null) {
response += line;
line = reader.readLine();
}
JSONObject object = new JSONObject(response);
JSONArray lists = object.getJSONArray("lists");
for (int i = 0; i < lists.length(); i++) {
JSONObject listData = (JSONObject) lists.get(i);
MailChimpList mailChimpList = new MailChimpList();
mailChimpList.id = listData.getString("id");
mailChimpList.title = listData.getString("name");
String id = listData.getString("id");
String title = listData.getString("name");
Log.d("ashutosh","id are: "+id);
Log.d("ashutosh","list name are: "+title);
listTitles.add(mailChimpList);
}
} catch (Exception e) {
e.printStackTrace();
}
return listTitles;
}
#Override
protected void onPostExecute(List<MailChimpList> mailChimpLists) {
}
}
#Override
protected void onPostExecute(List<MailChimpList> mailChimpLists) {
MyCustomAdapter adapter = new MyCustomAdapter(context, mailChimpLists);
myListView.setAdapter(adapter);
}
As your list is customized list you need to write a customer adapter
You can declare your ListView as global variable and it can be accessed in post execute.

how to fetch json object from url in android

I want to fetch json data from json object.
My json data is:{"avg":2.5} and my android code is
public class AsyncTaskParseJson extends AsyncTask < String, String, String > {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://www.bsservicess.com/photoUpload/star_avg.php?bookName=" + book_name;
// contacts JSONArray
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String...arg0) {
try {
JSONParser jParser = new JSONParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
JSONObject dataJsonArr = json.getJSONObject(str);
String c = dataJsonArr.getString("avg");
na = c;
starts = Float.parseFloat(c);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
super.onPostExecute(strFromDoInBg);
netRate.setRating(starts);
Toast.makeText(mybookview.this, Float.toString(starts), Toast.LENGTH_SHORT).show();
}
But somehow its not working.I have trie every tutorial and evrything but nothing works.plz help me
your getting the json data in response is as {"avg":2.5}
simple remove the below code
JSONObject dataJsonArr = json.getJSONObject(str);
String c = dataJsonArr.getString("avg");
with below line
String c = json.getString("avg");
this is for simple get data from url example:
Parse JSON from HttpURLConnection object
and if you want use library then try Volley:
tutorial link:
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
A very simple solution to your problem
String str = "{ \"avg\" :0 }";
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(str);
String value = object.get("avg").getAsString();
But first of all you have to correct the warning in your backend.
EDIT the complete solution
public class AsyncTaskParseJson extends AsyncTask < String, String, String > {
HttpURLConnection urlConnection;
#Override
protected String doInBackground(String...args) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL("http://www.bsservicess.com/photoUpload/star_avg.php?bookName=" + book_name);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader( in ));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(result);
String value = object.get("avg").getAsString();
}
}
But first of all remove the warning from the web response!

is there anything that i don't know about Json in Code

i'm trying to do some work with methods of json in android.
i read the documentation of json and its methods but when i use them,they don't do what i expected they do.
public class getData_jason extends AsyncTask{
String KholaseKQuery;
String User;
public getData_jason(String link,String user) {
KholaseKQuery = link;
User = user;
}
#Override
protected String doInBackground(Object[] params) {
try{
URL mylink = new URL(KholaseKQuery);
URLConnection connect = mylink.openConnection();
BufferedReader read = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sB = new StringBuilder();
String eline;
while((eline = read.readLine())!= null)
{
sB.append(eline);
}
//MainActivity.jason_rs = sB.toString();
MainActivity.result = sB.toString();
MainActivity.is = true;
JSONObject jObj;
try{
jObj = new JSONObject(MainActivity.result.replace("callback(","")).getJSONObject("response");
JSONArray jsonArray = jObj.optJSONArray("Username");
for (int i = 0;i < jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject.getBoolean("ali")){
MainActivity.jason_rs = jsonObject.optString("Name");
//MainActivity.jason_rs = jsonObject.getString("Name");
}
}
}catch (Exception e){
}
}catch (Exception e){
/*Any Exception Here*/
}
return "";
}
}
when the process of reading from database is finished,in the result string is:
{"Username":["Name":"ali","Name":"hasan"]},{"Password":["aliali","hasanhasan"]}
so when i want to get ali name from the jsonObject,the value of jason_rs is null.
plz guid me what is that i don't know yet about using json or i do it wrong.
Your "json" is invalid. You can't have the same key more than once in a hash, on the other hand you also can't have keys (certainly not strings) in an array. You can validate it on http://jsonlint.com

How to parse or read json file from external storage on Android app

I currently implemented parsing json from a server (url). But I couldn't find a way to parse json from sdcard (/Download/example.json). Can someone help me to solve this issue/change this code?
I used asyncTask for this. sample tutorial or sample code is more appreciated. (sorry for my English.)
public class Main extends Activity {
private TextView shopsDisplay;
private static String searchURL = "http://example.com/sample.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.baby);
//reference throughout class
shopsDisplay = (TextView)findViewById(R.id.tweet_txt);
new GetShops().execute(searchURL);
}
private class GetShops extends AsyncTask<String, Void, String> {
/*
* Carry out fetching task in background
* - receives search URL via execute method
*/
#Override
protected String doInBackground(String... shopsURL) {
//start building result which will be json string
StringBuilder shopsFeedBuilder = new StringBuilder();
//should only be one URL, receives array
for (String searchURL : shopsURL) {
HttpClient shopsClient = new DefaultHttpClient();
try {
//pass search URL string to fetch
HttpGet shopsGet = new HttpGet(searchURL);
//execute request
HttpResponse shopsResponse = shopsClient.execute(shopsGet);
//check status, only proceed if ok
StatusLine searchStatus = shopsResponse.getStatusLine();
if (searchStatus.getStatusCode() == 200) {
//get the response
HttpEntity shopsEntity = shopsResponse.getEntity();
InputStream shopsContent = shopsEntity.getContent();
//process the results
InputStreamReader shopsInput = new InputStreamReader(shopsContent);
BufferedReader shopsReader = new BufferedReader(shopsInput);
String lineIn;
while ((lineIn = shopsReader.readLine()) != null) {
shopsFeedBuilder.append(lineIn);
}
}
else
shopsDisplay.setText("Whoops - something went wrong!");
}
catch(Exception e){
shopsDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();
}
}
//return result string
return shopsFeedBuilder.toString();
}
/*
* Process result of search query
* - this receives JSON string representing shops with search term included
*/
protected void onPostExecute(String result) {
//start preparing result string for display
StringBuilder shopsResultBuilder = new StringBuilder();
try {
//get JSONObject from result
JSONObject resultObject = new JSONObject(result);
//get JSONArray contained within the JSONObject retrieved - "results"
JSONArray shopsArray = resultObject.getJSONArray("shops");
//loop through each item in the shops array
for (int t=0; t<shopsArray.length(); t++) {
//each item is a JSONObject
JSONObject shopsObject = shopsArray.getJSONObject(t);
//for if condition
String id = (String) shopsObject.get("id");
//get the name and description for each shops
if (id.equals("550")){
shopsResultBuilder.append(shopsObject.getString("name")+": ");
shopsResultBuilder.append(shopsObject.get("description")+"\n\n");
}
}
}
catch (Exception e) {
shopsDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();
}
//check result exists
if(shopsResultBuilder.length()>0)
shopsDisplay.setText(shopsResultBuilder.toString());
else
shopsDisplay.setText("Sorry - no shops found for your search!");
}
}
}
For JSONObject, use standard Java file I/O to read the file into a String, then pass it to the JSONObject constructor.
If you have a large JSON file, though, you may wish to switch to some other JSON parser (e.g., JsonReader), which may give you different options (e.g., use a FileReader with JsonReader).

How to make onPostExecute() or Json parsing work?

I am a beginner in Android, and I am writing a short program to download a JSON feed from URL and parse it. I use AsyncTask to do the downloading.
The doInBackground() part seems to work well. Then I set my breakpoint to onPostExecute(), it can even stop at parseJSON(result), and 'result' is showing the correct json string downloaded. But when I try to step into parseJSON(result), it will NOT step into the function correctly(either throw JSONException directly or go to some random lines within parseJSON(result)).
From DDMS log it's not showing any valuable information as well.
How might I find what the problem is? Is it because I used onPostExecute() incorrectly, or parseJSON() has some problem?
public class MainActivity extends Activity {
private listItem[] items;
public class listItem {
String title;
String description;
String imageHref;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items = new listItem[50];
new DownloadJsonFeed().execute("http://dl.dropbox.com/u/10168342/facts.json");
}
private class DownloadJsonFeed extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
return downloadUrl(params[0]);
} catch (IOException e) {
return "Unable to retrieve json feed. URL may be invalid.";
}
}
#Override
protected void onPostExecute(String result) {
try {
parseJSON(result); // Here !!!!!!
} catch (JSONException e) {
}
}
}
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
// Convert the InputStream into a string
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString();
} finally {
if (is != null) {
is.close();
}
}
}
private void parseJSON(String feed) throws JSONException {
JSONObject json_obj = new JSONObject(feed);
title = json_obj.getString("title");
String rows = json_obj.getString("rows");
JSONArray jArray = new JSONArray(rows);
for (int i = 0; i < jArray.length(); i++) {
JSONObject tmp = jArray.getJSONObject(i);
items[i].title = tmp.getString("title");
items[i].description = tmp.getString("description");
items[i].imageHref = tmp.getString("imageHref");
}
}
JSONObject.getString() will try to get String type value, but what you want is array type.
I think you didn't get the JSON array right. The json_obj.getString will give you an String instead an array.
Try to change as follows:
private void parseJSON(String feed) throws JSONException {
JSONObject json_obj = new JSONObject(feed);
title = json_obj.getString("title");
String rows = json_obj.getString("rows");
JSONArray jArray = json_obj.getJSONArray("rows"); //<---- change this line
for (int i = 0; i < jArray.length(); i++) {
JSONObject tmp = jArray.getJSONObject(i);
items[i].title = tmp.getString("title");
items[i].description = tmp.getString("description");
items[i].imageHref = tmp.getString("imageHref");
}
}

Categories

Resources