In my MainActivity.java i have set some text to a TextView, how do I get the text that I had set to the TextView
My Textview -
<TextView
android:id="#+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible" />
ASyncTask -
public class fetchdata extends AsyncTask<Void, Void, Void> {
private String data = "";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://blablabla.com/hello.json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
data = bufferedReader.readLine();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.show.setText(this.data);
}
}
MainActivity -
private static TextView show;
...... show is static
show = findViewById(R.id.show);
String data = show.getText().toString();
but data is empty instead of me getting "this is the text I want to get"
Considering the fact that the following two lines are together,
show = findViewById(R.id.show);
String data = show.getText().toString();
I'm gonna guess that they are in the onCreate, thereby resulting in empty data.
You'll need to wait for the AsyncTask to complete and TextView to have it's value set in onPostExecute before you try to get it in the UI thread. (You could use a callback)
class fetchdata extends AsyncTask<Void, Void, String> {
private String data = "";
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL("https://blablabla.com/hello.json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
return data = bufferedReader.readLine();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
show.setText(aVoid);
}
}
Related
I am having issues getting data from a website.
So I want android studio to show the html in the logcat.
When I am entering the app,the screen become white and unresponsive.
I am getting no errors.
every time I try using AsyncTask and it just refusing to work.
Thanks for the help.
btw,I allowed the INTERNET permission on "Android Manifest".
public class MainActivity extends AppCompatActivity {
public class DownloadTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask download = new DownloadTask();
String result = null;
try {
result = download.execute("https://www.usmagazine.com/celebrities/a/").get();
Log.d("WORKING?", result);
}catch (Exception e){
}
}
}
Your
return result;
in doInBackground returns result to a method called onPostExecute in your AsyncTask. Please override that method, and perform the task there.
Here I'm trying to read an HTML file and log it but the problem is every time i check the logs I see hundreds of numbers instead of the actual code of the HTML.
I added the Internet permission in case you asked
public class MainActivity extends AppCompatActivity {
public class downloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += data;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return "Failed";
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("Result is:", s);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downloadTask task = new downloadTask();
task.execute("https://samples.openweathermap.org/data/2.5/weather?id=2172797&appid=439d4b804bc8187953eb36d2a8c26a02");
}
}
the response of API is in JSON format.
You must parse JSON response before getting data.
Here an example of JSON parsing in java.
Good luck!
I am trying to send data to url from where i am parsing json data and i want to know can we edit json data in url if we created random json store from myjson.com or we have to maintain our own server to edit json data.Here i created random json store and i am parsing data from that url and i also wanted to edit the data in url thats the problem i was not able to do .Its not working.please help???
This was structure
[{"name":"pavan","hit":true}]
this was mainactivity code from where fetchdata executes in background
public class MainActivity extends AppCompatActivity {
Button click;
public static TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click=(Button)findViewById(R.id.button);
data=(TextView)findViewById(R.id.fetcheddata);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fetchdata process=new fetchdata();
process.execute();
}
});
}
}
This is fetchdata class from where fetching data from url and displaying in text view of mainactivity
public class fetchdata extends AsyncTask<Void,Void,Void> {
String data="";
String dataparsed="";
String singleparsed="";
boolean flag=false;
#Override
protected Void doInBackground(Void... params) {
try {
URL url=new URL("https://api.myjson.com/bins/1854yb");
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
InputStream inputStream=httpURLConnection.getInputStream();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
String line="";
while (line!=null)
{
line=bufferedReader.readLine();
data=data+line;
}
JSONArray JA=new JSONArray(data);
for(int i=0;i<JA.length();i++)
{
JSONObject JO= (JSONObject) JA.get(i);
singleparsed="Name:"+JO.get("name")+"\n"+"Feed key:"+JO.get("hit");
dataparsed=dataparsed+singleparsed;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
MainActivity.data.setText(this.dataparsed);
JSONObject postData = new JSONObject();
try {
postData.put("name","sai");
postData.put("hit", false);
new senddata().execute("https://api.myjson.com/bins/1854yb", postData.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is senddata to url code from postexecute of fetchdata this was executing and nothing is happening in url please help i am working on this from 3 days
public class senddata extends AsyncTask<String,Void, String> {
String data="";
String dataparsed="";
String singleparsed="";
boolean flag=false;
#Override
protected String doInBackground(String... params) {
String data = "";
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes("PostData=" + params[1]);
wr.flush();
wr.close();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
data += current;
}
dataparsed=data;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e("TAG", result);
}
}
This api doesn't accept any paramter after its url.
It is a get method Api url not post method . Try running it in post method in postman , it will give error.
If u run in get method ,it will produce same output ,even if u add something after url :-"https://api.myjson.com/bins/1854yb"
I think you have some issue with myJson in creating api. If you are a beginner in android your can also try with Link for ready made Api for Android
They have created different kind of Apis for understanding the json concept.
also get some update about PostMan Link for postman
I have a Async task like this in my app:
private class getUserSummary extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DashboardActivity.this);
pDialog.setMessage("Getting sales summary...");
//pDialog.setTitle("Getting sales summary...");
pDialog.setIndeterminate(true);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... strings) {
String JsonResponse = null;
String JsonDATA = "email=my email address";
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
ServiceUrl smf = new ServiceUrl();
URL url = new URL(smf.getUserSummaryUrl());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
// is output buffer writter
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//set headers and method
Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
writer.write(JsonDATA);
// json data
writer.close();
int responseCode = urlConnection.getResponseCode();
if (responseCode == 400) {
InputStream inputResponse = urlConnection.getErrorStream();
reader = new BufferedReader(new InputStreamReader(inputResponse));
StringBuffer errorBuffer = new StringBuffer();
String errorLine;
while ((errorLine = reader.readLine()) != null) {
errorBuffer.append(errorLine + "\n");
}
Log.i("Error text", errorBuffer.toString());
return new JSONObject(errorBuffer.toString());
}
//Log.i("Response code", String.valueOf(inputStream));
InputStream inputStream = urlConnection.getInputStream();
//input stream
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine + "\n");
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
JsonResponse = buffer.toString();
//response data
Log.i("RESPONSE", JsonResponse);
return new JSONObject(JsonResponse);
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("ERROR", "Error closing stream", e);
}
}
}
return null;
}
protected void onPostExecute(JSONObject result) {
pDialog.dismiss();
//post operation here
}
}
and calling this in onCreate() method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
ButterKnife.bind(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initCollapsingToolbar();
new getUserSummary().execute();
}
I am running this as soon as user login activity distroyed. that's why I need to call this on onCreate() method. But I am getting this error when the call this in onCreate() method
android.view.WindowLeaked: Activity softlogic.computers.softlogicsalesreward.DashboardActivity has leaked window com.android.internal.policy.PhoneWindow$DecorView{5329b90 V.E...... R......D 0,0-1002,348} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:603)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:326)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:109)
at android.app.Dialog.show(Dialog.java:505)
at softlogic.computers.softlogicsalesreward.DashboardActivity$getUserSummary.onPreExecute(DashboardActivity.java:88)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:604)
at android.os.AsyncTask.execute(AsyncTask.java:551)
at softlogic.computers.softlogicsalesreward.DashboardActivity.onResume(DashboardActivity.java:65)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1287)
at android.app.Activity.performResume(Activity.java:7015)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4210)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4323)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3426)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
is there any other event where I can call this? or what I am doing wrong?
Your asyncTask must be like this.After see your code it may possible that You may forgot some method of AsyncTask.Compare with this example to better understand.
This is complete example of asyncTask:
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
private String resp;
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
publishProgress("Sleeping..."); // Calls onProgressUpdate()
try {
int time = Integer.parseInt(params[0])*1000;
Thread.sleep(time);
resp = "Slept for " + params[0] + " seconds";
} catch (InterruptedException e) {
e.printStackTrace();
resp = e.getMessage();
} catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
progressDialog.dismiss();
finalResult.setText(result);
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this,
"ProgressDialog",
"Wait for "+time.getText().toString()+ " seconds");
}
#Override
protected void onProgressUpdate(String... text) {
finalResult.setText(text[0]);
}
}
call like this:
new AsyncTaskRunner (this).execute();
you can use thread policy for this. It's work great.
Just add two line below setcontent.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build();
StrictMode.setThreadPolicy(policy);
You Forget to call pDialog.dismiss();
in onPostExecute method of Async task
public class MainActivity extends AppCompatActivity {
Where I set up the url and HttpUrlConnection which allows the program to read the contents of the url.
public class DownloadTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try{
url = new URL(urls[0]);
urlConnection =(HttpURLConnection)url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data != -1){
char current = (char) data;
result += current;
data =reader.read();
}
return result;
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
String result = null;
try {
result = task.execute("http://www.historyplace.com/specials/").get();
Log.i("Contents of URL", result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
I believe my code is written correctly because the logCat does display a few lines of code. Unfortunately it does not display all of it. I am trying to first retrieve all of the code so I can use Regex to extract certain pictures and names for an educational school project.