I am trying to get JSON response from a URL. I have tried below code several time but i couldn't get the response. Please Help me to sort this out
I am using API level 29
Here i am using this url for getting data, url -> https://api.androidhive.info/contacts/
My Code :
public class MainActivity extends AppCompatActivity {
private final static String URL = "https://api.androidhive.info/contacts/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue queue = Volley.newRequestQueue(this);
JsonArrayRequest arrayRequest = new JsonArrayRequest(
Request.Method.GET, URL,null,new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("Response : ", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error : ", error.getMessage());
}
});
queue.add(arrayRequest);
}
}
AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.volleyparsing">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The Logcat response :
2020-05-03 22:19:49.600 11515-11515/? I/e.volleyparsin: Not late-enabling -Xcheck:jni (already on)
2020-05-03 22:19:49.749 11515-11515/? E/e.volleyparsin: Unknown bits set in runtime_flags: 0x8000
2020-05-03 22:19:53.066 11515-11515/com.example.volleyparsing D/Volley: [2] 2.onErrorResponse: Error :
2020-05-03 22:19:50.513 11515-11545/com.example.volleyparsing W/libc: Unable to set property "qemu.gles" to "1": connection failed; errno=13 (Permission denied)
Your response is jsonObject not jsonArray. That's way you are getting parsing error. Use jsonObject:
RequestQueue queue = Volley.newRequestQueue(context);
JsonObjectRequest objectRequest = new JsonObjectRequest(
Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray jsonArray = null;
try {
jsonArray = response.getJSONArray("contacts");
Log.d("Response : ", jsonArray.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error : ", error.getMessage());
}
});
queue.add(objectRequest);
Use android:usesCleartextTraffic="true" on your manifest file on application.
<application
...
android:usesCleartextTraffic="true"
... >
Related
I am sending images to firebase. but when my upload pictures method starts running, I get no auth token printed into my logcat couple of times. I tried using both camera and gallery, but they both make the same output even though my firebase storage rules are:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
And my code is:
if (fragment3.isAdded()) {
EditText plantdetails = (EditText) fragment3.getView().findViewById(R.id.plantdetails);
if (plantdetails.getText().toString().equals("")) {
Toast.makeText(newPlant.this, "I think you forgot something.", Toast.LENGTH_LONG).show();
} else {
plants plantss = new plants();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
prefs.edit().putString("pldetails", plantdetails.getText().toString()).apply();
String pname = prefs.getString("plname","null");
String pdate = prefs.getString("pldate","null");
String petails = prefs.getString("pldetails","null");
plantss.setPlname(pname);
plantss.setPldate(pdate);
plantss.setPldetails(petails);
reference.child("Plants").child(pname).setValue(plantss);
try {
Fileuploader();
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
if (fragment4.isAdded()){
}
}
});
}
private void Fileuploader() throws FileNotFoundException {
String imageid;
progress.showProgress(newPlant.this,"Loading...",false);
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
Cursor getimage = databaseHelper.GetPath();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
String plname = prefs.getString("plname","null");
int count = 0;
int count2 = 0;
if (getimage !=null){
while (getimage.moveToNext()) {
System.out.println("IMAGE IS THIS MY MAN: "+ getimage.getString(0));
Bitmap bm = BitmapFactory.decodeFile(getimage.getString(0));
if (bm == null){
return;
}else {
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 35, out);
imageid = System.currentTimeMillis() + "_" + (count++) + "." + getExtension(uri);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Plants").child(plname).child("PlantImages");
String imagekey = reference.push().getKey();
reference.child(imagekey).child("ImageID").setValue(imageid);
reference.child(imagekey).child("ID").setValue(count2++);
System.out.println("IMAGES UPLOADEDDDD: " + imageid);
byte[] data = out.toByteArray();
StorageReference Ref = mStorageRef.child(imageid);
Ref.putBytes(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
//Uri downloadUrl = taskSnapshot.getDownloadUrl();
//Toast.makeText(profuctadd.this,"Image uploaded",Toast.LENGTH_LONG).show();
progress.hideProgress();
Intent intent = new Intent(newPlant.this, Donenewplant.class);
startActivity(intent);
finish();
DatabaseHelper mDatabaseHelper = new DatabaseHelper(newPlant.this);
Cursor cursor2 = mDatabaseHelper.DeleteDataOfTableImagesAr();
cursor2.moveToNext();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(newPlant.this, "Failed", Toast.LENGTH_LONG).show();
System.out.println("FAILED:::: "+exception);
}
});
}
}
}
}
Mainfest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.varroxsystems.plant">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/plant"
android:label="#string/app_name"
android:roundIcon="#drawable/plant"
android:supportsRtl="true"
android:requestLegacyExternalStorage="true"
android:theme="#style/AppTheme">
<activity android:name=".Donenewplant"></activity>
<activity android:name=".newPlant" />
<activity android:name=".MainActivity" />
<activity android:name=".Splash_screen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.varroxsystems.plant.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
</application>
</manifest>
So does anyone know a solution for that, or is it just a bug, because I use the same exact code in another app and it works just fine.
EDIT: The other app I use uses a different database, not the same one.
I'm getting this error message "java.net.UnknownHostException: Unable to resolve host "api.themoviedb.org": No address associated with hostname".
All the stackoverflow posts I read said that the manifest file might be wrong, but I think at this point it's right, so I'm not sure how to continue.
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.flixster">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
MainActivity.java:
package com.example.flixster;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.codepath.asynchttpclient.AsyncHttpClient;
import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import okhttp3.Headers;
import static com.facebook.stetho.inspector.network.PrettyPrinterDisplayType.JSON;
public class MainActivity extends AppCompatActivity {
public static final String NOW_PLAYING_URL =
"https://api.themoviedb.org/3//movie/now_playing?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed";
public static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// make get request on URL to get currently playing movies
AsyncHttpClient client = new AsyncHttpClient();
// JSON response handler since API returns JSON- deals with response success/failure
client.get(NOW_PLAYING_URL, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Headers headers, JsonHttpResponseHandler.JSON json) {
Log.d(TAG, "onSuccess");
JSONObject jsonObject = json.jsonObject;
try {
JSONArray results = jsonObject.getJSONArray("result");
Log.i(TAG, "Results: " + results.toString());
} catch (JSONException e) {
Log.e(TAG, "Hit json exception", e);
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Headers headers, String response, Throwable throwable) {
Log.d(TAG, "onFailure");
}
});
}
}
Looking at your code I found 2 issues:
Your NOW_PLAYING_URL has an additional slash (themoviedb.org/3//movie/) after 3 so replace the string as
public static final String NOW_PLAYING_URL = "https://api.themoviedb.org/3/movie/now_playing?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed";
That was the reason why your api call returns a failure.
Next, the response is success but in your onSuccess() try block you are fetching data for "result" but your API response returns "results" so replace that key as below and you should not be having any issues.
JSONArray results = jsonObject.getJSONArray("results");
Hope this helps.
I have implemented an app and I have used facebook login to it. Application is running without crashing but facebook login is not working. When I open up the app and click the facebook login button it will show a progress bar and it will be disappeared immediately without doing anything. I have got the following error in the logcat.
2019-08-29 12:45:24.290 19304-19328/com.appic.testfbauth
E/GraphResponse:
{
HttpStatus: 400,
errorCode: 100,
subErrorCode: 33,
errorType: GraphMethodException,
errorMessage: Unsupported get request. Object with ID '742177629556035' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api
}
refer below for work I have done.
public class MainActivity extends AppCompatActivity {
private LoginButton loginButton;
private CircleImageView circleImageView;
private TextView txtName, txtEmail;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FacebookSdk.sdkInitialize(getApplicationContext());
loginButton = findViewById(R.id.login_button);
circleImageView = findViewById(R.id.profile_pic);
txtName = findViewById(R.id.profile_name);
txtEmail = findViewById(R.id.profile_email);
checkLoginStatus();
callbackManager = CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
AccessTokenTracker tokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
if(currentAccessToken == null) {
txtEmail.setText("");
txtName.setText("");
circleImageView.setImageResource(0);
Toast.makeText(MainActivity.this, "User Logged Out!", Toast.LENGTH_SHORT).show();
}
else loadUser(currentAccessToken);
}
};
private void loadUser(AccessToken newAccessToken) {
GraphRequest request = GraphRequest.newMeRequest(newAccessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String first_name = object.getString("first_name");
String last_name = object.getString("last_name");
String email = object.getString("email");
String id = object.getString("id");
String image_url = "https://graph.facebook.com/"+ id +"/picture?type=normal";
txtEmail.setText(email);
txtName.setText(first_name +" "+ last_name);
RequestOptions requestOptions = new RequestOptions();
requestOptions.dontAnimate();
Glide.with(MainActivity.this).load(image_url).into(circleImageView);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name,last_name,email,id");
request.setParameters(parameters);
request.executeAsync();
}
private void checkLoginStatus() {
if(AccessToken.getCurrentAccessToken() != null) {
loadUser(AccessToken.getCurrentAccessToken());
}
}
}
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id"/>
<meta-data android:name="com.facebook.sdk.ApplicationName"
android:value="#string/app_name"/>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="#string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
</application>
I just want to integrate the facebook login and get email, name, image url, id.
I have no enough replication for comment so i paste answer. You just give me answers to my below questions.
You test your app in real device or emulator.?
Get the permission for image?
Please check your browser any facebook account already login there?
If you not getting email and name please try below code:
JSONObject res;
res = new JSONObject(json_object.toString());
String id = res.getString("id");
String name = res.getString("name");
String email = res.getString("email");
Update:
Please Uninstalled FB app from your device and try to login with FB in your app it's working fine.
Update 25/11/209
Also please update your hash key - Please follow this answer
After that convert hash key into base 64 - tomeko.net
I am new to firebase. I was using an old version code where the parameters i put were atleast working for the url. but now when link is clicked, the browser opens and its a 400 error that requested url was not found. it works with only the dynamic link
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri BASE_URI = Uri.parse("http://example.com/");
Uri APP_URI = BASE_URI.buildUpon().
appendQueryParameter("extra1", "value").build();
String encodedUri = null;
try {
encodedUri = URLEncoder.encode(APP_URI.toString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.v("ENCODED URI: ", encodedUri);
Uri deepLink = Uri.parse("https://eh62u.app.goo.gl/y6N7/?link="+encodedUri);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_EMAIL, "");
intent.putExtra(Intent.EXTRA_SUBJECT, "GET TICKETS" );
intent.putExtra(Intent.EXTRA_TEXT, "Click here to get the booked tickets: " + deepLink);
startActivity(Intent.createChooser(intent, "Send Email"));
}
});
}
Main Activity OnCreate code:
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
FirebaseDynamicLinks.getInstance().getDynamicLink(getIntent())
.addOnSuccessListener(this, new OnSuccessListener<PendingDynamicLinkData>() {
#Override
public void onSuccess(PendingDynamicLinkData data) {
if (data == null) {
Log.d("NULL DATA ", "getInvitation: no data");
return;
}
// Get the deep link
Uri deepLink = data.getLink();
String requestId2 = deepLink.getQueryParameter("extra1");
// Handle the deep link
// [START_EXCLUDE]
Log.d("DEEP LINK URL ", "deepLink:" + deepLink);
if (deepLink != null) {
if(requestId2 == "value") {
Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
startActivity(intent);
}
}
// [END_EXCLUDE]
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w("onFailure: ", "getDynamicLink:onFailure", e);
}
});
Android Manifest Code:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter> <action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data
android:host="example.com"
android:scheme="https"/>
</intent-filter>
</activity>
<activity android:name=".Main2Activity">
</activity>
</application>
how do i put the parameter and then get it in the onSuccess? Thanks
The problem that i finally figured out by trial and error was the encoding part of the code. When i removed the :
encodedUri = URLEncoder.encode(APP_URI.toString(), "UTF-8");
part and just passed APP_URI to the deep link like
Uri deepLink = Uri.parse("https://eh62u.app.goo.gl/y6N7/?link="+APP_URI);
or even constructing the link using builder as:
Uri.Builder URLbuilder = new Uri.Builder()
.scheme("https")
.authority(Constants.DOMAIN)
.path("/")
.appendQueryParameter("link", getBaseUri(value))
.appendQueryParameter("apn", context.getPackageName());
It worked. No Problems. Retrieving the parameter was the usual.
I have this simple code, that makes a get to a webservice.
For some reason it cant connect and gives the error in the log unknownHostException
This is the code:
String URL = "http://services.sapo.pt/EPG/GetChannelList";
String result = "";
final String tag = "Data received: ";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button btnSearch = (Button)findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
callWebService();
}
});
} // end onCreate()
public void callWebService(){
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(URL);
ResponseHandler<String> handler = new BasicResponseHandler();
try {
result = httpclient.execute(request, handler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
Log.i(tag, result);
}
This is part of my manifest
<permission android:name="android.permission.INTERNET"/>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".AndroidApp"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I found the solution.
I putted the internet permission using the GUI in manifest which added the tag
< permission android:name"android.permission.INTERNET"/>
Then by hand, i putted the correct tag that is:
< uses-permission android:name="android.permission.INTERNET" />
which is a different tag and it worked. GUI fail.
Not sure if you have already checked this, but please check if you are behind a proxy or firewall. Here is a way to configure the HttpClient for a proxy and official apache documentation.