IT Challangers

Tutorials, Free Online Tutorials,It Challengers provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, core java, sql, php, c language etc. for beginners and professionals.

Breaking

1:52 pm

How to get String in response using Retrofit 2? Retrofit Android example

Today we are going to look at another awesome library Retrofit to make the http calls. Retrofit is denitely the better alternative to volley in terms of ease of use, performance, extensibility and other things. It is a type-­safe REST client for Android built by Square. Using this tool android developer can make all network stuff much more easier. As an example, we are going to download some json and show it in RecyclerView as a list.

retrofit get api example
Retrofit get api example

 Follow those steps:-

1.Add the permission to access internet in the AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="demo.mukesh.app.com.myapplication">

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

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity android:name=".activity.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

    </application>

</manifest>

6:52 am

Retrofit Android Example

Today we are going to look at another awesome library Retrofit to make the http calls. Retrofit is denitely the better alternative to volley in terms of ease of use, performance, extensibility and other things. It is a type-­safe REST client for Android built by Square. Using this tool android developer can make all network stuff much more easier. As an example, we are going to download some json and show it in RecyclerView as a list.

 Follow those steps:-

1.Add the permission to access internet in the AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="demo.mukesh.app.com.myapplication">

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

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity android:name=".activity.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

    </application>

</manifest>

2.Open build.gradle and add Retrofit, Gson dependencies

dependencies {

    implementation 'com.android.support:recyclerview-v7:27.1.1'
//retrofit, gson
    implementation 'com.squareup.retrofit2:retrofit:2.1.0'
    implementation 'com.google.code.gson:gson:2.6.2'
    implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
}

First, we need to know what type of JSON response we will be receiving
 

 3.Creating Model Class


public class Test {
    @SerializedName("userId")
    @Expose
    private Integer userId;
    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("title")
    @Expose
    private String title;
    @SerializedName("body")
    @Expose
    private String body;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }
}


4. Let’s see how our APIInterface.java class looks like

public interface APIInterface {

    @GET("posts")
    Call<ArrayList<Test>> getALLData();
}

5.Create APIClient.java Setting Up the Retrofit Interface
 
public class APIClient {
    private static String BASE_URL="https://jsonplaceholder.typicode.com/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {

        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                //.client(client)
                .build();

        return retrofit;
    }

}

 
6. MyAdapter.java
 
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    private Context context;
    private ArrayList<Test> arrTest;

    public MyAdapter(Context context, ArrayList<Test> arrTest) {
        this.context = context;
        this.arrTest = arrTest;

    }

    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_items, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        Test test= arrTest.get(position);
        holder.title.setText(test.getTitle());
        holder.desc.setText(test.getBody());

    }

    @Override
    public int getItemCount() {
        return arrTest.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView title,desc;

        public MyViewHolder(View itemView) {
            super(itemView);
            title=(TextView)itemView.findViewById(R.id.tvTitle);
            desc=(TextView)itemView.findViewById(R.id.tvDesc);
        }
    }
}
 
7.MainActivity.java
public class MainActivity extends AppCompatActivity {
    private ArrayList<Test> arrTest;
    private Activity activity;
    private RecyclerView recyclerView;
    private MyAdapter adapter;

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

    private void callAPI() {
        APIInterface apiInterface = APIClient.getClient().create(APIInterface.class);
        Call<ArrayList<Test>> call = apiInterface.getALLData();
        call.enqueue(new Callback<ArrayList<Test>>() {
            @Override
            public void onResponse(Call<ArrayList<Test>> call, Response<ArrayList<Test>> response) {
                arrTest = response.body();
                initRecycler();
            }

            @Override
            public void onFailure(Call<ArrayList<Test>> call, Throwable t) {

            }
        });
    }

    private void initRecycler() {
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        LinearLayoutManager mLayout = new LinearLayoutManager(activity);
        recyclerView.setLayoutManager(mLayout);
        adapter = new MyAdapter(activity, arrTest);
        recyclerView.setAdapter(adapter);
    }
}
 


1:00 pm

PHP interview questions and answers for freshers

Welcome !!!. In this section we are providing you some frequently asked PHP Interview Questions which will help you to win interview session easily. Candidates must read this section,Then by heart the questions and answers. Also, review sample answers and advice on how to answer these typical interview questions. PHP is an important part of the web world, and every web developer should have the basic knowledge in PHP.Common PHP interview questions, which should help you become a best PHP codder. We hope you find these questions useful. If you are an interviewer, Take the time to read the common interview questions you will most likely be asked.

  1. What is PHP?                                                                                                                            PHP is a server side scripting language commonly used for web applications. PHP has many frameworks and cms for creating websites.Even a non technical person can cretae sites using its CMS.WordPress,osCommerce are the famus CMS of php.It is also an object oriented programming language like java,C-sharp etc.It is very eazy for learning

  2. What is the use of "echo" in php?                                                                                               It is used to print a data in the webpage, Example: <?php echo 'Car insurance'; ?> , The following code print the text in the webpage

  3. How to include a file to a php page?                                                                                         We can include a file using "include() " or "require()" function with file path as its parameter.

  4. What's the difference between include and require?                                                                 If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.
  5. require_once(), require(), include().What is difference between them?                                    require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page). So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don't include the file more times and you will not get the "function re-declared" error.

  6. Differences between GET and POST methods ?                                                                    We can send 1024 bytes using GET method but POST method can transfer large amount of data and POST is the secure method than GET method .

  7. How to declare an array in php?                                                                                                       Eg : var $arr = array('apple', 'grape', 'lemon');

  8. What is the use of 'print' in php?                                                                                           This is not actually a real function, It is a language construct. So you can use with out parentheses with its argument list.

    Example print('PHP Interview questions');
    print 'Job Interview ');


  9. What is use of in_array() function in php ?                                                                                      in_array used to checks if a value exists in an array

  10. What is use of count() function in php ?                                                                                     count() is used to count all elements in an array, or something in an object

  11. What's the difference between include and require?                                                               It's how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.

  12. What is the difference between Session and Cookie?                                                            The main difference between sessions and cookies is that sessions are stored on the server, and cookies are stored on the user's computers in the text file format. Cookies can't hold multiple variable while session can hold multiple variables..We can set expiry for a cookie,The session only remains active as long as the browser is open.Users do not have access to the data you stored in Session,Since it is stored in the server.Session is mainly used for login/logout purpose while cookies using for user activity tracking
  13. How to set cookies in PHP? 
     Setcookie("sample", "ram", time()+3600);

  14. How to Retrieve a Cookie Value?                                                                                                eg : echo $_COOKIE["user"];

  15. How to create a session? How to set a value in session ? How to Remove data from a session?                                                                                                                                            Create session : session_start();
    Set value into session : $_SESSION['USER_ID']=1;
    Remove data from a session : unset($_SESSION['USER_ID'];.

  16. what types of loops exist in php? 
     for,while,do while and foreach (NB: You should learn its usage)

  17. Note:-
    MySQLi (the "i" stands for improved) and PDO (PHP Data Objects) are the MySQL extensions used to connect to the MySQL server in PHP5 or verions, MySQL extension was deprecated in 2012.
    MySQLi only works with MySQL databases whereas PDO will works with 12 other Database systems
    I recommend PDO because, if you want to choose another database instead of MySQL, then you only have to change the connection string and a few queries. But if you are using MySQLi you will need to rewrite the entire code

  18. How to create a mysql connection?
    Example (PDO)
    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";

    try {
        $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
        // set the PDO error mode to exception    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "Connected successfully";
        }
    catch(PDOException $e)
        {
        echo "Connection failed: " . $e->getMessage();
        }
    ?>

    Example (MySQLi Object-Oriented)
    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB"; // Optional

    // Create connection$conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    echo "Connected successfully";
    ?>

    Example (MySQLi Procedural)
    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB"; // Optional


    // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname);

    // Check connection if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }
    echo "Connected successfully";
    ?>

  19. How to execute an sql query? How to fetch its result ?
    Example (MySQLi Object-oriented)

    $sql = "SELECT id, firstname, lastname FROM MyGuests";
    $result = $conn->query($sql); // execute sql query

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) { // fetch data from the result set
            echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
        }
    } else {
        echo "0 results";
    }

    Example (MySQLi Procedural)

    $sql = "SELECT id, firstname, lastname FROM MyGuests";
    $result = mysqli_query($conn, $sql); // execute sql query

    if (mysqli_num_rows($result) > 0) {
        // output data of each row
        while($row = mysqli_fetch_assoc($result)) { // fetch data from the result set
            echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
        }
    } else {
        echo "0 results";
    }
    Example (PDO)

    Method 1:USE PDO query method
    $stmt = $db->query('SELECT id FROM Employee');  
    $row_count = $stmt->rowCount();  
    echo $row_count.' rows selected';

    Method 2: Statements With Parameters
    $stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");  
    $stmt->execute(array($name));  
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
     
  20. Write a program using while loop
    <?php
    $x = 1;

    while($x <= 5) {
        echo "The number is: $x <br>";
        $x++;
    }
    ?>
  21. How we can retrieve the data in the result set of MySQL using PHP?
    MySQLi methods
    • 1. mysqli_fetch_row
    • 2. mysqli_fetch_array
    • 3. mysqli_fetch_object
    • 4. mysqli_fetch_assoc
    PDO methods
    • 1. PDOStatement::fetch(PDO::FETCH_ASSOC)
    • 2. PDOStatement::fetch(PDO::FETCH_OBJ)
    • 3. PDOStatement::fetch()
    • 4. PDOStatement::fetch(PDO::FETCH_NUM).
    •  
  22. What is the use of explode() function ? Syntax : array explode ( string $delimiter , string $string [, int $limit ] );
    This function breaks a string into an array. Each of the array elements is a substring of string formed by splitting it on boundaries formed by the string delimiter.

  23. What is the difference between explode() and str_split() functions? str_split function splits string into array by regular expression. Explode splits a string into array by string.
  24. What is the use of mysql_real_escape_string() function? It is used to escapes special characters in a string for use in an SQL statement

  25. Write down the code for save an uploaded file in php.
    <?php
    if ($_FILES["file"]["error"] == 0)
    {
    move_uploaded_file($_FILES["file"]["tmp_name"],
          "upload/" . $_FILES["file"]["name"]);
          echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
    }
    ?>
  26. How to create a text file in php?
    <?php
    $filename = "/home/user/guest/newfile.txt";
    $file = fopen( $filename, "w" );
    if( $file == false )
    {
    echo ( "Error in opening new file" ); exit();
    }
    fwrite( $file, "This is a simple test\n" );
    fclose( $file );
    ?>
  27. How to strip whitespace (or other characters) from the beginning and end of a string ? The trim() function removes whitespaces or other predefined characters from both sides of a string.
  28. What is the use of header() function in php ? 
     The header() function sends a raw HTTP header to a client browser.Remember that this function must be called before sending the actual out put.For example, You do not print any HTML element before using this function.
8:46 am

Computer Question for Panchayat Sachiv/ secretary

Jharkhand SSC Computer Question for Panchayat Sachiv/ Panchayat secretary Practice Model Question Papers  and Jharkhand SSC LDC Panchayat Secretary Previous Year Question Papers ...



  1. Extension name of flash file is ___.
    (1) .pdf
    (2) .swf
    (3) .pmd
    (4) .prd
    (5) None of these
  2. Who invented world wide web?
    (1) Mosaic corporation
    (2) Opera corporation
    (3) Tim berner lee
    (4) Vint cert
    (5) None of these
  3. The small, touch-sensitive screen at the base of the keyboard on a laptop is known as the:
    (1) stylus
    (2) touchpad.
    (3) game control
    (4) trackball
    (5) None of these
  4. The two broad categories of software are:
    (1) word processing and spreadsheet.
    (2) transaction and application.
    (3) Windows and Mac OS.
    (4) system and application.
    (5) None of these
  5. Which shortcut key is used to spell check in MS word
    (1) F1
    (2) F2
    (3) F7
    (4) F9
    (5) None of these
  6. Software, such as Explorer and Firefox, are referred to as _____.
    (1) Systems software
    (2) Utility software
    (3) Browsers
    (4) Internet tools
    (5) Frontend Tools
  7. Which of the following is the communications protocol that sets the standard used by every computer that accesses Web – based information?
    (1) XML
    (2) DML
    (3) HTTP
    (4) HTML
    (5) None of these
  8. A concentric circle on a disk is called a________
    (1) cylinder
    (2) track
    (3) head
    (4) sector
    (5) none of these
  9. A sizeable geographical area with communication based on the telephone system is though as
    (1) Wide area network
    (2) Local area network
    (3) Modulator-Demodulator
    (4) All of the above
    (5) None of the above
  10. A Proxy server is used for which of the following?
    (1) To provide security against unauthorized users
    (2) To process client requests for web pages
    (3) To process client requests for database access
    (4) To provide TCP/IP
    (5) None of these
  11. To create a copy of files in the event of system failure, you create a __________.
    (1) restore file
    (2) backup
    (3) firewall
    (4) redundancy
    (5) None of these
  12. Windows XP is an example of __________ component of an information system.
    (1) People
    (2) procedure
    (3) data
    (4) hardware
    (5) software
  13. Temporary memory is called as
    (1) PROM
    (2) ROM
    (3) DOS
    (4) RAM
    (5) CAD
  14. To boot a computer means
    (1) keep it working
    (2) turn on the sounds
    (3) add extra drives
    (4) throw it out-it’s outdated
    (5) turn it on
  15. Which of the following terms describe 1024 kilobytes?
    (1) Kilobyte
    (2) Megabyte
    (3) Gigabyte
    (4) Terabyte
    (5) None of the above

Answer:--

  1. swf
  2. Tim berner lee
  3. Touchpad
  4. system and application
  5. F7
  6. Browsers
  7. HTTP
  8. Track
  9. Wide area network
  10. To process client requests for web pages
  11. backup
  12. software
  13. RAM
  14. turn it on
  15. Megabyte

4:22 pm

C++ Interview Questions


C++ Interview Questions


1.) What is the full form of OOPS?
Object Oriented Programming System.

2.) What is a class?
Class is a blue print which reflects the entities attributes and actions. Technically defining a class is designing an user defined data type.

3.) What is an object?
An instance of the class is called as object.

4.) List the types of inheritance supported in C++.
Single, Multilevel, Multiple, Hierarchical and Hybrid.

5.) What is the role of protected access specified ?If a class member is protected then it is accessible in the inherited class. However, outside the both the private and protected members are not accessible.

6.) What is encapsulation?
The process of binding the data and the functions acting on the data together in an entity (class) called as encapsulation.

7.) What is abstraction?
Abstraction refers to hiding the internal implementation and exhibiting only the necessary details.

8.) What is inheritance?
Inheritance is the process of acquiring the properties of the existing class into the new class. The existing class is called as base/parent class and the inherited class is called as derived/child class.

9.) Explain the purpose of the keyword volatile.
Declaring a variable volatile directs the compiler that the variable can be changed externally. Hence avoiding compiler optimization on the variable reference.

10.) What is an inline function?
A function prefixed with the keyword inline before the function definition is called as inline function. The inline functions are faster in execution when compared to normal functions as the compiler treats inline functions as macros.

11.) What is a storage class?
Storage class specifies the life or scope of symbols such as variable or functions.

12.) Mention the storage classes names in C++.
The following are storage classes supported in C++
auto, static, extern, register and mutable

13.) What is the role of mutable storage class specifier?
A constant class object’s member variable can be altered by declaring it using mutable storage class specified. Applicable only for non-static and non-constant member variable of the class.

14.) Distinguish between shallow copy and deep copy.
Shallow copy does memory dumping bit-by-bit from one object to another. Deep copy is copy field by field from object to another.
Deep copy is achieved using copy constructor and or overloading assignment operator.

15.) What is a pure virtual function?
A virtual function with no function body and assigned with a value zero is called as pure virtual function.

16.) What is an abstract class in C++?
A class with at least one pure virtual function is called as abstract class. We cannot instantiate an abstract class.

17.) What is a reference variable in C++?
A reference variable is an alias name for the existing variable. Which mean both the variable name and reference variable point to the same memory location. Therefore updation on the original variable can be achieved using reference variable too.
18.) What is role of static keyword on class member variable?
A static variable does exist though the objects for the respective class are not created.
Static member variable share a common memory across all the objects created for the respective class. A static member variable can be referred using the class name itself.
Explain the static member function.
A static member function can be invoked using the class name as it exists before class objects comes into existence. It can access only static members of the class.

19.) Name the data type which can be used to store wide characters in C++.
wchar_t

20.) What are/is the operator/operators used to access the class members?
Dot (.) and Arrow ( -> )

21.) Can we initialize a class/structure member variable as soon as the same is defined?
No, Defining a class/structure is just a type definition and will not allocated memory for the same.

22.) What is the data type to store the Boolean value?
bool, is the new primitive data type introduced in C++ language.

23.) What is function overloading?
Defining several functions with the same name with unique list of parameters is called as
function overloading.

24.)What is operator overloading?Defining a new job for the existing operator w.r.t the class objects is called as operator overloading.

25.) Do we have a String primitive data type in C++?
No, it’s a class from STL (Standard template library).

26.) Name the default standard streams in C++.
cin, cout, cerr and clog.

27.) Which access specifier/s can help to achive data hiding in C++?
Private & Protected.

28.) When a class member is defined outside the class, which operator can be used to associate the function definition to a particular class?
Scope resolution operator (::)

29.) What is a destructor? Can it be overloaded?
A destructor is the member function of the class which is having the same name as the class name and prefixed with tilde (~) symbol. It gets executed automatically w.r.t the object as soon as the object loses its scope. It cannot be overloaded and the only form is without the parameters.

30.) What is a constructor?
A constructor is the member function of the class which is having the same as the class name and gets executed automatically as soon as the object for the respective class is created.

31.) What is a default constructor? Can we provide one for our class?
Every class does have a constructor provided by the compiler if the programmer doesn’t provides one and known as default constructor. A programmer provided constructor with no parameters is called as default constructor. In such case compiler doesn’t provides the constructor.

32.) Which operator can be used in C++ to allocate dynamic memory?
‘new’ is the operator can be used for the same.

33.) What is the purpose of ‘delete’ operator?
‘delete’ operator is used to release the dynamic memory which was created using ‘new’ operator.

34.) Can I use malloc() function of C language to allocate dynamic memory in C++?
Yes, as C is the subset of C++, we can all the functions of C in C++ too.

35.) Can I use ‘delete’ operator to release the memory which was allocated using malloc() function of C language?
No, we need to use free() of C language for the same.

36.) What is a friend function?
A function which is not a member of the class but still can access all the member of the class is called so. To make it happen we need to declare within the required class following the keyword ‘friend’.

37.) What is a copy constructor?
A copy constructor is the constructor which take same class object reference as the parameter. It gets automatically invoked as soon as the object is initialized with another object of the same class at the time of its creation.