can not set value to string from onPostExcecute in AsyncTask android - java

this is the class for reading json string from web
{
public class JSONmethod extends AsyncTask<String,String,String>
{
public String result_string;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
BufferedReader reader = null;
HttpURLConnection connection = null;
StringBuffer buffer;
try {
URL url;
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
String line= "";
buffer = new StringBuffer();
while ((line = reader.readLine())!= null)
{
buffer.append(line);
}
return buffer.toString();
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
result_string=result;
}
public String result_string_josn()
{
return result_string;
}
}
method "result_string_json()" return null string
i want to use this class frequntly for reading the json string from the web
so i made this method for return string which will returns from onPostExecute
this is the class where i want that value which is generate in post execute through method or anything else
simple.java
package com.bhatti.bis;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class simple extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple);
JSONmethod j = new JSONmethod();
j.execute("here is json string");
Toast.makeText(this,j.result_string_josn(),Toast.LENGTH_LONG).show();
}
}

Use EventBus library. It's very easy to use and will perfectly fix your problem:
First create a simple class for your Event:
public class MyEvent{
private String data;
public MyEvent(String data) {
this.data = data;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
Then in your Activity or wherever, register and unregister the EventBus, as explained in the docs.
Now post the appropriate event:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
EventBus.getDefault().post(new MyEvent(jsonArray.toString()));
}
All that's left for you to do is to listen for that event wherever you want (in another Activity, Fragment, Service - that's what makes EventBus great):
#Subscribe
public void onMyEvent(MyEvent myEvent){
String data = myEvent.getData();
//do whatever you wish with the text (e.g. make a toast, write it somewhere)
}

Async Task is asynchronous task, please read https://en.wikipedia.org/wiki/Asynchrony_%28computer_programming%29
Remove Toast just after :
JSONmethod j = new JSONmethod();
j.execute("here is json string");
And put it in onPostExecute :
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(this,result,Toast.LENGTH_LONG).show();
}

Android handles input events/tasks with a single User Interface (UI) thread and the thread is called Main thread. Main thread cannot handle concurrent operations as it handles only one event/operation at a time.For detail read this tutorials
JSONmethod jSONmethod = new JSONmethod();
jSONmethod.execute("Your json string");
public class JSONmethod extends AsyncTask<String,String,String>
{
public String result_string;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
BufferedReader reader = null;
HttpURLConnection connection = null;
StringBuffer buffer;
try {
URL url;
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
String line= "";
buffer = new StringBuffer();
while ((line = reader.readLine())!= null)
{
buffer.append(line);
}
return buffer.toString();
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("JSONmethod","result = "+result);
}
}

Related

How to parse data from json(url) and send data to url

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

Access a private field from MainActivity Class to another Class

I have declared a private field in the MainActivity Class with getter and setter method. Now I want to setText from another class in this field. But after running the device the app is crushing. I want to fetch some json data by using this code. I am not getting how to call this field from another class and how to set the value to run the app smoothly. My code looks like this.
public class MainActivity extends AppCompatActivity {
private TextView tvData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnHit=(Button)findViewById(R.id.btnHit);
tvData=(TextView)findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JSONTask jsonTask=new JSONTask("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt"); //error showing this cannot be applied
jsonTask.execute();
}
});
}
The another class is
public class JSONTask extends AsyncTask<String,String,String>{
private TextView tvData;
public JSONTask(TextView tvData) {
this.tvData =tvData;
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvData.setText(result);
}
}
Make your AsyncTask like this:
class JSONTask extends AsyncTask<String ,String,String>{
private TextView textView;
public JSONTask(TextView textView) {
this.textView = textView;
}
#Override
protected String doInBackground(String... params) {
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
textView.setText(s);
}
}
now call this class from MainActivity
JSONTask jsonTask = new JSONTask(yourTextView);
jsonTask.execute();
Hope it will work for you .
#override
protected void onPostExecute(String result){
super.onPostExecute(result);
new MainActivity().setTvData().setText(result);
Use setTvData().setText() to set the value if you only one data in your json string .

Get Result form AsyncTask to set on another value

i want to get the result form AsyncTask , i can show with system.out.println(), but i want keep that result and save on a new attribute, outside from AsyncTask;
OnTaskFinished.java
public interface OnTaskFinished
{
public void onFeedRetrieved(String feeds);
}
RetrieveFeedTask.java
class RetrieveFeedTask extends AsyncTask<String, Void, String>
{
String HTML_response= "";
String VideoLink;
public String getVideoLink() {
return VideoLink;
}
public void setVideoLink(String videoLink) {
this.VideoLink = videoLink;
}
OnTaskFinished onOurTaskFinished;
public RetrieveFeedTask(OnTaskFinished onTaskFinished)
{
onOurTaskFinished = onTaskFinished;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls)
{
try
{
URL url = new URL(urls[0]); // enter your url here which to download
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = br.readLine()) != null)
{
//System.out.println(inputLine);
if(inputLine.toString().contains("<meta property='og:image'"))
{
String str =inputLine;
str = str.replace("<meta property='og:image' content=\"", "");
//System.out.println(str);
VideoLink=str;
setVideoLink(str);
inputLine=str;
}
HTML_response += inputLine;
}
br.close();
//System.out.println("Done");
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return VideoLink;
}
#Override
protected void onPostExecute(String feed)
{
onOurTaskFinished.onFeedRetrieved(feed);
}
}
and here is how i call
Main.java
String data;
....
new RetrieveFeedTask(new OnTaskFinished()
{
#Override
public void onFeedRetrieved(String feeds)
{
System.out.println(feeds);
}
}).execute(VideoUrl);
i want that feeds get out and set on a diferente value outside from RetrieveFeedTask
on this case set the result on data;

NetworkOnMainThreadException but Using AsyncTask

I coded a class which starts a http connection for getting the text of e.g. website.
I used AsyncTask but I got NetworkOnMainException. May u help me?
The class
public class getXMLData extends AsyncTask<String, Void, String> {
TextView _textview;
public getXMLData(TextView textview) {
_textview = textview;
}
protected String doInBackground(String... url)
{
String _text = "";
try {
try {
URL _url = new URL(url[0]);
HttpURLConnection con = (HttpURLConnection) _url.openConnection();
_text = readStream(con.getInputStream());
}
catch (Exception e) {
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
return _text;
}
protected void onPostExecute(String result)
{
_textview.setText(result.toCharArray(), 0, result.length());
}
private String readStream(java.io.InputStream in) {
java.io.BufferedReader reader = null;
String result = "";
reader = new BufferedReader(new InputStreamReader(in));
try {
while ((reader.readLine() != null)) {
result = result + reader.readLine();
}
}
catch (java.io.IOException i)
{
}
finally
{
try {
reader.close();
}
catch (java.io.IOException e) {
e.printStackTrace();
}
}
return result;
}
Here how I start the AsyncTask:
bu_aktualize.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_getXMLData.doInBackground("http://www.google.de");
}
});
Thanks for your help.
You do not call doInBackground() yourself. Instead, you call execute() or executeOnExecutor() to start the AsyncTask.
You may wish to review the documentation for AsyncTask, which shows an example of setting up an AsyncTask, including a call to execute().

AsyncTask from Activity Class

I am using this class to download txt file
class RetreiveFeedTask extends AsyncTask<String, Void,String> {
#Override
protected ArrayList<Item> doInBackground(String... params) {
try{
URL url = new URL("myurl");
InputStream is = url.openStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String str;
while ((str = in.readLine()) != null){
}
in.close();
return str;
}
catch (MalformedURLException e){}
catch (IOException e){}
return null;
}
protected void onPostExecute(Strin str) {
}
this is how i call this class from my activity:
new RetreiveFeedTask().execute();
And i want to know if there is a way to pass out this result to the activity that make the call.
You can create a listener which you'll pass in the constructor of your AsyncTask. In your onPostExecute you just call this listener.
Something like that:
public interface OnTaskCompleteListener {
void onTaskComplete(String result);
}
protected void onPostExecute(String str) {
onTaskCompleteListener.onTaskComplete(str);
}

Categories