I am trying to do a simple APP that parses Currency data from Yahoo finance using their YQL query language. I tried parsing data with Google's finance API and it works fine but when I try it with Yahoo's URL it freezes before I even get to my parsing algorithm which is very strange.
package com.sfc.watcher;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Xml;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class ForexActivity extends Activity {
String temp1;
String temp2;
TableLayout tl1;
View temp3;
private static final String URL1 ="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(\"" ;
private static final String URL2="\")&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
// This TAG is used for logging
private static final String TAG = "ForexWatcherActivity";
// These String constants refer to the XML elements we will be displaying
private static final String NAME = "Name";
private static final String RATE = "Rate";
private static final String DATE = "Date";
private static final String TIME = "Time";
private static final String ASK = "Ask";
private static final String BID = "Bid";
// This String refers to the attribute we are collecting for each element in
// our XML
private static final String DATA = "data";
// This HashMap will store, in key-value pairs, the currency data we receive.
private HashMap<String, String> hmCurrencyData = new HashMap<String, String>();
// This is the edit control that users will key into
private EditText edittext1 = null;
// This is the button that, when pressed, will request currency price data.
private Button button1 = null;
// This variable will hold the currency symbol value the user has keyed in.
private String symbol = "";
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
temp3=v;
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.edit:
return true;
case R.id.delete:
tl1.removeView(temp3);
return true;
case R.id.save:
return true;
default:
return super.onContextItemSelected(item);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.forex);
tl1 = (TableLayout) findViewById(R.id.myTableLayout);
button1 = (Button)findViewById(R.id.bn_retrieve);
edittext1 = (EditText) findViewById(R.id.edit_symbol1);
edittext1.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable arg0) {
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
}
// here we respond to users key input events
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// collect the text from the edit control, and trim off spaces.
symbol = edittext1.getText().toString().trim();
// if the user has entered at least one character, enable the
// bnRetrieve button.
// otherwise, disable it.
button1.setEnabled(symbol.length() > 0);
}
});
final EditText edittext2 = (EditText) findViewById(R.id.edit_symbol2);
//First spinner for input forex
Spinner spinner1 = (Spinner) findViewById(R.id1.spinner);
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
this, R.array.forex_array, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(new SellListener());
//Second spinner for Output forex
Spinner spinner2 = (Spinner) findViewById(R.id2.spinner);
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
this, R.array.forex_array, android.R.layout.simple_spinner_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter2);
spinner2.setOnItemSelectedListener(new BuyListener());
// Capture our button from layout
Button button2 = (Button)findViewById(R.id.bn_convert);
// Register the onClick listener with the implementation above
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText( getApplicationContext(),"Selling "+ "$"+ edittext2.getText().toString()+ " "+ temp1 + " Buying "+ "$"+ temp2, Toast.LENGTH_LONG).show();
}
});
}
public class SellListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
temp1=parent.getItemAtPosition(pos).toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
public class BuyListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
temp2=parent.getItemAtPosition(pos).toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
public void retrieveQuote(View vw) {
// our "symbol" variable already has the text from the edSymbol view via
// the onTextChanged() event capture.
String request = URL1 + symbol + URL2;
CurrencyRetrieveTask task = new CurrencyRetrieveTask();
task.execute(new String[] { request });
}
private class CurrencyRetrieveTask extends AsyncTask<String, Void, String> {
private static final String TAG = "CurrencyRetrieveTask";
private ProgressDialog pDlg = null;
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
hideKeyboard();
pDlg = createProgressDialog(ForexActivity.this,
getString(R.string.retrieving));
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
Log.i(TAG, "doInBackground");
StringBuilder sb = new StringBuilder();
// Remember that the array will only have one String
String url = urls[0];
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
sb.append(s);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
return sb.toString();
}
#Override
protected void onPostExecute(String response) {
readResponse(response);
displayResponse();
pDlg.dismiss();
}
}
private void hideKeyboard() {
// hide the soft keyboard, if it is currently visible.
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edittext1.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
private ProgressDialog createProgressDialog(final Context context,
final String message) {
Log.i(TAG, "createProgressDialog");
final ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setMessage(message);
progressDialog.setProgressDrawable(getWallpaper());
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.show();
return progressDialog;
}
private void readResponse(String response) {
Log.i(TAG, "displayResponse");
// initialize our HashMap, resetting it if it was previously used.
hmCurrencyData = new HashMap<String, String>();
try {
String elementName = "";
String elementValue = "";
String nameSpace = "";
StringReader xmlReader = new StringReader(response);
XmlPullParser parser = Xml.newPullParser();
parser.setInput(xmlReader);
elementName = parser.getName();
while (!elementName.equals("rate"))
{
parser.nextTag();
elementName = parser.getName();
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
e.printStackTrace();
}
}
private void updateTextView(String name, TableRow Row) {
if(hmCurrencyData.containsKey(name))
{
TextView TV1= new TextView(getApplicationContext());
TV1.setText(hmCurrencyData.containsKey(name) ? hmCurrencyData.get(name) : "");
TV1.setLayoutParams(new TableRow.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
Row.addView(TV1);
}
}
private void displayResponse() {
Log.i(TAG, "displayResponse");
TableRow tr = new TableRow(getApplicationContext());
tr.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
tr.setPadding(0, 10, 0, 10);
updateTextView(NAME, tr);
updateTextView(RATE, tr);
updateTextView(DATE, tr);
updateTextView(TIME, tr);
updateTextView(ASK, tr);
updateTextView(BID, tr);
registerForContextMenu(tr);
tl1.addView(tr,new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
}
}
The table is not defined. The URL returns this error:
No definition found for Table yahoo.finance.xchange
When run in the browser:
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22%22%29&diagnostics=true
Related
I'm trying to create the favorites list from Json Objects which I received by URL.
When I got Json array, I defined methods OnItemLongClickListener and OnItemClickListener that get different things:
The OnItemClickListener method has to open another activity with description of product
The OnItemLongClickListener method has to add product to favorite list
The Problem that method OnItemClickListener which I defined in MainActivity is override method OnItemLongClickListener which I defined in FragmentActivty and the method OnItemLongClickListener doesn't work at all then I tried to define both methods in FragmentActivity but after that both methods don't work at all.
Is there any way to determine this problem?
Main Activity:
package com.boom.kayakapp.activities;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.boom.kayakapp.R;
import com.boom.kayakapp.adapters.AirlinesAdapter;
import com.boom.kayakapp.controllers.AppController;
import com.boom.kayakapp.fragment.AirlinesFragment;
import com.boom.kayakapp.fragment.FavoriteFragment;
import com.boom.kayakapp.model.Airlines;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private Fragment contentFragment;
AirlinesFragment airlinesFragment;
FavoriteFragment favoriteFragment;
// JSON Node names
public static final String TAG_NAME = "name";
public static final String TAG_PHONE = "phone";
public static final String TAG_SITE = "site";
public static final String TAG_LOGO = "logoURL";
public static final String TAG_CODE = "code";
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Airlines json url
private static final String url = "https://www.kayak.com/h/mobileapis/directory/airlines";
public ProgressDialog pDialog;
public List<Airlines> airlinesList = new ArrayList<Airlines>();
public ListView listView;
public AirlinesAdapter adapter;
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
listView = (ListView) findViewById(R.id.list);
adapter = new AirlinesAdapter(this, airlinesList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Listview on item click listener
listView.setOnItemClickListener(new AdapterView.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 phone = ((TextView) view.findViewById(R.id.phone))
.getText().toString();
String site = ((TextView) view.findViewById(R.id.site))
.getText().toString();
String logoURL = String.valueOf(((ImageView) view.findViewById(R.id.logoURL)));
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_PHONE, phone);
in.putExtra(TAG_SITE, site);
in.putExtra(TAG_LOGO, logoURL);
startActivity(in);
}
});
// changing action bar color
getSupportActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest airlinesReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Airlines airlines = new Airlines();
airlines.setName(obj.getString("name"));
airlines.setLogoURL(obj.getString("logoURL"));
airlines.setPhone(obj.getString("phone"));
airlines.setCode(obj.getInt("code"));
airlines.setSite(obj.getString("site"));
// adding airlines to movies array
airlinesList.add(airlines);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(airlinesReq);
FragmentManager fragmentManager = getSupportFragmentManager();
/*
* This is called when orientation is changed.
*/
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("content")) {
String content = savedInstanceState.getString("content");
if (content.equals(FavoriteFragment.ARG_ITEM_ID)) {
if (fragmentManager.findFragmentByTag(FavoriteFragment.ARG_ITEM_ID) != null) {
setFragmentTitle(R.string.favorites);
contentFragment = fragmentManager
.findFragmentByTag(FavoriteFragment.ARG_ITEM_ID);
}
}
}
if (fragmentManager.findFragmentByTag(AirlinesFragment.ARG_ITEM_ID) != null) {
airlinesFragment = (AirlinesFragment) fragmentManager
.findFragmentByTag(AirlinesFragment.ARG_ITEM_ID);
contentFragment = airlinesFragment;
}
} else {
airlinesFragment = new AirlinesFragment();
// setFragmentTitle(R.string.app_name);
switchContent(airlinesFragment, AirlinesFragment.ARG_ITEM_ID);
}
}
#Override
public void onDestroy () {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
if (contentFragment instanceof FavoriteFragment) {
outState.putString("content", FavoriteFragment.ARG_ITEM_ID);
} else {
outState.putString("content", AirlinesFragment.ARG_ITEM_ID);
}
super.onSaveInstanceState(outState);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
setFragmentTitle(R.string.favorites);
favoriteFragment = new FavoriteFragment();
switchContent(favoriteFragment, FavoriteFragment.ARG_ITEM_ID);
return true;
}
return super.onOptionsItemSelected(item);
}
public void switchContent(Fragment fragment, String tag) {
FragmentManager fragmentManager = getSupportFragmentManager();
while (fragmentManager.popBackStackImmediate()) ;
if (fragment != null) {
FragmentTransaction transaction = fragmentManager
.beginTransaction();
transaction.replace(R.id.content_frame, fragment, tag);
//Only FavoriteFragment is added to the back stack.
if (!(fragment instanceof AirlinesFragment)) {
transaction.addToBackStack(tag);
}
transaction.commit();
contentFragment = fragment;
}
}
protected void setFragmentTitle(int resourseId) {
setTitle(resourseId);
getSupportActionBar().setTitle(resourseId);
}
/*
* We call super.onBackPressed(); when the stack entry count is > 0. if it
* is instanceof ProductListFragment or if the stack entry count is == 0, then
* we finish the activity.
* In other words, from ProductListFragment on back press it quits the app.
*/
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
super.onBackPressed();
} else if (contentFragment instanceof AirlinesFragment
|| fm.getBackStackEntryCount() == 0) {
finish();
}
}
}
FragmentActivity:
package com.boom.kayakapp.fragment;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.boom.kayakapp.R;
import com.boom.kayakapp.adapters.AirlinesAdapter;
import com.boom.kayakapp.model.Airlines;
import com.boom.kayakapp.util.SharedPreference;
import java.util.ArrayList;
import java.util.List;
public class AirlinesFragment extends Fragment implements OnItemClickListener, OnItemLongClickListener{
public static final String ARG_ITEM_ID = "airlines_list";
Activity activity;
ListView airlinesListView;
List<Airlines> airlines;
AirlinesAdapter airlinesAdapter;
public AirlinesFragment() {
airlines = new ArrayList<>();
}
SharedPreference sharedPreference;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
sharedPreference = new SharedPreference();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_list, container,
false);
findViewsById(view);
airlinesAdapter = new AirlinesAdapter(activity, airlines);
airlinesListView.setAdapter(airlinesAdapter);
airlinesListView.setOnItemClickListener(this);
airlinesListView.setOnItemLongClickListener(this);
return view;
}
private void findViewsById(View view) {
airlinesListView = (ListView) view.findViewById(R.id.list);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Airlines airlines = (Airlines) parent.getItemAtPosition(position);
Toast.makeText(activity, airlines.toString(), Toast.LENGTH_LONG).show();
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long arg3) {
ImageView button = (ImageView) view.findViewById(R.id.favorite_button);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(activity, airlines.get(position));
Toast.makeText(activity,
activity.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.heart_red);
} else {
sharedPreference.removeFavorite(activity, airlines.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.heart_grey);
Toast.makeText(activity,
activity.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
#Override
public void onResume() {
getActivity().setTitle(R.string.app_name);
super.onResume();
}
}
In my way I deleted definition both Methods from FavoriteFragment and defined it in MainActivity:
Json Array
listView = (ListView) findViewById(R.id.list);
adapterAirlines = new AirlinesAdapter(this, airlinesList);
listView.setAdapter(adapterAirlines);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Listview OnItemClickListener
listView.setOnItemClickListener(new AdapterView.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 phone = ((TextView) view.findViewById(R.id.phone))
.getText().toString();
String site = ((TextView) view.findViewById(R.id.site))
.getText().toString();
String logoURL = String.valueOf(((ImageView) view.findViewById(R.id.logoURL)));
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_PHONE, phone);
in.putExtra(TAG_SITE, site);
in.putExtra(TAG_LOGO, logoURL);
startActivity(in);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
ImageView button = (ImageView) view.findViewById(R.id.favorite_button);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(MainActivity.this, airlinesList.get(position));
Toast.makeText(MainActivity.this,
MainActivity.this.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.heart_red);
} else {
sharedPreference.removeFavorite(MainActivity.this, airlinesList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.heart_grey);
Toast.makeText(MainActivity.this,
MainActivity.this.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
});
now it works
I tried to explain my problem as best as I could so sorry if it didn't make sense.
The problem I'm having is when I call the asyncTask class in the onCreate method the String doesn't seem to get passed to doInBackground.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.Timer;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class MainActivity extends Activity {
String question;
TextView price;
Document document;
TextView article;
private Element overview;
EditText respText;
TextView text;
TextView ans;
String siteUrl;
private class ParseURL extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
StringBuffer buffer = new StringBuffer();
try {
Log.d("JSwa", "Connecting to ["+strings[0]+"]");
Document doc = Jsoup.connect(strings[0]).get();
Log.d("JSwa", "Connected to ["+strings[0]+"]");
//Get document (HTML page) title
String title = doc.title();
Log.d("JSwA", "Title ["+title+"]");
buffer.append("Title: " + title + "\r\n");
// Get meta info
Elements metaElems = doc.select("meta");
buffer.append("META DATA\r\n");
for (Element metaElem : metaElems) {
String name = metaElem.attr("name");
String content = metaElem.attr("content");
buffer.append("name ["+name+"] - content ["+content+"] \r\n");
}
Elements topicList = doc.select("h2.topic");
buffer.append("Topic list\r\n");
for (Element topic : topicList) {
String data = topic.text();
buffer.append("Data ["+data+"] \r\n");
}
}
catch(Throwable t) {
t.printStackTrace();
}
return buffer.toString();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
ans.setText(s);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText edtUrl = (EditText) findViewById(R.id.edtURL);
Button btnGo = (Button) findViewById(R.id.btnGo);
//respText = (EditText) findViewById(R.id.edtResp);
ans = (TextView) findViewById(R.id.textView2);
siteUrl = edtUrl.getText().toString();
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// String siteUrl = edtUrl.getText().toString();
( new ParseURL() ).execute(new String[]{siteUrl});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Get text from EditText on click of button instead of inside onCreate method:
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
siteUrl = edtUrl.getText().toString();
new ParseURL().execute(siteUrl);
}
});
Ok the app populates the list view from a Url(json). But I want to change the app so that the list view is populated by user input. How do I go about this. Here is my main activity so far:
package ionictech.com.onspot;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Cache;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.Cache.Entry;
import com.android.volley.Request.Method;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import ionictech.com.onspot.adapter.FeedListAdapter;
import ionictech.com.onspot.app.AppController;
import ionictech.com.onspot.data.FeedItem;
public class OnSpotActivity extends ActionBarActivity {
private DrawerLayout drawerLayout;
private String[] Menu;
private static final String TAG = OnSpotActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://api.androidhive.info/feed/feed.json";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_on_spot);
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem> ();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable (Color.parseColor ("#ffba00")));
getActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
// We first check for cached request
Cache cache = AppController.getmInstance ().getmRequestQueue ().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d (TAG, "Response: " + response.toString ());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getmInstance ().addToRequestQueue(jsonReq);
}
}
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
And here is my feed item list class:
package ionictech.com.onspot.adapter;
import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import java.util.List;
import ionictech.com.onspot.FeedImageView;
import ionictech.com.onspot.R;
import ionictech.com.onspot.app.AppController;
import ionictech.com.onspot.data.FeedItem;
/**
* Created by MarcusLee on 9/30/14.
*/
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<FeedItem> feedItems;
ImageLoader imageLoader = AppController.getmInstance ().getImageLoader();
public FeedListAdapter (Activity activity, List<FeedItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.feed_item, null);
if (imageLoader == null)
imageLoader = AppController.getmInstance().getImageLoader();
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
TextView statusMsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
NetworkImageView profilePic = (NetworkImageView) convertView
.findViewById(R.id.profilePic);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
FeedItem item = feedItems.get(position);
name.setText(item.getName());
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString (
Long.parseLong (item.getTimeStamp ()),
System.currentTimeMillis (), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
// Chcek for empty status message
if (!TextUtils.isEmpty (item.getStatus ())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml ("<a href=\"" + item.getUrl () + "\">"
+ item.getUrl () + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance ());
url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// user profile pic
profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
return convertView;
}
}
I know that the input has to be sent to a server and then read and put into the list view, I just don't know the methods and such. Any help would be most grateful!
I am getting a JSON from a url to generate a list view of contact names & numbers. I intend to make it where users can just tap on the contact name or phone to make a call directly. But I am having problem to get the tap on the item detected. I tried to put a log on the 'onItemClick' but it seems that it is not being called. Can you help see where I did wrong? Here is my code
package com.example.hk.sample;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class AllAccepted extends Activity {
ListView list;
TextView phone;
TextView name;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url;
//JSON Node Names
private static final String TAG_OS = "myjson";
private static final String TAG_VER = "phone";
private static final String TAG_NAME = "name";
JSONArray android = null;
//String matchId = Singleton.getInstance().getMatchIdString();
String matchId = "80";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_accepted);
list = (ListView) findViewById(R.id.listView1);
url = "http://demo.com/list.php?match_id="+ matchId;
Log.e("final view", "final layout array list");
oslist = new ArrayList<HashMap<String, String>>();
new JSONParse().execute();
final Button btnHistory = (Button) findViewById(R.id.goHome);
btnHistory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(myIntent);
}
});
}
protected void onItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
Log.e("item clicks", "selected: " + position);
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
phone = (TextView)findViewById(R.id.listPhone);
name = (TextView)findViewById(R.id.listName);
pDialog = new ProgressDialog(AllAccepted.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
oslist.add(map);
//list=(ListView)findViewById(R.id.listView1);
ListAdapter adapter = new SimpleAdapter(AllAccepted.this, oslist,
R.layout.all_accepted_layout,
new String[] { TAG_VER,TAG_NAME }, new int[] {
R.id.listPhone,R.id.listName});
list.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onBackPressed() {
}
}
Thanks in advance.
SOLUTION FOUND:
add this into onCreate method
list = (ListView) findViewById(R.id.listView1);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.e("item clicks", "selected: " + position);
String item = list.getItemAtPosition(position).toString();
String contactNum = ((TextView)view.findViewById(R.id.listPhone)).getText().toString();
Log.e("phone number", contactNum);
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + contactNum));
startActivity(intent);
}
});
thanks to Kunu for the help
Use this on your onCreate()
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
Log.e("item clicks", "selected: " + position);
String contactNum = ((TextView)view.findViewById(R.id.listPhone)).getText().toString();
phoneCall(contactNum);
}
});
and don't forget to import import android.widget.AdapterView.OnItemClickListener;
After retrieving the number try this to make a call
public void phoneCall(String number)
{
String phoneCallUri = "tel:"+number;
Intent phoneCallIntent =new Intent(Intent.ACTION_CALL);
phoneCallIntent.setData(Uri.parse(phoneCallUri));
startActivity(phoneCallIntent);
}
to set the itemClickListener use :
listView.setOnItemClickListener(ActivityName.this);
Override the method, and also inside the xml
set the focusableInTouchMode to false, and also focusable to false for the textviews
Hope that helps
in OnCreate list.setOnItemClickListener(new OnItemClickListener() {});and then Add unimplement method
public class MainActivity extends Activity {
ListView lView ;
String[] ara={"a","b","c","d","e","f"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lView=(ListView)findViewById(R.id.listView1);
ListAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,ara);
lView.setAdapter(adapter);
lView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}});
}
}
A search api is returning me some meta data i.e a url "eventURL" and trackbackurl i.e "trackBack". I am placing the data in the listview, each row containing some data and a unique url and trackback url.When user taps on the row in the listview, a alert dialog is displayed presenting user 2 options. Clicking on option 1 should launch trackback url in a webview while clicking on second opion should launch eventURL in a webview.I have created a WebViewActivity for it,Problem is that my webview is always blank.
Main Activity
package my.stayactive.plan;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import my.stayactive.plan.ActiveHelper.ApiException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class StayActiveActivity extends Activity implements OnItemClickListener {
//private EditText m_search_text;
protected EditText m_zip;
private ListView m_search_results;
private Button m_search_btn;
private JSONArray m_results;
private LayoutInflater m_inflater;
private InputMethodManager m_ctrl;
private Spinner m_radius;
private Spinner m_activity_selector;
public static int radius = 0;
public static String activities;
public String url;
public String trackBack;
public static String assetId;
static final private int EXIT_ID = Menu.FIRST;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// m_search_text = (EditText) findViewById(R.id.search_text);
m_zip = (EditText) findViewById(R.id.zip);
m_search_btn = (Button) findViewById(R.id.search_button);
// m_searchm_results = (ListView) findViewById(R.id.lview);
m_search_btn .setOnClickListener(go_handler);
m_ctrl = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
m_inflater = LayoutInflater.from(this);
addListenerOnSpinnerItemSelection();
addListenerOnSpinner1ItemSelection();
m_search_results = (ListView)findViewById(R.id.lview);
m_search_results.setOnItemClickListener(this);
}
public void addListenerOnSpinnerItemSelection() {
m_radius = (Spinner) findViewById(R.id.spinner);
m_radius.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public void addListenerOnSpinner1ItemSelection(){
m_activity_selector = (Spinner) findViewById(R.id.spinner1);
m_activity_selector.setOnItemSelectedListener(new ActivitySelectedListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
menu.add(0, EXIT_ID, 0, R.string.exit);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()){
case EXIT_ID:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
OnClickListener go_handler = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//m_ctrl.hideSoftInputFromWindow(m_search_text.getWindowToken(), 0);
m_ctrl.hideSoftInputFromWindow(m_zip.getWindowToken(), 0);
//String searchText = Uri.encode(m_search_text.getText().toString());
String zip = Uri.encode(m_zip.getText().toString());
new SearchTask().execute("?k=Fall+Classic" + "&m=meta:channel=" + activities + "&l="+ zip + "&r=" + radius);
// Show a toast showing the search text
Toast.makeText(getApplicationContext(),
getString(R.string.search_msg) + " " +
activities, Toast.LENGTH_LONG).show();
}
};
private class SearchTask extends AsyncTask<String, Integer, String>
{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(StayActiveActivity.this,"","Please Wait...");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
String result = ActiveHelper.download(params [0]);
return result;
} catch (ApiException e) {
e.printStackTrace();
Log.e("alatta", "Problem making search request");
}
return "";
}
#Override
protected void onPostExecute(String result) {
dialog.hide();
try {
JSONObject obj = new JSONObject(result);
m_results = obj.getJSONArray("_results");
if (m_results == null || m_results.length() == 0)
{
Toast.makeText(getApplicationContext(),
"No Results found for " + activities,
Toast.LENGTH_LONG).show();
}
else
m_search_results.setAdapter(new JSONAdapter(getApplicationContext()));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class JSONAdapter extends BaseAdapter
{
public JSONAdapter(Context c){
}
public int getCount()
{
return m_results.length();
}
public Object getItem(int arg0){
return null;
}
public long getItemId(int pos){
return pos;
}
public View getView(int pos, View convertView, ViewGroup parent) {
View tv;
TextView t;
if (convertView == null)
tv = m_inflater.inflate (R.layout.item, parent, false);
else
tv = convertView;
try {
/* For each entry in the ListView, we need to populate
* its text and timestamp */
t = (TextView) tv.findViewById(R.id.text);
JSONObject obj = m_results.getJSONObject(pos);
t.setText (obj.getString("title").replaceAll("</?(?i:<|>|...|"|&|;|)(.|\n)*?>", ""));
//("\\<.*?\\>", ""))
t = (TextView) tv.findViewById(R.id.created_at);
JSONObject meta = obj.getJSONObject("meta");
// url = meta.getString("eventURL");
trackBack = obj.getString("url");
assetId = meta.getString("assetTypeId");
//String eventDate = meta.getString("startDate");
Calendar currentDate = Calendar.getInstance();
long dateNow = currentDate.getTimeInMillis();
String eventDate = meta.getString("startDate");
String endDate = meta.getString("endDate");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
Date date2 = null;
try {
date = formatter.parse(eventDate);
date2 = formatter.parse(endDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long modifiedDate= date.getTime();
long modifiedEndDate = date2.getTime();
if ( Long.valueOf(dateNow).compareTo(Long.valueOf(modifiedDate)) > 0 || Long.valueOf(dateNow).compareTo(Long.valueOf(modifiedEndDate)) > 0)
{
t.setText ("Was:" + "\t"+eventDate+"\n"+"Location:" +"\t" +meta.getString("location")+"\n" + meta.getString("eventURL") +"\n"+ obj.getString("url"));
}
else {
t.setText ("When:" + "\t"+eventDate+"\n"+"Location:" +"\t" +meta.getString("location")+"\n"+ meta.getString("eventURL") +"\n"+ obj.getString("url"));
}
} catch (JSONException e) {
Log.e("alatta", e.getMessage());
}
return tv;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*try {
JSONObject obj = m_results.getJSONObject(position);
JSONObject meta = obj.getJSONObject("meta");
url = meta.getString("eventURL");
//Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
//StayActiveActivity.this.startActivity(intent);
} catch (JSONException e) {
Log.e("alatta",e.getMessage());
}*/
// TODO Auto-generated method stub
final CharSequence[] items = {"Register", "Additional Information"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please Select an Option");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if (which == 0){
Intent intent1 = new Intent (StayActiveActivity.this, ReviewActivity.class);
StayActiveActivity.this.startActivity(intent1);
}
else if ( which == 1){
Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
StayActiveActivity.this.startActivity(intent);
}
}
});
AlertDialog alert = builder.create();
alert.show();
}}
WebViewActivity
package my.stayactive.plan;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewActivity extends StayActiveActivity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView);
WebSettings setting = webView.getSettings();
setting.setJavaScriptEnabled(true);
if (url != null && url.length()>0) {
webView.loadUrl(url);
}
}
}
You didn't pass URL to your WebViewActivity. To do that:
Before calling startActivity(), attach your URL to the intent with setData().
In onCreate() of WebViewActivity, retrieve the URL with getData(), then load it.
Or search for putExtra(...). You can transfer a number of data with Intent.
— edited —
Example:
To set data:
import android.net.Uri;
//...
Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
intent.setData(Uri.parse("your-url"));
StayActiveActivity.this.startActivity(intent);
To retrieve data:
//...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
Uri uri = getIntent().getData();
//...
webView.loadUrl(uri.toString());
}
My guess is that your URLs are redirecting and that you aren't handling the redirects so nothing is being shown.
try adding this to your webview activity:
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return false;
}
});
Also it would be a good idea since you have an if statement in your WebView activity to log the url so that you can be certain that it is actually making it in to the activity correctly. If not the web view would never load anything.
EDIT: actually upon closer look it doesn't seem like you're setting the 'url' variable anywhere so it would be null, thus not calling your loadUrl method because of the if statement.