android,html,json,android-json , My json is appearing as a HTML when parsed (android)

My json is appearing as a HTML when parsed (android)


Tag: android,html,json,android-json

I'm trying to parse and get the values from a URL with JSON format. The format of the JSON when the URL is used in a browser is shown below:

{"CompanyID":"1","Message":"Not active user","Success":"false","UserID":"2"}

My JsonParser code is shown below:

import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


* Created by Fathi on 6/16/2015.
public class JsonParser {
final String TAG = "";

static InputStream is = null;
static JSONObject jObj = null;
static JSONArray jArray = null;
static String result = "";

public JSONArray getJSONFromUrl(String url) {

    // make HTTP request
    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);

        HttpResponse httpResponse = httpClient.execute(httpget);
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        Log.e(TAG, "JSON status code:  " + statusCode);

        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
    } catch (ClientProtocolException e) {
    } catch (IOException e) {

    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");
        result = sb.toString();
        Log.e(TAG, "JSON string:  " + result);

    } catch (Exception e) {
        Log.e(TAG, "Error converting result " + e.toString());

    // try parse the string to a JSON object
    try {           
        jArray = new JSONArray(result);

    } catch (JSONException e) {
        Log.e(TAG, "Error parsing data " + e.toString());

    // return JSON String
    return jArray;


The code I'm using in my activity is as follows:

    public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

    final String TAG = "";

    // set your json string url here
    String yourJsonStringUrl = "**MY URL COMES HERE**";

    // contacts JSONArray
    JSONArray dataJsonArr = null;

    protected void onPreExecute() {}

    protected String doInBackground(String... arg0) {

        try {

            // instantiate our json parser
            JsonParser jParser = new JsonParser();

            // get json string from url

            JSONArray jsonArray = jParser.getJSONFromUrl(yourJsonStringUrl);

            // loop through all users
            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject c = jsonArray.getJSONObject(i);

                // Storing each json item in variable
                String Success = c.getString("Success");

                // show the values in our logcat
                Log.e(TAG, "Success: " + Success);

            } } catch (JSONException e) {

        return null;

    protected void onPostExecute(String strFromDoInBg) {}

My Logcat is giving me the following error (I have the HTTP response and the string):

06-16 03:50:10.841    2470-2489/iss.voltappinterface E/﹕ JSON     status code:  200
06-16 03:50:10.911    2470-2489/iss.voltappinterface E/﹕ JSON string:  <html><head><title>Object moved</title></head><body>n<h2>Object moved to <a href="/voln
06-16 03:50:10.921    2470-2489/iss.voltappinterface E/﹕ Error parsing data org.json.JSONException: Value <html><head><title>Object of type java.lang.String cannot be converted to JSONObject

I can see that my JSON is being processed as HTML for some reason, and that is what I don't understand, seeing as it looks perfect in the browser. Any help would much appreciated.


Look at content-type header on your endpoint, it's probably text/html and should be application/json

Edit : As @Fathi Eid suggest, you can force the Content-type:

httpget.setHeader("Content-Type", "application/json");
httpget.setHeader("Accept", "application/json");

Note that is a fix and you should really consider changing the response content type on the api server and not in the client.


Android Espresso: Test running failed. No test results Empty test suite. Why?

Can't make my Espresso UI test work. Where's the problem? What result should I get for this simple app to consider that it's working? I have "" for Instrumentation runner in Edit Confirurations. From AndroidManifest.xml: <instrumentation android:name="" android:targetPackage="my.package"/> From build.gradle: defaultConfig { applicationId "my.package" minSdkVersion 18 targetSdkVersion 22 versionCode 1...

Dagger 2 Custom Scope for each Fragment

I'm a little confused about how to best use the custom scoping in Dagger 2. I've looked at a couple different articles which seem to suggest two different ways of doing it: MVP Presenters that Survive Configuration Changes Part-2 (Github repo): Uses unique custom scopes for each fragment, e.g. @Hello1Scope...

Div with the form of a pencil [duplicate]

This question already has an answer here: CSS triangle custom border color 2 answers How can i create a div with the form of a pencil, just like this: It seems a basic thing but im trying to do it since some time ago and still couldnt do it....

Android Implicit Intent for Viewing a Video File

In my Android app, I have a button that when clicked, launches the external application of my choice to play a video (I gather that this is called an "implicit intent"). Here is the relevant Java code from my onCreate method. Button button = (Button) findViewById(; button.setOnClickListener ( new Button.OnClickListener()...

submitting form then showing loading image by javascript

I am submitting a form and loading loading gif in the same div by replacing html of form by html of loading image. I am first submitting the form then loading gif, because I have to replace the content of div(in which form exist) with loading image. Logs 1,2,3 are...

Website showing differently in windows xp and mobile

I made a website for one of my clients, and I change the background and font color. Now on windows xp and smartphones the background changed color to the default color and the fonts remained the same. The website is I don't know what to do to make it...

Android set clickable text to go one fragment to another fragment

I need to do something like this. Suppose I have 2 fragments A and B.There is a text which can be clickable in fragment A and when user click this text , he can go to fragment B. This example helped me to do it but I think it does...

how does android ImageView resize my image?

I have some 100*100 icons and I cannot find better resolution icons so I put them inside drawable folder. The width and height of the image view are set to wrap_content. When the image is shown on a xhdpi screen will the image be scaled to 200*200 automatically? or should...

Why i get can not resolve method error in class android?

I use this tutorial: JSON and part of code to this: protected String doInBackground(String... urls) { TextView lbl=(TextView) findViewById(; person = new Person(); person.setName(lbl.getText().toString()); //person.setCountry("1853"); //person.setTwitter("1892"); return POST(urls[0],person); } but in the this line: person.setName(lbl.getText().toString()); i get this error: Can not resolve method. How can i solve that?what happen? my...

How to set speaker phone off when the app is killed by the “Recent App drawer”

I implemented an app which has a button speaker, which is manually set "on" by myAudioManager.setSpeakerphoneOn(true) and "off" vice-versa. But the bug is when you close the application while the speaker is on, it forgets the speaker was on. The next time, the speaker remains on and the call is...

Notification whenever a new topic is created on mosquitto

I am trying to implement Push notifications on Android, using Mosquitto broker. So, different android application create topics based on tehir id on which they will receive notifications. To send notifications to those android applications we need the name of the topic. I am wondering if there is a way...

Set value for Spinner with custom Adapter in Android

I am developing a android application with spinner in a form. The spinner items and spinner values are different. I want to collect all the value from the from including spinner and set a rest api service to web back end. here is the response array. {"Status":true,"errorType":null,"countryList":[{"Code":"US","Name":"United States"},{"Code":"CA","Name":"Canada"},{"Code":"AU","Name":"Australia"},{"Code":"GB","Name":"United Kingdom"}]} I...

Dynamically resize side-by-side images with different dimensions to the same height

I have two images side-by-side within a block-level container with arbitrarily different dimensions (as in, they could be any two images) that I want to dynamically adjust the width of so that the overall height of the two images is the same. I don't think this can be done in...

Unfortunately, (My app) has stopped. Eclipse Android [duplicate]

This question already has an answer here: What is a Null Pointer Exception, and how do I fix it? 12 answers I'm a beginner in android developing and I'm trying to build a simple app but I'm getting this error in the emulator.(Unfortunately,(App) has unexpectedly stopped). LogCat package...

Centering navbar pills vertically within the navbar using flexbox

I am terrible at CSS so I am having trouble centering my <li> (navbar pills) vertically for my navbar. This navbar is from twitter bootstrap Here is the HTML for my navbar: <div class="container"> <nav class="navbar navbar-default navbar-fixed-top"> <ul id="nav_pills" class="nav nav-pills" role="tablist"> <li role="presentation"> <a href="/">About</a> </li> <li role="presentation">...

Click on link next link should be display on same page

I have a single page website and need to link the navigation to IDs in the page. I have three links: "About us", "Our Project", "contact". So if user clicks on "About ", the About section will be displayed, same with other links. Inside Our project there is Two buttons...

show div only when printing

Let's say that I have <div id="printOnly"> <b>Title</b> <p> Printing content </p> </div> Is it possible to hide this div when page rendering and to show only when printing this div?...

tag in HAML

How do I create a I-tag in haml? Example: <i class="fa fa-search"></i> ...

Is there any sdk to log exceptions, events and errors in production app?

I want to catch all the un expected/undesirable events in my app during production. I want something which can send a error log file to server and I can easily read it through a web application. Do you know anything of this sort ?

Floating Action Button in Xamarin.Forms

I had completed my App's home page in Xamarin.Forms Portable. Now i want to add a Flotation Action Button In my Android Project ! Is there any way to add FAB for Android in my existing home page, which was coded in Xamarin.Forms Portable. OR I want to create a...

Get elements containing text from array

I want to search all the elements containing any string in the array. For example I have following list of items <ul> <li>cricket bat</li> <li>tennis ball</li> <li>golf ball</li> <li>hockey stick</li> </ul> and this array var arr = ['bat', 'ball']; It should select all the elements having text bat and ball....

change css dynamically by selecting dropdown list item

I have the following Dropdownlist with yes or no options-:` <asp:DropDownList ID="ddlchangecss" runat="server"> <asp:ListItem Text="yes">yes</asp:ListItem> <asp:ListItem Text="no"></asp:ListItem> </asp:DropDownList> i want to add a css dynamically like that-: .imgFullWidth { width: 100%; height: auto; float: left; margin: 0px 0px 20px 0px; } when I select yes option in Dropdownlist. How can...

How to make background body overlay when use twitter-bootstrap popover?

Currently I used this twitter-bootstrap popover: <button type="button" class="btn btn-default" style="margin-top:11px; padding-bottom:4px; padding-top:4px;" data-container="body" data-toggle="popover" data-trigger="focus" data-placement="left" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus."> Upgrade The output: How I can make the background overlay like bootstrap modal? My expected output I use this jquery to popover $(function(){ $('[data-toggle="popover"]').popover({ placement...

Automatically calling server side class without

I have an anchor which calls a server side class when clicked, but I want to modify it so that the class is called as soon as the page loads, without having to click an anchor. <a href="#" class="_repLikeMore" data-id="1234" data-type="pid" data-app="forums"> ...

how to add menu items to action bar in more than 30 activities

I have created an app in android studio that has more than 30 activities .I created menu items in some activities by adding them in individual menu files and they worked fine . But the problem is that it is a real headache to add all the menu items in...

How to resolve Out of Memory Error on Bitmap in Android?

I want to set an image in image view,I am retrieving the image path in my first activity and I am passing it via intent as a String to second activity.In the second activity I set the path to an image view,It is working properly , and I need to...

CSS :hover that shows more than one image

I have an icon on my website. I want to change the icon to 4 different images when ever I hover over the first one. So I know how to switch between the regilar image to yellow0.png, but how do I continue to the next one (after half a second...

Get current latitude and longitude android

Requirement: 1.Sometimes(not everytime) I am getting latitude and longitude 0.0. 2.I want to know how to get the location update after user has enabled the gps from the settings. Here is my code public class GPSTracker extends Service implements LocationListener { private final Context mContext; // flag for GPS status...

Target next instance of an element/div

I have the following HTML structure and JavaScript file: .html <li> <button class="show-more"></button> some more elements <div class="hidden"></div> </li> JavaScript $( ".show-more" ).click(function() { event.preventDefault(); $( this ).next().slideToggle( "fast", function() { }); }); I need the click event to toggle the next first instance of .hidden, however the click event...

custom arraylist get distinct

is there any way to get the distinct values of a custom arraylist? public class mystatistic extends BaseActivity { public String objectid; public String playerid; public String playername; public String enemyid; public String enemyname; public String question; public mystatistik(String objectid, String playerid, String playername, String enemyid, String enemyname, String question)...

why i don't get return value javascript

When i debug my code i can see i have value but i don't get value to createCheckBoxPlatform FN function createCheckBoxPlatform(data) { var platform = ""; $.each(data, function (i, item) { platform += '<label><input type="checkbox" name="' + item.PlatformName + ' value="' + item.PlatformSK + '">' + item.PlatformName + '</label>' +...

Keep HashMap with object data while app is idle - Android

I have a HashMap that contains data relevant to a specific Activity. The problem is that when the app is opened after being idle for some time, the HashMap is empty. I am fetching all the data in the main activity and storing the corresponding objects in a HashMap in...

Top header 100% of screen, but body only 70%?

Pretty new to CSS and just having quite a bit of trouble, I've tried everything, searched here, but can't seem to make it work. Right now my header/body are both 70% of the screen. However I want my top header (.mainheader) to be 100% of the screen, but have the...

Can I install 2 or more Android SDK when using Eclipse

I am new to android developments. I am setting up my android development environment using Eclipse. I have a test smart phone with Android version 4.2.2. The automatic installation installed the latest Android SDK version, which is 5.1.1. My questions are: 1. Do I have to install the SDK version...

Android String if-statement

I have a if-statement in the start of my app if (ready.equals("yes")){ ... } and later on my code I have ready="yes"; but the if statement is never called, why? The ready="yes"; is called from a background thread, is that why? public void DownloadFromUrl(final String fileName) { //this is the...

Fixed element in android?

I am using a FAB(Floating action button) and a ViewPager that has a list inside a fragment. The ViewPager stops due to the FAB block and each are blocks the ViewPager being on top of the FAB activity_main.xml <LinearLayout xmlns:android="" xmlns:tools="" xmlns:fab="" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:fitsSystemWindows="true">...

Getting particular view from expandable listview

In my list view I have an textview in expandable group and I want to open the dialog when textview is clicked to fill the information through edittext and update textview. Problem: how could I get the groupview textview item in my fragment oncreateview() method....

How to remove all the borders of a selectbox?

How can I remove the all the borders of the selectbox using css or Jquery ? My code, <select id="doctor_ch"> <option value="1" selected>One</option> <option value="2">Two</option> </select> CSS #doctor_ch{ background-color: #88AFF2; color:#fff; margin-top: 15px; } When I use this code it only changes the arrow style. I want to remove the...

How do I display my mysql table column headers in my php/html output?

2 Questions... Scenario: I would like to query my database table via a form and then display the results that occur(if there are results) and my current situation is that it does work but it clears the form completely and leaves my to an empty page with just the results...

BitmapFont class does not have getBound(String) method

Previously I used getBound method for BitmapFont class in libgdx, but now, I am unable to use it. I cannot find the changes in latest version. Any help is appreciated. Thank you...

Dynamically select from a dynamically generated dropdown

I have a dynamically generated dropdown list - list of course identifiers and names. On the basis of a variable, “assigned_course_id”, I would like to preselect the appropriate value from the dropdown list. My best attempt is as follows. Thanks in advance for your assistance. <select name="course_id" id="course_id"> <?php $assigned_course_id...

Detect when the jQuery UI slider is being moved?

I have this custom video time UI slider to change the time of the YouTube video when scrubbed. My problem is that when the video is trying to load when the user is moving the slider, it causes the handle to jerk around and flip around. What I'm trying to...

why is Android app publishing taking several days [on hold]

I have uploaded my app on the store 3 days ago and it status still : PENDING PUBLICATION I have uploaded all the app listing needed : description, screen shots ... and google didn't contact me on E-mail. does anyone had the same case before ???...

Is there any way to use a pre-existing database from Xamarin without copying it from Assets?

I have a rather large SQLite database (~20 mb) I need to access from my Android Xamarin-Forms app. Everything online I've read says you can read the database by copying it to the filesystem first. For example, this question. However, won't that mean the large database is duplicated, wasting users'...

Problems implementing ViewHolder pattern

I'm working on an android app from a book. I'm getting errors : "crimeHolder cannot be resolved" and I can't understand why.. public View getView(int poisition, View convertView , ViewGroup parent) { //If we weren't given a view, inflate one if (convertView == null) { convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_crime, null); ViewHolder...

CSS - Linear Gradient Background Color no-repeat is not working for if it has multiple tds

I want to apply css3 gradient (left and right transparent) background color for a TR element like below. Below code is working fine if it has only one TD element, where as more than one td, background gradient started repeating for each td... Am I missing something? Online Demo CSS...

Android custom calendar view disable specific dates

i'm new to android developing and started to develop an booking app. There is a calendar view and i want to disable booked dates in that calendar. I found out that disabling feature is not there in android default calendar. so could you please help me to find a good...

How to remove unmatched row in html table using jquery

I have two tables. I want to delete unmatching rows. Compare with first column in Table1 and compare with first column in Table2. Table1 111 aaa 222 bbb 333 ccc Table2 333 xxx 444 zzz 111 vvv result of Table2 333 xxx 111 vvv I tried some thing here Please...

Twitter4j - cannot resolve method - setUsessl(boolean)

I'm using twitter4j 4.0.3 core I have this code: public final class TwitterUtil { private RequestToken requestToken = null; private TwitterFactory twitterFactory = null; private Twitter twitter; private TwitterUtil() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setOAuthConsumerKey(ConstantValues.TWITTER_CONSUMER_KEY); configurationBuilder.setOAuthConsumerSecret(ConstantValues.TWITTER_CONSUMER_SECRET); configurationBuilder.setUseSSL(true); Configuration configuration =...

Android programming, draw a rectangle with specific coordinates

I am new to android programming. I am trying to draw a rectangle as in the image below. I have no idea how to do it with Rect(int left, int top, int right, int bottom). Can someone help me with this thanks. ...