parse data from a network thread object to another object android - java

I want to parse JSON object that returns from a url to a textview. for that I used class which extends AsyncTask to get the network connection. my problem is I can't parse the returning string value to my main class.
my main class as follows
package com.example.janitha.condd;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
final String ur ="https://maps.googleapis.com/maps/api/place/textsearch/json?query=keells+super&location=6.849813513872538,79.90265075223242&key=AIzaSyDQ6fVTYb1_3MmD7j3Sei4CAhbZ_eIOphs";
String outcome=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv=(TextView)findViewById(R.id.text1) ;
Connection con=new Connection();
con.execute(ur);
outcome =con.getFinalData();
tv.setText(outcome);
}
}
my connection class as follows
package com.example.janitha.condd;
import android.os.AsyncTask;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Janitha on 7/10/2016.
*/
public class Connection extends AsyncTask<String, Void, String> {
String finalData="123";
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
finalData=result;
}
public String downloadUrl(String myurl) throws IOException {
InputStream is = null;
int len = 50000;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
is = conn.getInputStream();
String contentAsString = readIt(is, len);
return contentAsString;
} finally {
if (is != null) {
is.close();
}
}
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
public String getFinalData() {
return finalData;
}
}
each time when code executes it gives me the value as 123 which means the value that I initialized for variable finalData. what is wrong with my code?

You should understand how AsyncTask works. When you call con.execute(ur), it runs on the background thread (off UI/Main thread). Now control on your main thread reaches outcome =con.getFinalData() and by that time the background thread hasn't completed the task and thus con.getFinalData() returns "123" because finalData was not yet updated.
What you should do this is to provide a callback to the AysncTask and when onPostExecute is called, you should return the result using that callback.
Edit 1:
Your interface:
public interface OnTaskCompleted {
void onTaskCompleted(String value);
}
Your activity should implement this:
public class MainActivity implements OnTaskCompleted {
//...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
Connection con=new Connection(MainActivity.this);
con.execute(url);
...
}
#Override
public onTaskCompleted(String value) {
// you will receive the data here.
}
}
Changing constructor of the AsyncTask:
public class Connection extends AsyncTask<String, Void, String> {
private OnTaskCompleted listener;
public Connection(OnTaskCompleted listener){
this.listener=listener;
}
String finalData="123";
#Override
protected String doInBackground(String... urls) {
Return data onPostExecute:
#Override
protected void onPostExecute(String result) {
if(listener!=null) {
listener.onTaskCompleted(result);
}
}

Related

How can I use a variable outside the onPostExecute method?

I have a MySQL database on a webserver and I read the data from this database in my application, but after I read the variables I can't use the "volt" variable outside the onPostExecute. I try t use adapter, but i can't use the data in the adapter like a intiger variable, just i can add to listview. So far i Don't find a solution for my problam.
I hope you can help me.
package com.example.wifis;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayAdapter<String> adapter;
// int tomb []={};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView)findViewById(R.id.list_item);
adapter= new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
new Conection().execute();
}
class Conection extends AsyncTask<String, String, String>{
#Override
public String doInBackground(String... strings) {
String result="";
String host="http://localhost/store/cars.php";
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(host));
HttpResponse response = client.execute(request);
BufferedReader reader= new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer stringBuffer= new StringBuffer("");
String line = "";
while ((line = reader.readLine()) !=null ){
stringBuffer.append(line);
break;
}
reader.close();
result = stringBuffer.toString();
}
catch (Exception e){
return new String("There exeption: "+ e.getMessage());
}
return result;
}
#Override
public void onPostExecute(String result){
// Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
JSONObject jsonResult = null;
try {
jsonResult = new JSONObject(result);
int success = jsonResult.getInt("success");
if(success==1){
JSONArray cars = jsonResult.getJSONArray("cars");
JSONObject car = cars.getJSONObject(0);
int id = car.getInt("id");
int volt = car.getInt("szam");
String line = id + "-" + volt;
adapter.add(line);
// tomb[0]=szam;
}else{
Toast.makeText(getApplicationContext(), "NOT OK ", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
As I have tried to explain in my post here
the values you're trying to access aren't synchronous, meaning that your code does not execute top down. The AsyncTask returns a value at some point. we don't know when that will be, but when it returns the value, you'll have access to it within onPostExecute. this means that you can make use of the values as they are received there and only there, as that is the only place where you'll actually receive those values.
to get this value returned to your main activity, you can do something like this :
create an interface
public interface MyCallback {
void myResult(YourResultType output); //here, i believe this will be string for your specific case
}
This interface allows us to move the value we receive to another class when it's received
Next,
Go to your AsyncTask class, and declare interface MyCallback as a variable :
public class MyAsyncTask extends AsyncTask<String, String, String> {
public MyCallback callback = null;
#Override
protected void onPostExecute(String result) {
callback.myResult(result);
}
}
#Override
protected void onPostExecute(String result) {
callback.myResult(result);
}
now for your main activity:
public class MainActivity implements MyCallback {
MyAsyncTask asyncTask = new MyAsyncTask();
#Override
public void onCreate(Bundle savedInstanceState) {
//set your listener to this class
asyncTask.callback = this;
//execute the async task
asyncTask.execute();
}
//this overrides the implemented method from asyncTask
#Override
void myResult(YourResultType output){
//Here you will receive the result returned from the async task
}
}
please also note that async tasks are deprecated
also note, my java is quite rusty, I am fortunate enough to only use kotlin these days, feel free to correct me on any mistakes :)

Why Toast in this application does not show anything?

I wrote an application that connect to wamp server ( with a MySQl datatbase that one of its rows in table users have Username="pooriya" and Password="123")
This application checks if Username "pooriya" exist then Toast the password and if does not exist Toast "no user"
When i run this app on emulator , it should Toast "123", but
empty Toast is shown . Why ?
Even when i change the User to a not existing Username , like "poori" , again empty Toast is shown . Why ?
database name is "note_test_2_db"
And when i enter the address "http://127.0.0.1:8080/mysite1/index.php" in my browser , it shows "no user" , then i guess that the php file works correctly and the problem is in my android code .
Thanks
package com.example.GetDataFromServer;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MyActivity extends Activity {
public static String res = "";
Button btn;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button);
new getdata("http://127.0.0.1:8080/mysite1/index.php", "pooriya").execute();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), res, Toast.LENGTH_LONG).show();
}
});
}
}
package com.example.GetDataFromServer;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
/**
* Created with IntelliJ IDEA.
* User: Farid
* Date: 3/15/19
* Time: 4:09 PM
* To change this template use File | Settings | File Templates.
*/
public class getdata extends AsyncTask {
private String Link = "";
private String User = "";
public getdata(String link, String user) {
Link = link;
User = user;
}
#Override
protected String doInBackground(Object... objects) {
try {
String data = URLEncoder.encode("username", "UTF8") + "=" + URLEncoder.encode(User, "UTF8");
URL mylink = new URL(Link);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr= new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
MyActivity.res = sb.toString();
} catch (Exception e) {
}
return ""; //To change body of implemented methods use File | Settings | File Templates.
}
}
$con=mysql_connect("localhost","root","");
mysql_select_db("note_test_2_db",$con);
$user=$_POST['username'];
$sqlQ="select * from users where Username='$user'";
$result= mysql_Query($sqlQ);
$row=mysql_fetch_array($result);
if($row[0]){
print $row[1];
}
else{
print "no user";
}
mysql_close($con);
Problem: It seems your code to show Toast is incorrect.
new getdata("http://127.0.0.1:8080/mysite1/index.php", "pooriya").execute();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), res, Toast.LENGTH_LONG).show();
}
});
When the first line is executed, the app will start the AsyncTask which connects to your server to get the response ("123" or "No User").
If you click on the button btn before the AsyncTask completed, at this time, the value of res is "", that why you always get empty Toast.
Solution: You can do the following steps
Step 1: Because getdata is a separate class, so you need to define an interface to pass data ("123" or "No User" or any value) back to MyActivity.
public interface OnDataListener {
void onData(String result);
}
Step 2: Modify getdata class
public class getdata extends AsyncTask<Object, Void, String> {
private String Link = "";
private String User = "";
private WeakReference<OnDataListener> mListener;
public getdata(String link, String user, OnDataListener listener) {
Link = link;
User = user;
mListener = new WeakReference<>(listener);
}
#Override
protected String doInBackground(Object... objects) {
try {
String data = URLEncoder.encode("username", "UTF8") + "=" + URLEncoder.encode(User, "UTF8");
URL mylink = new URL(Link);
URLConnection connect = mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
// This string will pass as param of onPostExecute method.
return sb.toString(); // Will return "123" or "No User" if there is no exception occurs.
} catch (Exception e) {
}
// If your app reach this line, it means there is an exception occurs, using a unique string for debugging.
// This string will pass as param of onPostExecute method
return "An exception has been caught!!!";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Pass the result back to MyActivity's onData method.
if (mListener != null && mListener.get() != null) {
mListener.get().onData(result);
}
}
}
Step 3: Let MyActivity implements OnDataListener interface.
public class MyActivity extends AppCompatActivity implements OnDataListener {
public static String res = "";
Button btn;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button);
new getdata("http://127.0.0.1:8080/mysite1/index.php", "pooriya", this).execute();
// TODO: Comment-out this code
// btn.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Toast.makeText(getApplicationContext(), res, Toast.LENGTH_LONG).show();
// }
// });
}
#Override
public void onData(String result) {
// result is passed from the AsyncTask's onPostExecute method.
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
Note: Because you do not use any loading indicator while connecting to the server, so you need to wait a few seconds to see the Toast on the screen.
I solved the problem . I should use http://10.0.2.2:8080/mysite1/index.php instead http://127.0.0.1:8080/mysite1/index.php

Attempt to invoke interface method on a null object reference

I have class LoadJSONTask. In this class I am getting the error below.
My application is running but when I try to add progress bar in the code its not working.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.kalakaaristudios.json.listviewmenu, PID: 3809
java.lang.NullPointerException: Attempt to invoke interface method 'void in.kalakaaristudios.json.listviewmenu.LoadJSONTask$Listener.onLoaded(java.util.List)' on a null object reference
at in.kalakaaristudios.json.listviewmenu.LoadJSONTask$override.onPostExecute(LoadJSONTask.java:83)
at in.kalakaaristudios.json.listviewmenu.LoadJSONTask$override.access$dispatch(LoadJSONTask.java)
at in.kalakaaristudios.json.listviewmenu.LoadJSONTask.onPostExecute(LoadJSONTask.java:0)
at in.kalakaaristudios.json.listviewmenu.LoadJSONTask.onPostExecute(LoadJSONTask.java:21)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
LoadJSONTask class
package in.kalakaaristudios.json.listviewmenu;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ProgressBar;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
public class LoadJSONTask extends AsyncTask<String, Void, Response> {
private MainActivity activity;
private ProgressBar dwBar;
public LoadJSONTask(MainActivity activity) {
this.activity = activity;
dwBar = (ProgressBar) activity.findViewById(R.id.progress_bar);
}
public LoadJSONTask(Listener listener) {
mListener = listener;
}
public interface Listener {
void onLoaded(List<AndroidVersion> androidList);
void onError();
}
private Listener mListener;
#Override
protected Response doInBackground(String... strings) {
try {
String stringResponse = loadJSON(strings[0]);
Gson gson = new Gson();
return gson.fromJson(stringResponse, Response.class);
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (JsonSyntaxException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
MainActivity mn = new MainActivity();
dwBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Response response) {
dwBar.setVisibility(View.GONE);
if (response != null) {
mListener.onLoaded(response.getAndroid());//getting error here
} else {
mListener.onError();
}
}
private String loadJSON(String jsonURL) throws IOException {
URL url = new URL(jsonURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
return response.toString();
}
}
MainActivity.java
package in.kalakaaristudios.json.listviewmenu;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ProgressBar;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
public class LoadJSONTask extends AsyncTask<String, Void, Response> {
private MainActivity activity;
private ProgressBar dwBar;
public LoadJSONTask(MainActivity activity) {
this.activity = activity;
dwBar = (ProgressBar) activity.findViewById(R.id.progress_bar);
}
public LoadJSONTask(Listener listener) {
mListener = listener;
}
public interface Listener {
void onLoaded(List<AndroidVersion> androidList);
void onError();
}
private Listener mListener;
#Override
protected Response doInBackground(String... strings) {
try {
String stringResponse = loadJSON(strings[0]);
Gson gson = new Gson();
return gson.fromJson(stringResponse, Response.class);
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (JsonSyntaxException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
MainActivity mn = new MainActivity();
dwBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Response response) {
dwBar.setVisibility(View.GONE);
if (response != null) {
mListener.onLoaded(response.getAndroid());
} else {
mListener.onError();
}
}
private String loadJSON(String jsonURL) throws IOException {
URL url = new URL(jsonURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
return response.toString();
}
}
I think your issue is on this line
dwBar = (ProgressBar) activity.findViewById(R.id.progress_bar);
because you are using the activity class instance to obtain a reference to your ProgressBar View widget
You should inflate a layout that contains the ProgressBar widget and use the find to get an instance of your ProgressBar
View view = inflater.inflate(R.Layout_that_contains_progress_bar, null);
dwBar = (ProgressBar) activity.findViewById(R.id.progress_bar);
Alternatively, you can create ProgressBar programmatically like below
dwBar = new ProgressBar(activity);

Not able to print JSON object String in android TextView

So I am trying to fetch JSON string from a website which looks like this
[{"name":"Painting"},{"name":"Painting or varnishing doors"},{"name":"Painting or varnishing frames"},{"name":"Varnishing floors"},{"name":"Picking old wallpaper"},{"name":"Painting the facade"},{"name":"professional athlete"}]
I just want to fetch the first JSONObject with the string "Painting".
Here's my MainActivity.java code
package mobiletest.pixelapp.com.mobiletest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import model.Cup;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private String myString;
private String anotherString;
private String myVar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textView);
Cup myCup = new Cup();
String newString = myCup.myMethod();
try {
JSONArray jsonArray = new JSONArray(newString);
JSONObject jsonObject = jsonArray.getJSONObject(0);
Log.v("Key",jsonObject.getString("name"));
textView.setText(jsonObject.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here's my java class file cup.java
package model;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
/**
* Created by pruthvi on 12/2/2015.
*/
public class Cup {
public String myMethod()
{
String output = getUrlContents("http://xyz.co/tests/android-query.php");
return output;
}
private static String getUrlContents(String theUrl)
{
StringBuilder content = new StringBuilder();
// many of these calls can throw exceptions, so i've just
// wrapped them all in one try/catch statement.
try
{
// create a url object
URL url = new URL(theUrl);
// create a urlconnection object
URLConnection urlConnection = url.openConnection();
// wrap the urlconnection in a bufferedreader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
// read from the urlconnection via the bufferedreader
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return content.toString();
}
}
Now the problem, when I run this code as java I am easily able to print painting from the JSONObject, but when I try to run it as an android view by setting the text for my TextView, I am getting some strange system.err
12-02 14:06:26.809 19250-19250/mobiletest.pixelapp.com.mobiletest D/libc: [NET] getaddrinfo hn 10, servname NULL, ai_family 0+
12-02 14:06:26.809 19250-19250/mobiletest.pixelapp.com.mobiletest W/System.err: at java.net.InetAddress.lookupHostByName(InetAddress.java:393)
12-02 14:06:26.809 19250-19250/mobiletest.pixelapp.com.mobiletest W/System.err: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:244)
12-02 14:06:26.809 19250-19250/mobiletest.pixelapp.com.mobiletest W/System.err: at java.net.InetAddress.getAllByName(InetAddress.java:219)
I am new to java and android, and as of now I just want to get data from my remote server files and database.
Thanks in advance
look at this example it will give you an idea
AsyncTask<Void, Void, Void> asyncLoad = new AsyncTask<Void, Void, Void>()
{
#Override
protected Void doInBackground(Void... params)
{
URL url = new URL("http://www.omdbapi.com/?i=&t="
+ TITLE);
String URL2="http://www.omdbapi.com/?i=&t=saw";
Log.d("URL content", url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
Log.d("URL content", "register URL");
urlConnection.connect();
Log.d("URL connection", "establish connection");
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
}
};
asyncLoad.execute();
Do like that in onCrate Method
try {
JSONArray jsonArray = new JSONArray(newString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name")
textView.setText(name));}
} catch (JSONException e) {
e.printStackTrace();
}
It will set name to textView.
Happy to Help and Happy Coding
You can't do network task in UI Thread.
So
String newString = myCup.myMethod();
not properly working.
Main Reason of those errors are related with thread context.
If you want to do network task with android, use async task or other network library (personally I recommend retrofit).
try
{
JSONArray jsonArray = new JSONArray(newString);
if(jarray.length()>0){
String name = jarray.getJSONObject(0).getString("name");
displayName(name); //new method
}catch(Exception e){
}
Define the method displayName(String) like this outside onCreate()
public void displayName(final String name){
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(jsonObject.getString("name"));
}
});
}

Async class not passing the argument

My async class is throwing some errors. The line with AsyncLoadData says that I should create local variable url
public void getData() {
new AsyncLoadData(this,this).execute(url);
}
My AsyncLoadData class
package com.example.hay;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.EditText;
public class AsyncLoadData extends AsyncTask<String, Void, String> {
private Context mContext;
private ILoadDataListener mListener;
public AsyncLoadData(Context context, ILoadDataListener listener) {
this.mContext = context;
this.mListener = listener;
}
#Override
protected String doInBackground(String... params) {
try {
EditText tf = (EditText) this.findViewById(R.id.editText1);
String url = params[0];
url = tf.getText().toString();
Document doc;
doc = Jsoup.connect(url).get();
String title = doc.text();
return title;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private EditText findViewById(int edittext1) {
return null;
}
#Override
protected void onPostExecute(String result) {
mListener.complete(result);
}
#Override
protected void onPreExecute() {
mListener.loading();
}
public interface ILoadDataListener {
void loading();
void complete(String result);
}
}
As you can see the AsyncLoadData should pass the url variable.
Have you declared url somewhere else in the code before calling this line : new AsyncLoadData(this,this).execute(url); ?
If not, you should add line String url = "the value of the url you are trying to call"; just before it, otherwise the variable url does not exist in the getData method...

Categories