Pages

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.

Android Shared preferences

Shared preferences in android is very effective to handle session management and also for storing value for long time even if you close the application.
Following are simple code for shared preferences.
Note that you must commit the preferences for save the value.
It can be done with commit() method.

MainActivity.java.
package com.im.sharedpreferences;

import com.im.sharedpreferences.*;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {

TextView name ;
TextView phone;
TextView email;

public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "NAME";
public static final String Phone = "PHONE";
public static final String Email = "EMAIL";


SharedPreferences sharedpreferences;

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

name = (TextView) findViewById(R.id.editTextName);
phone = (TextView) findViewById(R.id.editTextPhone);
email = (TextView) findViewById(R.id.editTextEmail);


sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

if (sharedpreferences.contains(Name))
{
name.setText(sharedpreferences.getString(Name, ""));

}
if (sharedpreferences.contains(Phone))
{
phone.setText(sharedpreferences.getString(Phone, ""));

}
if (sharedpreferences.contains(Email))
{
email.setText(sharedpreferences.getString(Email, ""));

}
if (sharedpreferences.contains(Street))
{
street.setText(sharedpreferences.getString(Street, ""));

}
if (sharedpreferences.contains(Place))
{
place.setText(sharedpreferences.getString(Place,""));

}

}

public void run(View view){
String n = name.getText().toString();
String ph = phone.getText().toString();
String e = email.getText().toString();

Editor editor = sharedpreferences.edit();
editor.putString(NAME, n);
editor.putString(PHONE, ph);
editor.putString(EMAIL, e);


editor.commit();

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

}
activiy_main.xml.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".DisplayContact" >

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="370dp"

>

<EditText
android:id="@+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="5dp"
android:layout_marginLeft="82dp"
android:ems="10"
android:inputType="text" >

</EditText>

<EditText
android:id="@+id/editTextEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="textEmailAddress" />



<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="28dp"
android:onClick="run"
android:text="@string/save" />



<EditText
android:id="@+id/editTextPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="phone|text" />

</RelativeLayout>

</ScrollView>


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

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />

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

Saturday, 18 April 2015

Human Arts.


Occasionally, human are creating new arts through them. Sometimes they makes tattoo or design on their body and present arts. From this kind of arts they also wants to convey message to society.

1. 


2. 


3. 



4.


5.

Friday, 17 April 2015

Wednesday, 8 April 2015

Fact about facebook that you dont know even if you are using it.

1. The reason Facebook is blue, is because Mark Zuckerberg is colorblind.


2. Facebook tracks and records almost everything you do on the internet if you’re logged in at the same time.

3. More than 600,000 hacking attempts are made on Facebook accounts every day.

4. It’s possible to change your Facebook language to “Pirate”.


5. Al Pacino was the first “face” on Facebook.


Content  Courtesy -Unbelievable facts 

Tuesday, 7 April 2015

India Pulls Off Great Escape in Yemen, 4000 Evacuated From War Zone


Mission Accomplished. The government is looking to wrap up Operation Raahat with almost all the estimated 4000 Indians in Yemen evacuated safely from the war zone.

The Indian Navy's INS Tarkash will reach Djibouti from Al Hodeidah with 74 people this morning and the INS Sumitra will reach Al Hodeidah, to ferry out one of the last batches. Air India will run its last evacuation flights from Yemeni capital Sana'a and the government has asked all Indians who want to leave to reach the capital.

On Monday, India rescued more than 1,000 people by plane and ship, the second time in two days that such a large number have been brought out since Saudi Arabia launched air strikes against Iran-allied Houthi rebels in Yemen on March 26. India has been asked by 26 nations - including the United States - to help get their citizens out of the conflict zone.

The Indian Navy Ship Mumbai, a premier warship, rescued nearly 1000 people from nine countries in two batches. Though not designed to ferry people, the Mumbai carried one and a half times the number of crew on board.

The crew emptied five messes and their cabins so that women and children got bunks to sleep on. Hot food was served and doctors were at hand.
 
Other warships, the INS Sumitra and the INS Tarkash have done a similar job across the coast of war-torn Yemen.