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 .
Related
public class ConnectionTest extends AsyncTask<Void, Void, Void> {
String connection;
String loginFormUrl = "https://intranet.tam.ch/";
#Override
protected Void doInBackground(Void... voids) {
try{
Connection.Response loginForm = Jsoup.connect(loginFormUrl).method(Connection.Method.GET)
.execute();
connection = loginForm.toString();
System.out.print(title);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
My Activity should just display the connection in a TextView. I have also tried making a Thread and running it in the new Thread but it also won't work.
Here is my Activity
public class Test extends AppCompatActivity {
TextView textView;
ConnectionTest connectionTest = new ConnectionTest();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
connectionTest.getWebsite();
textView = findViewById(R.id.sdweedew);
textView.setText(connectionTest.connection);
}
}
Change your activity code like this,
I've used a TextView to display the status of the connection.
public class MainActivity extends AppCompatActivity {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
textView = findViewById(R.id.sdweedew);
new ConnectionTest().execute();
}
class ConnectionTest extends AsyncTask<Void, Void, String> {
String loginFormUrl = "https://intranet.tam.ch/";
#Override
protected String doInBackground(Void... voids) {
try {
Connection.Response loginForm = Jsoup.connect(loginFormUrl).method(Connection.Method.GET)
.execute();
return loginForm.statusMessage();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
if (textView != null) {
textView.setText(s);
}
super.onPostExecute(s);
}
}
}
And remember to add Internet permission in manifest file.
<uses-permission android:name="android.permission.INTERNET" />
please check this code
private void getWebsite() {
new Thread(new Runnable() {
#Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
Document doc = Jsoup.connect("https://intranet.tam.ch/").get();
String title = doc.title();
Elements links = doc.select("a[href]");
builder.append(title).append("\n");
for (Element link : links) {
builder.append("\n").append("Link : ").append(link.attr("href"))
.append("\n").append("Text : ").append(link.text());
}
} catch (IOException e) {
builder.append("Error : ").append(e.getMessage()).append("\n");
}
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(builder.toString());
}
});
}
}).start();
}
I'm new to Android and I was trying to communicate with my localhost using php script and accessing a simple database.
I have defined a task in the doInBackground() method which takes a value from the database stored on the localhost(I don't know if that part will work).
I want to set the text in the textview of an activity using the result that the doInBackground Method returns.
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
BackgroundWorker(Context ctx)
{
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String group = params[0];
String child = params[1];
String address = "http://10.0.2.2/conn.php";
URL url = null;
try {
url = new URL(address);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("group", "UTF-8") + "=" + URLEncoder.encode(group, "UTF-8") + "&"
+ URLEncoder.encode("child", "UTF-8") + "=" + URLEncoder.encode(child, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line;
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
And the Activity class:
public class viewTT extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_tt);
Button btnNextScreen = (Button) findViewById(R.id.button);
TextView txtName = (TextView) findViewById(R.id.textView);
TextView txtName2 = (TextView) findViewById(R.id.textView2);
Intent i = getIntent();
// Receiving the Data
String group= i.getStringExtra("group");
String child = i.getStringExtra("child");
txtName.setText(group+" "+child);
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(group,child);
btnNextScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0)
{
//Starting a new Intent
Intent nextScreen = new Intent(getApplicationContext(), MainActivity.class);
startActivity(nextScreen);
}
});
}
}
I want to set txtName2.
You can use a interface to return data to your activity
Interface
public interface AsyncResponse {
public void onFinish(Object output);
}
SomeAsyncTask Class
public class SomeAsyncTask extends AsyncTask<String, String, String> {
private AsyncResponse asyncResponse;
public SomeAsyncTask(AsyncResponse asyncResponse) {
this.asyncResponse = asyncResponse;
}
#Override
protected String doInBackground(String... params) {
//Do something
.....
//Finally return something
return "returnSomeString";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
asyncResponse.onFinish(s);
}}
In your activity where you want to set view call the SomeAsyncTask class like this
SomeAsyncTask someAsyncTask=new SomeAsyncTask(new AsyncResponse() {
#Override
public void onFinish(Object output) {
String result= (String) output;
//Finally set your views
}
});
someAsyncTask.execute();
}
Define an interface to take result of backgroundworker and make workers constructor to take second parameter that interface.call that interface object on post execute and put your result as parameter. than use it like:
BackgroundWorker backgroundWorker = new BackgroundWorker(this, new bgWorkerListener() {
#Override
public void onResult(String s) {
txtname2.settext(s);
}
});
backgroundWorker.execute(group, child);
Here is your string in main Thread
protected void onPostExecute(String s) {
// s is your string
super.onPostExecute(s);
}
in your BackgroundWorker class add this code...
private String textFortxtName2;
public String getTextFortxtName2() {
return textFortxtName2;
}
public void setTextFortxtName2(String textFortxtName2) {
this.textFortxtName2 = textFortxtName2;
}
then add this
protected void onPostExecute(String s) {
// s is your string
textFortxtName2 = s;
super.onPostExecute(s);
}
now you can get the text frome yor main activity,,,
...
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(group,child);
txtName2.setText(backgroundWorker.getTextFortxtName2());
that's all :)
if there will be any questions or bags please coment
I have created a class and extend with AsyncTask , now i want to return me a string to another activity throw this class . its getting jsonstring from mysql mDatabase
enter code here
public class GetJson extends AsyncTask<Void,Void,String> {
String JSON_STRING;
String json_url;
public String pasString;
Activity ab;
#Override
protected void onPreExecute() {
json_url="https://XXXXXXX.000webhostapp.com/Json_getData_Survey.php";
}
public GetJson(Activity b) {
ab=b;
}
#Override
protected String doInBackground(Void... params) {
try {
URL url =new URL(json_url);
HttpURLConnection httpURLConnection =(HttpURLConnection) url.openConnection();
InputStream inputStream =httpURLConnection.getInputStream();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder=new StringBuilder();
while ((JSON_STRING=bufferedReader.readLine())!=null)
{
stringBuilder.append(JSON_STRING+"\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
String strings =stringBuilder.toString().trim();
return strings;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
pasString=result;
// Toast.makeText(ab,pasString,Toast.LENGTH_LONG).show();
// json_string1=result;
}
}
i just need to return string1 to my another Activity , i have creaetd a another mehtod in GetJson class to return this string but when i display this it show nothing in it. please help
its Quite simple
make an interface class as following
public interface ResponseListener() {
void onResponseReceive(String data);
}
and add instance of this class in you GetJson class like this
public class GetJson extends AsyncTask<Void,Void,String> {
String JSON_STRING;
String json_url;
public String pasString;
Activity ab;
// this is new code
ResponseListener listener;
public void setOnResponseListener(ResponseListener listener) {
this.listener = listener;
}
#Override
protected void onPreExecute() {
json_url="https://XXXXXXX.000webhostapp.com/Json_getData_Survey.php";
}
// now add this code in onPost function
#Override
protected void onPostExecute(String result) {
pasString=result;
listener.onResponseReceive(pasString);
// Toast.makeText(ab,pasString,Toast.LENGTH_LONG).show();
// json_string1=result;
}
now when you call GetJson from your activity, just simple do that;
GetJson json = new GetJson(Activity.this);
json.setOnResponseListener(new ResponseListener() {
#Override
public void onResponseReceived(String data) {
// here you will get your response
}
});
hope you will understand. :)
Try using activity results. You can set the return value on the one activity, and get it when that activity terminates.
https://developer.android.com/training/basics/intents/result.html
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);
}
}
I need to build an android app for my final year project, (i am new to android development). Is there any idea to minimize the code or maybe separate into different classes.
I want to make my main activity shorter and cleaner for maintenance, and preferably if it can be coded using MVC architecture. There will be more UI components added later.
Thank you for ur attention.
public class MainActivity extends AppCompatActivity {
Button find_button;
EditText user_origin;
EditText user_destination;
private TextView json_output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
find_button = (Button)findViewById(R.id.find_button);
json_output = (TextView)findViewById(R.id.json_output);
user_origin = (EditText)findViewById(R.id.user_origin);
user_destination = (EditText)findViewById(R.id.user_destination);
find_button.setOnClickListener(new View.OnClickListener(){
String origin;
String new_origin;
String destination;
String new_user_destination;
#Override
public void onClick(View v){
origin = user_origin.getText().toString();
new_origin = origin.replaceAll(" ", "+");
destination = user_destination.getText().toString();
new_user_destination = destination.replaceAll(" ", "+");
String link = "https://maps.googleapis.com/maps/api/directions/json?origin=" + new_origin + "&destination=" + new_user_destination + "&mode=transit&key=AIzaSyD83XCiGtJyo6Ln8c7yyyrQwmFDFZB_oiU";
//json_output.setText(link);
new JSONTask().execute(link);
}
});
}
public class JSONTask extends AsyncTask<String,String,String> {
#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);
}
String final_json = buffer.toString();
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);
json_output.setText("result:" +result);
}
}
}
You can separate your JSONTask as a simple class,and execute its task,then define an interface in this class to pass some message or data should be handled by other class,and add a parameter type is this interface for constructor and save it as a field.like this:
public class JSONTask extends AsyncTask<String,String,String>{
private OnHandleResult mResult;
private String[] mParams;
public JSONTask(OnHandleResult onHandleResult,String... params){
this.mResult = onHandleResult;
this.mParams = params;
}
protected String doInBackground(String... params){
//params is empty,get params from this.mParams
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
//json_output.setText("result:" +result);
this.mResult.handleResult(result);
}
public static interface OnHandleResult{
void handleResult(final String result);
}
}
then let your activity implement interface onHandleResult,and hanlde result:set text to textview:
public class MainActivity extends AppCompatActivity implements JSONTask.OnHandleResult{
void handleResult(final String result){
json_output.setText("result:" +result);
}
}
and execute task like this:
new JSONTask(this,link).execute();
Usually it's good practise to have 1 class per file.
You can make your MainActivity a bit more readable
public class MainActivity extends AppCompatActivity {
Button find_button;
EditText user_origin;
EditText user_destination;
private TextView json_output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
find_button = (Button) findViewById(R.id.find_button);
json_output = (TextView) findViewById(R.id.json_output);
user_origin = (EditText) findViewById(R.id.user_origin);
user_destination = (EditText) findViewById(R.id.user_destination);
String link = build_link(user_origin, user_destination);
MyListener l = new MyListener(link);
find_button.setOnClickListener(l);
}
private String build_link(EditText user_origin, EditText user_destination) {
String origin = user_origin.getText().toString();
String new_origin = origin.replaceAll(" ", "+");
String destination = user_destination.getText().toString();
String new_user_destination = destination.replaceAll(" ", "+");
return "https://maps.googleapis.com/maps/api/directions/json?origin=" + new_origin + "&destination=" + new_user_destination + "&mode=transit&key=AIzaSyD83XCiGtJyo6Ln8c7yyyrQwmFDFZB_oiU";
}
by isolating your listener's implementation:
public class MyListener implements View.OnClickListener {
String link;
public MyListener(String link) {
this.link = link;
}
#Override
public void onClick(View v) {
new JSONTask().execute(link);
}