The constructor MainActivity.MyTask(TextView) is undefined - java

I'm getting an error stating: The constructor MainActivity.MyTask(TextView) is undefined after following a suggestion from another SO user as to how to fix my Android based web scraper:
How To Extract Table Data Via Android
I've attempted to create a constructor:
public MyTask(TextView tv) {
// TODO Auto-generated constructor stub
}
however that does not seem to resolve the issue (the error goes away - but the textview is never updated.)
ERROR:
The constructor MainActivity.MyTask(TextView) is undefined
SOURCE:
public class MainActivity extends Activity {
TextView tv;
final String URL = "http://news.google.com";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.TextView01);
new MyTask(tv).execute(URL);
}
private class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog prog;
String title = "";
#Override
protected void onPreExecute() {
prog = new ProgressDialog(MainActivity.this);
prog.setMessage("Loading....");
prog.show();
}
#Override
protected String doInBackground(String... params) {
try {
Document doc = Jsoup.connect(params[0]).get();
Element tableHeader = doc.select("tr").first();
for (Element element : tableHeader.children()) {
// Here you can do something with each element
System.out.println(element.text());
tv.setText(element.text());
}
title = doc.title();
} catch (IOException e) {
e.printStackTrace();
}
return title;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prog.dismiss();
tv.setText(result);
}
}
}
EDIT IN RESPONSE TO Raghunandan's ANSWER:
public class MainActivity extends Activity {
Context context;
TextView tv;
final String URL = "http://news.google.com";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.TextView01);
new MyTask().execute(URL);
}
private class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog prog;
String title = "";
#Override
protected void onPreExecute() {
prog = new ProgressDialog(MainActivity.this);
prog.setMessage("Loading....");
prog.show();
}
#Override
protected String doInBackground(String... params) {
try {
Document doc = Jsoup.connect(params[0]).get();
Element tableHeader = doc.select("tr").first();
for (Element element : tableHeader.children()) {
// Here you can do something with each element
// System.out.println(element.text());
// tv.setText(element.text());
// //cannot update ui here.
// use Log.i instead of System.out.println
}
title = doc.title();
} catch (IOException e) {
e.printStackTrace();
}
return value;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prog.dismiss();
// tv.setText(result);
Document doc = Jsoup.connect(params[0]).get();
Element tableHeader = doc.select("tr").first();
for (Element element : tableHeader.children()) {
// Here you can do something with each element
System.out.println(element.text());
tv.setText(element.text());
// cannot update ui here.
}
}
}
}

You have this
new MyTask(tv).execute(URL);
But in your asycntask you does not have constructor like
public MyTask(TextView tv)
{
}
There is not need to pass textview to the constructor if your asynctask is an inner class of your activity class coz you have textview declared as a activity class member.
You can set the text in onPostExecute. But you are setting text in doInbackground.
doInbackground is invoked on a background thread. So you cannot set text there. You need to update ui on the ui thread.
If asynctask is not an inner class then use a interface
Can't post response from AsyncTask to MainActivity
public class MainActivity extends Activity {
Context context;
TextView tv;
final String URL = "http://news.google.com";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
new MyTask().execute(URL);
}
private class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog prog;
String title = "";
#Override
protected void onPreExecute() {
prog = new ProgressDialog(MainActivity.this);
prog.setMessage("Loading....");
prog.show();
}
#Override
protected String doInBackground(String... params) {
try {
Document doc = Jsoup.connect(params[0]).get();
Element tableHeader = doc.select("tr").first();
for (Element element : tableHeader.children()) {
// Here you can do something with each element
//System.out.println(element.text());
//tv.setText(element.text());
//cannot update ui here.
// use Log.i instead of System.out.println
}
title = doc.title();
} catch (IOException e) {
e.printStackTrace();
}
return title;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prog.dismiss();
tv.setText(result);
}
}
}
For more info on asynctask
http://developer.android.com/reference/android/os/AsyncTask.html
Edit:
public class MainActivity extends Activity {
Context context;
ArrayList<String> aa = new ArrayList<String>();
ListView lv;
final String URL = "http://news.google.com";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv= (ListView) findViewById(R.id.listView1);
new MyTask().execute(URL);
}
private class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog prog;
String title = "";
#Override
protected void onPreExecute() {
prog = new ProgressDialog(MainActivity.this);
prog.setMessage("Loading....");
prog.show();
}
#Override
protected String doInBackground(String... params) {
try {
Document doc = Jsoup.connect(params[0]).get();
Element tableHeader = doc.select("tr").first();
for (Element element : tableHeader.children()) {
aa.add(element.text().toString());
}
title = doc.title();
} catch (IOException e) {
e.printStackTrace();
}
return title;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prog.dismiss();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,aa);
lv.setAdapter(adapter);
}
}
}
activtiy_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
Snap shot

Related

java.lang.IllegalStateException: Fragment not attached to Activity issue in android

I am facing strange issue during call of my activity with Fragment usage. I am getting error like,
java.lang.IllegalStateException: Fragment ScoreFragment{ee2b833
id=0x7f0e0198} not attached to Activity
On line 146. My Fragment code which have error is line like below
if(mPageFlag.equalsIgnoreCase(getString(R.string.winners))){
And My full code for same is below,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mPageFlag = getArguments().getString(ARG_PAGE_FLAG);
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser && !mIsPageLoaded){
mContext = getActivity();
mIsPageLoaded = true;
if(mPageFlag.equalsIgnoreCase(getString(R.string.winners))){
new getcontestscorewinners(mContext).execute();
}else{ //
new getcontestscorewinnersNew(mContext).execute();
}
}
}
public class getcontestscorewinners extends AsyncTask<String, Void, String> {
boolean response = false;
private Context mContext;
public getcontestscorewinners(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(mContext, "Processing...",
"Please wait....");
}
#Override
protected String doInBackground(String... params) {
NetworkTask.getContestScoreWinners(winnerHandler);
return "";
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
Let me know if someone can help me for get out of it. Thanks.
Try using isAdded():
Return true if the fragment is currently added to its activity.
So your code should be like this :
if(isAdded() && mPageFlag.equalsIgnoreCase(getString(R.string.winners))){

In AsyncTask on onPostExecute the textview value is not setting

Textview value is crashing with null pointer exception
Below is the code which i am using. Is there any issue in the code.
public class MainActivity extends Activity {
Button btn;
int i =0;
SharedPreferences.Editor preferences;
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button1);
preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
txt = (TextView) findViewById(R.id.textView1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new LongOperation().execute("");
}
});
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.interrupted();
}
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
txt.setText("Executed ----------------------- ");
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
}
After it is coming to onPostExecute the textview value is not setting the value.
Please help me. Thanks in advance.
Textview value is not setting because the value of id may be null. check it.

How to pass data from activity to another activity on Android

I want to pass data from my Login Page to My Detail Page. However the Detail Page cannot accept the data because the String sent in Login Page has null value on Detail Page.
This is my Login Page Code:
public class MainActivity extends AppCompatActivity {
EditText editText, editText1;
Button button;
int success = 0;
ProgressDialog progressDialog;
JSONObject jsonObject;
HTTPURLConnection service;
String strname ="", strpass="";
String response;
String path = "http://sumbanggagasan.890m.com/select2.php";
Intent intent;
DetailGagasanku detailGagasanku;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.nik);
editText1 = (EditText) findViewById(R.id.pass);
button = (Button) findViewById(R.id.signin);
service = new HTTPURLConnection();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!editText.getText().toString().equals("") && !editText1.getText().toString().equals("")){
strname = editText.getText().toString();
strpass = editText1.getText().toString();
response = null;
new PostDataTOServer().execute();
} else{
Toast.makeText(getApplicationContext(), "Please Enter all fields", Toast.LENGTH_LONG).show();
}
}
});
}
private class PostDataTOServer extends AsyncTask<Void, Void, Void> {
//Create hashmap Object to send parameters to web service
HashMap<String, String> postDataParams;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
postDataParams=new HashMap<String, String>();
postDataParams.put("NIK", strname);
postDataParams.put("pass", strpass);
//Call ServerData() method to call webservice and store result in response
response= service.ServerData(path,postDataParams);
try {
System.out.println(response + "menu");
jsonObject = new JSONObject(response);
//Get Values from JSONobject
System.out.println("success=" + jsonObject.get("successs"));
//success = jsonObject.getInt("success");
success = Integer.parseInt(jsonObject.getString("successs").trim());
System.out.println("Do in");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
System.out.println("Post 1");
System.out.println(strname);
if (progressDialog.isShowing()) {
System.out.println("Post 2");
System.out.println(strpass);
progressDialog.dismiss();
}
if(success==1) {
//Toast.makeText(getApplicationContext(), "Berhasil", Toast.LENGTH_LONG).show();
Intent intent;
Bundle b;
b = new Bundle();
b.putString("username", strname);
intent = new Intent(getApplicationContext(), LandingPage.class);
intent.putExtras(b);
startActivity(intent);
} else{
Toast.makeText(getApplicationContext(), "Login gagal", Toast.LENGTH_LONG).show();
}
}
}
And this is my Details code:
public class DetailGagasanku extends AppCompatActivity {
TextView judul, manfaat;
Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_gagasanku);
judul = (TextView)findViewById(R.id.textJudul);
manfaat = (TextView) findViewById(R.id.textManfaat);
bundle = getIntent().getExtras();
judul.setText(bundle.getString("judul_gagasan"));
if (bundle != null) {
if(bundle.containsKey("username"))
{
String s = bundle.getString("username");
manfaat.setText(s);
}
else
{
System.out.println("not send");
}
}
}
}
I want to ask why that username has null value. For your information, that "judul_gagasan" variable can receive value from another activity. I send it from My Adapter.
this is my Adapter code:
public class GagasanAdapter extends RecyclerView.Adapter<GagasanAdapter.GagasanHolder> {
List<String> gagasanList = new ArrayList<>();
public GagasanAdapter(List<String> gagasanList) {
this.gagasanList = gagasanList;
Log.v("gagasanSize", "" + gagasanList.size());
}
#Override
public GagasanHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_gagasan, parent, false);
return new GagasanHolder(v);
}
#Override
public void onBindViewHolder(final GagasanHolder holder, final int position) {
Log.v("Gagasan[" + position + "]", gagasanList.get(position));
String item = gagasanList.get(position);
holder.judulGagasan.setText(item);
holder.judulGagasan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, DetailGagasanku.class);
intent.putExtra("judul_gagasan", holder.judulGagasan.getText().toString());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return gagasanList.size();
}
public class GagasanHolder extends RecyclerView.ViewHolder{
TextView judulGagasan;
public GagasanHolder(View itemView) {
super(itemView);
judulGagasan = (TextView) itemView.findViewById(R.id.tvListGagasan);
}
}
}
You pass "username" in Bundle to LandingPage Activity, so you can't access in DetailGagasanku Activity.
So to access "username" in DetailGagasanku Activity, pass username from adapter.

how to parsing with jsoup using asynctask

I have to parse a web page and store the content of some tag in a ListView.
Now, I have this code:
public class MainActivity extends Activity
{
private MyTask myTask;
ListView listView;
final String URL = "http://en.wikipedia.org";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
myTask = new MyTask();
myTask.execute(URL);
}
class MyTask extends AsyncTask<String, Void, String>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String url = params[0];
Document doc;
Elements table = null;
try {
doc = Jsoup.connect(url).get();
table = doc.select("table").select("tbody");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return table.toString();
}
protected void onPostExecute(String result)
{
super.onPostExecute(result);
listView = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.riga);
listView.setAdapter(adapter);
}
}
}
but the execution return always a white screen. What can I do??
I'm sure that the error is in the postExecute method but I can't see it.

How To Extract Table Data Via Android

I'm attempting to extract data from a table on a web page. Thus far I've been able to extract the data from the title tag - but not the table data. How can this be accomplished using the source shown below?
SOURCE:
public class MainActivity extends Activity {
TextView tv;
final String URL="http://example.com";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.TextView01);
new MyTask().execute(URL);
}
private class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog prog;
String title = "";
#Override
protected void onPreExecute() {
prog = new ProgressDialog(MainActivity.this);
prog.setMessage("Loading....");
prog.show();
}
#Override
protected String doInBackground(String... params) {
try {
Document doc = Jsoup.connect(params[0]).get();
title = doc.title();
} catch (IOException e) {
e.printStackTrace();
}
return title;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prog.dismiss();
tv.setText(result);
}
}
}
EDIT - In Response to Matej Spili's comment below:
public class MainActivity extends Activity {
TextView tv;
final String URL="http://example.com";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.TextView01);
new MyTask().execute(URL);
}
private class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog prog;
String title = "";
#Override
protected void onPreExecute() {
prog = new ProgressDialog(MainActivity.this);
prog.setMessage("Loading....");
prog.show();
}
#Override
protected String doInBackground(String... params) {
try {
Document doc = Jsoup.connect(params[0]).get();
Element tableHeader = doc.select("tr").first();
for( Element element : tableHeader.children() )
{
// Here you can do something with each element
System.out.println(element.text());
tv.setText(element.text());
}
title = doc.title();
} catch (IOException e) {
e.printStackTrace();
}
return title;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prog.dismiss();
tv.setText(result);
}
}
}
^- (causes error: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views)
Pass the view that you want to update as constructor argument for the MyTask like
new MyTask(tv).execute(URL);
Change your MyTask accordingly to accept this argument.

Categories