android - how to assign textview value into string -


i want dynamically assign value of textview name "tvdistanceduration" string pass string activity

textview tvdistanceduration; public string f= "";  @override protected void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     setcontentview(r.layout.publicplaceactivity);      tvdistanceduration = (textview) findviewbyid(r.id.tv_distance_time);     // initializing      f = tvdistanceduration.gettext().tostring(); 

this code when view f shown nothing how can assign textview value f varaible ?

first activity contain textview

package com.example.project;  import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import java.net.httpurlconnection; import java.net.url; import java.util.arraylist; import java.util.hashmap; import java.util.list;  import org.json.jsonobject;  import android.content.intent; import android.graphics.color; import android.os.asynctask; import android.os.bundle; import android.support.v4.app.fragmentactivity; import android.util.log; import android.view.menu; import android.view.view; import android.widget.textview; import android.widget.toast;  import com.google.android.gms.maps.googlemap; import com.google.android.gms.maps.googlemap.onmapclicklistener; import com.google.android.gms.maps.supportmapfragment; import com.google.android.gms.maps.model.bitmapdescriptorfactory; import com.google.android.gms.maps.model.latlng; import com.google.android.gms.maps.model.markeroptions; import com.google.android.gms.maps.model.polylineoptions;   public class publicplaceactivity extends fragmentactivity {      googlemap map;     arraylist<latlng> markerpoints;     textview tvdistanceduration;     public string f= "";      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.publicplaceactivity);          tvdistanceduration = (textview) findviewbyid(r.id.tv_distance_time);         // initializing          f = tvdistanceduration.gettext().tostring();         markerpoints = new arraylist<latlng>();          // getting reference supportmapfragment of activity_main         supportmapfragment fm = (supportmapfragment)getsupportfragmentmanager().findfragmentbyid(r.id.map);          // getting map supportmapfragment         map = fm.getmap();          // enable mylocation button in map         map.setmylocationenabled(true);               // setting onclick event listener map         map.setonmapclicklistener(new onmapclicklistener() {              @override             public void onmapclick(latlng point) {                  // 2 locations                                 if(markerpoints.size()>1){                     markerpoints.clear();                     map.clear();                                     }                  // adding new item arraylist                 markerpoints.add(point);                                  // creating markeroptions                 markeroptions options = new markeroptions();                  // setting position of marker                 options.position(point);                   //int s = markerpoints.size();                 /**                   * start location, color of marker green ,                  * end location, color of marker red.                  */                 if(markerpoints.size()==1){                     options.icon(bitmapdescriptorfactory.defaultmarker(bitmapdescriptorfactory.hue_green));                 }else if(markerpoints.size()==2){                     options.icon(bitmapdescriptorfactory.defaultmarker(bitmapdescriptorfactory.hue_red));                 }                 else{                     options.icon(bitmapdescriptorfactory.defaultmarker(bitmapdescriptorfactory.hue_yellow));                 }                   // add new marker google map android api v2                 map.addmarker(options);                  // checks, whether start , end locations captured                 if(markerpoints.size() >= 2){                                        latlng origin = markerpoints.get(0);                     latlng dest = markerpoints.get(1);                     //latlng next = markerpoints.get(2);                      // getting url google directions api                     string url = getdirectionsurl(origin, dest);                                      downloadtask downloadtask = new downloadtask();                      // start downloading json data google directions api                     downloadtask.execute(url);                 }              }         });      }      private string getdirectionsurl(latlng origin,latlng dest ){          // origin of route         string str_origin = "origin="+origin.latitude+","+origin.longitude;          // destination of route         string str_dest = "destination="+dest.latitude+","+dest.longitude;          //string str_next = "next="+next.latitude+","+next.longitude;            // sensor enabled         string sensor = "sensor=false";                   // building parameters web service         string parameters = str_origin+"&"+str_dest+"&"+sensor;          // output format         string output = "json";          // building url web service         string url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;           return url;     }      public void onclick(view view) {         intent intent = new intent(this, sms.class);         intent.putextra("message_body",f);                 startactivity(intent);          }      /** method download json data url */     private string downloadurl(string strurl) throws ioexception{         string data = "";         inputstream istream = null;         httpurlconnection urlconnection = null;         try{                 url url = new url(strurl);                  // creating http connection communicate url                  urlconnection = (httpurlconnection) url.openconnection();                  // connecting url                  urlconnection.connect();                  // reading data url                  istream = urlconnection.getinputstream();                  bufferedreader br = new bufferedreader(new inputstreamreader(istream));                  stringbuffer sb  = new stringbuffer();                  string line = "";                 while( ( line = br.readline())  != null){                         sb.append(line);                 }                  data = sb.tostring();                  br.close();          }catch(exception e){                 log.d("exception while downloading url", e.tostring());         }finally{                 istream.close();                 urlconnection.disconnect();         }         return data;      }        // fetches data url passed     private class downloadtask extends asynctask<string, void, string>{                   // downloading data in non-ui thread         @override         protected string doinbackground(string... url) {              // storing data web service             string data = "";              try{                 // fetching data web service                 data = downloadurl(url[0]);             }catch(exception e){                 log.d("background task",e.tostring());             }             return data;                 }          // executes in ui thread, after execution of         // doinbackground()         @override         protected void onpostexecute(string result) {                        super.onpostexecute(result);                          parsertask parsertask = new parsertask();              // invokes thread parsing json data             parsertask.execute(result);          }            }      /** class parse google places in json format */     private class parsertask extends asynctask<string, integer, list<list<hashmap<string,string>>> >{          // parsing data in non-ui thread                 @override         protected list<list<hashmap<string, string>>> doinbackground(string... jsondata) {              jsonobject jobject;              list<list<hashmap<string, string>>> routes = null;                                   try{                 jobject = new jsonobject(jsondata[0]);                 directionsjsonparser parser = new directionsjsonparser();                  // starts parsing data                 routes = parser.parse(jobject);                 }catch(exception e){                 e.printstacktrace();             }             return routes;         }          // executes in ui thread, after parsing process         @override         protected void onpostexecute(list<list<hashmap<string, string>>> result) {             arraylist<latlng> points = null;             polylineoptions lineoptions = null;             string distance = "";             string duration = "";                if(result.size()<1){                 toast.maketext(getbasecontext(), "no points", toast.length_short).show();                 return;             }               // traversing through routes             for(int i=0;i<result.size();i++){                 points = new arraylist<latlng>();                 lineoptions = new polylineoptions();                  // fetching i-th route                 list<hashmap<string, string>> path = result.get(i);                  // fetching points in i-th route                 for(int j=0;j<path.size();j++){                     hashmap<string,string> point = path.get(j);                       if(j==0){   // distance list                         distance = (string)point.get("distance");                                                continue;                     }else if(j==1){ // duration list                         duration = (string)point.get("duration");                         continue;                     }                      double lat = double.parsedouble(point.get("lat"));                     double lng = double.parsedouble(point.get("lng"));                     latlng position = new latlng(lat, lng);                       points.add(position);                                        }                  // adding points in route lineoptions                 lineoptions.addall(points);                 lineoptions.width(3);                 lineoptions.color(color.red);                 }              tvdistanceduration.settext("distance:"+distance + ", duration:"+duration);              // drawing polyline in google map i-th route             map.addpolyline(lineoptions);                                    }                }          @override     public boolean oncreateoptionsmenu(menu menu) {         // inflate menu; adds items action bar if present.         getmenuinflater().inflate(r.menu.main, menu);         return true;     }    } 

second activiy take string in textview , put sms body

package com.example.project;   import android.app.activity; import android.app.pendingintent; import android.content.broadcastreceiver; import android.content.context; import android.content.intent; import android.content.intentfilter; import android.os.bundle; import android.telephony.smsmanager; import android.view.view; import android.widget.button; import android.widget.edittext; import android.widget.toast;  public class sms extends activity  {     button btnsendsms;     edittext txtphoneno;     edittext txtmessage;     /** called when activity first created. */     @override     public void oncreate(bundle savedinstancestate)      {         super.oncreate(savedinstancestate);         setcontentview(r.layout.main);              intent intent = getintent();         string name = intent.getstringextra("message_body");         btnsendsms = (button) findviewbyid(r.id.btnsendsms);         txtphoneno = (edittext) findviewbyid(r.id.txtphoneno);         txtmessage = (edittext) findviewbyid(r.id.txtmessage);         txtmessage.settext(name);         /*         intent sendintent = new intent(intent.action_view);         sendintent.putextra("sms_body", "content of sms goes here...");          sendintent.settype("vnd.android-dir/mms-sms");         startactivity(sendintent);         */          btnsendsms.setonclicklistener(new view.onclicklistener()          {             public void onclick(view v)              {                                string phoneno = txtphoneno.gettext().tostring();                  string message = txtmessage.gettext().tostring();                                if (phoneno.length()>0 && message.length()>0)                                     sendsms(phoneno, message);                                 else                     toast.maketext(getbasecontext(),                          "please enter both phone number , message.",                          toast.length_short).show();             }         });             }      //---sends sms message device---     private void sendsms(string phonenumber, string message)     {               /*         pendingintent pi = pendingintent.getactivity(this, 0,                 new intent(this, test.class), 0);                             smsmanager sms = smsmanager.getdefault();             sms.sendtextmessage(phonenumber, null, message, pi, null);                 */          string sent = "sms_sent";         string delivered = "sms_delivered";          pendingintent sentpi = pendingintent.getbroadcast(this, 0,             new intent(sent), 0);          pendingintent deliveredpi = pendingintent.getbroadcast(this, 0,             new intent(delivered), 0);          //---when sms has been sent---         registerreceiver(new broadcastreceiver(){             @override             public void onreceive(context arg0, intent arg1) {                 switch (getresultcode())                 {                     case activity.result_ok:                         toast.maketext(getbasecontext(), "sms sent",                                  toast.length_short).show();                         break;                     case smsmanager.result_error_generic_failure:                         toast.maketext(getbasecontext(), "generic failure",                                  toast.length_short).show();                         break;                     case smsmanager.result_error_no_service:                         toast.maketext(getbasecontext(), "no service",                                  toast.length_short).show();                         break;                     case smsmanager.result_error_null_pdu:                         toast.maketext(getbasecontext(), "null pdu",                                  toast.length_short).show();                         break;                     case smsmanager.result_error_radio_off:                         toast.maketext(getbasecontext(), "radio off",                                  toast.length_short).show();                         break;                 }             }         }, new intentfilter(sent));          //---when sms has been delivered---         registerreceiver(new broadcastreceiver(){             @override             public void onreceive(context arg0, intent arg1) {                 switch (getresultcode())                 {                     case activity.result_ok:                         toast.maketext(getbasecontext(), "sms delivered",                                  toast.length_short).show();                         break;                     case activity.result_canceled:                         toast.maketext(getbasecontext(), "sms not delivered",                                  toast.length_short).show();                         break;                                       }             }         }, new intentfilter(delivered));                  smsmanager sms = smsmanager.getdefault();         sms.sendtextmessage(phonenumber, null, message, sentpi, deliveredpi);                    }     } 

tvdistanceduration = (textview) findviewbyid(r.id.tv_distance_time); //collecting data string text = tvdistanceduration.gettext().tostring();  //sending activity intent = new intent(currentactivity.this,newactivity.class); //here 'mydata' key i.putextra("mydata",text); startactivity(i); 

from receiver activity, can collect data this

string arriveddata = getintent().getstringextra("mydata"); 

a detailed example can found here

the problem in code variable named f empty, because collecting text after initialization. if want collect data textview, must assign new value using textview.settext("new value") . , can collect data using f = tvdistanceduration.gettext().tostring();. f contain latest updated data.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -