Pages

Friday, 22 May 2015

Link List formation

Algorithm


node *n;
n=(node*)malloc(sizeof(node));
n->data=x,y,z;
n->next=21,22,Null;
C program of link list

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct newnode
{
int number;
struct newnode *nextnode;
};
struct newnode *firstnode;
void linklist()
{
char ch='a';
struct newnode *ptr,*n;
while(ch!='n')
{
printf("\nEnter elements");
n=(struct newnode*)malloc(sizeof(struct newnode));
scanf("%d",&n->nnumber);
n->nextnode=0;
if(firstnode==0)
{
firstnode=n;
}
else
{
for(ptr=firstnode ;ptr->nextnode!=0;ptr=ptr->nextnode);
{
ptr->nextnode=n;
}
}
printf("\npress y for continue and n for no");
ch=getch();
}
}
void display()
{
struct newnode *ptr;
printf("Elements are");
for(ptr=firstnode;ptr!=0;ptr=ptr->nextnode)
{
printf("\n%d",ptr->nnumber);
}
}
void main()
{
clrscr();
firstnode=0;
linklist();
display();
getch();
}

Wednesday, 20 May 2015

Android splash screen tutorial

It is best way to represent your logo or show start up image until all data are not loaded to the application or first page.
To understand the splash screen you must have a knowledge of Thread in java, because splash scree is appear for only some milliseconds (3000 i.e 3 secs) which means running thread for some time and after that we have to terminate it.

Now lets start the implementation of splash screen.

create new layout file and copy following code inside it.

activity_splash_screen.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/appsplash"
    android:orientation="vertical" >
</LinearLayout>

in above i have add image in background of LinearLayout. So replace it with your image.

Add new class file for splash sceeen.

SplashScreen.java

package com.ilearn.xtreme;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;

public class SplashScreen extends Activity {

    // Splash screen timer in milliseconds
    private static int SPLASH_TIME_OUT = 3000;
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_scren);
       
        
        new Handler().postDelayed(new Runnable() {


            @Override
            public void run() {
                // This method will be executed once the timer is over and name of target activity
              
                Intent i = new Intent(SplashScreen.this, MainActivity.class);
                startActivity(i);

                // close this activity
                finish();
            }
        }, SPLASH_TIME_OUT);
    }

}


Dont forget to make this activity as launcher activity in manifest file by adding following code.

<activity
.........some code
<intent-filter>
 <action android:name="android.intent.action.MAIN" />
 <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
.........some code
</activity>


screenshot of output is as follows





share it and enjoy.
comment wherever you stuck thank you :)

Android Webview with forward backward and reload page tutorial

Webview in android is builtin tool to create application with web interface. It allows us to include webpage within the app without opening browser.
This tutorial includes webview with forward,backward and reload control.

we will start with creating one layout file.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/relativeLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        
        
        <EditText
            android:id="@+id/edit_search"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="3dp"
            android:layout_marginRight="3dp"
            android:layout_marginTop="3dp"
            android:hint="Search Url"
            android:paddingBottom="5dp"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:paddingTop="5dp" />

        <Button
            android:id="@+id/btnsearch"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_alignRight="@+id/edit_search"
            android:layout_centerVertical="true"
            android:layout_marginRight="17dp"
            android:background="@drawable/search_icon"
            android:gravity="right"
            android:paddingBottom="5dp"
            android:paddingRight="5dp"
            android:paddingTop="5dp" />

    </RelativeLayout>



    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="410dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/relativeLayout2"
        android:background="#ffffff" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true" />


</RelativeLayout>



for adding menus add menu item in res/menu/main.xml
I have added image icon for menu so you can add your own icons in drawable folder.

main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.phenomax.xtreme.MainActivity" >

    <item
        android:id="@+id/action_settings"
        android:showAsAction="always"
        android:icon="@drawable/ic_menu_settings"/>
    
     <item
        android:id="@+id/backward"
        android:showAsAction="always"
        android:icon="@drawable/backward"/>
     <item
        android:id="@+id/forward"
        android:showAsAction="always"
        android:icon="@drawable/forward"/>
     <item
        android:id="@+id/reload"
        android:showAsAction="always"
        android:icon="@drawable/reload"/>
      <item
        android:id="@+id/appicon"
        android:showAsAction="always"
        android:icon="@drawable/app_icon"/>
    


</menu>









Create class file for webview. and copy paste following code.

MainActivity.java

package com.ilearn.xtreme;


import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.*;

public class MainActivity extends Activity {
    

WebView web;
ProgressBar progressBar;
ImageButton backw;
ImageButton forw;
ImageButton reload;
ImageButton appbtn;
Button search;
EditText searchurl;

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

        web = (WebView) findViewById(R.id.webView1);
     
        searchurl=(EditText)findViewById(R.id.edit_search);
        
        
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
           
            searchurl=(EditText)findViewById(R.id.edit_search);
            String urlname=searchurl.getText().toString();
           
            progressBar = (ProgressBar) findViewById(R.id.progressBar);
                progressBar.setProgress(30); 
           
            web.setWebViewClient(new myWebClient());
                web.getSettings().setJavaScriptEnabled(true);
                web.getSettings().setLoadWithOverviewMode(true);
                web.getSettings().setUseWideViewPort(true);
                web.getSettings().setBuiltInZoomControls(true);
                web.loadUrl("http://"+urlname);
                  
                   
            }
          });
        
        
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) { //this method is used for adding menu items to the Activity
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) { //this method is used for handling menu items' events
    // Handle item selection
    switch (item.getItemId()) {

    case R.id.backward:
    if(web.canGoBack()) { //for go back history
    web.goBack();
    }
    return true;

    case R.id.forward:
    if(web.canGoForward()) {  //for go forward
    web.goForward();
    }
    return true;
    
    case R.id.reload:
        {
        web.reload();
        }
        return true;
        
    case R.id.action_settings:
    {
    
    }
    return true;

    default:
    return super.onOptionsItemSelected(item);
    }
    }
    
    
    

    public class myWebClient extends WebViewClient
    {
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
    // TODO Auto-generated method stub
    super.onPageStarted(view, url, favicon);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
    // TODO Auto-generated method stub
                progressBar.setVisibility(View.VISIBLE);
                
    view.loadUrl(url);
    return true;

    }

    @Override
    public void onPageFinished(WebView view, String url) {
    // TODO Auto-generated method stub
    super.onPageFinished(view, url);

    progressBar.setVisibility(View.GONE);
    }
    }

    // To handle "Back" key press event for WebView to go back to previous screen.
public boolean goback(int keyCode, KeyEvent event)
{
if ( web.canGoBack()) {
web.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}

}


Now in the manifest file dont forget to add permission for Internet Access.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ilearn.xtreme"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="19" />

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

    <application
        android:allowBackup="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ilearn.xtreme.MainActivity"
            android:label="@string/notitle"
             android:icon="@drawable/noicon"
         >
          
          <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

            </intent-filter>
  
        </activity>
        
    </application>


</manifest>



Monday, 18 May 2015

Android JSON Parsing tutorial Using PHP and MySql Database and Display it on ListView

Today i am going to show tutorial how to parse JSON data to android and display it on ListView.
Here first of all we need to have php file that fetch data from MySql Database. 
PHP file will convert that data into JSON format.

json.php

<?php
$host = ""; // host of MySQL server
$user = ""; // MySQL user
$pwd = ""; // MySQL user's password
$db = ""; // database name

// Create connection
$con = mysqli_connect($host, $user, $pwd, $db);

// Check connection
if(mysqli_connect_errno($con)) {
    die("Failed to connect to MySQL: " . mysqli_connect_error());
}

// query the application data
$sql = "SELECT * FROM updates ORDER By id desc";
$result = mysqli_query($con, $sql);

// an array to save the application data
$rows = array();

// iterate to query result and add every rows into array
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $rows[] = $row;
}

// close the database connection
mysqli_close($con);

// echo the application data in json format
echo '{"updates":' ,json_encode($rows),'}';


Now we need one layout file for android app.

activity_main.xml

 <RelativeLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#e8e8e8"  
  >

<ListView android:id="@+id/toplist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="#e8e8e8"
        android:layout_marginLeft="7dp"
        android:layout_marginTop="5dp"
       android:layout_marginRight="7dp"
  />

 </RelativeLayout>


We need another xml file for elements for listview. Create another xml file inside res/layout folder, name it listview_item.xml

listview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/listitem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#f9c045"
        android:textSize="13sp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        />
</RelativeLayout>


for fetching the data we need to write one class file for GET and POST method to access JSON objects from Server.

JSONGet.java

package com.im.json;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONStudentParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONStudentParser() {

    }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}


Now its time for main coding that is java file that will fetch the data and display it on ListView.

MainActivity.java

package com.im.json;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.im.json.JSONGet;

public class Result extends Activity  {
  ListView list;

  ArrayList<HashMap<String, String>> reslist = new ArrayList<HashMap<String, String>>();
  
  private static String url = "http://localhost:8080/json.php";  //change to your server url
  
  private static final String TAG_RESULT = "updates";
  private static final String TAG_NAME = "mark";  //JSON tag name
  
  
  JSONArray android = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main.xml);
        getActionBar().setDisplayHomeAsUpEnabled(true);  // for up navigation
        reslist = new ArrayList<HashMap<String, String>>();
      
       
new parsedata().execute()
    }

    private class parsedata extends AsyncTask<String, String, JSONObject> {
       private ProgressDialog pDialog;
       
      
      @Override
        protected void onPreExecute() {
            super.onPreExecute();
             
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
      }
      @Override
        protected JSONObject doInBackground(String... args) {
       
        JSONStudentParser jParser1 = new JSONStudentParser();
      
        
        
        List<NameValuePair> params = new ArrayList<NameValuePair>();
 params.add(new BasicNameValuePair("no_parameter","")); //here we do not want want to                                                            fetch data on such condition hence parameter will be blank.
       JSONObject json = jParser1.getJSONFromUrl(url, params);
        
        return json;
      }
       @Override
         protected void onPostExecute(JSONObject json) {
         pDialog.dismiss();
         try {
  
            android = json.getJSONArray(TAG_RESULT);
            for(int i = 0; i < android.length(); i++){
            JSONObject c = android.getJSONObject(i);
  
            String name = c.getString(TAG_NAME);
            
            HashMap<String, String> map = new HashMap<String, String>();
            map.put(TAG_NAME, name);
            
            reslist.add(map);
            list=(ListView)findViewById(R.id.toplist);
            ListAdapter adapter = new SimpleAdapter(MainActivity.this, reslist,
                R.layout.listview_item,
                new String[] { TAG_NAME }, new int[] {R.id.listitem});
                list.setAdapter(adapter);
                list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                       
                    }
                });
            }
            
             } catch (JSONException e) {
          e.printStackTrace();
        }
       }
    }
    
    
    
}


Enjoy :)

Share because share knowledge, get knowledge.

Comment if you find any error and ask if me you stuck.


How Much Traffic Do You Need To Make $100 With Google AdSense

It is possible to earn $100 in one year from google adsense.
Also, you must make sure that your website category is advertising friendly because your AdSense income depends a lot upon the category of your website. You can use Google AdWords Keyword Planner tool to find out the competition in your industry. If there is enough competition then we can assume that Google will fill your ad spaces with high paying ads

How Much Traffic Do You Need To Make Money With AdSense?

Let’s say you want to make $100 a year from Google AdSense and/or Google AdSense alternatives.

So, you have to create either:  pages that earn $1 a day pages that earn 50 cents a day OR pages that earn 25 cents a day .
Page Views
A page view is what Google counts in your reports every time a user views a page displaying Google ads. We will count one page view regardless of the number of ads displayed on that page.
For example, if you have a page displaying three ad units and it is viewed twice, you will generate two page views.
Clicks
For standard content ads, Google counts a click when a user clicks on an ad.
For link units, Google counts a click when a user clicks on an ad on the page of ads, after selecting a link in the link unit.
Page Click Through Rate (Page CTR)
The Page Click Through Rate (CTR) is the number of ad clicks divided by the number of impressions or page views that you have received.
Page CTR = Clicks / Page Views
For example, if you received 5 Clicks from 100 Page Views, then your Page CTR would be 5%. (5/100*100=5%)
Cost Per Click (CPC)
The Cost Per Click (CPC) is the amount you earn each time a user clicks on your ad. The CPC for any ad is determined by the advertiser; some advertisers may be willing to pay more per click than others, depending on what they’re advertising.
Page Revenue Per Thousand Impressions (Page RPM)
Page Revenue Per Thousand Impressions (RPM) is calculated by dividing your estimated earnings by the number of page views you received, then multiplying by 1000.
Page RPM = (Estimated Earnings / Number of Page Views) * 1,000
For example, if you earned an estimated $0.15 from 25 page views, then your page RPM would equal ($0.15 / 25) * 1000, or $6.00.
Estimated Earnings
Your account balance (or earnings) for the time period selected.