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();
Related
I new to Android... I am trying Android JSON parsing Retrieve from URL and set MySQL DB data into TextView but I got an error. I tried many solutions but it's not working Help me to solve this error
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String org.json.JSONObject.getString(java.lang.String)' on
a null object reference at
com.example.testapplication.MainActivity$GetDataFromServerIntoTextView.onPostExecute(MainActivity.java:123)at
com.example.testapplication.MainActivity$GetDataFromServerIntoTextView.onPostExecute(MainActivity.java:63)
Error shows this line textView.setText(jsonObject.getString("distance"));
My Code
HttpResponse httpResponse;
Button button;
TextView textView;
static JSONObject jsonObject = null ;
String StringHolder = "" ;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
textView = (TextView)findViewById(R.id.textView);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progressBar.setVisibility(View.VISIBLE);
new GetDataFromServerIntoTextView(MainActivity.this).execute();
}
});
}
public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetDataFromServerIntoTextView(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpClient httpClient = new DefaultHttpClient();
String HttpURL = "https://api.myjson.com/bins/1cuzhn";
// Adding HttpURL to my HttpPost oject.
HttpPost httpPost = new HttpPost(HttpURL);
try {
httpResponse = httpClient.execute(httpPost);
StringHolder = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jsonArray = new JSONArray(StringHolder);
jsonObject = jsonArray.getJSONObject(0);
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
textView.setText(jsonObject.getString("distance"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
}
}
I modified your AsyncTask and tested below code and its working fine. Let me know if you found any issue.
Add below dependencies
// OKHTTP
implementation 'com.squareup.okhttp:okhttp:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation 'org.apache.httpcomponents:httpcore:4.4.10'
and
public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void,String>
{
public Context context;
public GetDataFromServerIntoTextView(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... voids) {
String strUrl = "https://api.myjson.com/bins/1cuzhn";
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d(TAG, "Exception while downloading url " + e.toString());
} finally {
try {
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
urlConnection.disconnect();
}
return data;
}
#Override
protected void onPostExecute(String data) {
super.onPostExecute(data);
try {
if (data != null) {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Here is your all data of distance and time
Log.e(TAG, "distance " + jsonObject.get("distance"));
Log.e(TAG, "time " + jsonObject.get("time"));
}
} else {
Log.e(TAG, "onPostExecute: null json object");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You are using POST request where as your api is expecting GET request
Here is more details about GET and POST
HttpPost httpPost = new HttpPost(HttpURL);
replace this with following
HttpGet request = new HttpGet(HttpURL);
To avoid crash replace your code with
textView.setText(jsonObject.getString("distance"));
this
textView.setText(jsonObject.isNull("distance") ? "null object" : jsonObject.getString("distance"));
I was developing a simple application that exctracts some fields of a JSon that tells me in real time what weather is in that exact moment, and I have exctracted only one filed, and I was asking myself: Is it possible to extract more than on field at time?
Here is the the link from where i parse the Json:
https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139
And here's my code:
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
ArrayMap<Integer, String> arrayMap = new ArrayMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139");
}
});
}
public class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
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);
if (pd.isShowing()) {
pd.dismiss();
}
try {
JSONObject Object = new JSONObject(result);
JSONArray arr = new JSONArray(Object.getString("weather"));
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
//txtJson.append("main: " + jsonPart.getString("main") + '\n');
arrayMap.put(i, jsonPart.getString("main"));
txtJson.append("main: " + arrayMap.get(i) + '\n');
}
} catch (JSONException e) {
e.printStackTrace();
//txtJson.setText(result);
}
//txtJson.setText(result);
}
}
}
If I understand correctly you want to extract other object alongwith main from the array weather
"weather": [
{
"id": 701,
"main": "Mist",
"description": "mist",
"icon": "https://cdn.glitch.com/6e8889e5-7a72-48f0-a061-863548450de5%2F50n.png?1499366021876"
}
If that is the requirement then you can use the same process like you have done just change the name of the object.
arrayMap.put(i, jsonPart.getString("description"));
or
you can use gson and convert the object in pojo class in one go. Then use the object of the pojo and access the data.
Hope it helps.
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.
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);
}
}
i want to show in my search if it wont recieve similar result to my word i enterd it should Toast me "No Result.but problem is that it gets data after 0.5 seconds.so when i click button first it Toasts No results then gets data and show them in recyclerview.I want if there is not similar word it toast me No result at the end;
String text = txtsearch.getText().toString();
new AsyncTaskSearch("http://192.168.1.100/afgApp/search.php", text).execute();
final Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!Activity_Search.data.equals("")) {
Toast.makeText(Activity_Search.this, data, Toast.LENGTH_SHORT).show();
timer.cancel();
}else {
Toast.makeText(Activity_Search.this, "No results", Toast.LENGTH_SHORT).show();
}
}
});
}
},1,500);
Activity_Search.data = "";
}
//Asynctask.java
public class AsyncTaskSearch extends AsyncTask{
public String link="";
public String text="";
public AsyncTaskSearch(String link,String text){
this.link=link;
this.text=text;
}
#Override
protected Object doInBackground(Object[] params) {
try{
String data= URLEncoder.encode("text","UTF8")+"="+URLEncoder.encode(text,"UTF8");
URL url=new URL(link);
URLConnection connection=url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter writer=new OutputStreamWriter(connection.getOutputStream());
writer.write(data);
writer.flush();
BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder builder=new StringBuilder();
String line=null;
while((line=reader.readLine())!=null){
builder.append(line);
}
Activity_Search.data=builder.toString();
}catch (Exception e){
}
return "";
}
}
I don't know how you are using your AysncTask. Try this code, it's working fine for me:
private class AsyncGetClass extends AsyncTask<Object, Void, String> {
ProgressDialog progressDialog;
String TAG, url;
AsyncHttpResponseHandler asyncHttpResponseHandler;
Context context;
public AsyncGetClass(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (!isProgressHiding)
if (progressDialog == null) {
progressDialog = createProgressDialog(context);
progressDialog.show();
} else {
progressDialog.show();
}
}
#SuppressWarnings("unchecked")
#Override
protected String doInBackground(Object... params) {
// TODO Auto-generated method stub
TAG = (String) params[0];
url = (String) params[1];
asyncHttpResponseHandler = (AsyncHttpResponseHandler) params[3];
InputStream is = null;
String result = "";
// HTTP post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
Log.e(TAG, url);
HttpResponse response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e(TAG, "Error in http connection " + e.toString());
Toast.makeText(Activity_Search.this, "No results", Toast.LENGTH_SHORT).show();
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
// Log.i(TAG + ".result", result);
return result;
} catch (Exception e) {
Log.e(TAG, "Error converting result " + e.toString());
return null;
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (!isProgressHiding)
if (progressDialog != null)
progressDialog.dismiss();
if (result != null)
try {
Log.i(TAG, result);
asyncHttpResponseHandler.onSuccess(result);
} catch (Exception e) {
Log.e(TAG, "Must implement the interface " + e.toString());
}
}
}