Monday, December 28, 2015

PHP Web-Services to Return JSON Array | PHP Web services | Simple JSON Array web services




<?php
//open database connection
$con = mysql_connect('localhost','root','root') or die('Cannot connect to the DB');
mysql_select_db('mydb',$con);

//make a sql query to store data
$sql="SELECT * from `mydb`.`user`";
$qur=mysql_query($sql);

//check the database response is it true or false
 if($qur){
 if (mysql_num_rows($qur)>0) {
//write data into json array
$info = array();

while ($row = mysql_fetch_assoc($qur))
{
     $arr = array();
     $arr["name"] = $row["name"];
     $arr["email"] = $row["email"];
     $info[] = $arr;
}

$json=array("status"=>1,"message"=>"done","result"=>$info);

}
else{
$json=array("status"=>0,"message"=>"No Record found!");
}
}
else{
$json=array("status"=>0,"message"=>"error");
}


OutPut:

{
    "status": 1,
    "message": "done",
    "result": [
        {
            "name": "manish",
            "email": "manish@gmail.com"
        },
        {
            "name": "Test",
            "email": "test@tes.com"
        }      
 ]
}

Thanks,
Manish

Thursday, November 26, 2015

PHP Login web service | PHP code for login | PHP Simple webservices



<?php
//take the values from client as json
$json = file_get_contents('php://input');
//open database connection
$con = mysql_connect('localhost','root','root') or die('Cannot connect to the DB');
mysql_select_db('mydb',$con);
//take json values into data variable
$data = json_decode($json);

//make a sql query to store data
$sql="SELECT * from `mydb`.`user` WHERE email = '".$data->{'email'}."' AND password = '".$data->{'password'}."'";
$qur=mysql_query($sql);

//check the database response it is true or false
 if($qur){
 if (mysql_num_rows($qur)>= 1 ) {
$json=array("status"=>1,"message"=>"done");
}
else{
$json=array("status"=>0,"message"=>"email or password not match!");
}
}
else{
$json=array("status"=>0,"message"=>"error");
}
//close the database connection
mysql_close($con);
//set header
header('Content-type: application/json');
//print the result as json object
echo json_encode($json);
?>

Sunday, October 18, 2015

Android Fragmnet Example code with full stack maintain | Fragment demo application | Simple Fragment example with action bar back button stack handle

Hello Friend,

Today I am going to share code for how to create android fragment and how to handle back stack. Have a look at below code or you can download full code from GIT server.



1)LoginActivity.java-

package com.androidhub4you.fragmentdemo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
public class LoginActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        findViewById(R.id.button__activity_main).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent mIntent=new Intent(LoginActivity.this,MainActivity.class);
                startActivity(mIntent);
            }
        });
    }
}


2)activity_login.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:text="Login Activity"
        android:textSize="26sp"
        android:textStyle="bold"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        android:layout_height="wrap_content" />
    <TextView
        android:layout_above="@+id/button__activity_main"
        android:layout_width="match_parent"
        android:text="(From Login Activity we will open Main Activity and inside Main Activity we will add Main Fragment in container)"
        android:textSize="18sp"
        android:textStyle="bold"
        android:gravity="center"
        android:layout_marginBottom="50dp"
        android:layout_centerHorizontal="true"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/button__activity_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="15dp"
        android:text="Open Main Activity"
        android:textSize="20sp"
        android:layout_centerInParent="true"
        android:paddingTop="15dp" />
</RelativeLayout>

  
 3)MainActivity.java-
package com.androidhub4you.fragmentdemo; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; /** * Manish Srivastava */ public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.v("<<main activity>>", "<<screen>>"); //display home back button ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); //In side Create method of MainActivity we will add main fragment FragmentTransaction transaction = getFragmentManager().beginTransaction(); FragmentMain fragmentMain = new FragmentMain(); transaction.addToBackStack("fragmentMain"); transaction.replace(R.id.container, fragmentMain); transaction.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.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: handleBackStack(); break; case R.id.action_settings: //do nothing break; } return super.onOptionsItemSelected(item); } //handle back stack from hardware back button and top action bar home back button public boolean handleBackStack() { //on back press check the count of fragment in stack int count = getFragmentManager().getBackStackEntryCount(); Log.v("<<Fragment in stack>>",String.valueOf(count)); if (count == 1) { //if count is 0 then finish main activity finish(); }else { //else remove one fragment from the stack FragmentTransaction transaction = getFragmentManager().beginTransaction(); getFragmentManager().popBackStackImmediate(); transaction.commit(); } return true; } //set action bar title name public void setActionBarTitle(String title) { getSupportActionBar().setTitle(title); } //handle the hardware back press @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode==KeyEvent.KEYCODE_BACK){ handleBackStack(); return true; } return super.onKeyDown(keyCode, event); } }
4)activity_main.xml-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

5)FragmentMain.java-
package com.androidhub4you.fragmentdemo;

import android.app.FragmentTransaction;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

/**
 * Manish Srivastava
 */
public class FragmentMain extends Fragment {


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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        final Button mButtonFragmentMain=(Button)view.findViewById(R.id.button__fragment_main);

        Log.v("<< main fragment>>","<<screen>>");

        mButtonFragmentMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //call the child fragment
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                FragmentChild fragmentChild = new FragmentChild();
                transaction.addToBackStack("fragmentChild");
                transaction.replace(R.id.container, fragmentChild);
                transaction.commit();

            }
        });

        //call the main activity set tile method
        ((MainActivity)getActivity()).setActionBarTitle("Home Fragment");

        return view;
    }
}
6)fragment_main.xml-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="Main Fragment Screen"
        android:textSize="26sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/button__fragment_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:paddingBottom="15dp"
        android:paddingTop="15dp"
        android:text="Open Child Fragment"
        android:textSize="20sp" />
</RelativeLayout>
7)FragmentChild.java-
package com.androidhub4you.fragmentdemo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Manish Srivastava
 */
public class FragmentChild extends Fragment {


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


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_child, container, false);

        //call the main activity set tile method
        ((MainActivity)getActivity()).setActionBarTitle("Child Fragment");


        return view;
    }
}

8)fragment_child.xml-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Child Fragment Screen"
        android:textSize="26sp"
        android:textStyle="bold" />
</RelativeLayout>

DOWNLOAD FULL CODE 
 
Thanks!
Manish

Saturday, September 26, 2015

Write PHP web service to store JSON Array into mysql database | PHP web-service simple example | Save json array values from android client device into mysql database using pho web-services

Hello Friends,
 Below is another  simple php code to store JSON Array into MySQL database from android client device-

 
1)saveJSONArray.php
<?php
//take the values from client as json
$json = file_get_contents('php://input');
//open database connection
$con = mysql_connect('localhost','root','Manish') or die('Cannot connect to the DB');
mysql_select_db('a4298774_mydb',$con);
//take json values into data variable
$data = json_decode($json, true);
//create for loop to put all data into database
foreach ($data as $item) {
//get the json values from client in name and number variable
$name = $item['name'] ;
$number= $item['number'] ;
//make a sql query to store data
$sql="INSERT INTO `a4298774_mydb`.`callhistory`(srnumber, name,number)VALUES (NULL,'$name', '$number')";
$qur=mysql_query($sql);

}
//check the database response it is true or false
if($qur){
$json=array("status"=>1,"message"=>"done");
}
else{
$json=array("status"=>0,"message"=>"error");
}
//close the database connection
mysql_close($con);
//set header
header('Content-type: application/json');
//print the result as json object
echo json_encode($json);
?>

2)MainActivity.java
package com.androidhub4you.savecontacts;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.submit).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new saveContactData().execute();
}
});
}

public class saveContactData extends AsyncTask<String, Void, String> {

ProgressDialog pd = null;

@Override
protected void onPreExecute() {
pd = ProgressDialog.show(MainActivity.this, "Please wait",
"Loading please wait..", true);
pd.setCancelable(true);

}

@Override
protected String doInBackground(String... params) {
saveContacts();
return null;
}

@Override
protected void onPostExecute(String result) {
pd.dismiss();

}

}
public void saveContacts() {
try {
JSONObject json1 = new JSONObject();
json1.put("name", "ravi");
json1.put("number", "123456798");

JSONObject json2 = new JSONObject();
json2.put("name", "sumit");
json2.put("number", "123456798");

JSONArray json=new JSONArray();
json.put(json1);
json.put(json2);

HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,50000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
HttpClient client = new DefaultHttpClient(httpParams);

String url = "http://androidhub4you.com/saveJSONArray.php";

HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes(
"UTF8")));
request.setHeader("Accept", "application/json");
request.addHeader("Content-Type", "application/json");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
if (entity != null) {
InputStream instream = entity.getContent();

Log.v("<<server response>>", converResponseToString(instream));
}
} catch (Throwable t) {
}
}
//Method to change the inputstream into string

public String converResponseToString(InputStream InputStream)
{
String mResult="";
StringBuilder mStringBuilder;
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(InputStream,"UTF-8"),8);
mStringBuilder = new StringBuilder();
mStringBuilder.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null)
{
mStringBuilder.append(line + "\n");
}
InputStream.close();
mResult=mStringBuilder.toString();
return mResult;
}catch(Exception e){
return mResult;
}
}

}


3)activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.androidhub4you.savecontacts.MainActivity" >

<Button
android:id="@+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="submit" />

</RelativeLayout>

4)Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidhub4you.savecontacts"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.Black" >
<activity
android:name=".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>


  
Write comments for more query!


Thanks,
Manish