How to return string in java methods? - Stack Overflow

文章推薦指數: 80 %
投票人數:10人

Android studio wants to "transform 'featured_img_url' into final one element array". – zovin kc. Jan 19 '17 at 14:57. declare the ... Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore Howtoreturnstringinjavamethods? AskQuestion Asked 5yearsago Active 5yearsago Viewed 4ktimes -2 Ihaveaproblemwhereiamunabletoreturnastringfromthismethod.IwasunsuccessfulwhenItriedcreatinganewvariableoutsidetheResponse.Listener.ThisisprobablyverysimplebuthowdoIgoaboutreturningastringfromthismethod.ThestringIwanttoreturnisthe'featured_img_url'string. publicStringsecondServiceCall(Stringfeaturedmedia){ JsonObjectRequestjsonObjReq=newJsonObjectRequest(Request.Method.GET, "http://www.gadgetsinnepal.com/wp-json/wp/v2/media/"+featuredmedia,null,newResponse.Listener(){ @Override publicvoidonResponse(JSONObjectnested_response){ try{ JSONObjectguilld=nested_response.getJSONObject("guid"); Stringfeatured_img_url=guilld.getString("rendered"); Toast.makeText(getApplicationContext(),"IMAGE:"+featured_img_url,Toast.LENGTH_LONG).show(); }catch(JSONExceptione){ e.printStackTrace(); Toast.makeText(getApplicationContext(), "Error:"+e.getMessage(), Toast.LENGTH_LONG).show(); } } },newResponse.ErrorListener(){ @Override publicvoidonErrorResponse(VolleyErrorerror){ Toast.makeText(getApplicationContext(), "ERROR"+error.getMessage(),Toast.LENGTH_LONG).show(); } }); MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjReq); returnfeatured_img_url; } javaandroid Share Improvethisquestion Follow askedJan19'17at14:44 zovinkczovinkc 3111silverbadge55bronzebadges 3 2 Thefeatured_img_urlvariableonlyexistsinsideyouronResponse()method.ItdoesnotexistinsidesecondServiceCall.WhensecondServiceCallmethodcompletes,theonResponse()methodmightnotevenhavebeencalled,soitisimpossibletotryreturnavariablecreatedinsideit. – khelwood Jan19'17at14:46 Soasmypalscorrectlysaidyoucannotretrievethatvaluereturning,soyoushouldcreateamethodthattakesasparameteryourvariablefeatured_img_urlanduseit,thismethodneedstobecalledinsideonResponse() – marcosE. Jan19'17at14:49 simpledeclarethestringinglobalandupdatethisinsideonResponse. – AnkushBist Jan19'17at14:50 Addacomment  |  2Answers 2 Active Oldest Votes 0 updateyourcodeto: Stringfeatured_img_url=null; publicStringsecondServiceCall(Stringfeaturedmedia){ JsonObjectRequestjsonObjReq=newJsonObjectRequest(Request.Method.GET, "http://www.gadgetsinnepal.com/wp-json/wp/v2/media/"+featuredmedia,null,newResponse.Listener(){ @Override publicvoidonResponse(JSONObjectnested_response){ try{ JSONObjectguilld=nested_response.getJSONObject("guid"); featured_img_url=guilld.getString("rendered"); Toast.makeText(getApplicationContext(),"IMAGE:"+featured_img_url,Toast.LENGTH_LONG).show(); }catch(JSONExceptione){ e.printStackTrace(); Toast.makeText(getApplicationContext(), "Error:"+e.getMessage(), Toast.LENGTH_LONG).show(); } } },newResponse.ErrorListener(){ @Override publicvoidonErrorResponse(VolleyErrorerror){ Toast.makeText(getApplicationContext(), "ERROR"+error.getMessage(),Toast.LENGTH_LONG).show(); } }); MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjReq); returnfeatured_img_url; } Share Improvethisanswer Follow answeredJan19'17at14:52 AnkushBistAnkushBist 1,78411goldbadge1212silverbadges3232bronzebadges 6 Thiswillreturnthepreviousvalueornulliftheinstancenevergetaresponse.Thiscallisasynchronous. – AxelH Jan19'17at14:54 yeahforthatyoucanassignsomeerror.AsiftheasyncTaskwillnotgetresponsethatwillmovetosomeanothermethodoryoucanassignsomedefaultvaluetothevariable – AnkushBist Jan19'17at14:57 Itdoesn'twork.Androidstudiowantsto"transform'featured_img_url'intofinaloneelementarray". – zovinkc Jan19'17at14:57 declarethestringoutsidethemethod. – AnkushBist Jan19'17at14:58 1 @AxelHyouarerightthemethodwillreturnthestringbeforetherequestreturnsdata. – AnkushBist Jan19'17at15:03  |  Show1morecomment 0 Here,youshouldsimplypasstheinstancethatcallthismethodstoexecutethemethodsfromtheresponse. Sochangethemethodsto: publicvoidsecondServiceCall(Stringfeaturedmedia,finalMyClasscaller){ Notethatthiswillreturnnothing.AndthecallerinstanceneedtobefinaltobeusedintheinnerclassJsonObjectRequest. andintheresponse,youneedtopassthevaluetotheinstanceofMyClass.SoaddamethodinMyClass publicvoidsetFeatureImgUrl(StringfeaturedImgUrl){...} andyoujustneedtocallthisintheresponse. publicvoidonResponse(JSONObjectnested_response){ ... caller.setFeatureImgUrl(feature_img_url); ... } Note:ThiscouldbedonewithanObserverpatternbutIknowthatsomepeopledoesn'tlikeit.Icouldaddanexampleofitifneeded. Share Improvethisanswer Follow editedJan19'17at15:10 answeredJan19'17at15:05 AxelHAxelH 13.7k22goldbadges2424silverbadges5151bronzebadges 4 ButIwantthemethodtoreturnthestringattheendbecausethereisastatementinanothermethodthatiswaitingforastringresult.likesitem.img=secondServiceCall(featuredmedia) – zovinkc Jan19'17at15:17 @zovinkcYoucanalwaysseehowtosynchronizetwothreadstowaitforaresponse.ButIwouldsimplyupdatethisstatementtobedoneinthenewmethod(setFeatureImgUrl).Youcan'tsimplyreturntheStringbecausethisisasynchronous. – AxelH Jan19'17at15:19 BearwithmeforasecondbutIwanttounderstand.Whichportionisasynchronous,isittheOnResponsemethod? – zovinkc Jan19'17at15:23 @zovinkcBasicly,whatishappeningisthatyoubuildaninstancejsonObjReqandyoupushitintoaQueuewithaddToRequestQueue.Fromthere,themethodskeepsgoingandend.Thisisanotherthreadthatwilltakethatrequestinstancefromthequeuetoexecuteit,itcouldbenow,itcouldbein10sec(itdependsontheQueue).So,yes,onReponseisnotexecutedinthesameThreadasyoursecondServiceCallcall,thefullrequestpartisdoneinanotherthread – AxelH Jan19'17at16:24 Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedjavaandroidoraskyourownquestion. TheOverflowBlog Planfortradeoffs:Youcan’toptimizeallsoftwarequalityattributes AchatwiththefolkswholeadtrainingandcertificationatAWS FeaturedonMeta We’vemadechangestoourTermsofService&PrivacyPolicy-January2022 Newpostsummarydesignsongreatesthitsnow,everywhereelseeventually 2021:ayearinmoderation SunsettingJobs&DeveloperStory Related 3013 HowdoItestaclassthathasprivatemethods,fieldsorinnerclasses? 4101 WhatarethedifferencesbetweenaHashMapandaHashtableinJava? 7315 IsJava"pass-by-reference"or"pass-by-value"? 3701 HowdoIefficientlyiterateovereachentryinaJavaMap? 4268 AvoidingNullPointerExceptioninJava 4465 HowdoIread/convertanInputStreamintoaStringinJava? 3867 HowdoIgeneraterandomintegerswithinaspecificrangeinJava? 2210 HowtogetanenumvaluefromastringvalueinJava 3323 HowdoIconvertaStringtoanintinJava? 3536 HowcanIcreateamemoryleakinJava? HotNetworkQuestions Whatistheideabehind"pornotp"beingatautology? Dospellswithoptionsstackwhendifferentoptionsarechosen? HowtoremovetheredundantContourLabels Whataspectscontributemosttomebeingslowonthisbike? DidtheFBIwritealettertoMartinLutherKingJr,blackmailinghimtotakehisownlife? WhyisthearithmeticmeanthesameastheDCcomponentofitsfouriertransform? WordlePictionary! Whydoesthissentenceuse"towriting"insteadof"towrite"? DoesNorthKoreagetpermissiontotest-flyweaponsoverChinaandRussia?(ifitindeeddoes) Multi-trunkedelephantsinvadeEarth What'sthemathematicalreasonbehindPythonchoosingtoroundintegerdivisiontowardnegativeinfinity? Whatis"buyinghashrate"andhowcoulditbeprofitable? EliminatingVariablesinSemidefiniteProgramsUsingEqualityConstraints Howdoisay“holdthebus?” Whichpartof2001takesplacein2001? Damagedcompanyequipmentbyaccident-companynowwantmetosignform Whyarequasi-categoriesbetterthansimplicialcategories? HowcanaScrumdailynotbeastatuspull? HowcanIuseAnimateObjectsincombat,withoutslowingcombatdownforeveryone? Canjointmeasurementbeachievedintwolabsfarapart? What'sabetterwaytoshowamountinstaffinalocationonabargraph? Isthemarketpriceobjective? Howtodeal[asareviewer]withapaperinpeerreviewthatbreaksanonymity HowshouldIfollowupwiththisprofessor? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-java Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?