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);
}
}
Related
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();
}
}
}
}
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.
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) {
}
I have to make attendance app for college.The app will take data from colleges website and display it on app according to user login and password.
When we login into college's website we have to put id and password, same thing I want on my app so that user can see it on an app itself.
I have searched httpurlconnection, httpget, httppost, jsoup.
Up till now, I have understood that I have to make httprequest for loading the college's attendance site and then httppost to post username and password and after that jsoup to grab the data from HTML page.
But I have seen tutorials only to request JSON pages, but how to request for HTML pages?and post login to it?
Here is what I tried and collected data from JSON
private TextView textresponse1;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Get= (Button) findViewById(R.id.httprequest);
textresponse1= (TextView)findViewById(R.id.textresponse);
progressDialog=new ProgressDialog(this);
Get.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoList.txt");
progressDialog.setMessage("Collecting Data");
progressDialog.show();
}
public class JSONTask extends AsyncTask<String,String,String >{
#Override
protected String doInBackground(String... params) {
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
URL url=new URL(params[0]);
connection=(HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(stream));
String line="";
StringBuffer buffer=new StringBuffer();
while ((line = reader.readLine())!=null) {
buffer.append(line);
}
String finaljosn=buffer.toString();
StringBuffer add =new StringBuffer();
JSONObject parentobject=new JSONObject(finaljosn);
JSONArray parentarray=parentobject.getJSONArray("movies");
for(int i=0;i<parentarray.length();i++) {
JSONObject moviename = parentarray.getJSONObject(i);
String finalmovie = moviename.getString("movie");
int finalyear = moviename.getInt("year");
add.append(finalmovie +"- "+finalyear + "\n");
}
return add.toString();
// return finalmovie +" -Rushabh- " +finalyear;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException 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);
progressDialog.dismiss();
textresponse1.setText(result);
}
}
String mLoadURL="http://www.google.com";
public class LoadHtml extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
URL url = null;
try {
url = new URL(mLoadURL);
StringBuilder stringBuilder = new StringBuilder();
URLConnection conn = url.openConnection();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = rd.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (!s.trim().isEmpty()) {
//load html to webview
}
}
}
Call Above AsyncTask using:
LoadHtml loadHtml= new LoadHtml();
load.execute();
I make a login but i need know when the conection to server is fail
,this is my event of button
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
usuario=(EditText)findViewById(R.id.etUsuario);
contrasena=(EditText)findViewById(R.id.etContrasena);
usuario_ws = usuario.getText().toString();
pass_ws = contrasena.getText().toString();
new HttpAsyncTask().execute(GET());
}
});
and this is my asynctask for the response of my server
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
return GET();
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
// Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
// etResponse.setText(result);
Integer respuesta_ws = Integer.valueOf(result);
if (respuesta_ws>=1){
sesionIn();
}
else if (respuesta_ws==0){
sesionFail();
}
}
}
public String GET() {
String url = "http://"+ippref+":8080/WSAppInventario/webresources/inventario.users/Login/"+usuario_ws+"/"+pass_ws+"";
String result = "";
BufferedReader inStream = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
HttpResponse response = httpClient.execute(httpRequest);
inStream = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));
StringBuffer buffer = new StringBuffer();
String line = "";
//String NL = System.getProperty("line.separator");
while ((line = inStream.readLine()) != null) {
buffer.append(line);
}
inStream.close();
result = buffer.toString();
respuesta_ws = Integer.valueOf(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
The string ippref
It is an object to keep before SharedPreferences
this should work
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
return GET();
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
// Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
// etResponse.setText(result);
if (result=="failed"){
sesionFail();
}
else{
sesionIn();
}
}
}
public String GET() {
String url = "http://"+ippref+":8080/WSAppInventario/webresources/inventario.users/Login/"+usuario_ws+"/"+pass_ws+"";
String result = "";
BufferedReader inStream = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
HttpResponse response = httpClient.execute(httpRequest);
inStream = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));
StringBuffer buffer = new StringBuffer();
String line = "";
//String NL = System.getProperty("line.separator");
while ((line = inStream.readLine()) != null) {
buffer.append(line);
}
inStream.close();
result = buffer.toString();
respuesta_ws = Integer.valueOf(result);
} catch (Exception e) {
e.printStackTrace();
return "failed";
}
return result;
}