how to make my code (AsyncTask) cleaner? - java

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);
}

Related

Android - Problem with executing AsyncTask thread

I'm trying to write an app that sends a POST request on asynchronous task. My AsyncTask does not seem to execute since my progress bar doesn't show up. I don't really know what is wrong here, since I followed many solutions/tutorials.
Here's my code:
register.java
public class register extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
final Activity thisActivity = this;
final EditText userNameEditText = findViewById(R.id.registerUsername);
final EditText emailEditText = findViewById(R.id.registerEmail);
final EditText passwordEditText = findViewById(R.id.registerPassword);
final ProgressBar progressBar = findViewById(R.id.progressBar);
Button btnRegisterDB = findViewById(R.id.btnRegistrationDB);
final TextView respondText = findViewById(R.id.responseRegister);
btnRegisterDB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = String.valueOf(userNameEditText.getText());
String email = String.valueOf(emailEditText.getText());
String password = String.valueOf(passwordEditText.getText());
//execute asynchronous task in background and wait for response
RegisterParams params = new RegisterParams(username, email, password);
registrationDB async = new registrationDB();
async.setProgressBar(progressBar);
async.setRespondText(respondText);
async.getParentActivity(thisActivity);
async.execute(params);
}
});
}
public boolean onOptionsItemSelected(MenuItem item){
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
return true;
}
public static class RegisterParams {
public String username;
public String email;
public String password;
RegisterParams(String username, String email, String password){
this.username = username;
this.email = email;
this.password = password;
}
}
}
and here is registrationDB.java
public class registrationDB extends AsyncTask<register.RegisterParams, Void, String> {
openHTTP openHTTP = new openHTTP();
String respond;
ProgressBar pb;
TextView respondTextView;
Activity parentActivity;
public void setProgressBar(ProgressBar progressBar){
this.pb = progressBar;
}
public void setRespondText(TextView textView){
this.respondTextView = textView;
}
public void getParentActivity(Activity parentActivity){
this.parentActivity = parentActivity;
}
#Override
public void onPreExecute(){
pb.setVisibility(View.VISIBLE);
//parentActivity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
// WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
super.onPreExecute();
}
#Override
protected String doInBackground(register.RegisterParams... params) {
try {
HttpURLConnection httpConn = openHTTP.prepareConnection("someurl");
String jsonInputString = "{ username: " + params[0].username +", email: " + params[0].email
+ ", password: " + params[0].password + "}";
try(OutputStream os = httpConn.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
} catch (Exception e){
e.printStackTrace();
}
try(BufferedReader br = new BufferedReader(
new InputStreamReader(httpConn.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
respond = response.toString();
return respond;
} catch (Exception e){
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
pb.setVisibility(View.GONE);
respondTextView.setText(s);
super.onPostExecute(s);
}
}
and I have external class openHTTP.java which is responsible for opening HttpUrlConnection:
public class openHTTP {
public openHTTP(){
}
//provide URL to external file that you want make POST request to
public HttpURLConnection prepareConnection(String URL){
try {
java.net.URL url = new URL(URL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
return con;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Thanks in advance for help!
UPDATE
After logging processes I've discovered that exception:
java.io.IOException: Cleartext HTTP traffic to url not permitted, now I'm on my way searching for this problem
MY SOLUTION
So, it was enough to add android:usesCleartextTraffic="true" in AndroidManifest.xml
Thanks for your help!
After logging processes I've discovered that exception: java.io.IOException: Cleartext HTTP traffic to url not permitted.
So, it was enough to add android:usesCleartextTraffic="true" in AndroidManifest.xml Thanks for your help!

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 .

use result of doInBackground to set a textView

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

how to fetch data without button click

how to fetch first image without click fetch image button
click to view image
this code work fine but on click fetch image button but i want fetch image with out click fetch images button i want to remove this button
Public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
private String imagesJSON;
private static final String JSON_ARRAY ="result";
private static final String IMAGE_URL = "url";
private JSONArray arrayImages= null;
private int TRACK = 0;
private static final String IMAGES_URL = "http://www.simplifiedcoding.16mb.com/ImageUpload/getAllImages.php";
private Button buttonFetchImages;
private Button buttonMoveNext;
private Button buttonMovePrevious;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
}
private void extractJSON(){
try {
JSONObject jsonObject = new JSONObject(imagesJSON);
arrayImages = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showImage(){
try {
JSONObject jsonObject = arrayImages.getJSONObject(TRACK);
getImage(jsonObject.getString(IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext(){
if(TRACK < arrayImages.length()){
TRACK++;
showImage();
}
}
private void movePrevious(){
if(TRACK>0){
TRACK--;
showImage();
}
}
private void getAllImages() {
class GetAllImages extends AsyncTask<String,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Fetching Data...","Please Wait...",true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
imagesJSON = s;
extractJSON();
showImage();
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
}
GetAllImages gai = new GetAllImages();
gai.execute(IMAGES_URL);
}
private void getImage(String urlToImage){
class GetImage extends AsyncTask<String,Void,Bitmap>{
ProgressDialog loading;
#Override
protected Bitmap doInBackground(String... params) {
URL url = null;
Bitmap image = null;
String urlToImage = params[0];
try {
url = new URL(urlToImage);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Downloading Image...","Please wait...",true,true);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
loading.dismiss();
imageView.setImageBitmap(bitmap);
}
}
GetImage gi = new GetImage();
gi.execute(urlToImage);
}
#Override
public void onClick(View v) {
if(v == buttonFetchImages) {
getAllImages();
}
if(v == buttonMoveNext){
moveNext();
}
if(v== buttonMovePrevious){
movePrevious();
}
}
}
You can trigger it in onCreate(),but you must not run it on UI thread,for it might be a time-consuming operation.Read Specifying the Code to Run on a Thread to help,
you might add the following block in your onCreate() method:
new Runnable() {
#Override
public void run() {
getAllImages();
}
}.run();

Asynctask unknown type execute

This is my first time with getting APIS to return the result JSON object. I think I have got the async task code right but I just don't know how to execute it. This is my class code.
For my layout all I have is one button with an onClick () method gg, a progress bar and one text view.
This is the async task:
public class MainActivity extends Activity
{
ProgressBar progressBar;
TextView responseView;
EditText emailText;
String URL;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
responseView = (TextView) findViewById(R.id.responseView);
emailText = (EditText) findViewById(R.id.emailText);
URL = "https://kgsearch.googleapis.com/v1/entities:search?query=taylor+swift&key=APIKEY&limit=1&indent=True";
}
public void gg(View v)
{
new RetrieveFeedTask.execute();
}
private class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
Toast.makeText(MainActivity.this, "pre execute", Toast.LENGTH_LONG).show();
}
protected String doInBackground(Void... urls) {
String email = emailText.getText().toString();
// Do some validation here
try {
URL url = new URL(URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
Toast.makeText(MainActivity.this, "post execute", Toast.LENGTH_LONG).show();
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
}
}
}
So in the public void gg(View v)
I call the .execute method but it gives me an error
Unknown type execute
Do I have to add some params to the execute method?
If so what?
Thanks.
Try
new RetrieveFeedTask().execute();

Categories