Android giving error while accessing json data from the internet - java

I am a beginner, building a goofy app that uses an online API. I uploaded the .json file to GitHub, from where my app accesses it and gives the output. However, it always runs the statements for onErrorResponse. Am I doing something wrong?
Here's the code for MainActivity:
package com.example.jsonparsing;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DownloadManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
RequestQueue requestQueue;
Button search;
EditText input;
TextView word;
TextView meaning;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = findViewById(R.id.button_getMeaning);
input = findViewById(R.id.editText_input);
word = findViewById(R.id.textView_word);
meaning = findViewById(R.id.textView_meaning);
requestQueue = Volley.newRequestQueue(this);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String term = input.getText().toString().toLowerCase();
String displayInput = term.toUpperCase() + ":";
word.setText(displayInput);
JsonObjectRequest jsonObjectRequest1 = new JsonObjectRequest(Request.Method.GET, "https://github.com/DeathVenom54/bonerDictionaryDatabase/blob/master/definitions.json", null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String definition = response.getString(term);
meaning.setText(definition);
} catch (JSONException e) {
e.printStackTrace();
meaning.setText("Sorry, this word doesn't exist in the boner database.");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Connection error, please check internet connection.", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonObjectRequest1);
}
});
}
}
The project uses Volley and I have added Internet permission in the manifest.
Edit: here's the .json :
https://github.com/DeathVenom54/bonerDictionaryDatabase/blob/master/definitions.json

The json url you have posted is a link to someone's github page with the json, but not the json itself. Whats most likely happening is volley is downloading the HTML page in its entirety which contains the json. Its then complaining that its not correctly formatted json.
If you want that json directly you need to find a way to host it somewhere. For example github has an api that you can access json files like this https://api.github.com/users/mralexgray/repos
For local testing you could always copy it into a local json file and import into the res/raw of your app and reference it from there.

Related

Backendless fetch all data from database but returning one result

I set up a database in Backendless and started running it on Android Studio. The app is able to access the database and the connection is stable. But when I run the app, it only returns one result from the database. Is it possible to loop through all the items in the database? I built the app using this tutorial: https://www.youtube.com/watch?v=KeYC6gJyt-k&t=1524s&ab_channel=JohanJurrius Here is my code.
package com.mbass.examples;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.backendless.Backendless;
import com.backendless.IDataStore;
import com.backendless.async.callback.AsyncCallback;
import com.backendless.exceptions.BackendlessFault;
import com.backendless.persistence.DataQueryBuilder;
import java.util.List;
import java.util.Map;
public class MainActivity extends Activity {
private TextView status;
private TextView listtext;
private Button updateButton;
List<VIdeos> videos;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Backendless.setUrl(Defaults.SERVER_URL);
Backendless.initApp(getApplicationContext(), Defaults.APPLICATION_ID, Defaults.API_KEY);
status = (TextView) findViewById(R.id.status);
updateButton = (Button) findViewById(R.id.update_button);
updateButton.setEnabled(false);
final int[] textViews = {R.id.textView1, R.id.textView2, R.id.textView3};
String whereClause = "name != 'Bill'";
DataQueryBuilder queryBuilder = DataQueryBuilder.create();
queryBuilder.setWhereClause(whereClause);
queryBuilder.setPageSize(10).setOffset(0);
queryBuilder.setSortBy("name");
Backendless.Persistence.of(VIdeos.class).find(queryBuilder, new AsyncCallback<List<VIdeos>>() {
#Override
public void handleResponse(List<VIdeos> response) {
for (int i = 0; i < response.size(); i++) {
Toast.makeText(MainActivity.this, "Name: " + response.get(i).getName() + "\n" +
"ID: " + response.get(i).getCreated(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void handleFault(BackendlessFault fault) {
Toast.makeText(MainActivity.this, fault.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
What happens when you comment out this line?
queryBuilder.setWhereClause(whereClause);
Your code sets the page size to 10 objects with the following line of code:
queryBuilder.setPageSize(10).setOffset(0)
The response is an array containing 10 objects. If you need more objects, change the page size. The maximum page size is 100

Retrofit how to pass location iside the GET

I want to show Nearby restaurants using my current location. I am using Retrofit, but I don't know how to pass my current latitude and longitude inside GET. I'm using ZOMATO API to get information about restaurants.
My geocode URL
If I get my location in MainActivity then how to pass it inside GET.
Please help me it's my first time working with Retrofit and API.
My interface class - ZomatoApi.java
package com.example.zomatoapi;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Headers;
public interface ZomatoApi {
String baseUrl = "https://developers.zomato.com/api/v2.1/";
#Headers("user-key: 1d63821dbb228ee5d09e8c8f7cfe10c3")
#GET("geocode?lat=18.521428&lon=73.8544541")
Call<CurrentCity> getRestaurant();
}
MainActivity
package com.example.zomatoapi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient mFusedLocationClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
Retrofit retrofit = new Retrofit.Builder().baseUrl(ZomatoApi.baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
ZomatoApi zomatoApi = retrofit.create(ZomatoApi.class);
final ListView listView = findViewById(R.id.restaurantList);
final ArrayList<String> restaurantNames = new ArrayList<>();
Call<CurrentCity> listCall = zomatoApi.getRestaurant();
listCall.enqueue(new Callback<CurrentCity>() {
#Override
public void onResponse(Call<CurrentCity> call, Response<CurrentCity> response) {
CurrentCity currentCity = response.body();
List<NearbyRestaurant> nearbyRestaurants = currentCity.getNearbyRestaurants();
for (NearbyRestaurant nearbyRestaurant : nearbyRestaurants) {
Restaurant restaurant = nearbyRestaurant.getRestaurant();
Log.i("heyy", restaurant.getName());
restaurantNames.add(restaurant.getName());
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, restaurantNames);
listView.setAdapter(arrayAdapter);
}
#Override
public void onFailure(Call<CurrentCity> call, Throwable t) {
}
});
}
}
Try this out :
#POST("nearestrestaurants?key=your_api_key")
// Call<MySnappedPoints> getNearestrestaurants();
Call<MySnappedPoints> getNearestRoad(#Query("points") String points);
To get this points :
String test = Double.toString(mGoogleMap.getCameraPosition().target.latitude) + "," +
Double.toString(mGoogleMap.getCameraPosition().target.longitude);
Call<MySnappedPoints> call = retrofitClientMap.getNearestRoad(test);
As per given documentation by Zomato, it accepts lat/lng as query params.
Try something like below
#Headers("user-key: xxxxxxxxxxxxxxx")
#GET("/geocode?")
Call<CurrentCity> getRestaurant(#Query(“lat”) double lat, #Query(“lng”) double lng);

I m doing barcode scanner. But I can display my resultCode in textview.

I want to display the scan result from ZXING. I integrated ZXING into my android app, the scan works ok. Now I want to display the barcode number result in textview. I'm using zxing library in my project. I set up result.setText(resultCode) but it's not works. so this is code i m'follow from the tutorial.
package com.example.norhanom.barcodeqrcode;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View; //view button or textfield
import android.widget.Toast; //to show and create message for user,appears
as floating view over app
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.google.zxing.Result;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class MainActivity extends AppCompatActivity {
private ZXingScannerView scannerView;
TextView result;
private ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView)findViewById(R.id.textView1);
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("loading");
pd.setCancelable(false);
pd.setCanceledOnTouchOutside(false);
}
public void scanCode(View view){
scannerView = new ZXingScannerView(this); // Programmatically initialize
the scanner view
scannerView.setResultHandler(new ZXingScannerResultHandler());
setContentView(scannerView); //Set the scanner view as the content view
scannerView.startCamera(); //scannerView open camera
}
#Override
public void onPause()
{
super.onPause();
scannerView.stopCamera(); //stop camera on pause
}
class ZXingScannerResultHandler implements ZXingScannerView.ResultHandler
{
#Override
public void handleResult(Result result1)
{
String resultCode = result1.getText(); //get the result
Toast.makeText(MainActivity.this,resultCode,Toast.LENGTH_LONG).show();
//show result
setContentView(R.layout.activity_main);
scannerView.stopCamera(); //camera stop
}
}
}
After using setContentView the next time, you should reassign the views.
//inside handleResult
setContentView(R.layout.activity_main);
result = (TextView)findViewById(R.id.textView1);
result.setText(resultCode);
scannerView.stopCamera();

Android Download File from webserver using Volley

Sorry I am a newbie with Android developing an app which sell digital downloads. I am using Volley Library to post INAPP_PURCHASE_DATA and INAPP_DATA_SIGNATURE to webserver to verify order and issue download link passing
http://domain.com/thankyou.php?purchaseData="+purchaseData+"&dataSignature="+dataSignature+"
If the order is verified a download link will be issued inside the page. The file name isn't static which means it's auto-generate by system so I can't guess the name each time issued from the server side. Can be file1.dat file2.dat file3.dat each time has a name depending on certain parameters I defined into the webserver.
<html>
<head>
<title>Thank You</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
<a href="http://domain.com/file.dat" title="Order" download>Download File</a>
</body>
</html>
Now I need to post the download file link to the app so the customer can download the file.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//download file on through a new in-app page
Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
})
I have created an activity_download.xml file and a new Download Class.
package com.example.app;
import java.util.List;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.app.R;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class Download extends Activity {
private String filename;
#Override
protected void onCreate (final Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView(R.layout.activity_download);
}
}
}
Sorry again I am a newbie with Android. Can you guide me a provide me with a way to have a complete Download.java class as a new page and then call it from the MainActivity.java side onresponse and successful result.
Thank you so much!
Cange your MainActivity code to this.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Intent intent = new Intent(MainActivity.this,Download.class);
startActivity(intent);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
})
As you want make a toast as soon as you get a Respons. dont do it in Activity class, do it in Download class becasue you will redirected to Download class soon as you get the response
public class Download extends Activity {
private String filename;
#Override
protected void onCreate (final Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView(R.layout.activity_download);
//download file on through a new in-app page
Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
}
}
}

Android: Internet works in emulator but not on my phone

I'm making an app which reads a certain part of a website and posts it to the screen. The app currently works in my android emulator but when I transfer it to my galaxy S2, it doesn't seem to access the website at all.
package com.example.beam;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
import org.apache.http.HttpResponse;
import org.apache.http.client.*;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
String current = null;
Button check;
TextView text;
TextView url;
String[] lines = new String[12];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
check = (Button) findViewById(R.id.checkstatus);
text = (TextView) findViewById(R.id.textView1);
url = (TextView) findViewById(R.id.url);
String[] lines = new String[12];
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// Attempt to the read the source from a website.
String bodyHtml = "null";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.spring8.or.jp/ext/ja/status/text.html");
ResponseHandler<String> resHandler = new BasicResponseHandler();
try {
bodyHtml = httpClient.execute(httpGet, resHandler);
} catch (Exception e) {
e.printStackTrace();
}
double current = 0;
try{
String derp = bodyHtml.substring(bodyHtml.lastIndexOf("mA") - 5, bodyHtml.lastIndexOf("mA"));
current = Double.parseDouble(derp);
}
catch(Exception e){
}
url.setText(current + " mA");
}
});
}
}
Apologies if the coding is a bit poor and messy, I'm quite new to all this. How do I fix this issue? Thank you
Also, I'm pretty sure I've set the permission correctly in the manifest.
Try this....
Its a good practice to Keep the UI work on UI thread and Non-UI work on Non-UI thread, but that became a LAW from the release of HONEYCOMB Android version.... That may be causing the error.
So you can do the following....
Do the Http on a separate thread, and then place the value on the UI using Handler, Handler Keep the reference of the thread in which it was created.
You can use AsyncTask which is specially designed for android to make a sync between
UI and Non-UI thread.
Note:
Please check the Internet Permission in AndroidManifest, though i know you have done it, cause the app ran on the emulator.... but still..no harm in checking it again.

Categories