Use of an API toke in my android app - android

I got an api token for my api but don't know how to implement it in my code...
this is the code i have for reaching my api:
public class DataVoetbalWebservice extends AsyncTask<VoetbalDataInterface, Void, JSONArray> {
private static final int CONNECTION_TIMEOUT = 12000;
private static final int DATARETRIEVAL_TIMEOUT = 12000;
VoetbalDataInterface listener;
private ProgressDialog dialog;
Context context;
public void setActivity(Context context) {
this.context = context;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
dialog.setMessage("De Verschillende competities ophalen, even geduld aub.");
dialog.show();
}
#Override
protected JSONArray doInBackground(VoetbalDataInterface... params) {
listener = params[0];
// execute search
disableConnectionReuseIfNecessary();
HttpURLConnection urlConnection = null;
try {
// create connection
//URL urlToRequest = new URL("http://datatank.stad.gent/4/bevolking/geboortes.json?%2Fbevolking%2Fgeboortes=");
URL urlToRequest = new URL("http://api.football-data.org/v1/competitions");
urlConnection = (HttpURLConnection)
urlToRequest.openConnection();
urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
urlConnection.setReadTimeout(DATARETRIEVAL_TIMEOUT);
// handle issues
int statusCode = urlConnection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
} else if (statusCode != HttpURLConnection.HTTP_OK) {
// handle any other errors, like 404, 500,..
}
// create JSON object from content
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
return new JSONArray(getResponseText(in));
} catch (MalformedURLException e) {
// URL is invalid
Log.d("Info", e.getMessage());
} catch (SocketTimeoutException e) {
// data retrieval or connection timed out
Log.d("Info", e.getMessage());
} catch (IOException e) {
// could not read response body
// (could not create input stream)
Log.d("Info", e.getMessage());
} catch (JSONException e) {
// response body is no valid JSON string
Log.d("Info", e.getMessage());
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#Override
protected void onPostExecute(JSONArray json) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ArrayList <Competitie> competities = new ArrayList<>();
try {
for (int i = 0; i < json.length(); i++) {
Competitie competitie = new Competitie();
JSONObject jsonObject = json.getJSONObject(i);
competitie.setId(jsonObject.getInt("id"));
competitie.setCaption(jsonObject.getString("caption"));
competitie.setLeague(jsonObject.getString("league"));
competitie.setYear(jsonObject.getString("year"));
competitie.setCurrentMatchday(jsonObject.getInt("currentMatchday"));
competitie.setNumberOfMatchdays(jsonObject.getInt("numberOfMatchdays"));
competitie.setNumberOfTeams(jsonObject.getInt("numberOfTeams"));
competitie.setNumberOfGames(jsonObject.getInt("numberOfGames"));
JSONObject links = jsonObject.getJSONObject("_links");
JSONObject teams = links.getJSONObject("teams");
JSONObject stand = links.getJSONObject("leagueTable");
competitie.setTeamString(teams.getString("href"));
competitie.setStandUrl(stand.getString("href"));
competities.add(competitie);
}
} catch (JSONException e) {
e.printStackTrace();
}
listener.updateScreenCompetities(competities);
}
/**
* required in order to prevent issues in earlier Android version.
*/
private static void disableConnectionReuseIfNecessary() {
// see HttpURLConnection API doc
if (Integer.parseInt(Build.VERSION.SDK)
< Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false");
}
}
private static String getResponseText(InputStream inStream) {
// very nice trick from
// http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html
return new Scanner(inStream).useDelimiter("\\A").next();
}
}
where do i add the token so i can contact the api?..
because for know i can't read anymore data because the request capacity is full. i already got my api token emailed to me.
This is the documentation for the api, how do i add the request header?
Documentation about token use
thanks in advance
EDIT
added this line of code and now it works!
urlConnection.setRequestProperty("X-Auth-Token","6a0c52afadac44f5bc65bd0dcfb363c2");

Related

Getting Data from JSON?

I want to get the username from this
Json url.
I have this code but it doesn't let me get the data saying
Json parsing error
Here is the code:
HttpHandler.java
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "https://someLink";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString("username");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("username", name);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"username"}, new int[]{R.id.name});
lv.setAdapter(adapter);
}
}
}
This is an example i found on google and tried to change it a bit in my needs.I've put an empty JsonArray.I also tried other examples but i can't understand what is going wrong.
**
> New question
If my url is like this?What is the difference with the other?
**
You don't have an array to parse in the output. Your URL giving you an Object. Your code should be something like this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("username");
//... now use the whereever you want
}
catch (final JSONException e) {
//... put your error log
}
Please edit your code in MainActivity to get the username from json string as follows :
if(jsonStr!=null)
{
JSONObject jsonObj = new JSONObject(jsonStr);
if(jsonObj !=null)
{
String name = jsonObj .getString("username");
}
}
i suggest you to use this one.
public class HttpGetResources extends AsyncTask<String, Void, Object> {
#SuppressLint("StaticFieldLeak")
private ProgressBar progressBar;
private static final String RAW_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSz";
private String urlString;
private String apiName;
private Class Response_Class;
private static final Gson GSON = new GsonBuilder().setDateFormat(RAW_DATE_FORMAT).create();
private Context context;
public HttpGetResources(Context context,Class Response_Class, String apiName, String urlString) {
this.Response_Class = Response_Class;
this.apiName = apiName;
this.urlString = urlString;
this.context=context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Object response) {
super.onPostExecute(response);
}
HttpURLConnection conn = null;
OutputStreamWriter out = null;
Object result = null;
BufferedReader buffer = null;
final ExecutorService executor = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
static public Future<Object> future;
#SuppressWarnings("unchecked")
#Override
protected Object doInBackground(final String... params) {
// JsonObject res=null;
future = executor.submit(new Callable<Object>() {
#Override
public Object call() throws IOException {
try {
URL url = new URL(urlString + apiName);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setConnectTimeout(3000);
conn.setReadTimeout(15000);
conn.setDoInput(true);
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(params[0]);
out.flush();
out.close(); out=null;
buffer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// res= GSON.fromJson(buffer, JsonObject.class);
// result = new Gson().fromJson(res.toString(), Response_Class);
result = GSON.fromJson(buffer, Response_Class);
buffer.close(); buffer=null;
// result = new Gson().fromJson(res.toString(), Response_Class);
} catch (Exception e) {
//
} finally {
if (buffer!=null) {
try {
buffer.close();
} catch (Exception e) { //
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) { //
}
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
});
try {
result = future.get(10, TimeUnit.SECONDS);
} catch (Exception ignored) {
}
return result;
}
}
--and call method--
public synchronized Object HttpGetRes(final Object REQUEST_CLASS, final Class RESPONSE_CLASS, final String
API_NAME, final String URL) {
if(isNetworkAvailable()) {
response = null;
try {
Log.e(API_NAME, "url: " + URL);
Log.e(REQUEST_CLASS.getClass().getSimpleName(), new Gson().toJson(REQUEST_CLASS));
HttpGetResources resource = new HttpGetResources(BaseContext,RESPONSE_CLASS, API_NAME,
URL);
response = resource.execute(new Gson().toJson(REQUEST_CLASS)).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if (response != null) {
String x = new Gson().toJson(response);
Log.e(RESPONSE_CLASS.getSimpleName(), x);
return response;
} else {
}
}
return null;
}
Try to use GSON library in the future, it will auto convert the JSON object to a java object automatically for you. This will be useful to avoid parsing complex JSON objects or JSON arrays. https://github.com/google/gson

How to get response from url in json for android and than after reponse i want to parse it

I am trying to fetch data from thingspeak api and I am taking Input for channel id and passing it on URL. But I have to check if the url is responding or not, if it is responding than go ahead with the code else user have to change channel id.
Error I am getting is 'int java.lang.String.length()' on a null object reference
and
W/System.err: java.io.FileNotFoundException: https://api.thingspeak.com/channels/497971/feeds.json?results=1
This is invalid url if I change it to
https://api.thingspeak.com/channels/497970/feeds.json?results=1
This will work
Code I am trying is
public class MainActivity extends AppCompatActivity {
TextView a, b;
String result = "";
String field1,field2,field3;
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
a = (TextView) findViewById(R.id.a);
b = (TextView) findViewById(R.id.b);
new CountDownTimer(100000, 10000) {
#Override
public void onTick(long l) {
DownloadTask task = new DownloadTask();
task.execute("https://api.thingspeak.com/channels/497970/feeds.json?results=1");
}
#Override
public void onFinish() {
}
}.start();
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
URL url;
result = "";
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
search(result);
}
public void search(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONObject fieldinfo = jsonObject.getJSONObject("channel");
String ff1 = fieldinfo.optString("field1","No Value");
String ff2 = fieldinfo.optString("field2","No Value");
JSONArray weatherInfo = jsonObject.getJSONArray("feeds");
JSONObject legsobject = weatherInfo.getJSONObject(0);
field1 = legsobject.getString("field1");
field2 = legsobject.getString("field2");
a.setText(ff1);
c.setText(field1);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
}
Here is the Image of error
The issue here is that you are not taking into account that HTTP connections sometimes do fail, like in this case. And it fails because the channel id does not exist.
When you set a correct channel id, the URL is also correct because the resource exists and therefore you get the desired results.
However, when you set a wrong channel id the HTTP request fails (because that URL does not exist). Regardless of this, you are attempting to read the response and that's when it all blows up.
When you make an HTTP request to a server, it responds with a status code indicating what happened with your request. You are completely ignoring this status code.
Look at the headers that a request to that URL throws using:
curl -i https://api.thingspeak.com/channels/497971/feeds.json?results=1:
HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: close
Status: 400 Bad Request
... [Shortened] ...
You can learn all about HTTP status codes in a simple Google search but the summary is that it is a number between 100 and 599 that indicates:
Request successfully handled: when it is between 200 and 299.
Request could not be handled, it failed: when it is between 400 and 499.
The request failed because the server basically blew up: (> 500).
In order to retrieve this status code, you need to call the getResponseCode() method of the urlConnection instance.
Only when the status code is successful (between 200 and 299) the call to urlConnection.getInputStream() will succeed. In case of error you need to call urlConnection.getErrorStream().
So in order to fix your code, you need to do something like this:
#Override
protected String doInBackground(String... urls) {
URL url;
result = "";
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
// Open the conection
urlConnection = (HttpURLConnection) url.openConnection();
// Retrieve status code
int statusCode = urlConnection.getResponseCode();
// Determine whether the request was handled successfully or not
boolean success = (statusCode >= 200) && (statusCode < 300);
InputStream in;
if(success) {
// Read the response when request was handled successfully
in = urlConnection.getInputStream();
} else {
// Read the error stream when the request failed
in = urlConnection.getErrorStream();
}
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
// Close the connection
if(urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
First of all, don't forget to close the connection once you are done (I included the disconnection in the finally {} block).
If you debug or log that code, you will see that the status code you are receiving is 400. That is the HTTP status code for Bad Request, indicating that your request is not correct and you need to fix it. If you analyze the content of the result variable, you will see that the value equals to -1.
Therefore in the onPostExecute callback you should make sure the value is different than -1 before attempting to deserialize it, since otherwise it will blow up again.
You can fix your onPostExecute callback like this:
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
if(result.equals(-1)) {
// Do something else, show an error to the user indicating the channel id is wrong
} else {
// Since there is no error, you can proceed with the deserialization of the response
search(result);
}
}
I hope it helps and that it was clear enough.
Cheers!
As you described you need to update your code like
public class MainActivity extends AppCompatActivity {
TextView a, b;
String result = "";
String field1,field2,field3;
private int count = 0;
int channelId=497970;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
a = (TextView) findViewById(R.id.a);
b = (TextView) findViewById(R.id.b);
startCounter(channelId);
}
public void startCounter(int channelId){
new CountDownTimer(100000, 10000) {
#Override
public void onTick(long l) {
DownloadTask task = new DownloadTask();
task.execute("https://api.thingspeak.com/channels/"+channelId+"/feeds.json?results=1");
}
#Override
public void onFinish() {
}
}.start();
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
URL url;
result = "";
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (FileNotFoundException e){
startCounter(channelId+1);
}
catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
search(result);
}
public void search(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONObject fieldinfo = jsonObject.getJSONObject("channel");
String ff1 = fieldinfo.optString("field1","No Value");
String ff2 = fieldinfo.optString("field2","No Value");
JSONArray weatherInfo = jsonObject.getJSONArray("feeds");
JSONObject legsobject = weatherInfo.getJSONObject(0);
field1 = legsobject.getString("field1");
field2 = legsobject.getString("field2");
a.setText(ff1);
c.setText(field1);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
}

My application is working on emulator but not on real devices

i am using simple asynctask function for getting values from mysql database through json.it was working fine with emulator but if i am trying from the mobile i am getting error. like Java.lang.NullPointerExceprtion:Attempt to invke virtual metho 'java.lang.string.java.lang.stringbuilder.toString() on a null object reference.
I tried with new project but result is same. this application is not working in all the devices except emulator. can you help me on this.
My Code is -
public class MainActivity extends AppCompatActivity {
private static final String Latest_Products7 = "Questions";
JSONArray productsArray7 = null;
public static final int CONNECTION_TIMEOUT7=100000;
public static final int READ_TIMEOUT7=150000;
HashMap<String,ArrayList<WorldPopulation>> hasmap = new HashMap<String,ArrayList<WorldPopulation>>();
ArrayList<WorldPopulation> arraylist7 = null;
StringBuilder result7;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncLogin7().execute();
}
private class AsyncLogin7 extends AsyncTask<String, String, StringBuilder> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn7;
URL url7 = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected StringBuilder doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url7 = new URL("http:/Samplesite/****/somephp.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn7 = (HttpURLConnection)url7.openConnection();
conn7.setReadTimeout(READ_TIMEOUT7);
conn7.setConnectTimeout(CONNECTION_TIMEOUT7);
conn7.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn7.setDoInput(true);
conn7.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder7 = new Uri.Builder().appendQueryParameter("reg_id", "hai") ;
String query7 = builder7.build().getEncodedQuery();
// Open connection for sending data
OutputStream os7 = conn7.getOutputStream();
BufferedWriter writer7 = new BufferedWriter(new OutputStreamWriter(os7, "UTF-8"));
writer7.write(query7);
writer7.flush();
writer7.close();
os7.close();
conn7.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
int response_code7 = conn7.getResponseCode();
// Check if successful connection made
if (response_code7 == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input7 = conn7.getInputStream();
BufferedReader reader7 = new BufferedReader(new InputStreamReader(input7));
result7 = new StringBuilder();
String line7;
while ((line7 = reader7.readLine()) != null) {
result7.append(line7);
}
// Pass data to onPostExecute method
}
} catch (IOException e) {
e.printStackTrace();
} finally {
conn7.disconnect();
}
return result7;
}
#Override
protected void onPostExecute(StringBuilder result7) {
super.onPostExecute(result7);
Log.e("dai",result7.toString());
Toast.makeText(MainActivity.this,result7.toString(),Toast.LENGTH_LONG).show();
pdLoading.dismiss();
/* Intent intnt = new Intent(Checklist_activity.this,Task_main.class);
intnt.putExtra("task",hasmap);
startActivity(intnt);*/
}
}
}
Change
try {
int response_code7 = conn7.getResponseCode();
// Check if successful connection made
if (response_code7 == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input7 = conn7.getInputStream();
BufferedReader reader7 = new BufferedReader(new InputStreamReader(input7));
result7 = new StringBuilder();
String line7;
while ((line7 = reader7.readLine()) != null) {
result7.append(line7);
}
// Pass data to onPostExecute method
}
} catch (IOException e) {
e.printStackTrace();
} finally {
conn7.disconnect();
}
return result7;
To
try {
int response_code7 = conn7.getResponseCode();
result7 = new StringBuilder();
// Check if successful connection made
if (response_code7 == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input7 = conn7.getInputStream();
BufferedReader reader7 = new BufferedReader(new InputStreamReader(input7));
String line7;
while ((line7 = reader7.readLine()) != null) {
result7.append(line7);
}
// Pass data to onPostExecute method
}
} catch (IOException e) {
e.printStackTrace();
} finally {
conn7.disconnect();
}
return result7;
Try something like this
Log.e("dai",MainActivity.this.result7.toString());
Toast.makeText(MainActivity.this,MainActivity.this.result7.toString(),Toast.LENGTH_LONG).show();
OR
#Override
protected void onPostExecute(StringBuilder result) {
super.onPostExecute(result);
Log.e("dai",result.toString());
Toast.makeText(MainActivity.this,result.toString(),Toast.LENGTH_LONG).show();
pdLoading.dismiss();
/* Intent intnt = new Intent(Checklist_activity.this,Task_main.class);
intnt.putExtra("task",hasmap);
startActivity(intnt);*/
}
}

Retrieve data from Google Books API

I'm new to Android and using web APIs, and I'm writing an Android App that scans a barcode from a book and then search its ISBN in Google Books API.
I have this url after the barcode scan: https://www.googleapis.com/books/v1/volumes?q=isbn:9788432250651&AIzaSyCpYez5556X4UzPV6rF4kkspj9DsCs_Q_c
And the next code:
private class GetBookInfo extends AsyncTask <View, Void, Integer> {
#Override
protected Integer doInBackground(View... urls) {
// make Call to the url
makeCall("https://www.googleapis.com/books/v1/volumes?" +
"q=isbn:" + ean_content + "&AIzaSyCpYez5556X4UzPV6rF4kkspj9DsCs_Q_c");
//print the call in the console
System.out.println("https://www.googleapis.com/books/v1/volumes?" +
"q=isbn:" + ean_content + "&AIzaSyCpYez5556X4UzPV6rF4kkspj9DsCs_Q_c");
return null;
}
#Override
protected void onPreExecute() {
// we can start a progress bar here
}
#Override
protected void onPostExecute(Integer result) {
String ruta = save_cover(getApplicationContext(), title, book_cover);
Intent intent = new Intent(MainActivity.this, Spreadsheets.class);
// intent.putExtra(title,title);
// intent.putExtra(author,authors);
// intent.putExtra(date,date);
// intent.putExtra(category,categories);
// intent.putExtra(description,description);
//finish();
startActivity(intent);
finish();
}
}
public void makeCall(String stringURL) {
URL url = null;
BufferedInputStream is = null;
JsonReader jsonReader;
try {
url = new URL(stringURL);
} catch (Exception ex) {
System.out.println("Malformed URL");
}
try {
if (url != null) {
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
is = new BufferedInputStream(urlConnection.getInputStream());
}
} catch (IOException ioe) {
System.out.println("IOException");
}
if (is != null) {
try {
jsonReader = new JsonReader(new InputStreamReader(is, "UTF-8"));
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
if (name.equals("title")) {
title = jsonReader.nextString();
}
else if (name.equals("authors")) {
authors = jsonReader.nextString();
}
else if (name.equals("publishedDate")) {
date = jsonReader.nextString();
}
else if (name.equals("categories")) {
categories = jsonReader.nextString();
}
else if (name.equals("description")) {
description = jsonReader.nextString();
}
// else if (name.equals("averageRating")) {
// rating = jsonReader.nextString();
// }
else if (name.equals("thumbnail")) {
image = jsonReader.nextString();
book_cover = download_cover(image);
}
else {
jsonReader.skipValue();
}
}
jsonReader.endObject();
}
catch (Exception e) {
System.out.println("Exception");
}
}
}
This isn't retrieving anything from the API. I would appreciate your help, thank you!
I think what you need to do next is request a connection from the API, open the connection, using JSON retrieve data from the API and use the inputStream to get the data stored in an array.
something like :Implement these methods in a class:
private static String makeHttpRequest(URL url) throws IOException
private static String readFromStream(InputStream inputStream) throws IOException
private static List extractFeatureFromJson(String booksJson)
public static List featchBookData(String requestUrl)
Here is a full code example of how to use Google Books API in Android with Feign or Retrofit. These libraries provide a higher level abstraction on top of HTTP so that you can use simple method calls and objects in your code, instead of messing with requests, responses and JSON deserialization.

Showing ProgressBar on parsing and downloading json result

In my App I am hitting a service which can have no result to n number of results(basically some barcodes). As of now I am using default circular progressbar when json is parsed and result is being saved in local DB(using sqlite). But if the json has large number of data it sometimes takes 30-45 min to parse and simultaneously saving that data in DB, which makes the interface unresponsive for that period of time and that makes user think the app has broken/hanged. For this problem I want to show a progressbar with the percentage stating how much data is parsed and saved so that user get to know the App is still working and not dead. I took help from this link but couldn't find how to achieve. Here's my Asynctask,
class BackGroundTasks extends AsyncTask<String, String, Void> {
private String operation, itemRef;
private ArrayList<Model_BarcodeDetail> changedBarcodeList, barcodeList;
private ArrayList<String> changeRefList;
String page;
public BackGroundTasks(String operation, String itemRef, String page) {
this.operation = operation;
this.itemRef = itemRef;
this.page = page;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try{
if (!connection.HaveNetworkConnection()) {
dialog.dismiss();
connection.showToast(screenSize, "No Internet Connection.");
return null;
}
if (operation.equalsIgnoreCase("DownloadChangeItemRef")) {
changeRefList = DownloadChangeItemRef(params[1]);
if (changeRefList != null && !changeRefList.isEmpty()) {
RefList1.addAll(changeRefList);
}
}
if ((changeRefList != null && changeRefList.size() >0)) {
setUpdatedBarcodes(changedBarcodeList);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#SuppressLint("SimpleDateFormat")
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
ArrayList<String> DownloadChangeItemRef(String api_token) {
ArrayList<String> changedRefList = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(thoth_url + "/" + todaysDate
+ "?&return=json");
String url = thoth_url + "/" + todaysDate + "?&return=json";
String result = "";
try {
changedRefList = new ArrayList<String>();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpClient.execute(postRequest, responseHandler);
JSONObject jsonObj = new JSONObject(result);
JSONArray jsonarray = jsonObj.getJSONArray("changes");
if (jsonarray.length() == 0) {
return null;
}
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
changedRefList.add(obj.getString("ref"));
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
// when there is no thoth url
Log.i("inclient: ", e.getMessage());
return null;
} catch (Exception e) {
// when there are no itemref
return null;
}
return changedRefList;
}
private boolean setUpdatedBarcodes(
final ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
BarcodeDatabase barcodeDatabase = new BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
n++;
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
if (dialog != null) {
dialog.dismiss();
}
connection.showToast(screenSize, "Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}

Categories

Resources