My app makes a call to FourSquare API. The call happens in my getResponse() function, and that function gets called every time I do new Explore().execute();
Now, I am able to get a string from the API... But when I pass that string to displayResults() function, it becomes null (I have a code comment below to show exactly where). And because this string becomes null, I can not parse the JSON. What is causing this issue?
public TextView mBusinessName;
public TextView mCategorie;
public WebView mLocationView;
private class Explore extends AsyncTask<Void, String, String>{
String resp = "";
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(Void... String) {
//I get a complete JSON string and assign to resp HERE.
resp = getResponse();
return null;
}
#Override
protected void onPostExecute(String s) {
//pass resp to display results
displayResults(resp);
}
}
public String getResponse(){
String clientSecret = getResources().getString(R.string.client_secret);
String clientID = getResources().getString(R.string.client_id);
String url = "https://api.foursquare.com/v2/venues/explore?ll="
+ mLatitude + "," + mLongitude
+ "&limit=" + 5
+ "&radius=" + mRadius
+ "&query=" + mTerm
+ "&oauth_token="
+ "&client_secret="+ clientSecret
+ "&client_id="+ clientID
+ "&v=20150610";
String getResponseString = "";
try{
URL searchUrl = new URL(url);
HttpURLConnection httpsClient =
(HttpURLConnection) searchUrl.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(httpsClient.getInputStream()));
try{
getResponseString = "";
while((getResponseString = reader.readLine()) != null){
Log.d("Response ==== ", getResponseString);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(reader != null){
try{
reader.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}catch (Exception e){
e.printStackTrace();
}
return getResponseString;
}
public void displayResults(String resp){
//HERE is where it fails. The String resp becomes null/empty
// have tried logging resp, the log doesn't show up at all
// because of this, JSON string can not be parsed!!!!
try {
JSONObject json = new JSONObject(resp);
JSONArray items = json.getJSONObject("response")
.getJSONArray("groups").getJSONObject(0)
.getJSONArray("items");
//randomize items
JSONObject item = items.getJSONObject(getRandomIndex(items.length()-1));
String name = item.getJSONObject("venue").optString("name");
String categorie = item.getJSONObject("venue").getJSONArray("categories").getJSONObject(0).getString("name");
String latitude = item.getJSONObject("venue").getJSONObject("location").optString("lat");
String longitude = item.getJSONObject("venue").getJSONObject("location").optString("lng");
String image = "http://maps.google.com/maps/api/staticmap?center="
+ latitude + "," + longitude
+ "&markers=size:tiny%color:red%7C" + latitude + "," + longitude
+"&zoom=17&size=375x225&sensor=false";
mLocationView.loadUrl(image);
mBusinessName.setText(name);
mCategorie.setText(categorie);
} catch (JSONException e) {
e.printStackTrace();
}
}
EDIT: The variable resp becomes null/empty inside the function displayResults(). I don't know how this is happening.
Your getResponse() method does nothing. You need to change it so that it actually returns the complete string.
try{
StringBuilder sb = new StringBuilder();
getResponseString = "";
while((getResponseString = reader.readLine()) != null){
Log.d("Response ==== ", getResponseString);
sb.append(getResponseString);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(reader != null){
try{
reader.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
return sb.toString();
Related
I want to get the youtube video title from a url so I found this code below (IOUtils) is depreciated any other way to do this
public class SimpleYouTubeHelper {
public static String getTitleQuietly(String youtubeUrl) {
try {
if (youtubeUrl != null) {
URL embededURL = new URL("http://www.youtube.com/oembed?url=" +
youtubeUrl + "&format=json"
);
return new JSONObject(IOUtils.toString(embededURL)).getString("title");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
second way i tried
class getYoutubeJSON extends Thread {
String data = " ";
#Override
public void run() {
try {
URL url = new URL("http://www.youtube.com/oembed?url="+" https://www.youtube.com/watch?v=a4NT5iBFuZs&ab_channel=FilipVujovic"
+ "&format=json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null){
data =data + line;
}
if(!data.isEmpty()){
JSONObject jsonObject = new JSONObject(data);
// JSONArray users = jsonObject.getJSONArray("author_name");
Log.d("RT " , jsonObject.toString());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This code gets a an error Cleartext HTTP traffic to www.youtube.com not permitted
so I found this answer Android 8: Cleartext HTTP traffic not permitted but I am still getting some error I don't understand.
I solved this problem by using the volley library.
My requested url was:
String Video_id = "jhjgN2d7yok";
String url = "https://www.youtube.com/oembed?url=youtube.com/watch?v=" +Video_id+ "&format=json";
Im trying to have a few getter methods for a few strings to get returned after getting them from an online JSON. In order to save space I decided to put that all in an object and call them from there.
Object:
public class InventoryItem extends AsyncTask<Void,Void,Void>{
String imageURL = "";
String itemName = "";
String itemDesc = "";
String itemRarity = "";
String itemType = "";
JSONObject itemJson = null;
InventoryItem(JSONObject json){
itemJson = json;
Log.d("StringSubclass","Inventory Item");
}
#Override
protected Void doInBackground(Void... voids) {
Log.d("StringSubclass","doInBG Inventory Item");
try {
imageURL = "http://www.bungie.net"+itemJson.getJSONObject("Response").getJSONObject("data").getJSONObject("inventoryItem").getString("icon");
Log.d("StringSubclass",imageURL);
itemName = itemJson.getJSONObject("Response").getJSONObject("data").getJSONObject("inventoryItem").getString("itemName");
itemDesc = itemJson.getJSONObject("Response").getJSONObject("data").getJSONObject("inventoryItem").getString("itemDescription");
itemRarity = itemJson.getJSONObject("Response").getJSONObject("data").getJSONObject("inventoryItem").getString("tierTypeName");
itemType = itemJson.getJSONObject("Response").getJSONObject("data").getJSONObject("inventoryItem").getString("itemTypeName");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public String getItemType() {
return itemType;
}
public String getItemRarity() {
return itemRarity;
}
public String getItemDesc() {
return itemDesc;
}
public String getItemName() {
return itemName;
}
public String getImageURL() {
return imageURL;
}
}
The problem is that the getter methods at the end send back "" even though I changed their value in doInBackground.
This is how I called getImageURL():
InventoryItem subclass = new InventoryItem(makeJSON(HOST+"Manifest/6/"+subclassHash+"/"));
subclass.execute();
Log.d("StringSubclass",subclass.getImageURL());
intentHome.putExtra("SubclassImageURL",subclass.getImageURL());
makeJSON():
public JSONObject makeJSON(String url){
JSONObject json = null;
String apiKey = "36c346318fa54fc6bc659ad6321a6d41";
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("X-API-KEY", apiKey);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
String response = "";
while ((inputLine = in.readLine()) != null) {
response += inputLine;
}
in.close();
JsonParser parser = new JsonParser();
JsonObject gson = (JsonObject) parser.parse(response);
json = new JSONObject(gson.toString());
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
I checked the URL and it is working fine in chrome.
Any help will be appreciated.
I kind of new to this so please explain as much as possible.
Thanks
How to solve error of getting same user information in login with Facebook for different user in my web application developed in Java?
Here is the main connection class to connect with facebook.
public class FBConnection
{
public static final String FB_APP_ID = "1729*******";
public static final String FB_APP_SECRET = "2c5******";
public static final String REDIRECT_URI = "http://example.com";
static String accessToken = "";
This method gives Code for getting access token from facebook.
public String getFBAuthUrl() {
String fbLoginUrl = "";
try {
fbLoginUrl = "http://www.facebook.com/dialog/oauth?" + "client_id="
+ FBConnection.FB_APP_ID + "&redirect_uri="
+ URLEncoder.encode(FBConnection.REDIRECT_URI, "UTF-8")
+ "&scope=email,public_profile";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return fbLoginUrl;
}
This method will generate graph url to fetch access token.
public String getFBGraphUrl(String code) {
String fbGraphUrl = "";
try {
fbGraphUrl = "https://graph.facebook.com/oauth/access_token?"
+ "client_id=" + FBConnection.FB_APP_ID + "&redirect_uri="
+ URLEncoder.encode(FBConnection.REDIRECT_URI, "UTF-8")
+ "&client_secret=" + FB_APP_SECRET + "&code=" + code;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return fbGraphUrl;
}
This method get access token from code got from redirect url.
public String getAccessToken(String code) {
if ("".equals(accessToken)) {
URL fbGraphURL;
try {
fbGraphURL = new URL(getFBGraphUrl(code));
} catch (MalformedURLException e) {
e.printStackTrace();
throw new RuntimeException("Invalid code received " + e);
}
URLConnection fbConnection;
StringBuffer b = null;
try {
fbConnection = fbGraphURL.openConnection();
BufferedReader in;
in = new BufferedReader(new InputStreamReader(fbConnection.getInputStream()));
String inputLine;
b = new StringBuffer();
while ((inputLine = in.readLine()) != null)
b.append(inputLine + "\n");
in.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Unable to connect with Facebook " + e);
}
accessToken = b.toString();
if (accessToken.startsWith("{")) {
throw new RuntimeException("ERROR: Access Token Invalid: " + accessToken);
}
}
return accessToken;
}
I have an android app that I am programming to post an array of data to a php file in local server. The data is in the format as bellow.
Name1->Quantity1
Name2->Qunatity2
I am trying to send it as json array but the problem is that whenever I am sending the data it shows that it is successful in posting that data. However i am not able to see any change of database that was suppose to be as a result of data that was sent form the android app. I will be thankful if someone guides or solves this problem of mine. please help me in this.
Bellow are the classes i am using to send and receive data
This is the class which is sending the data
public class Thirdscreen extends Activity {
private static String url = "http://10.0.2.2/bootstrap-dist/postingdata.php";
public ArrayList<QantityModelProduct> quantitymodel=new ArrayList<QantityModelProduct>();
// Progress Dialog
private ProgressDialog pDialog;
// Json parser object
JSONParser jsonParser = new JSONParser();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thirdscreen);
QantityModelProduct qmp;
TextView showCartContent = (TextView) findViewById(R.id.showCart);
TextView showCarttotal = (TextView) findViewById(R.id.showtotal);
Button btn = (Button) findViewById(R.id.subtractQuantity);
final Controller aController = (Controller) getApplicationContext();
int cartSize = aController.getCart().getCartSize();
String showString = "";
int total = 0;
for (int i = 0; i < cartSize; i++) {
String pName = aController.getCart().getProducts(i)
.getProductName();
int pPrice = aController.getCart().getProducts(i).getProductPrice();
int quantity = aController.getCart().getProducts(i)
.getProductQuantity();
int dataProQuantityStore = aController.getCart()
.getProducts(i).getDatabaseProductQuantity();
String pDisc = aController.getCart().getProducts(i)
.getProductDesc();
total = total + (pPrice * quantity);
showString += "\n\nProduct Name : " + pName + "\n" + "Price : "
+ pPrice + "\t" + "Quantity: " + quantity + "\n"
+ "Discription : " + pDisc + ""
+ "\n -----------------------------------";
//databaseQuantity-Current quantity
int finalVal = dataProQuantityStore - quantity;
String finalstringValue=""+finalVal;
qmp=new QantityModelProduct(pName,finalstringValue);
quantitymodel.add(qmp);
}
showCarttotal.setText("Your Total is: " + total + "Tk");
showCartContent.setText(showString);
final int productSize=quantitymodel.size();
Toast.makeText(getApplicationContext(),"Array size: "+productSize, Toast.LENGTH_SHORT).show();
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
new getQuantity().execute();
}
});
}
class getQuantity extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Thirdscreen.this);
pDialog.setMessage("Processing your request..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
JSONArray jsonArray = new JSONArray();
for (int i=0; i < quantitymodel.size(); i++) {
jsonArray.put(quantitymodel.get(i).getJSONObject());
}
jsonParser.getandpostJSONFromUrl(url, "POST",jsonArray);
return null;
}
#Override
protected void onPostExecute(String file_url) {
final Controller aController = (Controller) getApplicationContext();
// dismiss the dialog once done
pDialog.dismiss();
aController.getCart().clearCart();
aController.getProductsArraylist().clear();
Toast.makeText(getBaseContext(), "I am in second loop", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getBaseContext(), FirstScreen.class);
finish();
startActivity(i);
}
}
}
public class QantityModelProduct {
private String ProductName;
private String ProductQuantity;
public QantityModelProduct(String productName, String productQuantity) {
ProductName = productName;
ProductQuantity = productQuantity;
}
public JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
try {
obj.put("Name", ProductName);
obj.put("Quantity", ProductQuantity);
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
}
The following is the Json Parser Class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getandpostJSONFromUrl(String url, String method,JSONArray name) {
// Making HTTP request
try {
// defaultHttpClient
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(name.toString()));
HttpResponse httpResponse = httpClient.execute(httpPost);
httpPost.setHeader("jsonArray",json.toString());
HttpEntity httpEntity = httpResponse.getEntity();
int response = httpResponse.getStatusLine().getStatusCode();
is = httpEntity.getContent();
Log.e("posting Status", "Post status: " + response);
}
if (method == "GET") {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (method == "POST") {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
} catch (Exception e) {
Log.e("Buffer error", "Buffer error" + e);
}
} else if (method == "GET") {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
// return JSON String
return jObj;
}
}
and lastly the php file that is suppose to receive those datas.
?php
define('DB_NAME', 'sshop');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if(!$link){
die('could not connect: '.msql_error());
}
$db_selected=mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('Can not use '.DB_NAME.':'.mysql_error());
}
if (isset($_POST['jsonArray'])){
$jArray = json_decode($jsonArray,true);
foreach ($jArray['jsonArray'] as $obj) {
$ProductName = $obj['Name']; //String
$ProductQuantity= $obj['Quantity'];
$sql="Update productlist Set Quantity='$ProductQuantity' where Name='$ProductName';";
echo $ProductName." ".$ProductQuantity;
}
}else {
echo 'empty';
}
?>
Firstly, you should not be comparing strings using ==
Try this!
if (method.equals("POST"))
Next, to debug, see what data you are sending via the Android app to the PHP webservice, by sending the same request as response. So you know exactly if you are sending the data.
If the above step works fine, means the issue is on the PHP end. Use http://hurl.it or Postman client in Chrome to do a Post via browser, and then debug the PHP code. See if the data is being inserted.
This should solve your problem.
Nithin
I want to insert some items into the database. In the main activity, I retrieve information from the user and pass it to the another class to do some parsing. My JSONObject keeps showing up as NULL.
I am sorry if I am not clear with the question . I've tried to explain it as much as possible.
Below is the code your inputs are welcome
public class MainActivity extends Activity {
/** THE FOLLOWING STRINGS WILL BE DISPLAYED IN LOGCAT */
final String TAG = "########-------MAIN ACTIVITY: LOGIN--------######";
final String URL = "http://46.51.193.32/timereport/ses/sessions";
UserHelper userAdapter;
UserHelper db;
EditText edit_password,edit_username,edit_company;
String regName;
int duration = Toast.LENGTH_LONG;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db = new UserHelper(this);
userAdapter = new UserHelper(this);
edit_password = (EditText)findViewById(R.id.password);
edit_username = (EditText)findViewById(R.id.user_name);
edit_company = (EditText)findViewById(R.id.company_string);
Button login = (Button)findViewById(R.id.login_button);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
JSONObject jsonobj = new JSONObject();
try{
JSONObject subJson = new JSONObject();
subJson.put("username", edit_username.getText().toString());
subJson.put("password", edit_password.getText().toString());
subJson.put("company", edit_company.getText().toString());
jsonobj.put("user", subJson);
}
catch(JSONException e) {
Log.i("","#####-----error at catch jsonexception-----#####");
}
HandleJSON.SendHttpPost(URL, jsonobj);
String regNameSplit[] = regName.split("-");
try{
userAdapter.openDatabase();
long id = db.insertIntoDatabase(edit_username.getText().toString(),edit_company.getText().toString(), edit_password.getText().toString(),regNameSplit[0], regNameSplit[2]);
Toast.makeText(getApplicationContext(), "You have successfully logged in as: " +"\n" +regNameSplit[0], duration).show();
Log.i(TAG, "Printing value of id which will be inserted only to remove warnings "+id);
userAdapter.closeDatabase();
}
catch(SQLiteException e){
e.printStackTrace();
}
}
});
}
}
This is the class to which I am sending the JSON object to be parsed
public class HandleJSON{
UserHelper userAdapter;
private static final String TAG = "&&----HTTPClient-----**";
public static String SendHttpPost (String URL, JSONObject jsonobj) {
String regName = "";
try{
Log.v("Json object request is ",jsonobj.toString());
DefaultHttpClient httpClientInstance = GetHttpClient.getHttpClientInstance();
HttpPost httpPostRequest = new HttpPost(URL);
Log.v(TAG,"The url is "+URL);
StringEntity se;
se = new StringEntity(jsonobj.toString());
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpClientInstance.execute(httpPostRequest);
Log.i(TAG, "HTTPRESPONSE RECIEVED" +(System.currentTimeMillis()-t) + "ms");
String resultString = convertStreamToString(response.getEntity().getContent());
Log.v(TAG , "The response is " +resultString);
JSONObject jsonObj = new JSONObject(resultString);
JSONObject sessionJson = jsonObj.getJSONObject("session");
String sessionId = sessionJson.getString("sessionid");
String name = sessionJson.getString("name");
Log.v(TAG,"The session ID is "+sessionId);
Log.v(TAG,"The name is "+name);
regName = name+"-"+sessionId+"-"+URL;
} catch (Exception e){
e.printStackTrace();
}
return regName;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try{
while((line = reader.readLine()) !=null ){
sb.append(line + "\n");
}
}
catch (IOException e){
e.printStackTrace();
} finally{
try {
is.close();
} catch (IOException e){
e.printStackTrace();
}
}
return sb.toString();
}
}
I've just added some of the code that was missing at the MainActivity,
String regNameSplit[] = regName.split("-");
keeps showing up as null
Instead of your convertStreamToString() method try using system provided EntityUtils.toString(entity).
IMPORTANT: do not catch generic Exception, this hides unchecked (runtime) exceptions. You might be hiding the JSONException that happens in JSONObject constructor.
Update:
You are calling SendHttpPost and not assigning result to variable:
HandleJSON.SendHttpPost(URL, jsonobj);
should be:
regName = HandleJSON.SendHttpPost(URL, jsonobj);
I don't see anything wrong with this, could you tell me what is the use of regname ?
at your mainactivity just change the following:
regname = HandleJSON.SendHttpPost(URL, jsonobj);
Your not calling back regname to be assigned to name and sessionid that you are returning at the sendhttppost.