problem recived the earthquake JSON result - java

This Is the Error:-
E/QueryUtils: problem recived the earthquake JSON result
java.net.ProtocolException: Expected one of [OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, PATCH] but was Get
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.setRequestMethod(HttpURLConnectionImpl.java:606)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.setRequestMethod(DelegatingHttpsURLConnection.java:113)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.setRequestMethod(HttpsURLConnectionImpl.java)
at com.example.quakereport.QueryUtils.makeHttpRequest(QueryUtils.java:92)
at com.example.quakereport.QueryUtils.featchEarthquakeDate(QueryUtils.java:52)
at com.example.quakereport.MainActivity$EarthquakeAsyncTask.doInBackground(MainActivity.java:64)
at com.example.quakereport.MainActivity$EarthquakeAsyncTask.doInBackground(MainActivity.java:56)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:760)
MainActivity.java
public class MainActivity extends AppCompatActivity {
private EarthquakeAdapter mAdapter;
//URL for earthquake data from the USGS dataset
private static final String USGS_REQUEST_URL ="https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&eventtype=earthquake&orderby=time&minmag=6&limit=10";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** Find a refrence to the {#link ListView} in the layout*/
ListView eathquakeListView = (ListView) findViewById(R.id.list);
/** Create a new {#link ArrayAdapter} of earthquakes*/
mAdapter = new EarthquakeAdapter(this,new ArrayList<Earthquake>());
eathquakeListView.setAdapter(mAdapter);
/** Start the AsyncTask to fetch the earthquake data*/
EarthquakeAsyncTask task = new EarthquakeAsyncTask();
task.execute(USGS_REQUEST_URL);
eathquakeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// Find the current earthquake that was clicked on
Earthquake currentEarthquake = mAdapter.getItem(position);
//convert the String URL int a URI object(to pass into the intent constructor)
Uri eathquakeuri = Uri.parse(currentEarthquake.getmUrl());
//Create a new intent to view the earthquake URI
Intent websiteIntent = new Intent(Intent.ACTION_SEND, eathquakeuri);
// Send the intent to launch a new activity
startActivity(websiteIntent);
}
});
}
private class EarthquakeAsyncTask extends AsyncTask<String, Void, List<Earthquake>>{
protected List<Earthquake> doInBackground(String... urls) {
/** If there is a valid list of {#link Earthquake}, then add them to the adapter's data set. This will trigger the
* Listview to update*/
if(urls.length<1 || urls[0] == null){
return null;
}
List<Earthquake> result = QueryUtils.featchEarthquakeDate(urls[0]);
return result;
}
#Override
protected void onPostExecute(List<Earthquake> data) {
/** Clear the adapter of previous earthquake data*/
mAdapter.clear();
/** If there is a valid list of {#link Earthquake}s, then add them to the adapter's dataset. THis will trigger
* the ListVIew to update*/
if (data != null && !data.isEmpty()){
mAdapter.addAll(data);
}
}
}
}
QueryUtils.java
public final class QueryUtils {
/**
* Sample JSON response for a USGS query
*/
/**
* Create a private constructor because no one should ever create a {#link QueryUtils} object.
* This class is only meant to hold static variables and methods, which can be accessed
* directly from the class name QueryUtils (and an object instance of QueryUtils is not needed).
*/
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils() {
}
/**
* Query the USGS dataset and return a list of{#link Earthquake} objects.
*/
public static List<Earthquake> featchEarthquakeDate(String requestUrl)
{
// Create URL Object
URL url = createurl(requestUrl);
// Perform HTTP request to the URL and recive a JSON response back
String JSONResponse = null;
try{
JSONResponse = makeHttpRequest(url);
}catch (IOException e)
{
Log.e(LOG_TAG,"Problem Making http equest", e);
}
// Extract relevent fields fom the JSON response and create a list of {#link Earthquake}s
List<Earthquake> earthquakes = extractFeatureFromJson(JSONResponse);
//Return the list of {#link Earthquake}s
return earthquakes;
}
/**
* Return new URL from object from the given string URL
*/
private static URL createurl(String stringURL){
URL url = null;
try {
url = new URL(stringURL);
}catch (MalformedURLException e){
Log.e(LOG_TAG,"problem building the url", e);
}
return url;
}
/**
* Make an HTTP request to the given URL and return a string as the response.
* */
private static String makeHttpRequest(URL url)throws IOException{
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null){
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try{
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000/* millisecond*/);
urlConnection.setConnectTimeout(15000 /*milisecond*/);
urlConnection.setRequestMethod("Get");
urlConnection.connect();
//If the request was successful (response code 200), then read the Input Stream and parse the Response.
if (urlConnection.getResponseCode() == 200){
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}else {
Log.e(LOG_TAG,"Error Response code" + urlConnection.getResponseCode());
}
}catch (IOException e){
Log.e(LOG_TAG,"problem recived the earthquake JSON result",e);
}finally {
if (urlConnection!=null)
{
urlConnection.disconnect();
}
if (inputStream!=null){
/*
Closing the input Stream could throw an IOException, which is why the makeHttpRequest(URL url) method
signature specific than an IOException could be thrown.
*/
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException{
StringBuilder output = new StringBuilder();
if (inputStream != null){
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null){
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
/**
* Return a list of {#link Earthquake} objects that has been built up from
* parsing a JSON response.
*/
private static List<Earthquake> extractFeatureFromJson(String eartheuakeJSON) {
// If the JSON string is empity or null, then return early.
if (TextUtils.isEmpty(eartheuakeJSON))
{
return null;
}
// Create an empty ArrayList that we can start adding earthquakes to
List<Earthquake> earthquakes = new ArrayList<Earthquake>();
// Try to parse the JSON response string. If there's a problem with the way the JSON
// is formatted, a JSONException exception object will be thrown.
// Catch the exception so the app doesn't crash, and print the error message to the logs.
try {
// create a JSONObject from the JSON response string
JSONObject baseJsonResponse = new JSONObject(eartheuakeJSON);
// Extract the JSONArray associated with the key called "features", which represent a list of features(or earthquakes).
JSONArray earthquakeArray = baseJsonResponse.getJSONArray("features");
// For each earthquake in the earthquakeArray, create an {#link Earthquake} object
for (int i = 0; i < earthquakeArray.length(); i++) {
JSONObject currentEarthquake = earthquakeArray.getJSONObject(i);
// For a given earthquake, extract the JSONObject associated with the key called "properties", which represent a
// list of all properties for the earthquake.
JSONObject properties = currentEarthquake.getJSONObject("properties");
// Extract the value for the key called "mag"
Double magnitude = properties.getDouble("mag");
// Extract the value for the key called "place"
String location = properties.getString("place");
// Extract the value for the key called "time"
long time = properties.getLong("time");
// Extract the value for the key called "url"
String url = properties.getString("url");
// Create a new {#link Earthquake} object with the magnitude,locaton,time, and url
// from the JSON response
Earthquake earthquake = new Earthquake(magnitude, location, time,url);
// Add the new {#link Earthquake} to the list of earthquakes.
earthquakes.add(earthquake);
}
} catch (JSONException e) {
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
}
// Return the list of earthquakes
return earthquakes;
}
}
Earthquake.java
package com.example.quakereport;
import android.content.Context;
public class Earthquake {
private Double mMagnitude;
private String mLocation;
private String mDate;
private long mTimeInMillisecond;
private String mUrl;
public Earthquake(Double Magnitude, String Location, long TimeInMIllisecond, String Url) {
mMagnitude = Magnitude;
mLocation = Location;
mTimeInMillisecond = TimeInMIllisecond;
mUrl = Url;
}
public Double getmMagnitude() {
return mMagnitude;
}
public String getmLocation() {
return mLocation;
}
public String getmUrl() {
return mUrl;
}
public long getmTimeInMillisecond() {
return mTimeInMillisecond;
}
}
EartquakeAdapter.java
public class EarthquakeAdapter extends ArrayAdapter<Earthquake> {
private static final String LOCATION_SEPARATOR = "of";
public EarthquakeAdapter (Context context, List<Earthquake> place)
{
super(context,0,place);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null)
{
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.earthquake_list_item,parent,false);
}
Earthquake currentEarthQuake = getItem(position);
TextView magnitude = (TextView) listItemView.findViewById(R.id.magnitude);
// Formate The Magnitude to show 1 decimal place
String formattedMaginitude = formatedMagnitude(currentEarthQuake.getmMagnitude());
magnitude.setText(formattedMaginitude);
//Set the prope background color on the magnitude circle.
// Fetch the background fom the Textview, which is a GadientDrawable.
GradientDrawable maginitudeCircle = (GradientDrawable) magnitude.getBackground();
// Get the appropriate background color based on the current earthquake magnitude
int magnitudeColor = getMagnitudeColor(currentEarthQuake.getmMagnitude());
// Set the color on the magnitude cicle
maginitudeCircle.setColor(magnitudeColor);
String originallocation = currentEarthQuake.getmLocation();
String primaryLocation;
String locationOffset;
if(originallocation.contains(LOCATION_SEPARATOR))
{
String[] parts = originallocation.split(LOCATION_SEPARATOR);
locationOffset = parts[0] + LOCATION_SEPARATOR;
primaryLocation = parts[1];
}else {
locationOffset= getContext().getString(R.string.near_the);
primaryLocation = originallocation;
}
TextView primarrylocation = (TextView) listItemView.findViewById(R.id.location_primarry);
primarrylocation.setText(primaryLocation);
TextView locationOffsetView = (TextView) listItemView.findViewById(R.id.location_offset);
locationOffsetView .setText(locationOffset);
// TextView locationView = (TextView) listItemView.findViewById(R.id.location_primarry);
// locationView.setText(currentEarthQuake.getmLocation());
Date dateObject = new Date(currentEarthQuake.getmTimeInMillisecond());
TextView dateView = (TextView) listItemView.findViewById(R.id.date);
// Fomate the date string (ex "Mar 3, 1995")
String formattedDate = formatDate(dateObject);
dateView.setText(formattedDate);
TextView timeView = (TextView) listItemView.findViewById(R.id.time);
String formattedtime = formatTime(dateObject);
timeView.setText(formattedtime);
return listItemView;
}
private int getMagnitudeColor(double magnitude)
{
int mgnitudeColorResourceId;
int magnitudeFloor = (int) Math.floor(magnitude);
switch (magnitudeFloor)
{
case 0:
case 1:
mgnitudeColorResourceId = R.color.magnitude1;
break;
case 2:
mgnitudeColorResourceId = R.color.magnitude2;
break;
case 3:
mgnitudeColorResourceId = R.color.magnitude3;
break;
case 4:
mgnitudeColorResourceId = R.color.magnitude4;
break;
case 5:
mgnitudeColorResourceId = R.color.magnitude5;
break;
case 6:
mgnitudeColorResourceId = R.color.magnitude6;
break;
case 7:
mgnitudeColorResourceId = R.color.magnitude7;
break;
case 8:
mgnitudeColorResourceId = R.color.magnitude8;
break;
case 9:
mgnitudeColorResourceId = R.color.magnitude9;
break;
default:
mgnitudeColorResourceId = R.color.magnitude10plus;
break;
}
return ContextCompat.getColor(getContext(),mgnitudeColorResourceId);
}
private String formatDate(Date dateObject){
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");
return dateFormat.format(dateObject);
}
private String formatTime (Date dateObject){
SimpleDateFormat timeFormate = new SimpleDateFormat("h:mm a");
return timeFormate.format(dateObject);
}
private String formatedMagnitude(double magnitude){
DecimalFormat magnitudeFormate = new DecimalFormat("0.0");
return magnitudeFormate.format(magnitude);
}
}

In File: QueryUtils.java
You need to change this line of code
urlConnection.setRequestMethod("Get");
To this one
urlConnection.setRequestMethod("GET");
The error message explains it:
This Is the Error:- E/QueryUtils: problem recived the earthquake JSON result java.net.ProtocolException: Expected one of [OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, PATCH] but was Get at
It expected GET but it was Get

Related

Pull specific JSON objects from a specific array to put in another activity by an Intent in Android

I am creating a News Feed App, and I want to be able to pull information from a specific listing to a different layout that displays the title, source, image and content of the news listing. On the main page, the JSON will populate the list view with the title, source and image. I've sent an onItemClickListener, and when I click on each entry, I want it to open that entry in the new layout to display all the content. I have a class made just to pull the JSON info, so I'm not sure how to use that in the class with the onItemClick listener. I understand the putExtra, but I'm completely lost on the code to enter to transfer over what I need. Below is code from the page with the list, as well as the JsonQuery class. Thanks for any help!
TopHeadlinesFragment.java
public class TopHeadlinesFragment extends Fragment
implements LoaderManager.LoaderCallbacks<List<News>> {
public static final String NEWS_FEED_URL =
"https://newsapi.org/v2/top-headlines?country=us&apiKey=a3f791903c1a4163b223dd033563084b";
private static final int NEWS_LOADER_ID = 1;
private NewsAdapter mNewsAdapter;
private NewsAdapterListing mNewsAdapterListing;
public TopHeadlinesFragment(){
// Required empty public constructor
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.news_list, container, false);
mNewsAdapter = new NewsAdapter(getActivity(), new ArrayList<News>());
ListView listView = rootView.findViewById(R.id.list);
listView.setAdapter(mNewsAdapter);
final LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(NEWS_LOADER_ID, null, this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mNewsAdapterListing = new NewsAdapterListing(getActivity(), new ArrayList<News>());
News currentNews = mNewsAdapterListing.getItem(position);
Intent newsArticleDisplayIntent = new Intent(getActivity(), FullArticleListing.class);
startActivity(newsArticleDisplayIntent);
}
});
return rootView;
}
#Override
public Loader<List<News>> onCreateLoader(int id, Bundle args) {
return new NewsLoader(getActivity(), NEWS_FEED_URL);
}
#Override
public void onLoadFinished(Loader<List<News>> loader, List<News> data) {
mNewsAdapter.clear();
if (data != null && !data.isEmpty()){
mNewsAdapter.addAll(data);
}
}
#Override
public void onLoaderReset(Loader<List<News>> loader) {
mNewsAdapter.clear();
}
public static class NewsLoader extends AsyncTaskLoader<List<News>> {
private String[] mUrl;
public NewsLoader(Context context, String... url) {
super(context);
mUrl = url;
}
#Override
protected void onStartLoading() {
forceLoad();
}
#Override
public List<News> loadInBackground() {
if (mUrl.length < 1 || mUrl[0] == null) {
return null;
}
return JsonQueryUtils.fetchNewsData(mUrl[0]);
}
}
}
JsonQueryUtils.java
public class JsonQueryUtils {
/** Contains networking and JSON parsing code **/
private static final String LOG_TAG = "JsonQueryUtils";
private JsonQueryUtils(){
}
/** Helper method to fetch news data and call networking code within method **/
public static List<News> fetchNewsData(String requestUrl){
URL url = createUrl(requestUrl);
String jsonResponse = null;
try{
jsonResponse = makeHttpRequest(url);
} catch (IOException e){
Log.e(LOG_TAG, "Error closing input stream", e);
}
List<News> news = extractNews(jsonResponse);
Log.i(LOG_TAG, "fetchNewsData initialized");
return news;
}
private static List<News> extractNews (final String newsJSON) {
if (TextUtils.isEmpty(newsJSON)) {
return null;
}
List<News> news = new ArrayList<>();
try {
JSONObject jsonNewsObject = new JSONObject(newsJSON);
JSONArray newsArray = jsonNewsObject.getJSONArray("articles");
for (int i = 0; i < newsArray.length(); i++) {
JSONObject currentNews = newsArray.getJSONObject(i);
JSONObject source = currentNews.optJSONObject("source");
String imageUrl = currentNews.getString("urlToImage");
Bitmap newsImage = makeHttpRequest(imageUrl);
String title = currentNews.getString("title");
String sourceName = source.getString("name");
String content = currentNews.getString("content");
news.add(new News(newsImage, title, sourceName));
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(LOG_TAG, "problem with parsing", e);
} catch (IOException e){
e.printStackTrace();
}
return news;
}
/**
* Make an HTTP request to the given imageURL and return a Bitmap as the response.
*/
private static Bitmap makeHttpRequest (String imageUrl) throws IOException {
Bitmap newsImage = null;
if (imageUrl == null){
return newsImage;
}
URL url = createUrl(imageUrl);
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
newsImage = BitmapFactory.decodeStream(inputStream);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error reading bitmap input stream");
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return newsImage;
}
/**
* Make an HTTP request to the given URL and return a String as the response.
*/
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem reading input stream.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
/**
* Convert the {#link InputStream} into a String which contains the
* whole JSON response from the server.
*/
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
/** Helper method to create {#link} URL object **/
private static final URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "createUrl: error", e);
}
return url;
}
}
I noticed you extracted the 'content' from JSON response but I don't see anywhere the variable 'content' getting used to construct the News object... Is there a reason why you don't include it to News object?
Regarding sending the News object to the next activity, there are few ways to achieve this.
Use Parcelable to send the News to your next activity/fragment. For more details, click here.
Install GSON library and simple convert your News object to Json String. Put that String in your Intent as an extra and launch the next Activity. Retrieve the data by calling new Gson().fromJson(). However, since your object has Bitmap field, this won't be a suitable approach. For more details, click here
This is what I would have done, if the API allows: Simply call the API request again for more details about the current feed. For example, you can execute another API request in your FullArticleActivity along with an ID that is associated with the selected feed. (i.e. User clicks a feed with an id #3 -> Pass the id(Integer) to the next Activity as an extra -> Retrieve the id from extras and make another API request using the id to retrieve full article details.) However, this is possible only when your API provides a GET method like this.
Create a Singleton and let it hold your object temporarily. Retrieve the object in the next activity by simple calling something like YourSingletonClass.getInstance().getNews().

org.json.JSONException: Value OR-12345 at order_no of type java.lang.String cannot be converted to int

I am trying to populate the recycler view using json data from dummy api but it is not working. I have tried almost several solutions given in stack overflow.
Here is my code below:
public class loadOrdersList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
ordersList = new ArrayList<>();
rvor = findViewById(R.id.recycler_view_orders);
rvor.setHasFixedSize(true);
rvor.setLayoutManager(new LinearLayoutManager(OrdersActivity.this));
}
#Override
protected void onPostExecute(Void aVoid) {
if (new CheckNetworkUtil(OrdersActivity.this).isNetworkAvailable()) {
Log.d("TEST", "------------------ordersList: " + ordersList.size());
OrdersAdapter adapter = new OrdersAdapter(getApplicationContext(), ordersList);
rvor.setAdapter(adapter);
srl.setRefreshing(false);
} else
Toast.makeText(OrdersActivity.this, "No Internet Connection!", Toast.LENGTH_SHORT).show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected Void doInBackground(Void... voids) {
try {
OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder()
.url("https://api.myjson.com/bins/la2gh")
.build();
Response responses = client.newCall(request).execute();
JSONArray orders = new JSONArray(responses.body().string());
ordersList = new ArrayList<>();
for (int i = 0; i < orders.length(); i++) {
JSONObject name = orders.getJSONObject(i);
String customerName = name.getString("customer_name");
String agentAssigned = name.getString("agent_assigned");
String orderId = name.getString("order_id");
Integer totalQuantity = name.getInt("total_quantity");
String orderDate = name.getString("order_date");
Integer orderNo = name.getInt("order_no");
String schoolYear = name.getString("school_year");
String company = name.getString("company");
String deliveryDate = name.getString("delivery_date");
String orderStatus = name.getString("order_status");
Integer grossRevenue = name.getInt("gross_revenue");
Integer netRevenue = name.getInt("net_revenue");
Integer totalOrdered = name.getInt("total");
Integer grandTotalOrdered = name.getInt("grand_total");
OrderModel orderModel = new OrderModel(customerName
,agentAssigned
,orderId
,totalQuantity
,orderDate
,orderNo
,schoolYear
,company
,deliveryDate
,orderStatus
,grossRevenue
,netRevenue
,totalOrdered
,grandTotalOrdered);
ordersList.add(orderModel);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
I suspected that integer is not supported by the string during execution.
You are expecting order_no to be an Integer and thus written this
Integer orderNo = name.getInt("order_no");
But you are receiving an alphanumeric value for orderNo in recycler view.
So either you have to change the type of orderNo property of OrderModel from Integer to String or restrict values to Integer type only.

How to manage multiple AsyncTasks in Android

I want to create my AsyncTask in separated classes because of I have to parse XML and it's a bunch of code.
So I want to get noticed in the activity everytime an asynctask is completed.
I followed this question
The problem is that when I have to make multiple petitions, everytime one is completed call the same method.
I want to call different methods depending of the AsyncTask Class I called.
EDIT: One of my AsyncTask Classes
public class FichaProducto extends AsyncTask<Void,Void,String>{
private String codigo, descripcion, ubicacion, descPromocion, currentUser,ip,port,codigoBuscar, respuesta;
private float precio;
private static final String TAG = "Logger";
private OnTaskCompleted listener;
/**
* Without listener
* #param codigoBuscar
* #param currentUser
* #param ip
* #param port
*/
public FichaProducto(String codigoBuscar,String currentUser,String ip,String port) {
setCodigoBuscar(codigoBuscar);
setCurrentUser(currentUser);
setIp(ip);
setPort(port);
}
/**
* With listener
* #param codigoBuscar
* #param currentUser
* #param ip
* #param port
* #param listener
*/
public FichaProducto(String codigoBuscar, String currentUser, String ip, String port, OnTaskCompleted listener) {
setCodigoBuscar(codigoBuscar);
setCurrentUser(currentUser);
setIp(ip);
setPort(port);
this.listener = listener;
}
/**
* set the xml response
* #param response
*/
public void setRespuesta(String respuesta) {
this.respuesta = respuesta;
}
/**
* #return server xml response
*/
#Override
protected String doInBackground(Void... params) {
StringBuilder respuesta = new StringBuilder();
URL url;
HttpURLConnection conexion = null;
try{
//Create the connection and set parameters
url = new URL("http://"+getIp()+":"+getPort());
Log.d(TAG,url.toString());
conexion = (HttpURLConnection)url.openConnection();
conexion.setRequestMethod("POST");
conexion.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conexion.setRequestProperty("Content-Length", "" + Integer.toString(getXML().getBytes().length));
conexion.setRequestProperty("Content-Language", "es-ES");
conexion.setUseCaches(false);
conexion.setDoInput(true);
conexion.setDoOutput(true);
//Send the petition
DataOutputStream dos = null;
dos = new DataOutputStream(conexion.getOutputStream());
dos.writeBytes(getXML());
dos.flush();
dos.close();
//Get the response
InputStream is = conexion.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String linea;
while ((linea = br.readLine()) != null){
respuesta.append(linea);
respuesta.append("\n");
}
br.close();
Log.d(TAG,"From asynctask the response is: "+respuesta.toString());
return respuesta.toString();
}catch(MalformedURLException e){
Log.e(TAG,"MalformedURLException in AsyncTask "+e.getMessage());
return null;
}catch (IOException e){
Log.e(TAG,"IO Exception in AsyncTask "+e.getMessage());
return null;
} finally {
//Close the connection
if (conexion != null){
conexion.disconnect();
}
}
}
/**
* Set the response and call the listener
*/
#Override
protected void onPostExecute(String respuesta){
setRespuesta(respuesta);
//Here it'll read the xml received and will set the variables
if (listener != null){
listener.onTaskCompleted();
}
}
(If it's bad, excuse my english pls)
To check which task is compelte you can use follow:
Update OnTaskCompleted with onTaskCompleted(int id);
private OnTaskCompleted listener;
private int id;
public FichaProducto(String codigoBuscar, String currentUser, String ip,
String port, OnTaskCompleted listener, int id) {
setCodigoBuscar(codigoBuscar);
setCurrentUser(currentUser);
setIp(ip);
setPort(port);
this.listener = listener;
this.id = id
}
#Override
protected void onPostExecute(String respuesta){
setRespuesta(respuesta);
//Here it'll read the xml received and will set the variables
if (listener != null){
listener.onTaskCompleted(id);
}
}
In activity class you can use something like this:
private final int PARSE_XML = 0
private final int PARSE_JSON = 1
void parseXml(){
new FichaProducto(codigoBuscar, currentUser, ip, port, PARSE_XML)
}
#Override
onTaskCompleted(int id){
switch (id){
case PARSE_XML:
break;
case PARSE_JSON:
break;
}
}

Display And Use Information From A DownloadTask In Android Studio

First time using Android Studio in any large capacity. Using the code from here: https://stackoverflow.com/a/30937657/5919360, I was able to successfully pull the information I wanted from the URL, but I can't figure out how use it.
Note: I know IMEI is not a good way to check for user registration and will be changing it later.
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
// Create instance and populates based on content view ID
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// store IMEI
String imei = tm.getDeviceId();
// store phone
String phone = tm.getLine1Number();
// Display IMEI - Testing Purposes Only
TextView imeiText = (TextView) findViewById(R.id.imeiDisplay);
imeiText.setText("IMEI:" + imei);
// Display phone number - Testing Purposes Only
TextView phoneText = (TextView) findViewById(R.id.phoneDisplay);
phoneText.setText("Phone:" + phone);
new DownloadTask().execute("http://www.url.com/mobileAPI.php?action=retrieve_user_info&IMEI="+imei);
}
private class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
return downloadContent(params[0]);
} catch (IOException e) {
return "Unable to retrieve data. URL may be invalid.";
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
}
}
private String downloadContent(String myurl) throws IOException {
InputStream is = null;
int length = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
int response = conn.getResponseCode();
Log.d(TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = convertInputStreamToString(is, length);
return contentAsString;
} finally {
if (is != null) {
is.close();
}
}
}
public String convertInputStreamToString(InputStream stream, int length) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[length];
reader.read(buffer);
return new String(buffer);
}
}
This code returns an xml file, as a toast:
<?xml version="1.0" encoding="ISO-8859-1"?>
<mobile_user_info>
<rec>45</rec>
<IMEI>9900990099009</IMEI>
<fname>First</fname>
<lname>Last</lname>
<instance>instance1</instance>
<registered>N</registered>
</mobile_user_info>
I'm hoping someone can point me in the right direction for separating each line and using it independently. For example, if the Registered line comes back as N, a message is displayed like, 'You are not registered. Please contact administrator.'
Actually you should use an XML parser to parse the server's response. But if responses are always as simple as your example, you can use a regular expression to extract out the IMEI field.
String contentAsString = ...
Pattern pattern = Pattern.compile("<IMEI>(\d*)</IMEI>");
Matcher matcher = pattern.matcher(contentAsString);
if (matcher.find()) {
String imei = matcher.group(1);
}

Google Places API photo_reference

I have been trying to extract the goolge places api photo reference but have not had any success. I was wondering if someone could help me. Below is my code:
// KEY Strings
public static String KEY_REFERENCE = "reference"; // id of the place
public static String KEY_NAME = "name"; // name of the place
public static String KEY_VICINITY = "vicinity"; // Place area name
public static String KEY_PHOTO = "photo_reference";
class LoadPlaces extends AsyncTask<String, String, String> {
/**
* getting google places JSON response
* */
protected String doInBackground(String... args) {
// creating Places class object
googlePlaces = new GooglePlaces();
try {
String types = MenuActivity.type;
String keyword = MenuActivity.keyword;
// get nearest places
nearPlaces = googlePlaces.search(gps.getLatitude(),gps.getLongitude(),
types, keyword);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed Places into LISTVIEW
* */
// Get JSON response status
String status = nearPlaces.status;
// Check for OK status
if (status.equals("OK")) {
// Successfully got places details
if (nearPlaces.results != null) {
// loop through each place
for (Place p : nearPlaces.results) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_REFERENCE, p.reference);
map.put(KEY_NAME, p.name);
map.put(KEY_PHOTO,p.photo);
map.put(KEY_VICINITY, p.vicinity);
// adding HashMap to ArrayList
placesListItems.add(map);
}
// list adapter - removed rating
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, placesListItems,
R.layout.list_item, new String[] {
KEY_REFERENCE, KEY_NAME, KEY_VICINITY, KEY_PHOTO},
new int[] { R.id.reference, R.id.name, R.id.address, R.id.phptp});
// Adding data into ListView
lv.setAdapter(adapter);
}
}
}
Below is my code that performs the search and parses the data:
public class GooglePlaces {
/** Global instance of the HTTP transport. */
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private static final String LOG_KEY = "GGPlace";
// Google API Key
private static final String API_KEY = "";
// Google Places serach
private static final String PLACES_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?&rankby=distance";
private double _latitude;
private double _longitude;
private double _radius;
private String address;
public PlacesList search(double latitude, double longitude, String types, String keyword)
throws Exception {
this._latitude = latitude;
this._longitude = longitude;
try {
HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_SEARCH_URL));
request.getUrl().put("key", API_KEY);
request.getUrl().put("location", _latitude + "," + _longitude);
request.getUrl().put("sensor", "true");
if(types != null)
{
request.getUrl().put("types", types);
request.getUrl().put("keyword", keyword);
}
PlacesList list = request.execute().parseAs(PlacesList.class);
// Check log cat for places response status
Log.d("Places Status", "" + list.status);
return list;
} catch (HttpResponseException e) {
Log.e("Error:", e.getMessage());
return null;
}
}
public static HttpRequestFactory createRequestFactory(
final HttpTransport transport) {
return transport.createRequestFactory(new HttpRequestInitializer() {
public void initialize(HttpRequest request) {
GoogleHeaders headers = new GoogleHeaders();
headers.setApplicationName("APP NAME");
headers.gdataVersion="2";
request.setHeaders(headers);
JsonHttpParser parser = new JsonHttpParser(new JacksonFactory());
request.addParser(parser);
}
});
}
}
This is my PlaceList class:
public class PlacesList implements Serializable {
#Key
public String status;
#Key
public List<Place> results;
}
Here is my Place class:
public class Place implements Serializable {
#Key
public String id;
#Key
public String name;
#Key
public String reference;
#Key
public String vicinity;
#Key
public Geometry geometry;
#Key
public List<Photo> photos;
}
And finally my Photo class:
public class Photo implements Serializable {
#Key
public String photo_reference;
#Key
public int height;
#Key
public int width;
}
I guess I am calling or passing the photo_reference the wrong way. I am hoping there is someone out there that can help me out. I've been working on this for weeks and have almost completely given up.
Hi firstly your search url is wrong.
You have to follow this format:
https://developers.google.com/places/web-service/photos
Please see below for a complete example:
http://wptrafficanalyzer.in/blog/showing-nearby-places-with-photos-at-any-location-in-google-maps-android-api-v2/
If you download the source code, it will help you see how to fetch the json string in an array which is in another array.
The snippet below just answers the part where you have to fetch the image:
package in.wptrafficanalyzer.locationnearbyplacesphotos;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class PlaceJSONParser {
/** Receives a JSONObject and returns a list */
public Place[] parse(JSONObject jObject){
JSONArray jPlaces = null;
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces);
}
private Place[] getPlaces(JSONArray jPlaces){
int placesCount = jPlaces.length();
Place[] places = new Place[placesCount];
/** Taking each place, parses and adds to list object */
for(int i=0; i<placesCount;i++){
try {
/** Call getPlace with place JSON object to parse the place */
places[i] = getPlace((JSONObject)jPlaces.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
return places;
}
/** Parsing the Place JSON object */
private Place getPlace(JSONObject jPlace){
Place place = new Place();
try {
// Extracting Place name, if available
if(!jPlace.isNull("name")){
place.mPlaceName = jPlace.getString("name");
}
// Extracting Place Vicinity, if available
if(!jPlace.isNull("vicinity")){
place.mVicinity = jPlace.getString("vicinity");
}
if(!jPlace.isNull("photos")){
JSONArray photos = jPlace.getJSONArray("photos");
place.mPhotos = new Photo[photos.length()];
for(int i=0;i<photos.length();i++){
place.mPhotos[i] = new Photo();
place.mPhotos[i].mWidth = ((JSONObject)photos.get(i)).getInt("width");
place.mPhotos[i].mHeight = ((JSONObject)photos.get(i)).getInt("height");
place.mPhotos[i].mPhotoReference = ((JSONObject)photos.get(i)).getString("photo_reference");
JSONArray attributions = ((JSONObject)photos.get(i)).getJSONArray("html_attributions");
place.mPhotos[i].mAttributions = new Attribution[attributions.length()];
for(int j=0;j<attributions.length();j++){
place.mPhotos[i].mAttributions[j] = new Attribution();
place.mPhotos[i].mAttributions[j].mHtmlAttribution = attributions.getString(j);
}
}
}
place.mLat = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
place.mLng = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
} catch (JSONException e) {
e.printStackTrace();
Log.d("EXCEPTION", e.toString());
}
return place;
}
}
I first misunderstood photo_reference as Base64 Encoded String. But it is not indeed it is a reference parameter to identify and fetch a photo from google maps API. Imagine this as a token parameter. So to fetch a photo with max-width 400 you can use below URL.
https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=CnRtAAAATLZNl354RwP_9UKbQ_5Psy40texXePv4oAlgP4qNEkdIrkyse7rPXYGd9D_Uj1rVsQdWT4oRz4QrYAJNpFX7rzqqMlZw2h2E2y5IKMUZ7ouD_SlcHxYq1yL4KbKUv3qtWgTK0A6QbGh87GB3sscrHRIQiG2RrmU_jF4tENr9wGS_YxoUSSDrYjWmrNfeEHSGSc3FyhNLlBU&key=YOUR_API_KEY
For more details visit Google Places documentation
https://developers.google.com/places/web-service/photos

Categories