package com.mohd.tryapp;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends ActionBarActivity {
public static int flag;
TextView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
view=(TextView)findViewById(R.id.textvi);
getFlag var=new getFlag();
var.execute();
if(flag==1)
view.setText("true");
else
view.setText("false");
}
class getFlag extends AsyncTask<Void, Void, Void> {
private Exception exception;
#Override
protected Void doInBackground(Void... params) {
try{
String url="http://mohdgadi.netai.net/Register.php";
int timeout=15*1000;
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(timeout);
connection.connect();
flag=1;
} catch (Exception e) {
e.printStackTrace();
flag=0;
}
return null;
}
}
}
So this is the code for my main activity i want to connect to my 000webhost website but the connection always shows false.I even tried changing the url to http://mohdgadi.netai.net/Register but that doesnt seem to work what might be the problem because of which the result is always showing false
This is because, if you see the logs, you will notice that your code will throw a NetworkOnMainThreadException. This means that Android doesn't allow you to make a Network call on the main thread. Therefore, move your code into an AsyncTask.
You can see an example here.
You should use get() to wait for the result to get populated, although it is preferred that you use onPostExecute to execute your code after doInBackground returns.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
view=(TextView)findViewById(R.id.textvi);
getFlag var=new getFlag();
var.execute();
var.get();
if(flag==1)
view.setText("true");
else
view.setText("false");
}
Related
I have four classes:
MainActivity extends AppCompactActivity
MainAsyncTask extends AsyncTask<String, String, List>
Intermediate extends MainAsyncTask and have two functions. (FuncA, FuncB)
Leaf extends Intermediate and implementation of doInBackground() and onPostExecute().
When I run the application it prompts:
Unable to instantiate activity ComponentInfo{}: android.os.NetworkonMainThreadException.
How can I get rid off the Error. As far as My understanding is concerned, doInBackground() and onPostExecute()should be implemented in MainAsyncTask class?
Classes are :
MianActivity.java
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Leaf object = new Leaf();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button fab = (Button) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
object.execute();
}
});
}
}
MainAsyncTask.java
import android.os.AsyncTask;
public class MainAsync extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
return null;
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(String... text) {
}
}
Intermediate.java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
public class Intermediate extends MainAsync{
public Document FunA(){
System.out.println("Printed FunA()");
String url = "http://blogs.tribune.com.pk/story/37034/zakir-naik-has-a-large-following-in-pakistan-should-we-be-alarmed/";
Document doc = null;
try {
doc = Jsoup.connect(url).timeout(10 * 1000).get();
} catch (IOException e) {
e.printStackTrace();
}
return doc;
}
public void FunB(){ System.out.println("Printed FunB()");}
}
}
Leaf.java
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Leaf extends Intermediate{
Document HTM = FunA();
public void FunC() {
String heading = "";
System.out.println("Printed FunC()");
Elements seep = HTM.select("h1");
for (Element foo : seep) {
heading = foo.text();
System.out.println(heading);
break;
}
}
public void FunD() {
System.out.println("Printed FunD()");
}
public void FunE() {
System.out.println("Printed FunE()");
}
#Override
protected String doInBackground(String... params) {
FunB();FunC();FunD();FunE();
return null;
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(String... text) {
}
}
The purpose of doing in this way is to add FuncA and FuncB along with AsyncTask methods in one class that is Leaf class.
In the absence of a stack trace I would say:
Initiating your Leaf class causes the HTM variable to be initiated.
The HTM variable is initiated by calling the FunA method.
The FunA method runs network accessing code and is not running inside DoInBackground (and therefore running on the main thread).
Your network code can only be run inside DoInBackground if you wish to not get a NetworkOnMainThread Exception.
The exception is thrown before you even start the AsyncTask as just the act of creating it causes the FunA code to run.
Move this line inside DoInBackground so it runs when the AsyncTask is executed and not when it is created.
Document HTM = FunA();
On a separate note, your class hierarchy is very convoluted. You do not need Intermediate or Leaf classes. All that code could be easily moved to the MainAsync class and so would be much easier to understand.
Hi friends I know there is a bunch of questions about this topic but I can not get any result from them. i am parsing xml data with my ClassIsInternalParser extends default handler. I use this class in my activity in an inner class PostAsync extends AsyncTask
but the reason is i can not return the data that ı collected in PostAsync class to main activity. it sets only null
here is my codes
package com.example.uiexercisesplash;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ClassIsInternalListViewActivity extends Activity implements OnClickListener{
TextView tv, tv2;
Button back;
String[][] array = new String[10][3];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.classisinternal_listview);
new PostAsync().execute();
tv=(TextView) findViewById(R.id.tatar);
tv2= (TextView) findViewById(R.id.tatar2);
tv2.setText(array[0][0]); //Why this sets null!!
back= (Button) findViewById(R.id.back);
back.setOnClickListener(this);
}
class PostAsync extends AsyncTask<Void, Void,String[][]>{
ProgressDialog pd;
ClassIsInternalParser parser;
#Override
protected void onPreExecute() {
//we can set up variables here
pd = ProgressDialog.show(ClassIsInternalListViewActivity.this,
"Classisinternal","Loading last post...",true,false);
}
protected void onPostExecute(String[][] result) {
//in this way it sets correctly
tv.setText(result[0][0]);
array=result;
pd.dismiss();
pd.cancel();
}
protected String[][] doInBackground(Void... params) {
parser = new ClassIsInternalParser();
parser.get();
return parser.dataArray;
}
}
#Override
public void onClick(View v) {
finish();
}
}
Try to create PostAsync object and call execute() from that object. After that call get() method to retrieve your return array like this:
PostAsync obj=new PostAsync(this);
obj.execute();
String[][] array=obj.get();
tv2.setText(array[0][0]);
tv2.setText(array[0][0]); is null because you are getting array value before setting values in it,i.e. tv2.setText(array[0][0]); is execute before completing Asynctask.
So do this step in onPostExecute method as
protected void onPostExecute(String[][] result) {
//in this way it sets correctly
tv.setText(result[0][0]);
tv2.setText(result[0][2]);
array=result;
tv2.setText(array[0][0]);// add here
pd.dismiss();
pd.cancel();
}
I am developing an application in which I want some data from a website to display in activity. For this I'm using Jsoup to parse data. But I am getting error at:
org.jsoup.nodes.Document document = Jsoup.connect(url).get();
Here it is my complete code below, I am not getting any idea about what is wrong I'm doing...
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.DocumentsContract.Document;
import android.app.Activity;
import android.view.Menu;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
public class Events extends Activity
{
//WebView web1;
TextView t1;
String url="https://sites.google.com/site/holyfamilychurchpestomsagar/notices-for-the-week";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events);
t1=(TextView)findViewById(R.id.textView1);
Title t2=new Title();
t2.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.events, menu);
return true;
}
private class Title extends AsyncTask<Void, Void, Void> {
Elements title;
String desc;
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
// Connect to the web site
org.jsoup.nodes.Document document = Jsoup.connect(url).get();
// Get the html document title
title = document.select("meta[name=title]");
desc = title.attr("content");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// Set title into TextView
t1.setText(desc);
}
}
}
Is the device online? Ok, im sure you thought of that ;-) Are you
sure its exactly this line? Are you running in your catch clause, or
does the app crash?
You should always add a null pointer check when working with jsoup,
because when the selecting process is unsuccessful, the method will
return null!
Can you post your stacktrace?
Ok when the app crashes then Im pretty shure its not the connection itself but one of the lines below. Add a check for null pointers, or add a catch clause.
I'm working on getting a better handle on AsyncTask and am trying to create controls dynamically with asyncTask's onPostExecute().
The code I have below does work and it creates controls, but is there a way to loop this, but delay it so that variable I is incremented after the asynctask completes?
I've read through using the get() method, but I can't seem to make it work.
Can anyone advise how to either wait till a background task is complete or some other way to dynamically create controls based on a variable number?
package com.example.dynamicallycreatecontrols;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
Integer i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
while (i < 5) {
new createControl().execute(i);
i++;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//asynctask
public class createControl extends AsyncTask<Integer, Void, Button> {
Button btn = new Button(MainActivity.this);
LinearLayout ll = (LinearLayout) findViewById (R.id.llMain);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
protected void onPreExecute(Integer i) {
// nothing right now
}
#Override
protected Button doInBackground(Integer... arg0) {
// TODO Auto-generated method stub
// do the calculation
return null;
}
protected void onPostExecute(Button v) {
// build the controls here
btn.setText("Play" + i);
ll.addView(btn, lp);
SystemClock.sleep(1000);
}
}
}
I'm new to android development and java so i'm not sure if I'm just misunderstanding a concept of get() or if there is a better way to do this all together.
Thanks for any time allocated in assistance.
-nick
When doInBackground() done I move to onPostExecute(). I don't need any delays there. When I call task.execute(/**/) actually I invoke doInBackground() async task and I don't care when it finish but I know that I have callback onPostExecute() and I wait and update my main Thread from there.
To make it clearer lets say you have application where user wants to register to server and update GUI led to green color. User presses on button and calls method registerClient()
This method runs:
private void registerClient(){
...
dialog = ProgressDialog.show(LoginActivity.this, "", "Connecting. Please wait...", true);
HeavyTask task = new HeavyTask();
task.execute(user, password, domain);
}
So what we have in HeavyTask:
private class HeavyTask extends AsyncTask<String, Void, Void> {
private String username = "";
private String domain = "";
private String password = "";
// run async task
protected Void doInBackground(String... args) {
username = args[0];
password = args[1];
domain = args[2];
registerClientToServer(username, password, domain, null);
return null;
}
protected void onPostExecute(Void results) {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
updateGUI(username, domain);
}
}, 500);
}
}
Why not create an object and instantiate it? You can control if the object exists or if it already finished what he had to do.
Example:
public class MainActivity extends Activity {
private createControl cc = null;
Integer i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
while (i < 5) {
if (cc == null){
cc = new createControl();
cc.execute(i);
i++;
}
}
}
...
}
Then in onPostExecute just add cc = null;
I am experiencing a problem I have following code:
public void onCreate(Bundle savedInstanceState) {
MyDialog = ProgressDialog.show(this, "Nalagam kanale" , "Prosimo počakaj ... ", true);
MyDialog.show();
... }
Which should actually start he dialog... But the problem is that dialog is shown when everything is loaded...
How can I do solve that?
Actual code
package com.TVSpored;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
public class Currently extends Activity{
static final int PROGRESS_DIALOG = 0;
private ArrayList<CurrentlyItem> currentItems;
private CurrentAdapter aa;
private ListView currentListView;
private JSONArray CurrentShows;
private Communicator CommunicatorEPG;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.layout_currently);
CommunicatorEPG = new Communicator();
currentItems = new ArrayList<CurrentlyItem>();
if(currentItems == null)
int resID = R.layout.current_item;
aa = new CurrentAdapter(this, resID, currentItems);
currentListView = (ListView)findViewById(R.id.currentListView);
try {
currentListView.setAdapter(aa);
} catch (Exception e) {
Log.d(" * Napaka", e.toString());
}
try {
populateCurrent();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void populateCurrent() throws JSONException
{
CurrentShows = CommunicatorEPG.getCurrentShows(0);
for (int i = 0; i < CurrentShows.length(); i++)
{
JSONObject jsonObject = CurrentShows.getJSONObject(i);
String start = jsonObject.getString("1");
Integer duration = jsonObject.getInt("2");
String title = jsonObject.getString("3");
String epg_channel = jsonObject.getString("4");
String channel_name = jsonObject.getString("5");
CurrentlyItem newItem = new CurrentlyItem(1, 2, 3, 4, 5);
currentItems.add(i, newItem);
}
}
}
This is actual code... I would like to do populateCurrent(); in AsyncTask and meanwhile I would like a loading screen to be shown... Have been trying for few hours now but no actual success... I have successfully shown loading screen and wen trough JSONArray, but couldn't update listview...
Thanks for support!
Expected behaviour...
Show a dialog is a typical task of UI thread, but until you complete the onCreate method, the UI thread s not free to execute the dialog creation...
Two solution: create a dialog in a separate thread or execute your long task in a separate thread.
Some highlights here:
http://developer.android.com/guide/topics/ui/dialogs.html
You could wait to set the content of the activity until the you're finished with the progress dialog.
Update:
This would run your command in async-task:
new AsyncTask<Void, Void, Void> {
protected Long doInBackground(Void... voids) {
populateCurrent();
}
}.execute()
However, then you probably have to make sure to update the list in the GUI thread again and in some way tell the adapter that the list have been updated (since you've given that list to the adapter):
runOnUiThread(new Runnable() {
public void run() {
currentItems.add(i, newItem);
aa.notifyDataSetChanged();
}
}
It is probably best to create a new list entirely and set the view to view that.