mercredi 5 août 2015

Tornado - why does static files without StaticFileHandler donot work?


I am new to Tornado. I am trying to link a CSS file to the html template. I am using jinja2 with Tornado. But due to some unknown reasons the CSS file is not loading up.

EDIT: I have created my custom render_template function which is working fine.

Here is my Request Handler's Class:

class Index(RequestHandler):
def get(self):
    path = os.path.join('static/css/', 'custom.css')
    return self.write(render_template('index.html', path = path))

and here is my index.html template:

<!Doctype html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="{{path}}"/>
  </head>
  <body>
    <div>
      <div class="header">
         asdasdasd
      </div>
    </div><!--wrapper-->
  </body>

</html>

but the browser is returning the 404-NotFound error for the css file with the correct url, that is http://localhost/static/css/custom.css



via Chebli Mohamed

How to make div in grid view be of 90% height of page


I want to create grid view, where header contains 10% height of the page and body 90%.

I have tried to adjust this, but body part does not grow when element section on right hand scales.

I want to add elements in right panel in responsive manner.

Is there any good way to organize this?

fiddle: http://ift.tt/1W1eZGO

<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-xs-12" style="background-color:lavender;">
            <div class="header">Header Height should be 10% of the page</div>
        </div>  
    </div>

    <div class="row" >
        <div class="col-xs-8" style="background-color:lavenderblush; height:100%">Body, Height should be 90% of th page
        </div>
        <div class="col-xs-4" style="background-color:lavender;">
            <!-- 12 repeated rows as below, height should fit in 90% region in responsive manner -->
            <div class="row" >
                <div class="col-xs-6" style="background-color:lavender;">
                    <div class="element-box">Item1</div>
                </div>
                <div class="col-xs-6" style="background-color:lavender;">
                    <div class="element-box">item2</div>
                </div>
                <div class="col-xs-6" style="background-color:lavender;">
                    <div class="element-box">Item3</div>
                </div>
                <div class="col-xs-6" style="background-color:lavender;">
                    <div class="element-box">item4</div>
                </div>
                <div class="col-xs-6" style="background-color:lavender;">
                    <div class="element-box">Item5</div>
                </div>
                <div class="col-xs-6" style="background-color:lavender;">
                    <div class="element-box">item6</div>
                </div>
                <div class="col-xs-6" style="background-color:lavender;">
                    <div class="element-box">Item7</div>
                </div>
                <div class="col-xs-6" style="background-color:lavender;">
                    <div class="element-box">item8</div>
                </div>
                <div class="col-xs-6" style="background-color:lavender;">
                    <div class="element-box">Item9</div>
                </div>
                <div class="col-xs-6" style="background-color:lavender;">
                    <div class="element-box">item10</div>
                </div>
                <div class="col-xs-6" style="background-color:lavender;">
                    <div class="element-box">Item11</div>
                </div>
                <div class="col-xs-6" style="background-color:lavender;">
                    <div class="element-box">item12</div>
                </div>
         </div>
     </div>
</div>

</body>



via Chebli Mohamed

How to add video to html using flash player


I want to add video which is of format (mp4) to my page using flash player (not html5). I have tried this using Flowplayer but I am not able to do this:

<html>
    <head></head>
    <body>
        <div class="flowplayer is-splash"
            data-engine="flash"
            data-swf="../dist/flowplayer.swf">
            <video src="http://ift.tt/1MNeWKX" preload="none"></video>
        </div>
    </body>
</html>

Can someone please explain this? I searched a lot experimented a lot but didn't get results.



via Chebli Mohamed

Accepting and displaying HTML tags in Spring MVC Blog application


I am building a custom Blog using Spring MVC. This will have an administration module, where the Blog owner can manage articles.

The owner should be able to add HTML tags, which should then later on be displayed on the articles when a user looks at them. I.e. the owner should be able to build up the article by inputting something like:

<p>This is displayed as a paragraph <b>and this in bold</b></p>

Which should then be later on be placed as "real" html code in the article placed by Thymeleaf.

So basically, I want to be able to display actual HTML tags using thymeleaf.

What are things I should take into consideration and does Spring MVC already offer something to mitigate any security implications (for example, against XSS in case my owner's account is hijacked)?



via Chebli Mohamed

Submit datepicker with ajax


i'm having issues with submiting my datepicker.

I use the code below to load my datepicker page and other 2 pages in the page i want.

in the below html i load 3 external pages and one of those is my datepicker. every time i submit the datepicker nothing happens.

if i don't load the page via ajax, when i click on submit the data is send successfully to the database.

What do i need to change in my javascript file so i can make this working.

Thanks

$(document).ready(function() {
    //initial
    $('#content').load('content/index.php');


    //handle menu click
    $('ul#nav li a').on('click', function() {
        var page = $(this).attr('href');
        //$('#content').load('content/'+ page +'.php');

        $.ajax({
            url: 'content/'+ page +'.php',
            context: document.body,
            success: function(response){
                $('#content').html(response);   
                console.log(response);      
            }
        });

        return false;
    });
});

<html>
    <head>
        <link rel="stylesheet" href="css/style.css" />
        <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

        <script src="http://ift.tt/1E2nZQG"></script>
        <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
        <script src="js/general.js"></script>
    </head>
    <body>
        <div class="selector">
            <ul id="nav">
                <li><a href="index">Profil</a></li>
                <li><a href="planner">Planificare concediu</a></li>
                <li><a href="data">Usefull data</a></li>
                <li></li>
                <a href="logout.php">Logout</a>
            </ul>
            <div id="content"></div>    
        </div>

    </body>
<html>



via Chebli Mohamed

Detect if a textbox does not contain certain words


I want to know how to detect if a textbox does not contain certain words. For example if the textbox did not contain 'who', 'what', 'why', 'when' or 'where' some sort of function would run.

JavaScript:

function command() {
    var srchVar = document.getElementById("srch");
    var srch = srchVar.value;
    var t = srch;
    if (srch == '') {
        alert('Please do not leave the field empty!');
    }
    else if (srch.indexOf('time') != -1) {
        alert('The current time according to your computer is' + ShowTime(new Date()));
    }
    else if (srch.indexOf('old are you') != -1) {
        alert("I am as old as you want me to be.");
    }
    else {
        if (confirm('I am sorry but I do not understand that command. Would you like to search Google for that command?') == true) {
            window.open('http://ift.tt/1IMorZb' + srch, '_blank');
        }
        else { /* Nothing */ }
    }
}

HTML:

<!DOCTYPE html>
<html>
<head>
    <script src="script.js" type="text/javascript"></script>
    <link href="http://ift.tt/1f1Mm3V" rel="stylesheet">
    <script src="http://ift.tt/1dLCJcb"></script>
    <script src="http://ift.tt/1fJwIAs"></script>
</head>
<body>
    <div class="ui-widget">
        <input class="search-field" id="srch" onkeypress="searchKeyPress(event);" placeholder="ask me anything" spellcheck="false">
    </div>
</body>
</html>



via Chebli Mohamed

Trigger event on new line in contentediable div


I am trying to listen for an event that indicates a new line has been created in a contenteditable div. The purpose is to eventually show a user some options each time a new empty line is created and the caret is on that line, or if the user clicks the caret position to a currently empty line.

In my book there seem to be three events that would lead to the user being on a new line within a contentediable div:

  • pressing enter
  • pasting content that has a empty new line at the end
  • clicking the caret position to an empty line

of course in a contentediable div a new line means different things to different browsers, in chrome it seems to create <p></p> tags, but having browsed around SO enough it seems that other browsers might create <div></div> or perhaps another tag - <br/>

I've now tried to figure this out a couple of times and just have to get it done. Is it really the best way to listen for new elements being added under that div, and/or check if the caret position is currently within empty 'new line' tags. checking each time the caret moves seems highly inefficient - is there a better way to do this?

To summarise for tldr; people

  • is there a better way to check for new lines in contenteditable divs
  • how would i trigger an event based upon that efficiently

Just fyi this is within an Angular context and I have jQuery also.



via Chebli Mohamed

how to keep php output lines in one line


I just made a phone number to time zone converter and it displays result as:

Requested Phone No.: +1 732 78782722

Country: United States

Expected Region: Newark, New Brunswick

Timezone: America/New_York

Date: 2015-08-05

Time: 01:51:03 am

What I want to do is place all these outputs in a single line. Here's my output code

      if(!empty($record['country_name'])) {
            $this->display('<strong>Country:</strong> ' . $record['country_name']);
        }

        if(!empty($record['city'])) {
            $this->display('<strong>Expected Region:</strong> ' . $record['city']);
        }

        //echo json_encode($date); 

        if(!empty($record['zone_name'])) {
            $this->display('<strong>Timezone:</strong> ' . $record['zone_name']);
            $this->display('<h2><strong>Date:</strong> ' . date('Y-m-d') . '</h2>');
            $this->display('<h2><strong>Time:</strong> ' . date('H:i:s a') . '</h2>');
        }

Thanks for the help.



via Chebli Mohamed

Binding mouse events to dynamically created select


I have created select tag dynamically in jquery function. I want to bind the mouse events to it. I have dynamically created the selct tag

function loadValues()
{
var sel='<select id="flavor_slct'+index+'" class="popper" data-popbox="pop1"     

onclick="alert()">'+flavor_fetched_string+'</select>';
$("#attach").append(sel);

}

I have tried using the .on() jQuery function. Still events are not triggered.

$("body").on("hover","Select",function()
    alert("hovered");
)};

How should i bind events to dynamically created elements.?



via Chebli Mohamed

Copying a email will returns html [on hold]


I've created a list of different email links, however when i'm on the page trying to copy a email it will return email with the tags aswell is there any javascript code or something like this that can avoid this?



via Chebli Mohamed

Getting elements from table row within different tables with Javascript


i need help with returning some elements from tr with javascript(jquery)

Question 1. How can i reach td where is comment "i need to get to this item (based on question1)"? So i need to get last item with class "b" and first td that comes after it? Number of td's is not static. Classes b may not be in same table.

Question 2. Also if I want to select class "a" and give next 5 (for example) td's some class ("b" for example) how can i do it? Function nextAll can help but it will only get elements from single row.

Example is below:

<table>
<tr>
  <td></td>
  <td></td>
  <td class="a"></td>
  <td></td> <!-- this needs to get class b -->
  <td></td> <!-- this needs to get class b -->
  <td></td> <!-- this needs to get class b -->
</tr>
</table>

<table>
<tr>
  <td></td> <!-- this needs to get class b -->
  <td></td> <!-- this needs to get class b -->
  <td></td> <!-- i need to get to this item (based on question1) -->
  <td></td>
  <td></td> 
  <td></td>
</tr>
</table>

Thanks



via Chebli Mohamed

Javascript - Drag´n´Drop Script


At first here is my Fiddle:

So maybe it won´t work on Fiddle because the window size is too small. Here are the problems I have and I can´t solve after trying it for 8 days -.- . 1.Deactivate Drag option after once dropped: So once an item was dropped it shouldn´t be draggable anymore , so how is it possible to do this? 2.I can´t drop my items in the e.g. 6. or 7. row. 3.Everytime I try to add instead of a text in the header an image it won´t appear. 4.Also my footer doesn´t appear.

I hope someone can help me please, And sorry for my bad english :| Greetz



via Chebli Mohamed

Check if textbox contains a number


I'm currently working on a digital assistant website which is based around JavaScript and jQuery. The user can type in questions or tell the assistant things into the textbox and the assistant will respond with something relevant to the input. What I am planning to implement is to check if the textbox contains a number (intager) and if it does some sort of function will run. The concept sounds fairly simple and but I am having trouble. I have been searching around for a bit but I can't seem to find anything which will work with my code.

I will add my JavaScript and the nessacary parts of the HTML. But I am warning you, the code is messy.

JavaScript:

// JavaScript Document
function submitted() {
    var srch = document.getElementById("srch");
    command();
    getPlaceHolder();
    srch.value = "";
}

function searchKeyPress(e) {
    e = e || window.event;
    if (e.keyCode == 13) {
        //document.getElementById('btn').click();
        submitted();
    }
}

function goBtn() {
    submitted();
}

function refreshBtn() {
    getWelcome();
}

function stClock() {
    window.setTimeout("stClock()", 1000);
    today = new Date();
    self.status = today.toString();
}

function getWelcome() {
    var ar = new Array(20)
    ar[0] = "What's on your mind?";
    ar[1] = "How can I help?";
    ar[2] = "Anything you need help with?";
    ar[3] = "Ask me anything";
    ar[4] = "What can I help you with?";
    ar[5] = "What would you like me to do?";
    ar[6] = "What can I do for you?";
    ar[7] = "Need help with anything?";
    ar[8] = "Need someone to talk to?";
    ar[9] = "I'm here to help";
    ar[10] = "Anything you need to know?";
    ar[11] = "How else can I help?";
    ar[12] = "What can I do now?";
    ar[13] = "Need anything?";
    ar[14] = "Any problems you need solving?";
    ar[15] = "Hello, how do you do?";
    ar[16] = "Hi there";
    ar[17] = "Hi, I'm aurum";
    ar[18] = "Hello there";
    ar[19] = "How do you do?";
    var now = new Date();
    var sec = now.getSeconds();
    document.getElementById('output').innerHTML = ar[sec % 20];
}

function getPlaceHolder() {
    var ar = new Array(20)
    ar[0] = "What's on your mind?";
    ar[1] = "How can I help?";
    ar[2] = "Anything you need help with?";
    ar[3] = "Ask me anything";
    ar[4] = "What can I help you with?";
    ar[5] = "What would you like me to do?";
    ar[6] = "What can I do for you?";
    ar[7] = "Need help with anything?";
    ar[8] = "Need someone to talk to?";
    ar[9] = "I'm here to help";
    ar[10] = "Anything you need to know?";
    ar[11] = "How else can I help?";
    ar[12] = "What can I do now?";
    ar[13] = "Need anything?";
    ar[14] = "Any problems you need solving?";
    ar[15] = "Hello, how do you do?";
    ar[16] = "Hi there";
    ar[17] = "Hi, I'm aurum";
    ar[18] = "Hello there";
    ar[19] = "How do you do?";
    var now = new Date();
    var sec = now.getSeconds();
    document.getElementsByName('srch')[0].placeholder=ar[sec % 20];
}

function command() {
        var srchVar = document.getElementById("srch");
        var srch = srchVar.value;
        var t = srch;
        var outputElement = document.getElementById('output');
        if (srch == '') {
            outputElement.innerHTML = "How can I help you, if you don't say anything?";
        }
        else if (srch.indexOf('about') != -1) {
            outputElement.innerHTML = "Hello, I'm Aurum. I was designed by Omar Latreche to help people answer their questions. However, I also like to talk to people aswell as answer their questions.";
        }
        else if (srch.indexOf('time') != -1) {
            outputElement.innerHTML = 'The current time according to your computer is' + ShowTime(new Date());
        }
        else {
            if (confirm("I am sorry but for some reason I don't understand. You could either repeat that or would you like to search Google for that instead?") == true) {
                window.open('http://ift.tt/1ANNWBe' + srch, '_blank');
            }
            else { /* Nothing */ }
        }
    }
    //Show time in 12hour format
var ShowTime = (function() {
    function addZero(num) {
        return (num >= 0 && num < 10) ? "0" + num : num + "";
    }
    return function(dt) {
        var formatted = '';
        if (dt) {
            var hours24 = dt.getHours();
            var hours = ((hours24 + 11) % 12) + 1;
            formatted = [formatted, [addZero(hours), addZero(dt.getMinutes())].join(":"), hours24 > 11 ? "PM" : "AM"].join(" ");
        }
        return formatted;
    };
})();

And the HTML:

<!DOCTYPE html>
<html>
<body onload="getWelcome(); getPlaceHolder();">
    <div class="output" id="output">
        An error has occoured. Please make sure you have JavaScript enabled in your browser.
    </div>
    <div class="cont">
        <div class="ui-widget">
            <div class="search-cont">
                <input class="search-field" id="srch" name="srch" onkeypress="searchKeyPress(event);" placeholder="ask me anything" spellcheck="false"> <input class="refresh" onclick="refreshBtn()" title="Refresh the conversation" type="button"> <input class="go" onclick="goBtn()" type="button">
            </div>
        </div><br>
    </div>
</body>
</html>

I really appreciate any help provided. Thanks, Omar.

PS. I apologies for the long paragraph but that is the only way I could think to explain what I need.

PPS. If you need any more information on my project just incase, the URL is http://ift.tt/1InGUrg



via Chebli Mohamed

Will page automation with PhantomJS be lost after a page redesign?


I'm quite new to PhantomJS. I want to do page automation with PhantomJS to a web site by manipulating the HTML elements (for example: taking buttons/links by their IDs and triggering clicks) and going from one page to another and doing the same things.

What I was wondering is: This is actually a web system that is created and belongs to some company, so in the future if they decided to make a complete redesign to their system my whole work will be lost, since they will have completely new design with new HTML structure and new IDs of elements. Is that correct? Is there a way to handle this problem?



via Chebli Mohamed

Active menu Changer on Sticky Bar


I have designed a Parallax Page with Sticky Menu bar. I need to change the active menu on scrolling. I have made it to change the active class on Click event. But I need it to do for the scroll event.

Here is my HTML Code

<div class="main-menu">

    <ul>             
        <li><a class="active" href="#" data-delay="2000" data-appear="false" data-scrollto="#intro-slideshow">Home</a></li>
        <li><a href="#" data-delay="2000" data-appear="false" data-scrollto="#overview">Features</a></li>
        <li><a href="#" data-delay="2000" data-appear="false" data-scrollto="#categories">Categories</a></li>
        <li><a href="#" data-delay="2000" data-appear="false" data-scrollto="#contact">Contact Us</a></li>
    </ul>

</div>

Here is my JQuery Code for Onclick Active Menu Changer

$('*[data-scrollto]').click(function(){

        $( "a" ).removeClass( "active" );
        $(this).addClass("active");

        var dest = $(this).data('scrollto');                
        var pixels = $(dest).offset().top - 70;         
        var ms = Math.round(1000 + pixels/5);

        $('html, body').animate({               
            scrollTop: pixels
        }, ms, 'easeOutQuint');

    }); 

How do I change the active class on Scroll Event with the Data-Scrollto attribute ?



via Chebli Mohamed

Edit and Save Pivot Table in Database in ASP.NET


I want to create an ASP.Net web page which will have one DropDownList control and upon changing the selection of it. Pivot table should be created. The Column Headers and Row Headers of this table should come from Database. The values shown in this table will also be retrieved from Database with respect to the corresponding Column Header and Row Header. This table values should be editable and upon "SAVE" button click the Data in values should be saved in database for corresponding Column Header and Row Header. example:

           |   Lot1   |   Lot2  |   Lot3 |  ...
---------------------------------------------
Product1   |    100   |  2000   |   3000 |  ...
---------------------------------------------
Product2   |    1000  |  3000   |   4000 |  ...
---------------------------------------------
Product3   |    3500  |  6000   |   4500 |  ...
---------------------------------------------

. . These values should be editable and upon save button click these should save in database with respect to Lot number and Product.



via Chebli Mohamed

Change style of element which appears directly before another element on the same level


My issue is as follows: I've got a navigation bar with main navigation and some of these links have additional drop down menus. I'm trying to change the styling of the main link, whenever I hover over the drop down menu. I can't use classes as it will change the style of all the main nav links. Which means I can't use the following method

.dropdown:hover ~ .main{
    change css here
}

I also can't use individual IDs for the linked drop down and main nav as it appears on too many pages already.

The format of the HTML is as follows

<a class="main-link">Main Link</a>
<div class="drop-down"></div>

My question is; is there a way to change the style of an element which appears directly before an element within a HTML document?



via Chebli Mohamed

How to remove � sign from whole site in wordpress


I have uploaded wordpress site on live , then the one "�" sign is being appearing in between content , but it is fine in local. How to remove please suggest me ? I am not able fix the problem.

Example - Frédèric becomes Fr�d�ric.



via Chebli Mohamed

How to automatically sum input value boxes on each row in a HTML table


I have an HTML table with columns of input boxes(Quantity, Price, Discount and Total). I made a JS function for adding as many rows as I need. I would like to make the Total column, for each row, to display automatically the value of this formula:

(Quantity * Price) - ( Quantity * Price * (Discount/100)) .

I tried numerous JavaScript code, but I have been unable to get anything to correctly work.

HTML:

<table id="myTable">
<tr>
<th width="65%"></th>
<th align="center" width="5%">Q<br>-ty</th>
<th align="center" width="10%">Price,</br>$</th>
<th align="center" width="5%">Discount,<br>%</th>
<th align="center" width="15%">Total, $<br>(Without tax)</th>
</tr>
<tr>
<td width="65%"><input class="Left" size="100" type="text" name="Description"></td>
<td align="center" width="5%"><input type="number" name="quantity" min="1" max="99"></td>
<td align="center" width="10%"><input type="number" name="summ" min="0" max="999999"></td>
<td align="center" width="5%"><input type="number" name="rate" min="0" max="100"></td>
<td align="center" width="15%"><input align="center" type="number" name="total" min="0" max="99999999"></td>
</tr>
</table>
<button onclick="addRow()">Add Row</button>

Javascript:

function addRow() {
    var table = document.getElementById("myTable");
    var row = table.insertRow();
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    var cell4 = row.insertCell(3);
    var cell5 = row.insertCell(4);
    cell1.innerHTML = "<input class=\"Left\" size=\"100\" type=\"text\" name=\"Description\">";
    cell2.innerHTML = "<div align=\"center\"><input type=\"number\" name=\"quantity\" min=\"1\" max=\"99\"></div>";
    cell3.innerHTML = "<div align=\"center\"><input type=\"number\" name=\"summ\"  min=\"0\" max=\"999999\"></div>";
    cell4.innerHTML = "<div align=\"center\"><input type=\"number\" name=\"rate\"  min=\"0\" max=\"100\"></div>";
    cell5.innerHTML = "<div align=\"center\"><input type=\"number\" name=\"total\" min=\"0\" max=\"99999999\"></div>";
}

My code on FIDDLE.



via Chebli Mohamed

How to prevent an iframe to display external websites?


Let's say I display an iFrame on iframe.domain.com. I want this iframe to be able to display content from iframe.domain.com or sub.domain.com. But those websites contain link to external websites, for example google.com. If the users clicks on a link redirecting him to google.com, I want the iFrame to be redirected to sub.domain.com

How can I do that?



via Chebli Mohamed

is it possible to connect mysql db using angular js without php code


Is it possible to connect MySql db using angularjs without PHP code? based on client side scripting we can't connect MySql db. Is it any other way to connection?



via Chebli Mohamed

Strip all unwanted tags from html string but preserve whitespace in JS


I am trying to strip my html content of all unwanted tags and just return text with basic formatting (ul, b, u, p etc) or just plain text (but preserving new lines, spacing etc) however I am having trouble creating a catch all solution which will let me keep the structure of the content that I pasted.

Example string:

    <p class="Bodytext" style="color: rgb(51, 51, 51);background-color: rgb(255, 255, 255);">
        <span lang="EN-GB">Hello
            <span class="Apple-converted-space"> world,   </span>
            <span class="Cross-reference">
                <a href="" style="color: rgb(66, 139, 202);background-color: transparent;">Cough
                </a>
            </span>
            <span class="Apple-converted-space"></span>and
            <span class="Apple-converted-space"></span>
            <span class="Cross-reference">
                <a href="" style="color: rgb(66, 139, 202);background-color: transparent;">Feverish - risk assessment</a>
            </span>.
            <span class="Apple-converted-space"></span>
        </span>
    </p>
    <p class="Bodytext" style="color: rgb(51, 51, 51);background-color: rgb(255, 255, 255);">
        <span lang="EN-GB">Fin.  </span>
    </p>



via Chebli Mohamed

Attach div to the right of another div


I have a div which is like a container and inside of it there are 2 images. One image is on the left side of the div and the other is on the right. My container is Bootstrap's container

Both of them are wrapped with a div, and that div's position is fixed.

My problem is that I can't locate the right image to be attached to the right side of the conatiner. I tried the float and the right properties but they not give the expected result.

How can I attach div to the right of another div?



via Chebli Mohamed

How can I show a foundation.css dropmenu by jQuery


I tried to write a nav bar with foundation.css, but the sub-menu does not show when mouse move on.

The question is, how can I show the sub-menu of test in this webpage.

I tried to change the visibility, display, z-index, left, but nothing happend.



via Chebli Mohamed

Button get disappeared in IE 9 while using disabled prop


<button type="button" id="update">Submit</button>
<button type="button" id="updated">Update</button>

 $("#updated").click(function(){
     $("#update").prop('disabled',true);
 })

Hi,

I want disabled button,when I am using above It works fine for all browser,except some versions of IE like IE 9,In IE 9 button get disappeared when I am using above code.

can anybody say me why this happen.

Thanks, Nandkishor



via Chebli Mohamed

php link not found error


I recently started getting this error on my site :

The requested URL /ilanlar.php was not found on this server.

although the link is correct and I have set the path and everything correctly, the link I try to access is as follows :

http://ift.tt/1KQ5czY

here the surprising thing is, I have the link defined as:

<a href='http://ift.tt/1IkfLrp'>CLICKY</a>

but the %EF%BB%BF part is being added automatically on its own, what am I missing here?



via Chebli Mohamed

HTML content underneath WebGL animation not clickable


I am trying to figure out why HTML content underneath a WebGL animation cannot be clicked or interact with.

Please see example.

Currently the div containing the animation is set to:

.webgl-glitch {
    position: absolute;
    z-index: 2;
    overflow: hidden;
    opacity: 0.5;
}

..otherwise it will not display at all.

I have tried setting a z-index: 1; property on the header/container div, but this does not seem to help.

Here is the HTML section of the header including the animation div:

<!-- Begin Header animation -->
<div class="webgl-glitch"></div>
<!-- End Header animation -->


<header id="principalheader" class="centerContainer aligncenter fullScreen tintBackground stonebackground" style="z-index:1">
    <div>
        <div class="container">
            <!-- Site logo-->
            <a href="#" class="logo"><img alt="KUBO" src="img/logo.png"></a>
            <!-- Site Principal slogan-->
            <h1>Digital Exploration for the the digital age</h1>
            <!-- Site Resume-->
            <div class="row">
                <div class="hidden-xs col-md-10 col-md-offset-1">
                    <h2>CRAFT experiences that <strong>defy</strong> expectations<br/>
                        CREATE from the the twin <strong>virtues</strong> of inspiration and innovation<br/>
                        BEAUTY in simplicity and complexity <strong>combined</strong> for the best of both worlds</h2>
                </div>
                <div class="col-md-10 col-md-offset-1">
                    <a class="fa fa-angle-down" href="#" data-scrollto="#about"></a>
                </div>
            </div>
        </div>
    </div>
</header>

Another thing I have noticed is that if I wrap the .web-glitch animation div inside a HTML5 canvas element it also does not display at all? why would this be?

The only property I have on canvas in the the CSS at the moment is width: 100%;



via Chebli Mohamed

What is [object XMLDocument]


I am creating a program that will take in a message and then display it as an alert. Simple, but I get the message ' [object XMLDocument] ' when it should display it to the screen as an alert.

What does this mean?



via Chebli Mohamed

Jqgrid - Uncaught RangeError: Maximum call stack size exceeded


Dynamic Column width According to Its Content

I tried adjusting the column width dynamically according to the content this way ,by finding characters length of each row ,then finally getting the max length out of it and setting it to grid column width.

loadComplete : function () {
                $("#grid").on("jqGridAfterLoadComplete jqGridRemapColumns", function () {
                var $this = $("#grid"),
                colModel = $this.jqGrid("getGridParam", "colModel"),
                iCol,
                iRow,
                rows,
                row,
                n = $.isArray(colModel) ? colModel.length : 0;
                var rowData = "";
                var rowDataLen="";
                var input = [];
                var divs = $( "div" );
                var colWidth=125;
                for (iCol = 0; iCol < n; iCol++) {
                            input = [];
                            for (iRow = 0, rows = this.rows; iRow < rows.length; iRow++) {
                                        row = rows[iRow];
                                        rowData = $(row.cells[iCol]).find(divs).html();
                                        if(rowData != undefined)
                                            rowDataLen = rowData.length;
                                        input.push(rowDataLen);
                            }
                            var finalWidth =  Math.max.apply(null, input);
                            if(finalWidth < colWidth)
                                finalWidth = colWidth;
                            $("#grid").jqGrid("setColWidth", iCol, finalWidth);
                            var gw = $("#grid").jqGrid('getGridParam','width');
                            $("#grid").jqGrid('setGridWidth',gw);
                       }                    
            });     
        },

and it is working fine.

However it is too slow and getting Uncaught RangeError: Maximum call stack size exceeded

error when I have more records like 500.

Can anyone help to tweak the above solution so that it can be faster?

Here is my HTML Code:

<td role="gridcell" style="text-align:left;" title="Hot-forged Hot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forged." aria-describedby="grid_test">
<div style="max-height: 120px">Hot-forged Hot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forgedHot-forged.</i><br><br><i>tttttttttttttttttttttttttttttttt</i></div></td>

I am actually finding the max character size of the div content..will that be reduced if i directly take title attribute of tag as i have the same data in both the tags?

colum model formatter for fixed row height:

formatter : function(cellvalue){ if(cellvalue == undefined || cellvalue == null) { cellvalue = ""; } return '' + cellvalue + ''; },

Or how can i reduce the performace of this code? Please help..



via Chebli Mohamed

DIV show and hide with jumping to next when click on link


I'm using css & html to show/hide a few div's. (http://ift.tt/1eSrsuI)

I would like to extend this code with PREV and NEXT "buttons" which do exactly as is... So if DIV2 currently visible and hit the next button the jump to the DIV3...

Is it possible with CSS+HTML only?

<ul>
    <li><a href="#div1">Div one</a></li>
    <li><a href="#div2">Div two</a></li>
    <li><a href="#div3">Div three</a></li>
    <li><a href="#div4">Div four</a></li>
    <li><a href="#">hide</a></li>
</ul>

<div id="content">
    <div id="div1">This is div one</div>
    <div id="div2">This is div two</div>
    <div id="div3">This is div three</div>
    <div id="div4">This is div four</div>
</div>

#content > div {
    display: none;
    width: 50%;
    margin: 0 auto;
}

#content > div:target {
    display: block;
}

#content > div a.hide {
    display: block;
    text-align: right;
}



via Chebli Mohamed

Impact of td/th background over table border


I have a table element with a border:

.summary-table {
    font-family: sans-serif;
    -webkit-font-smoothing: antialiased;
    font-size: 115%;
    overflow: auto;
    width: 100%;
    border: 1px solid rgb(195, 195, 195) !important;
    border-radius: 4px;
    overflow: hidden;
}

When i use background color on thead tr it works fine

.summary-table thead tr{
    background-color: #E8E8E8 !important;
}

enter image description here

But when i use background color on thead th i get this (no border-top and left ):

.summary-table th {
    background-color: #E8E8E8 !important;
    font-weight: normal;
    color: black;
    padding: 20px 30px;
}

enter image description here

Can anyone tell nme why i get this?



via Chebli Mohamed

In different browsers input time field shows in different formats [duplicate]


This question already has an answer here:

I created an input time HTML element, with this line:

<input type="time" id="startTime" value="@DateTime.Now.ToString("HH:mm")" />

I am using C# Razor syntax, but it does not really matter.

I checked it in both Google Chrome and Mozilla Firefox and in both time is represented in 24 hour format. Later, when I shared the code with my colleagues, in their versions of Chrome the time is represented in 12-hour format with AM and PM. Is there a way to specify in my HTML code that time should be represented in one way in all browsers.

Thank you!



via Chebli Mohamed

prevent html injection in CodeIgniter


I have develop a site using codeignitor I am able to use security of XSS but I am unable to filter html. Which leads to html injection in the form and some message area so can some one please tell me how to patch this.



via Chebli Mohamed

calculation using dropdown box and textbox


Before you guys shoot me down for not trying the code, I am very new to Javascript and I need to implement this function into a very important work.

I got the basis dropdown calculation from this thread, Javascript drop-down form math calculation. I modified the code referred from the thread for my codes

Forgive me if my codes is totally wrong, I am still trying to do piece by piece. Will be grateful if you all can help me pinpoint the errors and/or issues.

So back to topic, I want to get the cost for each items, and then count the total cost to be calculated. The JSFiddle link is here. Appreciate for your helps rendered.

HTML CODES

<form name="priceCalc" action="">Laundry (Gentlemen)
<br/>Apparels:
<select name="gapparell" onchange="gentlemanl();">
    <option value="5.00">Tie</option>
    <option value="7.50">Shirt</option>
    <option value="12.50">Jacket</option>
</select>
<br>Quantity:
<input type="text" id="gqtyl" onchange="gentlemanl();" />
<br>
<br/>Dry Cleaning (Gentlemen)
<br/>Apparels:
<select name="gappareld" onchange="gentlemand();">
    <option value="6.00">Tie</option>
    <option value="8.50">Shirt</option>
    <option value="13.50">Jacket</option>
</select>
<br>Quantity:
<input type="text" id="gqtyd" onchange="gentlemand();" />
    <br/><br/><br/>Laundry (Ladies)
<br/>Apparels:
<select name="lapparell" onchange="ladiesl();">
    <option value="5.00">Tie</option>
    <option value="7.50">Shirt</option>
    <option value="12.50">Jacket</option>
</select>
<br>Quantity:
<input type="text" id="lqtyl" onchange="ladiesl();" />
<br>
<br/>Dry Cleaning (Ladies)
<br/>Apparels:
<select name="lappareld" onchange="ladiesd();">
    <option value="6.00">Tie</option>
    <option value="8.50">Shirt</option>
    <option value="13.50">Jacket</option>
</select>
<br>Quantity:
<input type="text" id="lqtyd" onchange="ladiesd();" />
<br>Total Cost:
<input type="text" id="prices">
<br/>
<input type="button" value="Figure out pricing!" onclick="total();">
<br>

JAVASCRIPT CODES

function gentlemanl() {
var Amt = document.priceCalc.gapparell;
var Qty = document.priceCalc.gqtyl;
var price = parseInt(Qty.value) * parseFloat(Amt.value);
document.getElementById("prices").value = price; 
}

function gentlemand() {
var Amt = document.priceCalc.gappareld;
var Qty = document.priceCalc.gqtyd;
var price = parseInt(Qty.value) * parseFloat(Amt.value);
document.getElementById("prices").value = price;
}

function ladiesl() {
var Amt = document.priceCalc.lapparell;
var Qty = document.priceCalc.lqtyl;
var price = parseInt(Qty.value) * parseFloat(Amt.value);
document.getElementById("prices").value = price;
}

function ladiesd() {
var Amt = document.priceCalc.lappareld;
var Qty = document.priceCalc.lqtyd;
var price = parseInt(Qty.value) * parseFloat(Amt.value);
document.getElementById("prices").value = price;
}

function total() {
//I am not sure how the function works
}



via Chebli Mohamed

How Post all selected values of dropdown to controller?


                <a class='btn btn-primary' href='http://localhost/index.php/Welcome/delete_pro/".$row->pid."'>DELETE</a>

that pid is not pass in the URL.



via Chebli Mohamed

Javascript and lightbox


So, I'm in a sort of competition based on synthetic biology and we need a website in order to post our results and work and introduce our team. The system for this website is quite...convoluted to say the least. We're meant to use certain rules so that we can't edit our content after a certain date and...well I'm not so great at web design anyway. I've taken an html/css course, but this goes beyond that.

For some reason, we don't get to use an ftp server and upload things. If we want css or javascript, we have to write it... well... It's hard to explain. You can read it for yourself:

http://ift.tt/1DpvCGx

So basically, I take that as a copy/paste the javascript for lightbox into a new page and just fiddle with the links a bit and it will work. Right? Well it hasn't so far. I'm not going to paste everything here because it's pointless but here's what I've done:

Pasted the javascript from lightbox into a new website. Also pasted the lightbox css into our css and uploaded the overlay/exit/loading pictures onto the website and changed their links

Called that website using the script type thing from the "rules" page. Used a basic < a href="blahblah" rel="lightbox">< img src="blahblah" / >< /a >

It doesn't work.

I really can't think of what would be making this not work. When I put everything together it just gives me the picture as a link to the picture's web address. No lightbox. No overlay. Nothing.

I've never done a website like this before. I thought most of the time it was just uloading the different files onto a server and then using them. This is hard. Any tips would be greatly appreciated.



via Chebli Mohamed

Wordpress on iPad, logo position issue


I'm developing this site: esident.logotypefactory.com Everything is ok on desktops, phones. But when it comes to iPads the logo duplicates or something is wrong...

So try this:

1) Go to esident.logotypefactory.com on your iPad 2) Swipe to the left so the screen goes to the right, you will see the second logotype.

Why does it do like that? What am I doing wrong?

What I want:

1) Have a logo always on the top left side. 2) When you click on the menu, have the logo also there on same place.

What I think:

That the second logo is the logo that should be viewable when you click on the menu. As when you click on the menu, you can't "swipe" to see the second logo.

Please help me guys.

<div class="fusion-header"><div class="fusion-row"><div class="fusion-logo" data-margin-top="65px" data-margin-bottom="31px" data-margin-left="0px" data-margin-right="0px"> <a href="http://ift.tt/1M988Ig"> <img src="http://ift.tt/1ImH3v2" width="221" height="51" alt="Esident" class="fusion-logo-1x fusion-standard-logo"> <img src="http://ift.tt/1ImH3v2" width="221" height="51" alt="Esident" style="width:221px; max-height: 51px; height: auto;" class="fusion-standard-logo fusion-logo-2x"> <img src="http://ift.tt/1M988Ii" alt="Esident" class="fusion-logo-1x fusion-mobile-logo-1x"> <img src="http://ift.tt/1ImH3v2" alt="Esident" style="max-width:195px; max-height: 47px; height: auto;" class="fusion-logo-2x fusion-mobile-logo-2x"> </a></div><div class="fusion-mobile-menu-icons"><a href="#" class="fusion-icon fusion-icon-bars"></a></div><div class="fusion-mobile-nav-holder"></div></div></div>

.fusion-header {



  padding-left: 30px;



  padding-right: 30px;



  -webkit-backface-visibility: hidden;



  backface-visibility: hidden;



}



.fusion-header-v2 .fusion-header,



.fusion-header-v3 .fusion-header,



.fusion-header-v4 .fusion-header,



.fusion-header-v5 .fusion-header {



  border-bottom: 1px solid transparent;



}



.fusion-logo {



  float: left;



  zoom: 1;



}



.fusion-logo:before,



.fusion-logo:after {



  content: " ";



  display: table;



}



.fusion-logo:after {



  clear: both;



}



.fusion-logo a {



  display: block;



}



.fusion-logo img {



  width: auto;



}



.fusion-logo-2x {



  display: none;



}



.fusion-mobile-logo-1x,



.fusion-mobile-logo-2x {



  display: none;



}



@media only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and (min-resolution: 144dpi), only screen and (min-resolution: 1.5dppx) {



  .fusion-standard-logo.fusion-logo-1x {



    display: none;



  }



  .fusion-standard-logo.fusion-logo-2x {



    display: inline-block;



  }



}



.fusion-secondary-header {



  min-height: 43px;



  border-bottom: 1px solid transparent;



}



.fusion-secondary-header .fusion-alignleft {



  float: left;



  margin-right: 0;



}



.fusion-secondary-header .fusion-alignright {



  float: right;



  margin-left: 0;



}



.fusion-header-v2 .fusion-secondary-header {



  border-top: 3px solid transparent;



}



.fusion-secondary-header .fusion-mobile-nav-holder {



  width: 80%;



  margin: 0 auto;



}



.fusion-header-separator {



  padding: 0 6px;



}



.fusion-contact-info {



  line-height: 43px;



}



.fusion-header-v4 .fusion-header {



  padding-top: 30px;



  padding-bottom: 30px;



}



.fusion-header-v4 .fusion-logo {



  width: 100%;



}



.fusion-header-v4 .fusion-logo a {



  float: left;



}



.fusion-header-v4 .searchform {



  float: right;



  margin-left: 15px;



}



.fusion-header-v4 .search-table {



  width: 286px;



}



.fusion-header-tagline {



  float: right;



  margin: 0;



  padding: 0;



  line-height: 32px;



  font-family: 'MuseoSlab500Regular', Arial, Helvetica, sans-serif;



  font-weight: normal;



}



.fusion-header-banner {



  float: right;



}



.fusion-logo .fusion-header-banner a {



  float: none;



}


via Chebli Mohamed

Displaying page specific content [on hold]


I am making a website with PHP and have encountered an issue.

  • All my webpages include a footer, and I want to display data in the footer depending on the opened webpage, I found a very non-robust way of doing this.

    if( $CU == 'http://www.example.com' 
         || $CU == 'http://example/index.php'     
         || $CU == 'http://example/index.php/'    
         || $CU == 'http://example/')
    { 
    $display = "<p>Already registered? <a href='login.php'>Sign in</a></p>";
    }
    
    elseif( $CU == 'http://ift.tt/1IGJxDG' 
         || $CU == 'http://ift.tt/1mNFg9X' )
     { 
     $display = "<p>Forgotten your password? <a href='reset_password.php'>Reset</a> your password!</p>";
     }
    
    

Question (edited): What is a robust method of dynamically loading content based on the current file?



via Chebli Mohamed

Check for duplicate IDs?


I'm using a simple website CMS called TidyCMS. It automatically gives an ID to every element made editable, like tidyautoid-32. However, this does not work so well and sometimes it makes duplicate IDs and modifying an element with an duplicate ID repeats the element on the website and does other unwanted things.

I've got 700 lines of HTML code, which I wouldn't want to manually review, and I couldn't remember all the numbers to review.

How can I check for duplicate IDs?



via Chebli Mohamed

CSS transformed parent affect child position


Why are child positions affected when you transform the parent?

I want the blue box stay in the bottom right position of the yellow box. But when I translate the red box, the blue box move to his parent.

In real life box-red represents my ui-view in Angular. The views are sliding in and out. I can't change the HTML hierarchy.

See my codepen http://ift.tt/1JLB1Zs

HTML

<div class="box-yellow">
    <div class="box-red">
        <div class="box-blue"></div>
    </div>
</div>

CSS

.box-yellow {
  background-color: yellow;
  position: relative;
  height: 200px;
  width: 200px;
}

.box-red {
  background-color: red;
  height: 100px;
  width: 100px;  
}

.box-blue {
  background-color: blue;
  bottom: 0;
  height: 50px;
  position: absolute;
  right: 0;
  width: 50px;
}

.box-move {
  transform: translateX(100%);
}



via Chebli Mohamed

Escape user-generated chat messages but render links


User enter chat messages, which gets rendered directly to the page using Mustache templates. Obviously, HTML should be escaped to prevent HTML injection, but then again links should be rendered as <a href='...'>.

There are different approaches I've tried to use {{{ ... }}} to return the unescaped HTML content, which means the link would get rendered and I need to take care of HTML escaping myself. Is there a safe way of doing that without relying on a half-baked solution I write myself?

jQuery.text() would be great, but I guess it will render the <a> again as text.

What else can I do here?



via Chebli Mohamed

HTML Injection Windows RT WebView


I am trying to insert values to a HTML Document on my Windows Universal App, the HTML Document is located on a Web-server.

And i am trying to insert username and password saved on the client device Winphone or PC Store App, I know the id and every thing about the elements, but I cant figure out how to insert a string into an input value, can someone provided a sample with InvokeScript("smth", new string[] {smthelse});

Or has someone a better idea to insert username and password from into the HTML content of a webview?

I'am stuck here and i really need this feature.

Thanks in advance



via Chebli Mohamed

How to add html/js query to gwt app using gwt-rpc?


We have a web client built with GWT that talks to a server via gwt-rpc. One part of the app will now use html/js to replace the GWT GUI and we want that part to talk to the server but not via gwt-rpc. What ways are there to migrate a gwt-rpc call to something that will work with a none a gwt client? Today we send and receive java collections that contain object graphs like a list of order objects that have them self order detail objects and so on.

Thanks



via Chebli Mohamed

Jquery slideToggle() to a certain height?


I have tried the below coding to slide my div up and down:

$("#toggle").click(function(e) {
    e.preventDefault();
    $("#numbers").slideToggle();
});

How do we let it to only slide until certain height for example half of my div?



via Chebli Mohamed

Bootstrap dropdown clipped by overflow:hidden container, how to change the container?


Using bootstrap, I have a dropdown menu(s) inside a div with overflow:hidden, which is needed to be like this. This caused the dropdowns to be clipped by the container.

My question, how can I solve this clipping issue, e.g. change the container of all dropdowns inside my project to be body, with lowest cost possible?

this is an example of the code: http://ift.tt/1Hq03XT



via Chebli Mohamed

How to remove extra space around div?


When i pass some input in the search box at that time search result is displayed.

But with search result div unwanted or extra white space also displaying at left & right side of result.

Just like one blank row.

How do i remove this to display proper result div of search bar.

Thanks in advance.



via Chebli Mohamed

How to create a search engine like google


I'm new in programming, but I already have 4 months of experience. I'm good in HTML and starting to learn CSS. I want to make search engine like google, that can search in many websites and display the results quick

this is what I already did:

<div id="search_div">
   <input type="text" placeholder="search" name="search">
</div>

how can I do the search? what else I need to know? is there's a ready code for this?

thanks a lot!



via Chebli Mohamed

How to Do the total web form in disable mode


I am having web Page which consist of 130 Drop downs and 100 Check Box list. Total no of lines are 7500. This page is used for only user VIEW by receiving a Query String from an other Page. I starting each and every control.enable = false but taking much time. how to do it.Thanks in advance.



via Chebli Mohamed

Value of submitted input is empty


I want to submit some data which I attach to an input element. The server get's this element, with correct ID, but it has no value.

<form id="sub_form" method="post" action="acc_manage.lp"> 
    <input type="text" name="container" id="sub_inp" value=""> </input>
</form>

sub_inp receives its input from a specific event, which calls:

function execute_submit(){
    $("#sub_inp").val(JSON.stringify(foo));
    // .val() returns a stringified object 
    console.log( $("#sub_inp").val() )
    if ($("#sub_inp").val() != "") {
        $("#sub_form").submit();
  };

Value of the post request on server-side is this:

post={ container={} }, formdata={}, errtag={} }

Why is this and how can I fix it? I am using jQuery 2.1.3



via Chebli Mohamed

Accessing Data stored in an iframe


If I have a .txt file embedded into my webpage via an iframe, how do I access the data stored in it? I had assumed that accessing the innerHTML would do fine, but since its not HTML, it doesn't work.

Is there an equivalent accessing scheme for other kinds of files other than HTML? Code currently looks like this:

innerDoc = document.getElementById("state_current").contentWindow.document;
var state = innerDoc.innerHTML;



via Chebli Mohamed

samedi 25 avril 2015

Send latitude and Longitude from the BoadcastReceiver when the internet connection is avialable


I want to send JSON String

{
    "latitude": 53.86898504,
    "longitude": 10.66561187,
    "time": "25.04.2015 11:37:11",
    "route": 4
} 

to the server every 60 seconds so when I try to send the JSON string from my internet connection BroadcastReceiver the JSON string is null there but when I send the data from onLocationChanged method I am getting the string in the PostData class but I want to send the data just when the internet connection is avialable if the internet is not avialable i will store the string for short time. How can I implement it to get the JSONString in the CONNECTIVITY_ACTION BroadcastReceiver?

I appreciate any help.

MainActivity class:

public class MainActivity extends ActionBarActivity {

Location location;
LocationManager locationManager;
String jSONString;

    TextView textJSON;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textJSON = (TextView) findViewById(R.id.textJSON);


        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        LocationListener ll = new myLocationListener();
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, ll);


    }

    private class BroadcastReceiverListener extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(
                    android.net.wifi.WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                     //code to get the strongest wifi access point in the JSON string the routes's value.
            }

            else if (intent.getAction().equals(
                    android.net.ConnectivityManager.CONNECTIVITY_ACTION)) {

                ConnectivityManager connectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);

                NetworkInfo netInfo = connectivityManager
                        .getActiveNetworkInfo();

                boolean isConnected = netInfo != null
                        && netInfo.isConnectedOrConnecting();
                if (isConnected) {
                    Toast.makeText(context,
                            "The device is connected to the internet ",
                            Toast.LENGTH_SHORT).show();
                if (location == null) {

                    Location locat = locationManager
                            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (locat == null) {

                        LocationListener locLis = new myLocationListener();
                        LocationManager locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                        Criteria criteria = new Criteria();
                        Looper myLooper = Looper.myLooper();

                        locMan.requestSingleUpdate(criteria, locLis,
                                myLooper);

                    } else {
                        System.out.println("locat is not null");
                    }

                } else {
                    PostData sender = new PostData();
                    sender.timer(jSONString);
                    textJSON.setText(jSONString);
                }


                } else {
                    Toast.makeText(context,
                            "Please connect the device to the internet.",
                            Toast.LENGTH_SHORT).show();
                }

            }
        }

    }

    class myLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location location) {

            if (location != null) {
                double pLong = location.getLongitude();
                double pLat = location.getLatitude();
                ...
                String time = sdf.format(location.getTime());

                jSONString = convertToJSON(pLong, pLat, time);
                System.out.println("The output of onLocationChanged: "+ jSONString);

                //The code works fine here. JSON string has its values here but in broadcastReceiver JSON string has null.
//              PostData sender = new PostData();
//              sender.timer(jSONString);
//              textJSON.setText(jSONString);



            }
        }
    }
}


Android sticky list headers


I want to make sticky list headers like Contact application ! I tried to make to parallel lists but I can not synchronize them.. Any idea how to it please !

Below the example (letter B)

enter image description here

Thanks !!


Copy sqlite db file from Android terminal to Windows OS


I want to copy the sqlite database from data/data/[package name]/databases/ to Windows Operating system.

Currently, I am inside Android Terminal shell of Android studio and my current path is /data/data/example.com.sensor/databases.

There is a sqlite file in this directory. The name is sensor.sqlite.

This is perhaps an easy question for experience user like you. However, I have spent 2 hours yet I find the result.

Thank you.

Regards,

Jimmy


Make Android Activity Dialog On Start


I want to to make an App. When it is started is should show an new Activty which is an dialog and has a transparent background like here: http://ift.tt/1f3ecyb

Do you have any idea, how I can make it with Android?


Responsive CSS works everywhere except the Internet Browser on Droid Phone (Galaxy S4)


I have got my website working everywhere except the default "Internet" browser on the Droid phone. It looks great in Chrome on the phone. It passes all the Google tests for mobile ready. It looks good on iPhone. Here's the site ... http://ift.tt/1DKrWbs.

It's driving me crazy. Does anyone know why?


How to save add button dynamically in android?


The code for add button dynamically when user need it , When user click on “addService” this code take (a name for button and a value to use in intent for this button) from second activity then add button dynamically in this activity with the name and intent and user can click it for service . How to save the button that add dynamically by user ? ..............................................................................

        Button btn = new Button(MainActivity.this);
        btn.setText(buttonName);
        layout.addView(btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = serviceNum;
                Intent e = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phone, null));
                startActivity(e);
            }
        });


Logo is not showing up on action bar


I'm trying to simply put a logo on my ActionBar in android but nothing seems to be working. I have literally tried every solution I could find on this website and others without any luck. Any help would be appreciated,

Jacob

Here is my java:

public class Home extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_home);





        getSupportActionBar().setDisplayUseLogoEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setLogo(R.drawable.ic_launcher);


        mNavItems.add(new NavItem("Home", "Find everything you need to know in one place", R.drawable.home_icon));
        mNavItems.add(new NavItem("Learn About Our Programs", "Learn about what we do to help the city", R.drawable.list));
        mNavItems.add(new NavItem("About Us", "Get to know about us on the personal level", R.drawable.info_circled_alt));
        mNavItems.add(new NavItem("Contact Us", "Want to know more about something? Send us an email or phone call", R.drawable.questionm));

        // DrawerLayout
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

        // Populate the Navigtion Drawer with options
        mDrawerPane = (RelativeLayout) findViewById(R.id.drawerPane);
        mDrawerList = (ListView) findViewById(R.id.navList);
        DrawerListAdapter adapter = new DrawerListAdapter(this, mNavItems);
        mDrawerList.setAdapter(adapter);

        // Drawer Item click listeners
        mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectItemFromDrawer(position);
            }
        });
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_opem, R.string.drawer_close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);

                invalidateOptionsMenu();
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                Log.d(TAG, "onDrawerClosed: " + getTitle());

                invalidateOptionsMenu();
            }


        };


        mDrawerLayout.setDrawerListener(mDrawerToggle);

    }


    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Pass the event to ActionBarDrawerToggle
        // If it returns true, then it has handled
        // the nav drawer indicator touch event
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        // Handle your other action bar items...

        return super.onOptionsItemSelected(item);
    }







    private void selectItemFromDrawer(int position) {


        // Close the drawer
        mDrawerLayout.closeDrawer(mDrawerPane);
        Intent intent;
        switch (position) {


            case 0:
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        Intent i = new Intent(Home.this, Home.class);
                        i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        startActivity(i);


                        overridePendingTransition(R.animator.animation1, R.animator.animation2);
                    }
                }, 300);
                break;
            case 1:
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        Intent i = new Intent(Home.this, FindOpp.class);
                        i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        startActivity(i);


                        overridePendingTransition(R.animator.animation1, R.animator.animation2);;
                    }
                }, 300);



                break;


            case 2:
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        Intent i = new Intent(Home.this, About_Us.class);
                        i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        startActivity(i);


                        overridePendingTransition(R.animator.animation1, R.animator.animation2);;
                    }
                }, 300);
                break;

        }
    }


    }

class NavItem {
    String mTitle;
    String mSubtitle;
    int mIcon;

    public NavItem(String title, String subtitle, int icon) {
        mTitle = title;
        mSubtitle = subtitle;
        mIcon = icon;
    }
}
class DrawerListAdapter extends BaseAdapter {

    Context mContext;
    ArrayList<NavItem> mNavItems;

    public DrawerListAdapter(Context context, ArrayList<NavItem> navItems) {
        mContext = context;
        mNavItems = navItems;
    }

    @Override
    public int getCount() {
        return mNavItems.size();
    }

    @Override
    public Object getItem(int position) {
        return mNavItems.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view;

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.drawer_item, null);
        }
        else {
            view = convertView;
        }

        TextView titleView = (TextView) view.findViewById(R.id.title);
        TextView subtitleView = (TextView) view.findViewById(R.id.subTitle);
        ImageView iconView = (ImageView) view.findViewById(R.id.icon);

        titleView.setText( mNavItems.get(position).mTitle );
        subtitleView.setText( mNavItems.get(position).mSubtitle );
        iconView.setImageResource(mNavItems.get(position).mIcon);

        return view;
    }

}
class PreferencesFragment extends Fragment {


    public PreferencesFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_prefences, container, false);
    }

}


How to clear html page before showing into a webview in Android?


I have the URL of a webpage to be displayed into a webview in my Android app. Before showing this page i want to clear the html code of this page from some tag (such as the header, footer, ecc..) in order to show only few information. How can i do it? I tried to solve the issue working with JSoup but i can't understand how to create and pass the "new page" to the webview. Anybody can help me?


Android colour resource - making a colour an alias of another


Is there a way to do something like the following?

<color name="gray1">#eeeeee</color>
<color name="separator_line_gray">@color/gray1</color>

So that I can use separator_line_gray in my code and quickly change it from gray1 to gray2 if needed


Cordova Plugin: Unable to retrieve path to picture


Searching for a solution to the following problem for a while and can't seem to find any solutions. Any help is welcome.

The camera plugin of cordova returns the following error when trying to access a picture using the camera.

Unable to retrieve path to picture!

I tried FILE_URI and DATA_URL.

I use cordova version 5.0.0 and cordova-plugin-camera.

The following path fails e.g.

/storage/emulated/0/Download/horse-331746_640.jpg 

The following path functions e.g.

/storage/emulated/0/WhatsApp/Media/WhatsApp Images/IMG-2015019-WA0000.JPG 

My Function:

function captureNow(bGallery){

    if(bGallery === true){
        navigator.camera.getPicture(onCapturePhoto, cameraOnFail, {
            quality: 100,
            correctOrientation: 1,
            targetWidth: 500,
            targetHeight: 500,
            encodingType: Camera.EncodingType.JPEG,
            destinationType: Camera.DestinationType.FILE_URI,
            sourceType: Camera.PictureSourceType.PHOTOLIBRARY
        });
    } else {
        navigator.camera.getPicture(onCapturePhoto, cameraOnFail, {
            quality: 100,
            correctOrientation: 1,
            targetWidth: 500,
            targetHeight: 500,
            encodingType: Camera.EncodingType.JPEG,
            destinationType: Camera.DestinationType.FILE_URI
        });
    }
}


Read large file data using buffered reader in android


hi i want to read large remote file into string using buffered reader.but i got half data of remote file.Please help to get full data of remote file.

BufferedReader reader = new BufferedReader(new InputStreamReader( inputstream),8*1024);

        StringBuilder sb = new StringBuilder(999999);
        String line;

        while ((line = reader.readLine()) != null) {
            Log.e("Line is ",line);
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
        Log.e("Content: ", sb.toString());


Working with the Youtube-Api


I have several Tutorial Videos on Youtube and i want to include them into my Application. So i have a fix set of Youtube-URL's.

I want to show a list of these videos for that i somehow need to get the thumbnail, the title and the description of each Youtube-URL and to show it. When the user clicks on a item of the listview i want the selected youtube video to be played inside my application.

Unfortunately i cant find example which are showing how to achieve these things. playing youtube videos is easy but i dont know how to get the thumbnail, title and descritpion of given youtube url's.


What is wrong in my android app with HttpPost?


I'm making a new android app, when I send a values with HttpPost to my web file post.php, but it is don't working. What is it wrong ?

activity_activity_main.xml

<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".ActivityPrincipal">

</RelativeLayout>

ActivityPrincipal.java

package com.pixelayer.httppost.httppostandroid;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class ActivityPrincipal extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_activity_principal);

    HttpClient httpClient = new DefaultHttpClient();

    HttpPost httpPost = new HttpPost("http://ift.tt/1zYSQMa"); //
    replace with
    // your url

    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);

    nameValuePair.add(new BasicNameValuePair("nome", "test_user"));

    nameValuePair.add(new BasicNameValuePair("site", "testeandroid"));

    // Encoding data

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
    } catch (UnsupportedEncodingException e) {
        // log exception
        e.printStackTrace();
    }

    // making request

    try {
        HttpResponse response = httpClient.execute(httpPost);
        // write response to log
        Log.d("Http Post Response:", response.toString());
    } catch (ClientProtocolException e) {
        // Log exception
        e.printStackTrace();
    } catch (IOException e) {
        // Log exception
        e.printStackTrace();
    }

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_activity_principal, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://ift.tt/nIICcg"
package="com.pixelayer.httppost.httppostandroid" >

<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".ActivityPrincipal"
        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>

</manifest>

Thank you so much


Would storing many images in an Android apk file be viable for a social app


I am creating a social app for android and am planning ahead, what would be a viable way in Android to store potentially millions of user generated uploaded photos. I have a MySQL database that saves the image path and was thinking of creating a folder outside of the /drawable directory to save the physical images. I could do that but then I thought that if I did then the Android APK file would just balloon in size since your storing all the images within the app; is there a better way to store many images? I been searching around for answers but there aren't many on this topic for android.


Authenticate method is NULL when automatic login


After a user has already logged into the app, I have their username and password saved to shared preferences, therefore when they login again, they should be able to authenticate automatically and subsequently bypass the login activity.

I have started and binded the service, and sent the authenticate methods to the server, yet the section:

                             result = imService.authenticateUser(
                                     userName.trim(),
                                     password.trim());

always returns NULL and does not allow automatic logging in.

Why would this be the case?

The loggingIn class

public class LoggingIn extends Activity {

     protected static final int NOT_CONNECTED_TO_SERVICE = 0;
     protected static final int FILL_BOTH_USERNAME_AND_PASSWORD = 1;
     public static final String AUTHENTICATION_FAILED = "0";
     public static final String FRIEND_LIST = "FRIEND_LIST";
     protected static final int MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT = 2;
     protected static final int NOT_CONNECTED_TO_NETWORK = 3;
     private EditText usernameText;
     private EditText passwordText;

     private JSONObject resultObject;
     public static String userId = null;

     private Manager imService;
     public static final int SIGN_UP_ID = Menu.FIRST;
     public static final int EXIT_APP_ID = Menu.FIRST + 1;

     // For GCM
     String regid;
     GoogleCloudMessaging gcm;
     AtomicInteger msgId = new AtomicInteger();
     SharedPreferences prefs;
     Context context;

     public static final String EXTRA_MESSAGE = "message";
     public static final String PROPERTY_REG_ID = "registration_id";
     private static final String PROPERTY_APP_VERSION = "appVersion";
     private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

     private ServiceConnection mConnection = new ServiceConnection() {
         public void onServiceConnected(ComponentName className, IBinder service) {
             // This is called when the connection with the service has been
             // established, giving us the service object we can use to
             // interact with the service. Because we have bound to a explicit
             // service that we know is running in our own process, we can
             // cast its IBinder to a concrete class and directly access it.
             imService = ((MessagingService.IMBinder) service).getService();

             if (imService.isUserAuthenticated() == true) {
                 // Intent i = new Intent(LoggingIn.this, ListOfFriends.class);
                 Intent i = new Intent(LoggingIn.this, MainActivity.class);
                 startActivity(i);
                 LoggingIn.this.finish();
             }
         }

         public void onServiceDisconnected(ComponentName className) {
             // This is called when the connection with the service has been
             // unexpectedly disconnected -- that is, its process crashed.
             // Because it is running in our same process, we should never
             // see this happen.
             imService = null;
             Toast.makeText(LoggingIn.this, R.string.local_service_stopped,
                     Toast.LENGTH_SHORT).show();
         }
     };

     /**
      * Called when the activity is first created.
      */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);

              /*
               * Start and bind the imService
               */
         startService(new Intent(getBaseContext(), MessagingService.class));

         // Bind it
         bindService(new Intent(getBaseContext(), MessagingService.class),
                 mConnection, Context.BIND_AUTO_CREATE);

         // Initiate Volley:
         final RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();

         //Remove title bar
         this.requestWindowFeature(Window.FEATURE_NO_TITLE);

         //Remove notification bar
         this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

         // For auto logging in:
         if (!SaveSharedPreference.getUserName(getApplicationContext()).isEmpty()) {

                     setContentView(R.layout.feast_loading_splash_page);

                     final String userName = SaveSharedPreference.getUserName(getApplicationContext());

                     final String password = SaveSharedPreference.getPassword(getApplicationContext());

                    Log.v("TEST GCM Service Login","SharedPref Username is " + userName + " and password " + password);

                     Thread loginThread = new Thread() {
                         private Handler handler = new Handler();

                         @Override
                         public void run() {
                             String result = null;

                             try {

                                 result = imService.authenticateUser(
                                         userName.trim(),
                                         password.trim());

                             } catch (UnsupportedEncodingException e) {

                                 e.printStackTrace();
                             }catch (NullPointerException e) {
                                 e.printStackTrace();
                             }

                             if (result == null || result.equals(AUTHENTICATION_FAILED)) {
                /*
                * Authenticatin failed, inform the user
                */
                                 handler.post(new Runnable() {
                                     public void run() {
                                         Toast.makeText(
                                                 getApplicationContext(),
                                                 R.string.make_sure_username_and_password_correct,
                                                 Toast.LENGTH_LONG).show();

                                         // showDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
                                     }
                                 });

                             } else {

                /*
                * if result not equal to authentication failed, result
                * is equal to friend and group list of the user 0: is
                * for friends, 1: is for groups
                */
                                 handler.post(new Runnable() {
                                     public void run() {
                                         Intent i = new Intent(LoggingIn.this,
                                                 MainActivity.class);
                                         startActivity(i);
                                         LoggingIn.this.finish();

                                     }
                                 });

                             }

                         }
                     };
                     loginThread.start();

                 }


         //setContentView(R.layout.loggin_in);
         setContentView(R.layout.feast_login_page);
         //setTitle("Login");

         ImageButton loginButton = (ImageButton) findViewById(R.id.button1);

             // So don't need to log in manually, just click the button
             usernameText = (EditText) findViewById(R.id.username);
             passwordText = (EditText) findViewById(R.id.password);

             // Used for expeditied login
             //usernameText.setText("kjakah08"); //(EditText) findViewById(R.id.username);
             //passwordText.setText("farside"); // (EditText) findViewById(R.id.password);

             loginButton.setOnClickListener(new OnClickListener() {
                 public void onClick(View arg0) {
                     if (imService == null) {
                         Toast.makeText(getApplicationContext(),
                                 R.string.not_connected_to_service,
                                 Toast.LENGTH_LONG).show();
                         // showDialog(NOT_CONNECTED_TO_SERVICE);
                         return;
                     } else if (imService.isNetworkConnected() == false) {
                         Toast.makeText(getApplicationContext(),
                                 R.string.not_connected_to_network,
                                 Toast.LENGTH_LONG).show();
                         // showDialog(NOT_CONNECTED_TO_NETWORK);

                     } else if (usernameText.length() > 0
                             && passwordText.length() > 0) {

                         Thread loginThread = new Thread() {
                             private Handler handler = new Handler();

                             @Override
                             public void run() {
                                 String result = null;

                                 try {
                                     result = imService.authenticateUser(
                                             usernameText.getText().toString().trim(),
                                             passwordText.getText().toString().trim());
                                 } catch (UnsupportedEncodingException e) {

                                     e.printStackTrace();
                                 }
                                 if (result == null
                                         || result.equals(AUTHENTICATION_FAILED)) {
                                      /*
                                       * Authenticatin failed, inform the user
                                       */
                                     handler.post(new Runnable() {
                                         public void run() {
                                             Toast.makeText(
                                                     getApplicationContext(),
                                                     R.string.make_sure_username_and_password_correct,
                                                     Toast.LENGTH_LONG).show();

                                             // showDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
                                         }
                                     });

                                 } else {

                                      /*
                                       * if result not equal to authentication failed,
                                       * result is equal to friend and group list of
                                       * the user 0: is for friends, 1: is for groups
                                       */
                                     handler.post(new Runnable() {
                                         public void run() {

                                             // If log in successful, then save
                                             // username and password to shared
                                             // preferences:

                                             SaveSharedPreference.setUserName(
                                                     getApplicationContext(),
                                                     usernameText.getText()
                                                             .toString());

                                             SaveSharedPreference.setPassword(
                                                     getApplicationContext(),
                                                     passwordText.getText()
                                                             .toString());

                                             Intent i = new Intent(LoggingIn.this,
                                                     MainActivity.class);
                                             startActivity(i);
                                             LoggingIn.this.finish();

                                         }
                                     });

                                 }

                             }
                         };
                         loginThread.start();

                     } else {
                          /*
                           * Username or Password is not filled, alert the user
                           */
                         Toast.makeText(getApplicationContext(),
                                 R.string.fill_both_username_and_password,
                                 Toast.LENGTH_LONG).show();
                         // showDialog(FILL_BOTH_USERNAME_AND_PASSWORD);
                     }

                     // GET the users id!!
                     JsonObjectRequest getUserId = new JsonObjectRequest(Request.Method.GET,
                             "http://" + Global.getFeastOnline() + "/getUserData/" + usernameText.getText().toString() + ".json", ((String) null),
                             new Response.Listener<JSONObject>() {
                                 @Override
                                 public void onResponse(JSONObject response) {

                                     // Parse the JSON:
                                     try {
                                         resultObject = response.getJSONObject("userInfo");
                                         userId = resultObject.getString("id");

                                         Log.v("USER ID", "The user id is " + userId);

                                     } catch (JSONException e) {
                                         e.printStackTrace();
                                     }

                                 }
                             },
                             new Response.ErrorListener() {
                                 @Override
                                 public void onErrorResponse(VolleyError error) {
                                     Log.d("Error.Response", error.toString());
                                 }
                             });

                     requestQueue.add(getUserId);

                 }
             });

     }

     @Override
     protected Dialog onCreateDialog(int id) {
         int message = -1;
         switch (id) {
             case NOT_CONNECTED_TO_SERVICE:
                 message = R.string.not_connected_to_service;
                 break;
             case FILL_BOTH_USERNAME_AND_PASSWORD:
                 message = R.string.fill_both_username_and_password;
                 break;
             case MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT:
                 message = R.string.make_sure_username_and_password_correct;
                 break;
             case NOT_CONNECTED_TO_NETWORK:
                 message = R.string.not_connected_to_network;
                 break;
             default:
                 break;
         }

         if (message == -1) {
             return null;
         } else {
             return new AlertDialog.Builder(LoggingIn.this)
                     .setMessage(message)
                     .setPositiveButton(R.string.OK,
                             new DialogInterface.OnClickListener() {
                                 public void onClick(DialogInterface dialog,
                                                     int whichButton) {
                                                    /* User clicked OK so do some stuff */
                                 }
                             }).create();
         }
     }

     @Override
     protected void onPause() {
         unbindService(mConnection);
         super.onPause();
     }

     @Override
     protected void onResume() {
         bindService(new Intent(LoggingIn.this, MessagingService.class),
                 mConnection, Context.BIND_AUTO_CREATE);

         super.onResume();
     }

     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
         boolean result = super.onCreateOptionsMenu(menu);

         menu.add(0, SIGN_UP_ID, 0, R.string.sign_up);
         menu.add(0, EXIT_APP_ID, 0, R.string.exit_application);

         return result;
     }

     @Override
     public boolean onMenuItemSelected(int featureId, MenuItem item) {

         switch (item.getItemId()) {
             case SIGN_UP_ID:
                 Intent i = new Intent(LoggingIn.this, SigningUp.class);
                 startActivity(i);
                 return true;
             case EXIT_APP_ID:

                 return true;
         }

         return super.onMenuItemSelected(featureId, item);
     }

 }