I have some data on the internet for each specific longitude and latitude. If a user inputs a particular latitude and longitude, the data is downloaded from the web and then used in further calculation. I want to save that data so that the next time the user inputs the same latitude and longitude, It bypasses the web connectivity and proceeds with the existing data.
My Input Class:
public class OpTilt extends Activity implements OnClickListener {
EditText latitude, longitude;
Button go;
String data1, data2, link, link1;
double dat1, dat2;
TextView gps;
SharedPreferences dataurl;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.optilt);
initialize();
go.setOnClickListener(this);
}
private void initialize() {
// TODO Auto-generated method stub
go = (Button) findViewById(R.id.loaddata);
latitude = (EditText) findViewById(R.id.lat);
longitude = (EditText) findViewById(R.id.lon);
dataurl = getSharedPreferences("url", 0);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
data1 = longitude.getText().toString();
data2 = latitude.getText().toString();
dat1 = Double.parseDouble(data1);
dat2 = Double.parseDouble(data2);
link = ("http://www.otilt.com/api.php?lat=" + dat2 + "&lon=" + dat1);
SharedPreferences.Editor editor = dataurl.edit();
editor.putString("key", link);
editor.commit();
Intent i = new Intent(OpTilt.this, DataRetrieve.class);
startActivity(i);
}
}
My Parsing Class:
public class DataRetrieve extends Activity {
HttpClient client;
String URL, re, element;
JSONObject json, getjson;
int i, j, statusCode;
HttpGet httpget;
HttpResponse response;
HttpEntity entity;
InputStream is;
BufferedReader reader;
StringBuilder sb, sb1;
WakeLock w;
SharedPreferences getinput, passjson;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
w = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "tag");
super.onCreate(savedInstanceState);
w.acquire();
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.dataretrieve);
// Bundle gotBasket = getIntent().getExtras();
// URL = gotBasket.getString("key");
getinput = getSharedPreferences("url", 0);
URL = getinput.getString("key", null);
Read r = new Read();
r.execute();
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pd = new ProgressDialog(DataRetrieve.this);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
re = null;
is = null;
json = null;
try {
client = new DefaultHttpClient();
httpget = new HttpGet(URL);
response = client.execute(httpget);
entity = response.getEntity();
is = entity.getContent();
statusCode = response.getStatusLine().getStatusCode();
} catch (Exception e) {
statusCode = -1;
Log.e("log_tag", "Erro http " + e.toString());
}
if (statusCode == 200) {
try {
reader = new BufferedReader(new InputStreamReader(is,
"UTF-8"), 8);
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
re = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Erro conversão " + e.toString());
}
}
return re;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
pd.dismiss();
try {
json = new JSONObject(result);
getjson = json.getJSONObject("Solar");
String H[] = new String[getjson.length()];
for (i = 0, j = 1; i < getjson.length(); i++, j++) {
H[i] = getjson.getString("" + j);
}
Bundle bundle = new Bundle();
bundle.putStringArray("key1", H);
Intent f = new Intent(DataRetrieve.this, Calculator.class);
f.putExtras(bundle);
startActivity(f);
}
catch (JSONException e) {
Log.e("log_tag", "Erro dados " + e.toString());
}
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
w.release();
finish();
}
}
So, how can I achieve my goal?
Related
below is my code there is a problem some where in getDataTask if i remove this class is work fine and print Toast message Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); but what is problem in my getDataTask im parsing below json file problem is some where in doinbackground method help me please
{"status":0,"message":"No such school found"}
public class thirdstep extends Activity {
ListView listCategory;
String status;
String message;
String MenuSelect;
ProgressBar prgLoading;
long Cat_ID;
String Cat_name;
String CategoryAPI;
int IOConnect = 0;
TextView txtAlert;
thirdstepAdapter cla;
static ArrayList<String> Category_ID = new ArrayList<String>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list2);
ImageButton btnback = (ImageButton) findViewById(R.id.btnback);
listCategory = (ListView) findViewById(R.id.listCategory2);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
cla = new thirdstepAdapter(thirdstep.this);
new getDataTask().execute();
listCategory.setAdapter(cla);
btnback.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
Intent iGet = getIntent();
Cat_ID = iGet.getLongExtra("category_id", 0);
Cat_name = iGet.getStringExtra("category_name");
Toast.makeText(this, Cat_ID + Cat_name, Toast.LENGTH_SHORT).show();
MenuSelect = Utils.MenuSelect;
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(thirdstep.this, fourthscreen.class);
iMenuList.putExtra("Cat_ID",Cat_ID);
iMenuList.putExtra("Menuitem", Category_ID.get(position));
startActivity(iMenuList);
}
});
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void>{
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
prgLoading.setVisibility(8);
if((Category_ID.size() > 0) || IOConnect == 0){
listCategory.setVisibility(0);
listCategory.setAdapter(cla);
}else{
txtAlert.setVisibility(0);
}
}
}
public void parseJSONData() {
CategoryAPI = Utils.MenuList + Cat_ID;
clearData();
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json = new JSONObject(str);
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
message = json2.getString("message");
if (status.equals("1")) {
JSONObject data = json.getJSONObject("data");
JSONArray school = data.getJSONArray("menu_groups");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
Category_ID.add(object.getString("id"));
Category_name.add(object.getString("title"));
Category_image.add(object.getString("image"));
}
}
else
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You are calling parseJSONData() in doInbackground and you have this
Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); // in parseJSONData()
you cannot update ui from doInbackground. You need to update ui on the ui thread. Return result in doInbackground. In onPostExecute update ui.
When I call asynctask function data is load and display in listview but whenever i go into this activity everytime that function execute and load data again. But I just want that function call only once and display in listview. So what is the solution for that.
This is My full class code:
public class Feed extends Fragment implements
PullToRefreshAttacher.OnRefreshListener {
Button btnSlider;
ListView lv;
String userid, success, message, eventType, feed_title, feed_desc,
timeDate, like, commemt, Feeduserid, photo, posted, hasLike,
latsId, noMore, feed_id, category_id, feedImg, result;
InputStream is;
ProgressDialog pDialog;
InterNetConnectionDetector isNet = new InterNetConnectionDetector(
getActivity());
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
FeedAdapter fdp;
HashMap<String, String> map;
private uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher mPullToRefreshAttacher;
int limit = 5;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
v = inflater.inflate(R.layout.feed, container, false);
if (android.os.Build.VERSION.SDK_INT > 8) {
StrictMode.ThreadPolicy stp = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(stp);
}
SharedPreferences pref = getActivity().getSharedPreferences("Login",
Activity.MODE_PRIVATE);
userid = pref.getString("user_id", "user_id");
btnSlider = (Button) v.findViewById(R.id.btnSlide);
lv = (ListView) v.findViewById(R.id.feed_ListView);
btnSlider.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
Sliding.viewActionsContentView.showActions();
} catch (Exception e) {
// TODO: handle exception
}
}
});
try {
if (fdp == null) {
new FeedData().execute();
} else {
lv.setAdapter(fdp);
}
} catch (Exception e) {
// TODO: handle exception
}
mPullToRefreshAttacher = new uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher(
getActivity(), lv);
// Set Listener to know when a refresh should be started
mPullToRefreshAttacher
.setRefreshListener((uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher.OnRefreshListener) this);
((LoadMore) lv)
.setOnLoadMoreListener(new com.example.getconnected.LoadImage.LoadMore.OnLoadMoreListener() {
public void onLoadMore() {
// Do the work to load more items at the end of list
// here
new LoadDataTask().execute();
}
});
return v;
}
/*
* #Override protected void onCreate(Bundle savedInstanceState) { // TODO
* Auto-generated method stub super.onCreate(savedInstanceState);
* setContentView(R.layout.feed);
*
* if (Build.VERSION.SDK_INT >= 8) { getActionBar().hide(); }
*
* if (android.os.Build.VERSION.SDK_INT > 8) {
*
* StrictMode.ThreadPolicy stp = new StrictMode.ThreadPolicy.Builder()
* .permitAll().build(); StrictMode.setThreadPolicy(stp);
*
* }
*
* try { new FeedData().execute();
*
* } catch (Exception e) { // TODO: handle exception }
*
* SharedPreferences pref = getSharedPreferences("Login",
* Activity.MODE_PRIVATE); userid = pref.getString("user_id", "user_id");
*
* btnSlider = (Button) findViewById(R.id.btnSlide); lv = (ListView)
* findViewById(R.id.feed_ListView); btnSlider.setOnClickListener(new
* OnClickListener() {
*
* #Override public void onClick(View arg0) { // TODO Auto-generated method
* stub
*
* int width = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
* 40, getResources() .getDisplayMetrics());
* SlideoutActivity.prepare(getActivity(), R.id.inner_content, width);
* startActivity(new Intent(getActivity(), MenuActivity.class));
* getoverridePendingTransition(0, 0);
*
* } });
*
* mPullToRefreshAttacher = new PullToRefreshAttacher(getActivity(), lv);
*
* // Set Listener to know when a refresh should be started
* mPullToRefreshAttacher .setRefreshListener((OnRefreshListener)
* getActivity());
*
* ((LoadMore) lv) .setOnLoadMoreListener(new
* com.example.getconnected.LoadImage.LoadMore.OnLoadMoreListener() { public
* void onLoadMore() { // Do the work to load more items at the end of list
* // here new LoadDataTask().execute(); } }); }
*/
public class FeedData extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = ProgressDialog.show(getActivity(), "", "Loading..");
pDialog.setCancelable(true);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// data=jobj.toString();
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://www.sevenstarinfotech.com/projects/demo/GetConnected/api/feed.php?user_id="
+ userid + "&" + "limit=" + limit;
HttpPost httppost = new HttpPost(url);
Log.v("Feed Url:", url);
httppost.addHeader("Content-Type",
"application/x-www-form-urlencoded");
httppost.addHeader("app-key",
"b51bc98b4d6fd0456f7f1b17278415fa49de57d5");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.v("Response is:", result);
} catch (Exception e3) {
Log.e("log_tag", "Error converting result " + e3.toString());
}
// parse json data
try {
JSONObject ja = new JSONObject(result);
JSONObject jdata = ja.getJSONObject("data");
success = jdata.getString("Success");
message = jdata.getString("Message");
latsId = jdata.getString("lastId");
noMore = jdata.getString("nomore");
JSONArray jArray = jdata.getJSONArray("Feeddetails");
for (int i = 0; i < jArray.length(); i++) {
map = new HashMap<String, String>();
JSONObject me = jArray.getJSONObject(i);
map.put("sucess", success);
map.put("message", message);
map.put("latsId", latsId);
map.put("noMore", noMore);
eventType = me.getString("type");
feed_id = me.getString("feed_id");
feed_title = me.getString("feed_title");
category_id = me.getString("category_id");
feed_desc = me.getString("feed_desc");
timeDate = me.getString("timeposted");
posted = me.getString("postedby");
like = me.getString("likes");
photo = me.getString("photo");
commemt = me.getString("comments");
Feeduserid = me.getString("user_id");
hasLike = me.getString("hasliked");
map.put("eventType", eventType);
map.put("feed_id", feed_id);
map.put("feed_title", feed_title);
map.put("category_id", category_id);
map.put("feed_desc", feed_desc);
map.put("timeDate", timeDate);
map.put("posted", posted);
map.put("like", like);
map.put("photo", photo);
map.put("commemt", commemt);
map.put("Feeduserid", Feeduserid);
map.put("hasLike", hasLike);
Log.v("Data:", feed_id + "/" + "/" + "/" + Feeduserid
+ "/" + "/" + "/" + like + "/" + "/" + "/"
+ commemt);
contactList.add(map);
}
Log.v("Length", contactList.size() + "");
} catch (Exception e1) {
Log.e("log_tag",
"Error in http connection " + e1.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
pDialog.dismiss();
fdp = new FeedAdapter(getActivity(), contactList);
lv.setAdapter(fdp);
}
}
#Override
public void onRefreshStarted(View view) {
/**
* Simulate Refresh with 4 seconds sleep
*/
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Notify PullToRefreshAttacher that the refresh has finished
mPullToRefreshAttacher.setRefreshComplete();
}
}.execute();
}
private class LoadDataTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
if (isCancelled()) {
return null;
}
// Simulates a background task
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
limit += 5;
DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://www.sevenstarinfotech.com/projects/demo/GetConnected/api/feed.php?user_id="
+ userid + "&" + "limit=" + limit;
HttpPost httppost = new HttpPost(url);
Log.v("Feed Url:", url);
httppost.addHeader("Content-Type",
"application/x-www-form-urlencoded");
httppost.addHeader("app-key",
"b51bc98b4d6fd0456f7f1b17278415fa49de57d5");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.v("Response is:", result);
} catch (Exception e3) {
Log.e("log_tag", "Error converting result " + e3.toString());
}
// parse json data
try {
JSONObject ja = new JSONObject(result);
JSONObject jdata = ja.getJSONObject("data");
success = jdata.getString("Success");
message = jdata.getString("Message");
latsId = jdata.getString("lastId");
noMore = jdata.getString("nomore");
JSONArray jArray = jdata.getJSONArray("Feeddetails");
for (int i = 0; i < jArray.length(); i++) {
map = new HashMap<String, String>();
JSONObject me = jArray.getJSONObject(i);
map.put("sucess", success);
map.put("message", message);
map.put("latsId", latsId);
map.put("noMore", noMore);
eventType = me.getString("type");
feed_id = me.getString("feed_id");
feed_title = me.getString("feed_title");
category_id = me.getString("category_id");
feed_desc = me.getString("feed_desc");
timeDate = me.getString("timeposted");
posted = me.getString("postedby");
like = me.getString("likes");
photo = me.getString("photo");
commemt = me.getString("comments");
Feeduserid = me.getString("user_id");
hasLike = me.getString("hasliked");
map.put("eventType", eventType);
map.put("feed_id", feed_id);
map.put("feed_title", feed_title);
map.put("category_id", category_id);
map.put("feed_desc", feed_desc);
map.put("timeDate", timeDate);
map.put("posted", posted);
map.put("like", like);
map.put("photo", photo);
map.put("commemt", commemt);
map.put("Feeduserid", Feeduserid);
map.put("hasLike", hasLike);
Log.v("Data:", feed_id + "/" + "/" + "/" + Feeduserid
+ "/" + "/" + "/" + like + "/" + "/" + "/"
+ commemt);
contactList.add(map);
}
pDialog.dismiss();
fdp = new FeedAdapter(getActivity(), contactList);
lv.setAdapter(fdp);
} catch (Exception e1) {
Log.e("log_tag",
"Error in http connection " + e1.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
// mListItems.add("Added after load more");
// We need notify the adapter that the data have been changed
fdp.notifyDataSetChanged();
// Call onLoadMoreComplete when the LoadMore task, has finished
((LoadMore) lv).onLoadMoreComplete();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
((LoadMore) lv).onLoadMoreComplete();
}
}
}
Better option is like, just declare your ADAPTER as public static in your ROOT class or in your activity. This will make single copy. And you are done with.
Suppose you have following structure.
ABC (ROOT/SPLASH) Activity -> class Feed extends Fragment
So basically you are calling Feed from ABC. Inside ABC, declare like
public class ABC...{
public static FeedAdapter fdp;
//.. all other stuffs
}
public class Feed...{
//.. to use that object delcared in ABC
ABC.fdp = new FeedAdapter(...);
}
I am using a webview for rendering an epub and I am able to implement text to speech functionality, but i am unable to highlight the text!
I tried:
public class Epub extends Activity implements OnInitListener, OnUtteranceCompletedListener {
ProgressDialog pDialog;
WebView webview;
String line, line1 = "", finalstr = "";
int i = 0;
Book book;
String linez;
String abspath="file://android_asset/Images/";
private TextToSpeech mTts;
String htmlTextStr;
private int MY_DATA_CHECK_CODE = 0;
private HashMap<String, String> params = new HashMap<String, String>();
private int uttCount = 0;
StringTokenizer st;
private int lastUtterance = -1;
ArrayList <String> words = new ArrayList<String> ();
ArrayList <String> Swords = new ArrayList<String> ();
String utteranceId;
HashMap<String, String> lastSpokenWord = new HashMap<String, String>();
String s;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Load().execute();
mTts = new TextToSpeech(this, this);
Button mBtnSpeak = (Button) findViewById(R.id.btn);
webview = (WebView) findViewById(R.id.tv);
mBtnSpeak.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doSpeak(htmlTextStr);
}
});
}
class Load extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Epub.this);
pDialog.setMessage("Loading Epub...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
AssetManager assetManager = getAssets();
try {
Intent j = getIntent();
final String pos= j.getExtras().getString("product");
InputStream epubInputStream = assetManager.open(pos+".epub");
book = (new EpubReader()).readEpub(epubInputStream);
//coverImage =BitmapFactory.decodeStream(book.getCoverImage().getInputStream());
// Log.i("epublib", "Coverimage is " + coverImage.getWidth() + " by " + coverImage.getHeight() + " pixels");
// DownloadResource("file:///android_asset/");
} catch (IOException e) {
Log.e("epublib", e.getMessage());
}
Spine spine = book.getSpine();
List<SpineReference> spineList = spine.getSpineReferences() ;
int count = spineList.size();
//tv.setText(Integer.toString(count));
StringBuilder string = new StringBuilder();
for (int i = 0; count > i; i++) {
Resource res = spine.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = string.append(line + "\n").toString();
System.err.println("res media"+res.getMediaType());
htmlTextStr = Html.fromHtml(linez).toString();
Log.e("Html content.",htmlTextStr);
}
} catch (IOException e) {e.printStackTrace();}
//do something with stream
} catch (IOException e) {
e.printStackTrace();
}
}
webview.getSettings().setAllowFileAccess(true);
//System.err.println("qaz"+hr);
webview.getSettings().setBuiltInZoomControls(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadDataWithBaseURL("file:///android_asset/", linez, "application/xhtml+xml", "UTF-8", null);
return null;
}
protected void onPostExecute(String file_url)
{
pDialog.dismiss();
}
}
public void doSpeak(String htmlTextStr) {
st = new StringTokenizer(htmlTextStr,".");
while (st.hasMoreTokens()) {
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,String.valueOf(uttCount++));
mTts.speak(st.nextToken(), TextToSpeech.QUEUE_ADD, params);
words.add(htmlTextStr);
}
String arr[] = htmlTextStr.split(",");
for(int i = 0; i < arr.length; i++){
System.out.println("arr["+i+"] = " + arr[i].trim());
s=arr[i].trim();
Swords.add(s);
runOnUiThread(new Runnable() {
public void run() {
webview.findAll(s);
System.err.println(" b - - >"+s);
webview.setSelected(true);
webview.findNext(true);
}
});
}
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
// status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR
if (status == TextToSpeech.SUCCESS) {
mTts.setOnUtteranceCompletedListener(this);
int result = mTts.setLanguage(Locale.UK);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
// Lanuage data is missing or the language is not supported.
Log.e("404","Language is not available.");
}
} else {
// Initialization failed.
Log.e("404", "Could not initialize TextToSpeech.");
// May be its not installed so we prompt it to be installed
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
installIntent.setAction(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
startActivity(installIntent);
}
}
#Override
public void onPause()
{
super.onPause();
if( mTts != null)
mTts.stop();
}
#Override
public void onDestroy() {
if (mTts != null) {
mTts.stop();
mTts.shutdown();
}
mTts.stop();
super.onDestroy();
}
#Override
public void onUtteranceCompleted(String utteranceId) {
// TODO Auto-generated method stub
Log.i("xsw",utteranceId);
lastUtterance = Integer.parseInt(utteranceId);
// createThread(s);
}
}
Could anybody help me out?
The below code is not working:
webview.findall("string");
webview.setSelected(true);
webview.findNext(true);
In my activity i have an AsyncTask, in which i had overridden doInBackGround.
In the same activity i have a camera intent to open the camera and allow user to take a pic
The problem is when i call the camera intent it is triggering the doInBackGround method i overrode. Which eventually gives me a SingleClientConnManager exception which asks me to release the client before allocating it again.
Here is my activity code:
public class UserProfileActivity extends Activity {
//many instance fiels here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_profile);
new LongOperation().execute("");
userImage = (ImageView) findViewById(R.id.profileImage);
userName = (TextView) findViewById(R.id.userName_profile);
userLocation = (TextView) findViewById(R.id.userLocation_profile);
editInfo = (TextView) findViewById(R.id.edit_profile);
changeImage = (TextView) findViewById(R.id.changeImage_profile);
userScore = (TextView) findViewById(R.id.userScore_profile);
friendsLabel = (TextView) findViewById(R.id.userFriends_profile);
changeImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
//Point 1
}
});
//Point 2
}
private class LongOperation extends AsyncTask<String, Void, String> {
private InputStream is;
private StringBuilder sb;
private String result;
private ProgressDialog dialog = new ProgressDialog(context);
#Override
protected String doInBackground(String... params) {
//Point 3
try {
HttpResponse response;
HttpPost httppost = new HttpPost(
"http://www.xxxxx.com/yyyy/zzzz");
//httpclient is global to maintain sessions
response = SignUpActivity.httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("error in reading input stream", e.toString());
}
try {
JSONObject jObj = new JSONObject(result);
String status = jObj.getString("status");
score = jObj.getInt("credits");
level = jObj.getInt("level");
image = jObj.getString("image");
fname = jObj.getString("fname");
lname = jObj.getString("lname");
city = jObj.getString("city");
email = jObj.getString("email");
clickedUserId = jObj.getInt("user_id");
JSONArray friendsJsonArray = jObj.getJSONArray("friends");
size = friendsJsonArray.length();
ArrayList<String> friendsNames = new ArrayList<String>();
friendsIds = new int[size];
for (int i = 0; i < size; i++) {
friendsNames.add(friendsJsonArray.getJSONObject(i)
.getString("name"));
friendsIds[i] = friendsJsonArray.getJSONObject(i)
.getInt("user_id");
}
adapter = new ArrayAdapter<String>(context,
R.layout.simple_listview_item, friendsNames);
} catch (Exception e) {
Log.d("error in creating json object", e.toString());
}
} catch (Exception e) {
//Point 5
Log.e("error main try", "Error in http connection" + e.toString());
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
friendsList.setAdapter(adapter);
userScore.setText(score + " points" + " level " + level);
userName.setText(fname + " " + lname);
userLocation.setText(city);
changeImage.setText("Change image");
editInfo.setText("Edit");
friendsLabel.setText("Friends");
Bitmap bitmap = null;
try {
bitmap = BitmapFactory
.decodeStream((InputStream) new URL(image).getContent());
userImage.setImageBitmap(bitmap);
} catch (MalformedURLException e1) {
e1.printStackTrace();
userImage.setImageResource(R.drawable.xxx);
} catch (IOException e2) {
e2.printStackTrace();
userImage.setImageResource(R.drawable.xxx);
}
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Point 4
if (resultCode == RESULT_OK) {
if (data != null) {
photo = (Bitmap) data.getExtras().get("data");
userImage.setImageBitmap(photo);
}else{
Intent intent = new Intent(UserProfileActivity.this,
UserProfileActivity.class);
startActivity(intent);
}
} else {
Intent intent = new Intent(UserProfileActivity.this,
UserProfileActivity.class);
startActivity(intent);
}
}
}
here in the code Point 1, 2, 3, 4, 5 gives the sequence of code flow once i click the changeImage TextView.
Please help me in solving this scenario.
Thank You.
If I am correct the problem is because of your device orientation get changed when you open camera.That calls your activity's onCreate() method again
please insert this line to your activity in menifest that is causing problem
<activity
android:name="your activity" android:configChanges="keyboardHidden|orientation"
/>
I success show my data from web service JSON in listview, but I want to add Asyntask.
Where I can put code Asyntask in my code.
This my code to show data in list view
public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
String status ="";
String date = "";
String result = "";
String url = "http://10.0.2.2/remix/view_list.php";
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
try
{
r_js = json.getJSONArray("view_list");
for (int i =0; i < r_js.length(); i++)
{
String my_array = "";
JSONObject ar = r_js.getJSONObject(i);
status = ar.getString("st");
date = ar.getString("date");
result = ar.getString("result");
if (status.trim().equals("er"))
{
my_array += "Sorry "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
else
{
my_array += "Date : "+date+" "+"Result : "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
adapter_listview();
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
setListAdapter(adapter);
}
}
And this JSONParser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject AmbilJson(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Where can I put code for Asyntask?
Ok, I get sample code, and my code now like this
public class Jadwal_remix extends ListActivity {
String v_date;
JSONArray r_js = null;
ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
private class myProses extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(Jadwal_remix.this, "", "Loading... Please wait", true);
}
protected Void doInBackground(Void... params) {
String status ="";
String date = "";
String result = "";
String url = "http://10.0.2.2/remix/view_list.php";
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
try
{
r_js = json.getJSONArray("view_list");
for (int i =0; i < r_js.length(); i++)
{
String my_array = "";
JSONObject ar = r_js.getJSONObject(i);
status = ar.getString("st");
date = ar.getString("date");
result = ar.getString("result");
if (status.trim().equals("er"))
{
my_array += "Sorry "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
else
{
my_array += "Date : "+date+" "+"Result : "+result;
HashMap<String, String> map = new HashMap<String, String>();
map.put("result", my_array);
myArray.add(map);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
protected void onPostExecute(Void unused) {
adapter_listview();
dialog.dismiss();
}
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, jadwalRemix,R.layout.my_list,new String[] { "result"}, new int[] {R.id.txtResult});
setListAdapter(adapter);
}
}
I'm get problem when server is die, it still loading.
How I can show message ex: can't connect to server?
Working ASyncTask tutorial,
Full ASyncTask Eclipse Project,
and here's some code that I think, when mixed with the above sample, will get you the result with the list that you desire (you'll have to adapt it to your needs a bit, though (pay attention to the list stuff, even though this is from a custom Dialog:
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Kies Facebook-account");
builder.setNegativeButton("Cancel", this);
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogLayout = inflater.inflate(R.layout.dialog, null);
builder.setView(dialogLayout);
final String[] items = {"Red", "Green", "Blue" };
builder.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.v("touched: ", items[which].toString());
}}
);
return builder.create();
}
This is my code please try this one,
MAinActivity.java
public class MyActivity extends Activity {
private ListView contests_listView;
private ProgressBar pgb;
ActivitiesBean bean;
ArrayList<Object> listActivities;
ActivityAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
contests_listView = (ListView) findViewById(R.id.activity_listView);
pgb = (ProgressBar) findViewById(R.id.contests_progressBar);
listActivities = new ArrayList<Object>();
new FetchActivitesTask().execute();
}
public class FetchActivitesTask extends AsyncTask<Void, Void, Void> {
int i =0;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pgb.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String url = "Your URL Here";
String strResponse = util.makeWebCall(url);
try {
JSONObject objResponse = new JSONObject(strResponse);
JSONArray jsonnodes = objResponse.getJSONArray(nodes);
for (i = 0; i < jsonnodes.length(); i++)
{
String str = Integer.toString(i);
Log.i("Value of i",str);
JSONObject jsonnode = jsonnodes.getJSONObject(i);
JSONObject jsonnodevalue = jsonnode.getJSONObject(node);
bean = new ActivitiesBean();
bean.title = jsonnodevalue.getString(title);
bean.image = jsonnodevalue.getString(field_activity_image_fid);
listActivities.add(bean);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pgb.setVisibility(View.GONE);
displayAdapter();
}
}
public void displayAdapter()
{
adapter = new ActivityAdapter(this, listActivities);
contests_listView.setAdapter(adapter);
contests_listView.setOnItemClickListener(new OnItemClickListener() {
//#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long id) {
// your onclick Activity
}
});
}
}
util.class
public static String makeWebCall(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
// HttpPost post = new HttpPost(url);
try {
HttpResponse httpResponse = client.execute(httpRequest);
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = httpResponse.getEntity();
InputStream instream = null;
if (entity != null) {
instream = entity.getContent();
}
return iStream_to_String(instream);
}
catch (IOException e) {
httpRequest.abort();
// Log.w(getClass().getSimpleName(), "Error for URL =>" + url, e);
}
return null;
}
public static String iStream_to_String(InputStream is1) {
BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String contentOfMyInputStream = sb.toString();
return contentOfMyInputStream;
}
}
ActivityBean.java
public class ActivitiesBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public String title;
public String image;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}