Can we use two Interface for two different asynctask - java

AsyncResponse.java:
public interface AsyncResponse {
void ProcessFinish(String Output);
}
AsyncResponseSecond.java:
public interface AsyncResponseSecond {
void ProcessFinishSecond(String Output);
}
This is for Asynctask OnPostExecute to get the result and save it in TextView.
I want to Know if the method which I am Using is correct or not . I am not getting the response
Asyncresponse is for one button and AsyncresponseSecond is for other Button
IntimeWorker.java:
public class InTImeWorker extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alertDialog;
public AsyncResponse delegate = null;
InTImeWorker(Context ctx) {
context = ctx;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("In Time Status !");
}
#Override
protected void onPostExecute(String result) {
delegate.ProcessFinish(result);
}
#Override
protected String doInBackground(String... params) {
String Emp_id = params[0];
String in_time_url = "http://192.168.0.107/RTOS/intime.php";
try {
URL url = new URL(in_time_url);
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("emp_id", "UTF-8") + "=" + URLEncoder.encode(Emp_id, "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();
}
return null;
}
}
OuttimeWorker.java:
public class OutTimeWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
public AsyncResponseSecond delegate = null;
OutTimeWorker(Context ctx){
context = ctx;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Out Time Status !");
}
#Override
protected void onPostExecute(String result) {
delegate.ProcessFinishSecond(result);
}
#Override
protected String doInBackground(String... params) {
String Emp_id = params[0];
String out_time_url = "http://192.168.0.107/RTOS/outtime.php";
try {
URL url = new URL(out_time_url);
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("emp_id","UTF-8")+"="+URLEncoder.encode(Emp_id,"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();
}
return null;
}
}
EmployeeActivity.java:
public class EmployeeActivity extends AppCompatActivity implements AsyncResponse , AsyncResponseSecond {
TextView name, In_time, Out_time;
SharedPreferences sp,sp1;
Button in_time_button, out_time_button;
private static final String KEY_IN_TIME_TEXTVIEW = "intimetextview_key";
private static final String KEY_OUT_TIME_TEXTVIEW = "outtimetextview_key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employee);
name = findViewById(R.id.text_name);
sp = getSharedPreferences("attendlogin", MODE_PRIVATE);
String emp_name = sp.getString("name", null);
name.setText(emp_name);
in_time_button = findViewById(R.id.buttonlogin);
out_time_button = findViewById(R.id.buttonlogout);
out_time_button.setEnabled(false);
In_time = findViewById(R.id.text_in_time);
Out_time = findViewById(R.id.text_out_time);
public void OnAttendLogin(View view) {
sp = getSharedPreferences("attendlogin", MODE_PRIVATE);
String emp_id = sp.getString("emp_id", null);
InTImeWorker inTImeWorker = new InTImeWorker(this);
inTImeWorker.delegate = (AsyncResponse) this;
inTImeWorker.execute(emp_id);
//shared pref for saving In_time in textview
sp1 = getSharedPreferences("InTime", MODE_PRIVATE);
SharedPreferences.Editor editor1 = sp1.edit();
String in_time_sharedpref = In_time.getText().toString();
editor1.putString("in_time_sp", in_time_sharedpref);
editor1.apply();
editor1.commit();
out_time_button.setEnabled(true);
in_time_button.setEnabled(false);
}
public void OnLogout(View view) {
sp = getSharedPreferences("attendlogin", MODE_PRIVATE);
String emp_id = sp.getString("emp_id", null);
OutTimeWorker outTimeWorker = new OutTimeWorker(this);
outTimeWorker.delegate = (AsyncResponseSecond) this;
outTimeWorker.execute(emp_id);
out_time_button.setEnabled(false);
in_time_button.setEnabled(false);
}
#Override
public void ProcessFinish(String Output) {
In_time.setText(Output);
}
#Override
public void ProcessFinishSecond(String Output) {
Out_time.setText(Output);
}}

Do it like this
CallAPI asyncTask = new CallAPI(getContext());
CallAPI asyncTask2 = new CallAPI(getContext());
final chat text = this;
sendb.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
String data = null;
//data to send
CallAPI asyncTask = new CallAPI(getContext());
asyncTask.delegate = text;
asyncTask.execute("", data, "sendMsg");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
sendb2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
String data = null;
//data to send
CallAPI asyncTask2 = new CallAPI(getContext());
asyncTask2.delegate = text;
asyncTask2.execute("", data, "sendMsg");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
#Override
public void onTaskCompleted(String output, String output2) {
}

Related

Content from web-site won't display in my logcat

I am trying to download content of some random web content to my Logcat. I already did this many time but now I am getting only 2020-05-17 13:24:20.850 24632-24632/com.example.jsondownload I/RezultatĀ URLa:: { and nothing else.Content is some random JSON small sample and I want to show it in my logcat, and nothing else.
I added internet permission.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String string = "https://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=6...3";
DownloadAsync downloadAsync = new DownloadAsync();
downloadAsync.execute(string);
}
public static class DownloadAsync extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... strings) {
StringBuilder rezultat = new StringBuilder();
URL url;
HttpURLConnection httpURLConnection;
try {
url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int podaci = inputStreamReader.read();
while (podaci!=-1){
char trenutnoSlovoKojeSeCita = (char) podaci;
rezultat.append(trenutnoSlovoKojeSeCita);
podaci = inputStream.read();
}
return rezultat.toString();
}
catch (Exception e){
e.printStackTrace();
return "Neuspesno";
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("Rezultat URLa: ",s);
}
}
}
I find a solution: I added BufferReader:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String string = "https://api.openweathermap.org/data/2.5/weather?q=Belgrade&appid=6c5022949de1b8e8448bc7232238dcf3";
DownloadAsync downloadAsync = new DownloadAsync();
downloadAsync.execute(string);
}
public static class DownloadAsync extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... strings) {
StringBuilder rezultat = new StringBuilder();
URL url;
HttpURLConnection httpURLConnection;
try {
url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line!=null){
rezultat.append(line);
line = reader.readLine();
}
return rezultat.toString();
}
catch (Exception e){
e.printStackTrace();
return "Neuspesno " ;
}
}
#Override
protected void onPostExecute(String rezultat) {
super.onPostExecute(rezultat);
try {
JSONObject jsonObject = new JSONObject(rezultat);
String weatherInfo = jsonObject.getString("weather");
JSONArray arr = new JSONArray(weatherInfo);
for (int i = 0; i < arr.length();i++){
JSONObject jsonObject1 = arr.getJSONObject(i);
String main = jsonObject1.getString("main");
String desc = jsonObject1.getString("description");
Log.i("main: ",main);
Log.i("description: ",desc);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}

Is it possible that the array map is too little for contain about 2000 items?

In my code i had caught data from a JSON file,
I executed the program, it stopped but didn't crash.
i've tried to change json file. I found one that is Smaller than the first one and so the program works.
this JSON file is made of data o premier legue(England) and contain 3 mainly data, the name, a key and a code of the squads.
public class MainActivity extends AppCompatActivity {
private ProgressDialog caric;
private String TAG = MainActivity.class.getSimpleName();
public ArrayMap<Integer, Valori> ArrayDati = new ArrayMap<>();
Button buttonProg;
TextView textViewProg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonProg = (Button) findViewById(R.id.button);
textViewProg = (TextView) findViewById(R.id.textView);
buttonProg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonCLASS().execute("https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.clubs.json");
}
});
}
private class JsonCLASS extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caric = new ProgressDialog(MainActivity.this);
caric.setMessage("Please wait");
caric.setCancelable(false);
caric.show();
}
#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 + "\n");
Log.d("Response: ", "> " + 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);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray Arr = new JSONArray(jsonObject.getString("clubs"));
for (int i = 0; i < Arr.length(); i++){
JSONObject jsonPart = Arr.getJSONObject(i);
ArrayDati.put(i,new Valori( jsonPart.getString("key"), jsonPart.getString("name"), jsonPart.getString("code")));
textViewProg.setText(textViewProg.getText()+"key : "+ ArrayDati.get(i).Key
+"\n"+textViewProg.getText()+"name : "+ ArrayDati.get(i).Name
+"\n"+textViewProg.getText()+"code : "+ ArrayDati.get(i).Code );
}
} catch (Exception e ){
e.printStackTrace();
}
if (caric.isShowing()) {
caric.dismiss();
}
}
}
}
And a class to pass the data
public class Valori {
String Key;
String Name;
String Code;
public Valori(String key, String name, String code) {
this.Key = key;
this.Name = name;
this.Code = code;
}
}
With this code the application stops but it doesn't close.

How to return background result?

I did the code in android to retrieve records from website url. But I am stuck in receiving the result in string variable.
I want to display received values in receiveddata variable. Please help me on this..
I did this code:
Main2Activity.java
btnsync.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String receiveddata="";
Toast.makeText(getApplicationContext(), "Syncing data...",Toast.LENGTH_SHORT).show();
SyncLoginData process = new SyncLoginData();
process.execute();
Toast.makeText(getApplicationContext(), "Data synced successfully....",Toast.LENGTH_SHORT).show();
}
});
SyncLoginData.java
public class SyncLoginData extends AsyncTask<Void, Void, Void> {
String data="";
String dataParsed = "";
DatabaseHelper mydb;
String singleParsed ="";
#Override
protected Void doInBackground(Void... voids) {
try
{
URL url = new URL("https://api.myjson.com/bins/1034t9");
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;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Main2Activity.data.setText(this.data);
}
}
Try this instead.
public class SyncLoginData extends AsyncTask<Void, Void, String> {
#Override
protected Void doInBackground(Void... voids) {
String data;
try {
URL url = new URL("https://api.myjson.com/bins/1034t9");
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;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String data) {
Main2Activity.data.setText(data);
}
}

FileNotFoundException encountered when trying to send JSON over network [duplicate]

This question already has answers here:
FileNotFoundException while getting the InputStream object from HttpURLConnection
(8 answers)
Closed 6 years ago.
My code to that sends JSON over the network works until OutputStream is invoked, but when I try actually sending the data, I get the following exception. Can anyone help me figure it out?
java.io.FileNotFoundException: http://hmkcode.appspot.com/jsonservlet
at
com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
at app.test.testapp2.MainActivity$HttpAsyncTask.doInBackground(MainActivity.java:84)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.accept);
textView = (TextView) findViewById(R.id.textView);
editName = (EditText) findViewById(R.id.editName);
editCountry = (EditText) findViewById(R.id.editCountry);
editTwitter = (EditText) findViewById(R.id.editTwitter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
HttpAsyncTask httpAsyncTask = new HttpAsyncTask(MainActivity.this);
httpAsyncTask.execute("http://hmkcode.appspot.com/jsonservlet", editName.getText().toString(), editCountry.getText().toString(), editTwitter.getText().toString());
}
});
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
private MainActivity mainActivity;
String result = "";
HttpAsyncTask(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
#Override
protected String doInBackground(String... strings) {
Person person = new Person();
person.setName(strings[1]);
person.setCountry(strings[2]);
person.setTwitter(strings[3]);
try {
URL url = new URL(strings[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
String json = "";
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", "!!!");
jsonObject.accumulate("country", "###");
jsonObject.accumulate("twitter", "####");
json = jsonObject.toString();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.setRequestProperty("content-type", "application/json");
InputStream is = httpURLConnection.getInputStream();
OutputStream os = httpURLConnection.getOutputStream();
os.write(json.getBytes("utf-8"));
os.flush();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
str = result;
mainActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONArray jsonArray = new JSONArray(str);
mainActivity.textView.setText(jsonArray.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
}
W/System.err: java.io.FileNotFoundException: http://hmkcode.appspot.com/jsonservlet
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
W/System.err: at app.test.testapp2.MainActivity$HttpAsyncTask.doInBackground(MainActivity.java:84)
.....
This is equivalent to HTTP status 404 - Not Found.

Run your request and receive new data Json

I have a problem. When I do a query in the stream, I have downloaded the data from the URL, everything works. But when I call AsynsTask example by pressing doInBackground() method that returns the same data, but they are updated on the URL. And they will not be updated as long as the program is restarted.
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL("data.php?"+new Random().nextInt(200));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
jSON_R = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return jSON_R;
}
All code
public class ParseTask extends AsyncTask<Void, Void, String> {
int intRow = 0;
String jSON_R = "";
private List<User> movieList;
Activity act;
ListView list;
LAdapter adapter;
boolean Unique = true;
public ParseTask (Activity act){
this.act = act;
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL("data.php?"+new Random().nextInt(200));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
jSON_R = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return jSON_R;
}
#Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
list = (ListView) act.findViewById(R.id.listVew);
Button b = (Button) act.findViewById(R.id.refresh);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//To do
}
});
movieList = new ArrayList<>();
adapter = new LAdapter(act, movieList);
list.setAdapter(adapter);
try {
JSONObject dataJsonObj = new JSONObject(strJson);
JSONArray jsa = dataJsonObj.getJSONArray("data");
for (int i = 0; i < jsa.length(); i++) {
JSONObject data1 = chat.getJSONObject(i);
String mes = data1.getString("mes1");
String mes2 = data1.getString("mes2");
String mes3 = data1.getString("mes3");
User m = new User(mes, mes2, mes3);
movieList.add(0, m);
}
adapter.notifyDataSetChanged();
intRow = jsa.length();
} catch (JSONException e) {
e.printStackTrace();
}
list.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem > 1){
Unique = false;
}else{
Unique = true;
}
}
});
Thread thread = new Thread() {
#Override
public void run() {
try {
while (true){
sleep(5000);
if (Unique){
act.runOnUiThread(new Runnable() {
#Override
public void run() {
Update();
}
});
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
private void Update(){
try {
JSONObject dataJsonObj = new JSONObject(strJson);
JSONArray jsa = dataJsonObj.getJSONArray("data");
for (int i = 0; i < jsa.length(); i++) {
JSONObject data1 = chat.getJSONObject(i);
String mes = data1.getString("mes1");
String mes2 = data1.getString("mes2");
String mes3 = data1.getString("mes3");
User m = new User(mes, mes2, mes3);
movieList.add(0, m);
}
adapter.notifyDataSetChanged();
intRow = jsa.length();
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
Calling the object in such a way
new ParseTask(getActivity()).execute();
Close the connection.
I mean use (better) reader.close() or inputStream.close()
Or try jsoup library https://jsoup.org/

Categories

Resources