I am trying to use the jsoup to return string from a website but my code breaks after the Jsoup.connect and it doesnt return any string
my code is:
class fetcher extends AsyncTask<Void,Void,Void>{
String myString = null;
#Override
protected Void doInBackground(Void... arg0) {
Document doc = null;
try {
doc = Jsoup.connect("http://www.ismmusalla.org/").get();
Elements divs = doc.select("div#title1");
for (Element div : divs) {
myString=myString+" " +div.text();
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result)
{
textview.setText(myString);
}
}
Because your AsyncTask's doInBackground() has void return type, just change it to String and put myString instead of null as return data,
Like,
protected String doInBackground(Void... arg0) {
return myString;
}
Also the declaration of AsyncTask is not suitable, extends AsyncTask<Void,Void,Void> it should be extends AsyncTask<Void,Void,String>.
Just look at http://developer.android.com/reference/android/os/AsyncTask.html
public class MainActivity extends Activity {
String myString="";
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
new TheTask().execute();
}
class TheTask extends AsyncTask <Void,Void,Void>
{
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
Document doc = null;
try {
doc = Jsoup.connect("http://www.ismmusalla.org/").get();
Elements divs = doc.select("div#title1");
for (Element div : divs) {
myString=myString+" " +div.text();
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
tv.setText(myString);
}
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
snap shot of emulator
Your title 1 in html code
Or
Edit:
Return string in doInbackground and update textview in onPostExecute
public class MainActivity extends Activity {
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
new TheTask().execute();
}
class TheTask extends AsyncTask <Void,Void,String> // change Void to String
{
String myString="";
#Override
protected String doInBackground(Void... arg0) { // return type is string
// TODO Auto-generated method stub
Document doc = null;
try {
doc = Jsoup.connect("http://www.ismmusalla.org/").get();
Elements divs = doc.select("div#title1");
for (Element div : divs) {
myString=myString+" " +div.text();
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return myString; //return string result
}
#Override
protected void onPostExecute(String result) { // recieve string result
// TODO Auto-generated method stub
super.onPostExecute(result);
tv.setText(result); // update textview with string result
}
}
}
Use below code:
class fetcher extends AsyncTask<Void,Void,String>{
String myString = "";
#Override
protected String doInBackground(Void... arg0) {
Document doc = null;
try {
doc = Jsoup.connect("http://www.ismmusalla.org/").get();
Elements divs = doc.select("div#title1");
for (Element div : divs) {
myString=myString+" " +div.text();
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return myString;
}
protected void onPostExecute(String result)
{
textview.setText(result);
}
}
Related
I have a navigation drawer containing 2 items. Now in my first item click, I load data using asynctask and the loaded data is populated in a listview in the corresponding fragment. Now when I switch to 2nd item, again I load data using AsyncTask for the 2nd fragment and show it in in listview.
Now the problem starts. When I go back to the 1st fragment, my
asyncTask is called again and the data is again fetched from the
server, I want to prevent this and load my data directly if it has
been already loaded once.
Please suggest
P.S - Please ask for the code if anyone needs it.
USERPAYFRAGMENT
public class UserPay extends Fragment {
ProgressDialog prg;
Properties prop;
private PrefSingleton mMyPreferences;
private JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> RequestList;
HashMap<String, String> map;
UserAdapter req_adp;
ListView req;
private boolean flag;
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
Toast.makeText(getActivity(), "ATTACHED", 1000).show();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
Toast.makeText(getActivity(), "CREATE", 1000).show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.user_pay, container, false);
initViews(rootView);
Toast.makeText(getActivity(), "ONCREATEVIEW", 1000).show();
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Toast.makeText(getActivity(), "ONACTIVITYCREATED", 1000).show();
mMyPreferences = PrefSingleton.getInstance();
mMyPreferences.Initialize(getActivity());
RequestList = new ArrayList<HashMap<String, String>>();
Resources resources = this.getResources();
AssetManager assetManager = resources.getAssets();
try {
InputStream inputStream = assetManager.open("jsonURL.properties");
prop = new Properties();
prop.load(inputStream);
} catch (IOException e) {
System.err.println("Failed to open jsonURL property file");
e.printStackTrace();
}
req_adp = new UserAdapter(getActivity(), RequestList);
req.setAdapter(req_adp);
if (!flag) {
new GetRequests().execute();
} else {
}
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(getActivity(), "ONSTART", 1000).show();
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
Toast.makeText(getActivity(), "ONRESUME", 1000).show();
}
private void initViews(View v) {
req = (ListView) v.findViewById(R.id.req_list);
}
private class GetRequests extends AsyncTask<Void, Void, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
prg = new ProgressDialog(getActivity());
prg.setIndeterminate(true);
prg.setMessage("Fetching Pending Requests...");
prg.setCanceledOnTouchOutside(false);
prg.show();
}
#Override
protected Integer doInBackground(Void... params) {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("userID", mMyPreferences
.getPreference("LoginId")));
String error_code = null;
Log.e("URL ", "is" + prop.getProperty("GET_REQUESTS_URL"));
try {
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(
Appconstant.GET_REQUESTS_URL, "POST", params1);
// Check your log cat for JSON response
Log.d("Inbox JSON: ", json.toString());
JSONObject jsonObj = json.getJSONObject("data");
error_code = jsonObj.getString("Error_Code");
RequestList.clear();
if ("1".equals(error_code)) {
JSONArray jArray = jsonObj.getJSONArray("result");
for (int i = 0; i < jArray.length(); i++) {
map = new HashMap<String, String>();
JSONObject jsonObj1 = jArray.getJSONObject(i);
String FBankId = jsonObj1
.getString("payment_from_bank_id");
String DestBankId = jsonObj1
.getString("payment_to_bank_id");
String FBank = jsonObj1.getString("fBank");
String TBank = jsonObj1.getString("tBank");
String reason = jsonObj1.getString("payment_reason");
String amt = jsonObj1.getString("amount");
String p_type = jsonObj1.getString("payment_type");
String status = jsonObj1.getString("status");
String r_date = jsonObj1
.getString("request_created_date");
map.put("FBankId", FBankId);
map.put("TBankId", DestBankId);
map.put("SourceBank", FBank);
map.put("DestBank", TBank);
map.put("ReqDate", r_date);
map.put("PayReason", reason);
map.put("Amt", amt);
map.put("PayType", p_type);
map.put("Status", status);
if (status.equals("pending")) {
if (p_type.equals("cheque")
|| p_type.equals("Net Banking")) {
RequestList.add(map);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return Integer.parseInt(error_code);
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (prg.isShowing()) {
prg.cancel();
}
if (result == 2) {
Toast.makeText(getActivity(),
"No User Request Details Available.Please Try Again",
Toast.LENGTH_SHORT).show();
}
req_adp.notifyDataSetChanged();
flag = true;
}
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
Toast.makeText(getActivity(), "ONPAUSE",1000).show();
}
#Override
public void onStop() {
// TODO Auto-generated method stub
super.onStop();
Toast.makeText(getActivity(), "ONSTOP", 1000).show();
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
Toast.makeText(getActivity(), "ONDESTROYVIEW", 1000).show();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(getActivity(), "ONDESTROY", 1000).show();
}
#Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
Toast.makeText(getActivity(), "ONDETACH", 1000).show();
}
}
There are 2 ways to solve
1 - store the data locally and make use stored data based on appropriate condition checks
2 - If your app is based on this 2 fragments, just create the instance of these fragments and store in in member variable of parent activity. do not give chance to recreate again and again
I am trying to get the result from the AsyncTask to another class. I am using interface to achieve this. I doing the same procedure in another module and it was working good but I fail to identify the issue in this case...
I'm calling like this from another class.
GroupDetails gd=new GroupDetails();
groups=gd.getGroupList("email");
public class GroupDetails implements AsyncResponse {
String result;
String[] groupList;
public String getGroupList(String userEmail){
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("user_email", userEmail));
PhpConnect phpcon=new PhpConnect("http://www.pinnacle2k14.com/letsmeet/get_group.php",postParameters);
phpcon.delegate=this;
phpcon.execute();
result="hello"
return result;
}
#Override
public void processFinish(String output) { //this method not functioning why?
// TODO Auto-generated method stub
result="hello";
//groupList=output.split(",");
}
}
PhpConnect.php
public class PhpConnect extends AsyncTask<String, Void, String> {
String url1;
ArrayList<NameValuePair> postParameters1;
public PhpConnect(String url,ArrayList<NameValuePair> postParameters){
url1=url;
postParameters1=postParameters;
}
public PhpConnect() {
// TODO Auto-generated constructor stub
}
String response;
public AsyncResponse delegate=null;
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost(url1,postParameters1);
} catch (Exception e) {
// TODO Auto-generated catch block
response=e.toString();
}
return response;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
delegate.processFinish(result);
}
}
AsynResponse interface
public interface AsyncResponse {
void processFinish(String output);
}
You know you can do
PhpConnect phpcon=new PhpConnect("http://www.pinnacle2k14.com/letsmeet/get_group.php",postParameters) {
#Override
public void onPostExecute(String result) {
//DO YOUR STUFF
}
};
phpcon.execute();
This way you can save the callback.
I use this code inorder to get the content of some website.
the textview stay empty. What I am doing wrong?
I added the jar into librires and also add internet permission to manifest.
public class MainActivity extends Activity {
MyTask mt;
TextView tvInfo;
String URL="http://www.example.com/";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvInfo = (TextView) findViewById(R.id.textView1);
}
public void onclick(View v) {
mt = new MyTask();
mt.execute(URL);
}
class MyTask extends AsyncTask<String, Void, String> {
Document doc;
String title=null;
#Override
protected void onPreExecute() {
super.onPreExecute();
tvInfo.setText("Please wait");
}
#Override
protected String doInBackground(String... params) {
try {
TimeUnit.SECONDS.sleep(2);
// doc = Jsoup.connect(params[0]).get();
// String title = doc.title();
doc = Jsoup.connect("http://www.example.com/").get();
Element content = doc.select("a").first();
title = content.text();
Log.d("AsyncTask doInBackground","URL: " + params[0]);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return title;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvInfo.setText(title);
}
}
}
I also not understand excaly when each method here is called
THANKS A LOT!
EDIT - the code after what was suggested in answer. Still not working:
public class MainActivity extends Activity implements OnClickListener{
MyTask mt;
TextView tvInfo;
String URL="http://www.example.com/";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvInfo = (TextView) findViewById(R.id.textView1);
tvInfo.setOnClickListener(this);
}
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String title = "hh";
try{
Document doc = Jsoup.connect("http://google.com").userAgent("Mozilla").get();
title = doc.title();
System.out.println("title : " + title);
// get all links
Elements links = doc.select("a[href]");
for (Element link : links) {
// get the value from href attribute
System.out.println("\nlink : " + link.attr("href"));
System.out.println("text : " + link.text());
}
}
catch (IOException e) {
e.printStackTrace();
}
return title;
}
#Override
protected void onPostExecute(String result) {
tvInfo.setText(result);
}
#Override
protected void onPreExecute() {
tvInfo.setText("Please wait");
}
}
#Override
public void onClick(View v) {
mt = new MyTask();
mt.execute(URL);
}
}
The AsyncTask executes everything in doInBackground() inside of another thread, which does not have access to the GUI where your views are.
preExecute() and postExecute() offer you access to GUI before and after the heavy lifting occurs in this new thread, you can even pass the result of the long operation to postExecute() to then show any results of processing.
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try{
Document doc = Jsoup.connect("http://google.com").userAgent("Mozilla").get();
String title = doc.title();
System.out.println("title : " + title);
// get all links
Elements links = doc.select("a[href]");
for (Element link : links) {
// get the value from href attribute
System.out.println("\nlink : " + link.attr("href"));
System.out.println("text : " + link.text());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
tvInfo.setText("Please wait");
}
}
public class Feedback extends ActivityGroup {
protected static LocalActivityManager mLocalActivityManager;
private EditText fd=null;
private Button send=null;
public int res_flag=0;
public String result="";
public String url="";
private RelativeLayout newaccount;
private TextView needhelp=null;
private String currentDateandTime="";
private boolean isonline;
protected String fd_text="";
public void replaceContentView(String id, Intent newIntent) {
View view = getLocalActivityManager().startActivity(id,newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)) .getDecorView(); this.setContentView(view);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.feedback);
initialization();
try{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
currentDateandTime = sdf.format(new Date());
}catch (Exception e) {
System.out.println(e);
}
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Feedback.Retrieve().execute();
}
});
}
private void initialization()
{
fd=(EditText)findViewById(R.id.fd);
send=(Button)findViewById(R.id.send);
}
class Retrieve extends AsyncTask<Void, Integer, Integer> {
ProgressDialog pd = null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(Feedback.this);
pd.setMessage("Please wait while sending feedback..");
pd.setCancelable(false);
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
try{
System.out.println("IN BKGRND");
StrictMode.ThreadPolicy policy1 = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy1);
url="url"+fd_text.toString().trim()+"&datetime="+currentDateandTime;
url=url.replace(" ","%20");
url=url.replace("+","%2B");
System.out.println(url);
JSONObject json = JSONfunctions.getJSONfromURL(url);
JSONObject response1=json.getJSONObject("response");
result=response1.getString("Success").toString().trim();
System.out.println(result);
if(result.equalsIgnoreCase("1"))
{
System.out.println("Logged In");
res_flag=1;
}
else
{
System.out.println("failed");
res_flag=5;
}
}
catch (JSONException e) {
System.out.println(e);
}catch (Exception e) {
System.out.println(e);
}
return null;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
}
Error is:
android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord#40e16110 is not valid; is your activity running?
PROBLEM
I calling activity through another tabhost.,It loading only the view .The webservice and button are not working ., When i click the buttons it shows above error.Help me to proceed guys..
Reference:
http://www.gamma-point.com/content/android-how-have-multiple-activities-under-single-tab-tabactivity
NOw the ActivityGroup is deprecated.., What should i use now..
For what you have posted, it doesn't seem like you need to use ActivityGroup at all. Simply extend your Feedback from Activity class. For example:
public class Feedback extends Activity
I have a problem with updating my table-layout from my async class.
MY async class is fetching XML data so I don't block the main thread. My logs show the XML data is coming through but I don't know how to update my view with the data.
So I am attempting to put the data in tablerows and add the rows to the TableLayout but the logs show errors suggesting the Async class is not allowed to update my TableLayout view.
My code is as follows:
public class RemotePrimary extends Activity {
private static String SERVER_PATH = "http://test2.icerge.com/";
private static String XML_FILE1 = "samplexml";
//private static String SERVER_PATH = "http://tqs.mamlambo.com/";
//private static String XML_FILE1 = "scores.jsp";
private String[] data = new String[10];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TableLayout datatable = (TableLayout)findViewById(R.id.TableLayout_data);
Downloader downloader = new Downloader();
downloader.execute(SERVER_PATH + XML_FILE1, datatable);
}
private class Downloader extends AsyncTask<Object, String, Boolean>{
TableLayout table;
#Override
protected Boolean doInBackground(Object... params) {
// TODO Auto-generated method stub
String path = (String)params[0];
table = (TableLayout)params[1];
XmlPullParser xmldata = null;
try {
URL serverPath = new URL(path);
xmldata = XmlPullParserFactory.newInstance().newPullParser();
xmldata.setInput(serverPath.openStream(), null);
addRecord(xmldata, table);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
#Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
//super.onProgressUpdate(values);
}
private boolean addRecord(XmlPullParser data, TableLayout table){
int eventType = -1;
boolean bFoundScores = false;
//find some records from xml
while(eventType != XmlResourceParser.END_DOCUMENT){
if( eventType == XmlResourceParser.START_TAG ){
//get the name of the tag(eg scores or score)
String strName = data.getName();
if( strName.equals("node") ){
bFoundScores = true;
String scoreValue = data.getAttributeValue(null, "Title");
String scoreRank = data.getAttributeValue(null, "Type");
String scoreUserName = data.getAttributeValue(null, "Nid");
Log.e("ADDING: ", scoreValue);
//Log.e("RETRIEVED", "collected : "+scoreValue+", "+scoreRank+", "+scoreUserName);
//publishProgress(scoreValue, scoreRank, scoreUserName);
TableRow newRow = new TableRow(RemotePrimary.this);
TextView rowText = new TextView(RemotePrimary.this);
rowText.setText(scoreValue);
newRow.addView(rowText);
table.addView(newRow);
}
}
try {
eventType = data.next();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return true;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}//close Downloader class
}//close RemotePrimary class
It's a bit much I know but I'll appreciate any help.
Thanks a great deal :-)
You can only make changes from the UI on the UI thread. The AsyncTask gives you an easy place to do this via onPostExecute. As it says in the docs, onPostExecute is always performed on the UI thread.
In doInBackground, do all of the hard work of building up the structured data that wish to display. Return that data so that it will be passed into onPostExecute, then in there add the appropriate table rows.