layout an XML website on my Android APP - android

I've been searching for a long time to answer to my simple question but haven't found it yet.
I've just started Android Development and I can't manage to layout this simple XML to the Android App I have just created.
There is my code :
public class MainActivity extends Activity {
private static final String TAG = null;
/** Called when the activity is first created. */
private String getPage() {
String str = null ;
Log.v(TAG, "testentreemethode");
try
{
HttpClient hc = new DefaultHttpClient();
Log.v(TAG, "testnew");
HttpPost post = new HttpPost("http://www.3pi.tf/test.xml");
Log.v(TAG, "testurl");
HttpResponse rp = hc.execute(post);
Log.v(TAG, "testpost");
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
str = EntityUtils.toString(rp.getEntity());
}
}catch(IOException e){
e.printStackTrace();
}
return str;
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txt = (TextView) findViewById(R.id.textview1);
Log.v(TAG, "test1");
txt.setText(getPage());
Log.v(TAG, "test2");
}
}
As you can see I put some Logcat to see where the "cursor" goes and it can't pass this line:
HttpResponse rp = hc.execute(post);
Can someone help me please?

Network operation cannot be performed on the main thread. Use an AsyncTask to execute it on a seperate thread like this:
public class GetXmlTask extends AsyncTask<Void, Void, String> {
// WeakReferences are used to prevent memory leaks.
// Always use WeakReferences when referencing Views or Activities or a Context from a seperate thread
private final WeakReference<TextView> textViewReference;
private final String url;
public GetXmlTask(TextView textView, String url) {
this.textViewReference = new WeakReference<TextView>(textView);
this.url = url;
}
#Override
protected String doInBackground(Void... params) {
HttpClient hc = new DefaultHttpClient();
Log.v(TAG, "testnew");
HttpPost post = new HttpPost(url);
Log.v(TAG, "testurl");
HttpResponse rp = hc.execute(post);
Log.v(TAG, "testpost");
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
return EntityUtils.toString(rp.getEntity());
}
return "Error";
}
#Override
protected void onPostExecute(String result) {
TextView textView = textViewReference.get();
if(textView != null) {
textView.setText(result);
}
}
}
You can execute the task like this:
GetXmlTask task = new GetXmlTask(textView, "http://www.3pi.tf/test.xml");
task.execute();

In any application you should avoid IO calls on main thread because it is used to handle user events and UI in general. in android doing so causes NetworkOnMainThreadException
Try to move your web calls to a background thread and it should work.
ex
public class MainActivity extends Activity {
TextView textView;
Handler mHandler;
private static final String TAG = null;
/** Called when the activity is first created. */
private String getPage() {
String str = null ;
Log.v(TAG, "testentreemethode");
try
{
HttpClient hc = new DefaultHttpClient();
Log.v(TAG, "testnew");
HttpPost post = new HttpPost("http://www.3pi.tf/test.xml");
Log.v(TAG, "testurl");
HttpResponse rp = hc.execute(post);
Log.v(TAG, "testpost");
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
str = EntityUtils.toString(rp.getEntity());
}
}catch(IOException e){
e.printStackTrace();
}
return str;
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtView = (TextView) findViewById(R.id.textview1);
mHandler = new Handler();
new Thread(){
#Override
public void run(){
final String str = getPage();
mHandler.post(new Runnable(){
#Override
public void run(){
textView.setText(str);
}
});
}
}.start();
Log.v(TAG, "test1");
Log.v(TAG, "test2");
}
}
Please take a look at this tutorial for better understanding of android threadining. tutorial

Related

Android: ProgressDialog in external async class (sth block async thread)

I have main activity:
public class ChooseWriteSentenceActivity extends ActionBarActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String userName = "Zdzisiu";
String password = "Ziemniak";
MainServie service = new MainService(this);
boolean isExsist = service.findUser(String userName, String password);
//more code...
}
}
In my app service uses repositories and jsonconsumers but for simpler code I'm skipping them.
public class MyService{
private Context context;
public MyService(Context context){
this.context = context
}
public boolean findUser(String userName, String password){
String resultS = null;
try{
resultS = new QueryExecutorFindUser(context).execute(userName,password).get();
}
catch(Exception ex){
ex.printStackTrace();
}
boolean realRes = jsonConsumer(resultS).getFindUser();
return realRes;
}
}
public class QueryExecutorFindUser extends AsyncTask<String,Void,String> {
protected final String connectionUrl = "http://myWebService:44302/Service.svc/";
protected ProgressDialog progressDialog;
protected Context curContext;
public QueryExecutor(Context context){
curContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = ProgressDialog.show(curContext,"Loading...",
"Loading application View, please wait...", false, false);
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
progressDialog.dismiss();
}
protected String doInBackground(String... args){
String result = null;
String url = connectionUrl + args[0] + "/" + args[1];
HttpResponse response = null;
HttpClient httpclient = this.getNewHttpClient();
HttpGet get = new HttpGet(url);
get.setHeader("Accept", "application/json");
get.setHeader("Content-type", "application/json");
try{
response = httpclient.execute(get);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
if(response != null){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
result = out.toString();
}
} else{
throw new IOException(statusLine.getReasonPhrase());
}
} catch(Exception ex){
ex.getMessage();
} finally{
if(response != null){
try{
response.getEntity().getContent().close();
} catch(Exception ex){
}
}
}
return result;
}
}
And progress dialog is show but only after all code in onCreatre in ChooseWriteSentenceActivity including doInBacground(...) from QueryExecutor is finished (so it disappears practically at the same time). It looks like sth waiting for thread with QueryExecutorFindUser.doInBackground() and it is runs like synchronously (?), I think that because when I debug code onPreExecute() is running correctly (and start before doInBackground(...)) and progressDialog.isShowing() == true (but not on the screen :( ).
If I remove extends AsyncTask from QueryExecutorFindUser and make private class with this extension in main activity (and run all code from onCreated() including service.findUser() in thisPrivateClass.doInBackground(...)) it works okey.
I prefer to have progressDialog in one place no in all main activities (of cource in practise I use QueryExecutor for all queries not only findUser) but I don't have idea what i am doing wrong. I spent all day on it with no result :(
Dialogs are tied to an Activity and ultimately must be hosted by one. So until your app's activity gets created, the dialog will not display.

using a String[] outside a method

I am trying to use the String[] mtake outside the onPostExecute(String) method. It gives me proper value inside the function but nothing in onCreate() method and simple crashes the app. Any help is appreciated. Thanks in advance. I have tried declaring it public static globally and inside the class. Static doesn't work either.
#SuppressLint({ "CutPasteId", "SimpleDateFormat", "SdCardPath" })
public class MainActivity extends Activity implements View.OnClickListener {
public String[] mtake;
public class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
}
catch (Exception e) {
e.printStackTrace();
}
}
return response.toString();
}
public void onPostExecute (String result) {
mtake = result.split("#");
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Handler handIn = new Handler();
final Timer T2 = new Timer();
T2.scheduleAtFixedRate(new TimerTask() {
public void run() {
handIn.post(new Runnable() {
public void run() {
txt = (TextView) findViewById(R.id.Text);
txt.setText(mtake[0]);
}
});
}
},0, 20000);
}
You aren't instantiating the mTake array with anything. In your onPostExecute method, you're calling mTake.equals(result.split("#")) which returns a boolean, not a String[]. Did you mean mTake = result.split("#")?

How to set instance variable of activity in onPostExecute?

I have an AsyncTask in my activity class and when I check some data in doInBackground(), I just want to change/set an instance variable of my activity class, but somehow there is nothing what is changing! :(
And if the variable is changed another AsyncTask should start.
Now here is the code:
public class LogIn extends Activity {
private boolean emailNotAvalaible;
private void setemailNotAvalaible(boolean emailNotAvalaible) {
this.emailNotAvalaible= emailNotAvalaible;
}
private Button loginBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
loginBtn = (Button) findViewById(R.id.login_btn);
loginBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Register().execute("");
if (emailNotAvalaible== true) {
new Installation().execute("");
}
}// end of onClick()
});// end of setOnClickListener
}// end of onCreate();
public class Register extends AsyncTask<String,Integer,String>{
#Override
protected void onPreExecute() {
...
}//end of onPreExecute()
#Override
protected String doInBackground(String... params) {
ArrayList<NameValuePair> postParamsEmail = new ArrayList<NameValuePair>();
postParamsEmail.add(new BasicNameValuePair("email", email));
try {
String emailCheck = executeHttpPost("http://.../doubleEmail.php", postParamsEmail);
try {
JSONArray jsonarr = new JSONArray( emailCheck );
String emailAvalaible = jsonarr.getString(0);
if( emailAvalaible.equals("no") ){ doubleEmail = "no"; }else{ doubleEmail = "yes"; }
} catch (JSONException e) {
e.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
return "String";
}// end of doInBackground()
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
if (doubleEmail.equals("no")){
LogIn.this.setEmailNotAvalaible(true);
}
}
}//end of AsyncTask class
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}//end of getHttpClient()
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}//end of executeHttpPost()
}//end of activity class
Some code is not shown, but this code isn't important for the solution.
The php-file just checks if the entered email does exist in the database.
So, the major question is how can I easily change the variable 'emailNotAvalaible' in doInBackground or in onPostExecute?
Thanks for your help!!!
EDIT:
Hello again, thanks for everybodys help, to change the variable works fine, but I guess my problem is, that before my Register AsyncTask is allready finished, the new AsyncTask proofs the variable and wants to start, but just a second after that the variable is set. So, How can I ensure that the second AsyncTask only starts when the first AsyncTask is Allready finished? thanks for your help guys!!!
There are several ways but the postExecute method can solve your problem look this: how to pass the result of asynctask onpostexecute method into the parent activity android
this should not be an issue. here is an example that works fine:
public class Register extends AsyncTask<String,Integer,String>{
#Override
protected void onPreExecute() {
Log.d("", "on pre bool: " + bool);
}//end of onPreExecute()
#Override
protected String doInBackground(String... params) {
bool = true;
return "";
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
Log.d("", "on post, bool: " + bool);
}
}
where bool = private boolean in your main activity. here is the logcat:
07-19 11:57:25.943: D/(21843): on pre bool: false
07-19 11:57:29.736: D/(21843): on post, bool: true
my guess is that your variable, doubleEmail, is not getting set to "no".
So, I think I have found at least one solution for my problem, this is maybe not the best one, but it works fine.
Now, for those who are interested in my solution.
I have found it here : multithreading , thanks to Boris Strandjev
I have chosen the 'get' - option : new Register().execute("").get(2000, TimeUnit.MILLISECONDS);
If there is any better solution, please tell me, otherwise thanks for trying to help me!

Need to access AsyncTask value in Main Class

I am facing an issue in Async task, can anyone please suggest me any solution.
I have downloaded this example from this link :
Source
My Current Structure is
Main Class extends MyTask and implements AsyncTaskCompleteListener interface.
AsyncTaskCompleteListener is an Interface contains the onTaskComplete Method .
MyTask extends Async Task and onPostExcute contains CallBackMethod which will return the result-set got from the doInBackground.
Http Class(Utils) contains the Http connection and returns the Result-set to AsyncTaskComleteListner from PostExecute.
I am trying to get my result-set Value in the main class from the interface method to perform my further operation.
I tried to get the value from static variables, static method but non of them worked, and also tried with creating a new class object to send and receive the result but every time it gives me NullPointerException . Because the statement written after the AsyncTask gets executes before getting the result.
I have also tried to get the Status of asyncTask from its method getStaus(), but it returns only Running and dose not notify when the task is completed or finished.
Here is the code sample:
Main Class Code :
package com.example.androidasynctask;
public class MainActivity extends Activity implements AsyncTaskCompleteListener {
public static String[] asyncResult;
String res[] = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btnclick(View view) {
/*MyTask asyncTask = new MyTask(this);
String [] asyncTaskResult = asyncTask.execute("fetchCategory.php","1%Id%1");*/
//AsyncTask<String, Void, String[]> asyncTaskRes = new MyTask(this).execute("fetchCategory.php","1%Id%1");
//new MyTask(this).execute("fetchCategory.php","1%Id%1");
MyTask asyncTask = (MyTask) new MyTask(this).execute("fetchCategory.php","1%Id%1");
if(asyncTask.getStatus().equals(AsyncTask.Status.FINISHED) || asyncTask.getStatus().equals(AsyncTask.Status.PENDING)) {
asyncTask.execute();
}
else {
Log.v("In Else","Get Value");
}
}
#Override
public void onTaskComplete(String[] result) {
Log.v("IN ON TASK COMPLETE","VALUE = "+result[1]);
}
/*#Override
public void onTaskComplete(String result) {
System.out.println("calling onTaskComplete SIMPLE....");
System.out.println("result :: "+ result);
}*/
public static class GetAsyncResult
{
static String[] returnValues;
public GetAsyncResult()
{}
public GetAsyncResult(String[] res)
{
returnValues = res;
Log.v("getResultSetValues","returnValues"+returnValues[1]);
}
public void getResultSetValues()
{
Log.v("getResultSetValues","returnValues"+returnValues[1]);
}
}
}
Async Task Code :
public class MyTask extends AsyncTask<String, Void, String[]> {
private Activity activity;
private ProgressDialog dialog;
private AsyncTaskCompleteListener callback;
public String[] asyncResultSetValue = null;
public MyTask(Activity act) {
Log.v("MY TASK","ACTIVITY"+act);
this.activity = act;
this.callback = (AsyncTaskCompleteListener)act;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.v("MY TASK","in ON PRE EXECUTE");
dialog = new ProgressDialog(activity);
dialog.setMessage("Loading...");
dialog.show();
}
#Override
protected String[] doInBackground(String... params) {
Log.v("MY TASK","DO IN BACKGROUND");
Log.v("PARAMS"," params[0] = "+params[0]+ "| params[1]"+params[1]);
asyncResultSetValue = Utils.process_query(params[0],params[1]);
return asyncResultSetValue;
}
#Override
protected void onPostExecute(String[] result) {
super.onPostExecute(result);
Log.v("MY TASK","in ON POST EXECUTE");
if (null != dialog && dialog.isShowing()) {
dialog.dismiss();
}
callback.onTaskComplete(result);
}
}
HTTP CLASS CODE :
public class Utils {
static String result = null;
String endResult;
static java.io.InputStream is = null;
static StringBuilder sb=null;
static String delimiter = "\\|";
static String delimiter1 = "\\%";
static String[] temp = null;
static String[] temp1 = null;
static ArrayList<NameValuePair> nameValuePairs;
static Context context;
static ProgressDialog mDialog;
static HttpResponse response;
static String[] resultset_value = null;
//static String url = "http://fortuneworkinprogress.in/News_App/"; //Global URL
static String url = "http://10.0.2.2/News_App/"; //Global URL
static String query_type,parameter;
/*************** PROCESS QUERY START ***************/
public static String[] process_query(String str_url, String parameter) {
// String strval = select_parameter;
String ret_val[] = null;
String get_sel_val[] = null;
int loopcount =0;
url = url+str_url; //!!!! ######### CONCATINATING AND CREATING FULL URL ######## !!!!!!//
Log.v("PROCESS QUERY PARAMETER","URL = "+url+" | PARAMTER = "+parameter);
nameValuePairs = new ArrayList<NameValuePair>();
//Log.i("STR VAL",""+strval); //To Check which values are recieved
try
{
String strval = parameter;
get_sel_val=strval.split(delimiter1);
for(int i =0; i < get_sel_val.length ; i++)
{
loopcount = Integer.parseInt(get_sel_val[0]); // First Delimeted Value which tells the number of count
Log.i("Loopcount","cnt = "+loopcount);
}
for(int j=1;j<=(loopcount*2);j=j+2) //For Loop for making Name Values Pares Dynamic
{
nameValuePairs.add(new BasicNameValuePair(get_sel_val[j],get_sel_val[j+1]));
//Log.i("J = ["+j+"]","pairvalue1 = "+get_sel_val[j]+"pairvalue2 ="+get_sel_val[j+1]);
}
}
catch(Exception e)
{
Log.w("Exception in the getting value","Exp = "+e);
}
//nameValuePairs.add(new BasicNameValuePair("id","1"));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
Log.v("CONNECT URL ","Final url "+url);
Log.w("CONNECTION STATUS ",httppost.toString());
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.w("PAERSE VALUE ",nameValuePairs.toString());
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.w("1", "Connection establised succesfuly");
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
Log.v("SB VALUE = ","sb = "+sb.toString());
String line="0";
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
// Toast.makeText(getBaseContext(), result ,Toast.LENGTH_LONG).show();
Log.w("result", result);
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
Toast.makeText(null, "error converting response to string" ,Toast.LENGTH_LONG).show();
}
String[] temp = null;
String[] tempResult = null;
if(result!=null)
{
tempResult = result.split(delimiter); //Split the entire return string into "rows"
for(int i =0; i < tempResult.length-1 ; i++)
{
temp = null;
temp = tempResult[i].split(delimiter1); //Find columns for each row
ret_val = temp;
resultset_value=ret_val;
}
}
else
{
Toast.makeText(null, "Cannot Find Routes" ,Toast.LENGTH_LONG).show();
}
Log.v("BEFORE RETUNR = ","ret_val = "+ret_val.toString());
return ret_val; //Returning the result value array
}
/*************** PROCESS QUERY ENDS ***************/
public static boolean isNetworkAvailable(Activity activity)
{
ConnectivityManager connectivity = (ConnectivityManager) activity
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null)
{
return false;
}
else
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
{
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
}
}
return false;
}
}
Thanks in advance.
Because the statement written after the AsyncTask gets executes before getting the result.
the reason is AsyncTask runs on separate thread,not on your Main(UI) thread.
MyTask extends Async Task and onPostExcute contains CallBackMethod which will return the result-set got from the doInBackground.
you will be getting result values on this method
#Override
public void onTaskComplete(String[] result) {
Log.v("IN ON TASK COMPLETE","VALUE = "+result[1]);
}
Comment following piece of code,
if(asyncTask.getStatus().equals(AsyncTask.Status.FINISHED) || asyncTask.getStatus().equals(AsyncTask.Status.PENDING)) {
asyncTask.execute();
}
else {
Log.v("In Else","Get Value");
}
Make change,
public static String[] asyncResult; to public String[] asyncResult = null;
Change following,
asyncResultSetValue = Utils.process_query(params[0],params[1]); to asyncResult = Utils.process_query(params[0],params[1]);
and return asyncResultSetValue; to return asyncResult ;
look at value by adding one more log,you will be getting result values on this method
#Override
public void onTaskComplete(String[] result) {
Log.v("IN ON TASK COMPLETE","VALUE = "+result[1]);
Log.v("IN ON TASK COMPLETE","VALUE = "+asyncResult[1]);
}

How to make a TextView show a value from a AsynTask class

I have an AsynTask which retrieve data from a web service and with this data to be viewed on the UI. So, in my MainActivity, I have a textView.
This is the data I received from the webservice:
{"name":"ezio","country":"italy"}{"name":"fufu","country":"tutu"}{"name":"chikaka","country":"aceVentura"}
The problem is, I do not know how to set the textView with the value of 'result' from the ClientConnection class. When I run the application, the textView is empty.
public class ClientConnection extends AsyncTask {
public static final String URL = "http://192.168.0.15/test.php";
static JSONObject jObj = null;
public static String result = "";
#Override
protected String doInBackground(Void... voids) {
// public JSONObject connect(){
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.e("HTTPStatus error:","Status not okay");
}
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "iso-8859-1"), 8);
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
JSONObject jsonObject = convertToJson(result);
// jsonObject.get()
//result = jsonObject.getString("name");
//JSONArray google = jsonObject.getJSONArray("");
} catch (Exception e) {
//Toast toast = Toast.makeText(null, e.getMessage(), Toast.LENGTH_LONG);
Log.e("Error","don't know what exception though");
}
return result;
}
private JSONObject convertToJson(String test){
JSONArray clients = new JSONArray();
try{
jObj = new JSONObject(test);
}catch (JSONException e){
Log.e("JSON Parser", "Error parsing data" + e.toString());
}
return jObj;
}
public String getResult(){
return result;
}
public JSONObject getjObj(){
return jObj;
}
}
And this is the Main Activity
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView textView = (TextView) findViewById(R.id.textViewTest);
ListView listView = (ListView) findViewById(R.id.listView);
Button buttonConnect = (Button) findViewById(R.id.buttonConnect);
final ClientJSONParsingActivity clientJSONParsingActivity = new ClientJSONParsingActivity();
buttonConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new ClientConnection().execute();
textView.setText(new ClientConnection().getResult());
}
});
}
}
Thank you for your help
You can display the result in the onPostExecute in the AsyncTask.
You should update textview in your asynctask. onPostExecute() method runs on UI thread
protected void onPostExecute(String result) {
textView.setText(result);
}
Pass the text view as an argument to the asynctask and set it in onPostExecute. On my mobile so no code, sorry ;-)
add this code under your doinbackground;
protected void onPostExecute(Long result) {
(find your text view here from the context where textview it is)
textView.setText(result);
}

Categories

Resources