How to restart Android Phone if phone is hanged

I have installed Android Lollipop on my Nexus 4 yesterday.. Today while chatting , suddenly my phone got hanged.. I have Screen lock set with Pattern.. After few seconds screen got locked.. Whenever i am trying to unlock i see following screen.. None of the buttons were working.. In nexus 4 you cant remove battery very easily and power off button also not working.. It was a complete deadlock..

10833970_760717293966106_1443141527_n

Suddenly i got an Idea.. I connected my nexus to my Laptop using USB cable.. Opened Up Android Studio.. then Opened up Adb Terminal.. Ran Reboot command from Adb shell.. Finally i could reboot my nexus 4..

retrieve

Steps:
1. Open Up Android Studio
2. Click on Tools –> Open Terminal
3. Type “adb shell” in the terminal below and press enter
4. Type “reboot” and press enter

Your device should reboot..

Few Android Apps Which you cant ignore

Android Listview Pagination

In  this is the basic step to implement paging concept in ListView .We can say dynamic loading of element. ListView is very useful and powerful view in android.So this will help you a lot.In this tutorials you see how to parse JSON data from REST API & then showing in ListView dynamically .

Create a blank activity , Java Page Name :MainActivity , XML Page Name :activity_main.

Don’t try to copy & paste code until you understand whats going on .

MainActivity.java

package com.example.androidjsontesting;

import android.app.*;
import android.os.*;
import android.widget.*;
import org.json.*;
import android.content.Context;
import android.util.Log;
import android.view.View;
import java.util.ArrayList;

public class MainActivity extends Activity {

public TextView lPageNavigatorText;
public Context lContext;
public Button lSearchButton ;
public EditText lSearchEdit;
public ListView lItemList;
public ProgressDialog lProgressDia;
public LinearLayout lPageNavLayout;

// contacts JSONArray
JSONArray lJSONArray = null;

int lItemsSize = 0;
int lPagesSize=0;
ContactListAdapter lListAdapter;
ArrayList<Contact> lResultContacts;

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

lContext = MainActivity.this;

lSearchButton=(Button)findViewById(R.id.buttonSearch);
lSearchButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View lView)
{
new GetContacts().execute();
}
});

lSearchEdit=(EditText)findViewById(R.id.Searchtext);
lPageNavigatorText = (TextView)findViewById(R.id.title);
lItemList = (ListView)findViewById(R.id.list);
lPageNavLayout = (LinearLayout)findViewById(R.id.btnLay);

lResultContacts = getEmptyContacts();

lListAdapter = new ContactListAdapter(lContext, new ArrayList<Contact>() );
lItemList.setAdapter(lListAdapter);

/* Get Total Size. */
lItemsSize = getItemsSize();

/* Get the pages. */
lPagesSize = calculatePages(lItemsSize, 10);

new GetContacts().execute();
}

@Override
public void onStart()
{
super.onStart();
}

/**
* Get the contacts.
*/
ArrayList<Contact> getEmptyContacts()
{
return new ArrayList<Contact>();
}

/**
* Get the total item size.
*/
public int getItemsSize()
{
return lResultContacts.size();
}

/**
* Get how much pages need to create for the item size.
*/
int calculatePages(int lSize, int lItemsPerPage)
{
int pages = lSize/lItemsPerPage;
if(pages * lItemsPerPage!= lSize)
{
pages ++;
}
return pages;
}

/**
* Draw the pages on screen.
*/
public void drawPages(int lSize)
{
final int lPageNumbers = lSize;
Button lPages[] = new Button[lPageNumbers];
for(int r = 0; r < lPages.length; r++)
{
lPages[r] = new Button(lContext);
lPages[r].setText( ( r + 1) + “”);
lPages[r].setId(r );
lPages[r].setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View lView)
{
manualClick(lView);
}
});
}

/* Add the button at scrollview. */
for(Button lPageButton:lPages)
{
lPageNavLayout.addView(lPageButton);
if(lPageButton.getId() == 0 && !lResultContacts.isEmpty())
{
manualClick(lPageButton);
}
}
}

/**
* Get the url from search edit.
*/
public String goToURL()
{
String ts= lSearchEdit.getText().toString();
String url = “http://latest.bloomapi.com/api/search?limit=50&offset=0&key1=last_name&op1=eq&value1=”+ts;
return url ;
}

public void manualClick(View lView)
{

int lPageNumber = lView.getId();
if(lItemList!=null && lListAdapter!=null)
{
if(!lResultContacts.isEmpty())
{
lListAdapter.lContactsData.clear();

try{
lListAdapter.lContactsData.add(lResultContacts.get(lPageNumber*10));

if(lResultContacts.size() >= ((lPageNumber*10) + 1 ))
{
lListAdapter.lContactsData.add(lResultContacts.get((lPageNumber*10) + 1 ));
}
if(lResultContacts.size() >= ((lPageNumber*10) + 2 ))
{
lListAdapter.lContactsData.add(lResultContacts.get((lPageNumber*10) + 2));
}
if(lResultContacts.size() >= ((lPageNumber*10) + 3 ))
{
lListAdapter.lContactsData.add(lResultContacts.get((lPageNumber*10) + 3));
}
if(lResultContacts.size() >= ((lPageNumber*10) + 4 ))
{
lListAdapter.lContactsData.add(lResultContacts.get((lPageNumber*10) + 4));
}
if(lResultContacts.size() >= ((lPageNumber*10) + 5 ))
{
lListAdapter.lContactsData.add(lResultContacts.get((lPageNumber*10) + 5 ));
}
if(lResultContacts.size() >= ((lPageNumber*10) + 6 ))
{
lListAdapter.lContactsData.add(lResultContacts.get((lPageNumber*10) + 6 ));
}
if(lResultContacts.size() >= ((lPageNumber*10) + 7 ))
{
lListAdapter.lContactsData.add(lResultContacts.get((lPageNumber*10) + 7 ));
}
if(lResultContacts.size() >= ((lPageNumber*10) + 8 ))
{
lListAdapter.lContactsData.add(lResultContacts.get((lPageNumber*10) + 8 ));
}
if(lResultContacts.size() >= ((lPageNumber*10) + 9 ))
{
lListAdapter.lContactsData.add(lResultContacts.get((lPageNumber*10) + 9 ));
}

lPageNavigatorText.setText(((lPageNumber*10)+1) +”-” + (((lPageNumber*10)+9)+1));

}catch(Exception lE){

/* Calculate how much items the page should contains. */
int lItemsShown = (lPagesSize -1)* 10;
/* but */
int lExtraItems = lItemsSize – lItemsShown;
int i = 0;
lListAdapter.lContactsData.clear();
while(i < lExtraItems)
{
lListAdapter.lContactsData.add(lResultContacts.get(lItemsShown + i));
i++;
}
//lPageNavigatorText.setText( (lPageNumber+1) + “” + lItemsSize + ” ” + ((lPageNumber*10)+1) +”-” + lItemsSize + “/” + lItemsSize);
lPageNavigatorText.setText(((lPageNumber*10)+1) +”-” + (((lPageNumber*10)+9)+1));
}
lListAdapter.notifyDataSetChanged();

}
}else{

}
}

/**
* Get private class to load contacts.
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {

ArrayList<Contact> lContactsArray;

@Override
protected void onPreExecute()
{
super.onPreExecute();
lProgressDia = new ProgressDialog(MainActivity.this);
lProgressDia.setMessage(“Please wait…”);
lProgressDia.setCancelable(false);
lProgressDia.show();
lContactsArray = new ArrayList<Contact>();
}

@Override
protected Void doInBackground(Void… arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(goToURL(), ServiceHandler.GET);
Log.d(“Response: “, “> ” + jsonStr);
if (jsonStr != null)
{
try
{
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
lJSONArray = jsonObj.getJSONArray(“result”);
// looping through All Contacts
for (int i = 0; i < lJSONArray.length(); i++) {
Integer a = lJSONArray.length();
Log.d(“loop”, a.toString());
JSONObject c = lJSONArray.getJSONObject(i);

String id = c.getString(“npi”);
String name = c.getString(“first_name”);
String email = c.getString(“last_name”);

Contact lContact = new Contact();
lContact.lName = name;
lContact.lEmail = email;
lContact.lMobile = id;

lContactsArray.add(lContact);

}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.d(“ServiceHandler”, “Couldn’t get any data from the url”);
}
return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (lProgressDia.isShowing())
lProgressDia.dismiss();

lResultContacts = lContactsArray;
/* Clear all views. */
lPageNavLayout.removeAllViewsInLayout();

lItemsSize = getItemsSize();
lPagesSize = calculatePages( lItemsSize, 10);
try
{
drawPages(lPagesSize);
}catch(Exception r){

}
lListAdapter.notifyDataSetChanged();
}

}

}

Here is my activity_xml page :

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical”>

<EditText
android:id=”@+id/Searchtext”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:ems=”10″
android:inputType=”textCapCharacters”
android:textColor=”@android:color/black”
/>

<Button
android:id=”@+id/buttonSearch”
android:layout_width=”125dp”
android:layout_height=”35dp”
android:text=”@string/search”
android:gravity=”center”
android:layout_gravity=”center”
android:background=”@android:color/holo_blue_bright”

/>

<TextView
android:id=”@+id/title”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:textColor=”@android:color/black”
android:gravity=”center”
android:textSize=”16sp”
android:background=”@android:color/darker_gray”
android:padding=”10dp”/>

<ListView
android:id=”@+id/list”
android:divider=”#000″
android:dividerHeight=”1dp”
android:cacheColorHint=”#00000000″
android:layout_width=”fill_parent”
android:layout_height=”0dp”
android:layout_weight=”1″
android:fadingEdge=”none”/>

<HorizontalScrollView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”>
<LinearLayout
android:id=”@+id/btnLay”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:orientation=”horizontal” >
</LinearLayout>
</HorizontalScrollView>

</LinearLayout>

Create another blank activity ,set xml file name :activity_single_contact.xml & java file name :SingleContactActivity.java

Here is my xml file

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:padding=”10dp”>
<!– Name Label –>
<TextView android:id=”@+id/name_label”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:textSize=”25sp”
android:textStyle=”bold”
android:paddingTop=”10dip”
android:paddingBottom=”10dip”
android:textColor=”#43bd00″/>
<!– Email Label –>
<TextView android:id=”@+id/email_label”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:textColor=”#acacac”/>
<!– Mobile Label –>
<TextView android:id=”@+id/mobile_label”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:textStyle=”bold”/>
</LinearLayout>

Here is my java file code .

package com.example.androidjsontesting;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleContactActivity extends Activity {

// JSON node keys
private static final String TAG_NAME = “name”;
private static final String TAG_EMAIL = “email”;
private static final String TAG_PHONE_MOBILE = “mobile”;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);

// getting intent data
Intent in = getIntent();

// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String email = in.getStringExtra(TAG_EMAIL);
String mobile = in.getStringExtra(TAG_PHONE_MOBILE);

// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblEmail = (TextView) findViewById(R.id.email_label);
TextView lblMobile = (TextView) findViewById(R.id.mobile_label);

lblName.setText(name);
lblEmail.setText(email);
lblMobile.setText(mobile);
}
}

Create list_item.xml which shows users name,email id , mobile number in listview .

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:orientation=”vertical”
android:padding=”10dp”
android:paddingLeft=”10dp”
android:paddingRight=”10dp” >

<!– Name Label –>

<TextView
android:id=”@+id/name”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:paddingBottom=”2dip”
android:paddingTop=”6dip”
android:textColor=”#43bd00″
android:textSize=”16sp”
android:textStyle=”bold” />

<!– Email label –>
<TextView
android:id=”@+id/email”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:paddingBottom=”2dip”
android:textColor=”#acacac” />

<!– Mobile number label –>
<TextView
android:id=”@+id/mobile”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:gravity=”left”
android:text=”Mobile: “
android:textColor=”#5d5d5d”
android:textStyle=”bold” />

</LinearLayout>

 Now create ServiceHandler class .

Here is my code :ServiceHandler.java

package com.example.androidjsontesting;

import java.io.IOException;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

/*
* Making service call
* @url – url to make request
* @method – http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}

/*
* Making service call
* @url – url to make request
* @method – http request method
* @params – http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;

// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}

httpResponse = httpClient.execute(httpPost);

} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, “utf-8″);
url += “?” + paramString;
}
HttpGet httpGet = new HttpGet(url);

httpResponse = httpClient.execute(httpGet);

}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);

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

return response;

}
}

Now create ContactListAdapter.java file .This page make a vital role over all project. Before starting this page you take a look about Android BaseAdapter .

Here is my code ContactListAdapter.java

package com.example.androidjsontesting;

import android.view.*;
import android.widget.*;

import android.content.Context;

import com.example.androidjsontesting.R;
import java.io.Serializable;
import java.util.ArrayList;

@SuppressWarnings(“serial”)
public class ContactListAdapter extends BaseAdapter implements Serializable
{

/* Variables. */
public ArrayList<Contact> lContactsData;
private LayoutInflater lInflater;

public ContactListAdapter(Context lContext, ArrayList<Contact> lDataList)
{
lContactsData = lDataList;
lInflater = LayoutInflater.from(lContext);
}

public int getCount(){
return lContactsData.size();
}

public Object getItem( int position) {
return lContactsData.get(position);
}

public String getName(int p){
return lContactsData.get(p).lName;
}

public ArrayList<Contact> getArrayData()
{
return lContactsData;
}

public long getItemId( int position) {
return position;
}

/**
* Get the view by return, List view will shows the views one by one.
*/
public View getView( int lPosition, View lView, ViewGroup lViewGroup)
{
/* Get a empty View Holder.*/
ViewHolder lViewHolder;
if (lView == null )
{
lView = lInflater.inflate(R.layout.list_item, null );
lViewHolder = new ViewHolder();
lViewHolder.lName = (TextView) lView.findViewById(R.id.name);
lViewHolder.lEmail = (TextView) lView.findViewById(R.id.email);
lViewHolder.lMobile = (TextView) lView.findViewById(R.id.mobile);

lView.setTag(lViewHolder);
}
else
{
lViewHolder = (ViewHolder) lView.getTag();
}

lViewHolder.lName.setText(((Contact)this.getItem(lPosition)).lName);
lViewHolder.lEmail.setText(((Contact)this.getItem(lPosition)).lEmail);
lViewHolder.lMobile.setText(((Contact)this.getItem(lPosition)).lMobile);

return lView;
}

/** private static class which hold the web name and thumb */
private static class ViewHolder {
TextView lName, lEmail, lMobile;
@SuppressWarnings(“unused”)
ImageView lThumb;
}
}

Finally i create Contact.java page . Where i initialize users name,email,mobile no.

package com.example.androidjsontesting;

public class Contact

{
public String lName, lEmail, lMobile;
}

If it give error for iamges then use any other images and run application & Add this code in your manifest file

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

Android Listview Pagination

How to send value from one activity to another in Android

I have explained how to open one activity from another activity on button click in an earlier post. This post is just an extension of that tutorial which shows how to send value from one activity to another activity in Android. As you have seen, we can easily open one activity from another using Android intent. To send some extra message, it again is the Android intent that would help us.

First, take an Android edittext in your layoutOne and get the value to a string variable in the layoutOne’s java page(inside the openNewActivity method of course.). Then add the value to the intent using putExtra method. Now call the second activity.  See the code below:

public void openNewActivity(View view) {

// Do something in response to button
Intent intent = new Intent(this, LayoutTwoActivity.class);

//get the value of the editText, convert it to string and store it in a string variable
EditText editText = (EditText) findViewById(R.id.myEditText);
String message = editText.getText().toString();

intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);

}

You also need to add the definition of the EXTRA_MESSAGE variable at the beginning of the class like,

public final static String EXTRA_MESSAGE = “com.example.buttonclicktutorial.MESSAGE”;

Inside the second layout, take a textview. Now, all you need to do is to get the value from the intent and set the value to the textview. We are going to do it inside the onCreate method of Course. See the code below:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_two);

//get the intent and take the value to a string message variable
Intent intent = getIntent();
String message = intent.getStringExtra(LayoutOneActivity.EXTRA_MESSAGE);

//set the value of message to the textview
TextView textView = (TextView)findViewById(R.id.myTextView);
textView.setText(message);
}

 

All done. Now run the app and see whether it works like the below screenshots or not:

button click1

 

button click2

 

Download the source code from here.

How to add additional email to the user accounts with codeigniter using flexi-auth

Frankly speaking, flexi-auth library doesn’t allow us to add additional emails to the user accounts. So, in order to do that within your codeigniter app you have to write your own methods within the flexi-auth library files.

Alright, first let’s say we’ve a controller method ‘addEmail’ which adds emails to the user accounts as follows:

 

public function addEmail()

{

if ($this->input->post(‘addEmail’))

{

$user_id = $this->flexi_auth->get_user_by_id()->result();

$username= $user_id[0]->uacc_username;

$email = $this->input->post(‘addEmail’);

$this->load->model(‘auth_model’);

$this->load->model(‘flexi_auth_model’);

//get the 40 digit token using Flexi-auth

$activation_token = sha1($this->flexi_auth_model->generate_token(20));

$check = $this->patient_model->set_patient_email_details($username,$email,$activation_token);

//check the email availability which is post by user

if(!empty($check))

{

$email_to = $email;

$this->session->set_flashdata(‘message’, ‘A activation code/link send to your email id.’);

$this->data['message'] = (! isset($this->data['message'])) ? $this->session->flashdata(‘message’) : $this->data['message'];

$this->auth_model->addNewEmail_Patient($email_to, $activation_token);

}else{

$this->session->set_flashdata(‘message’, ‘We have an account with this email id, please enter another email id.’);

$this->data['message'] = (! isset($this->data['message'])) ? $this->session->flashdata(‘message’) : $this->data['message'];

 }

//after all ckecking it will redirect to patient home page

redirect(‘patient’);

}

}

 

In the patient_model model the set_patient_email_details method is given as follows which checks if the recently added email is available,if it’s yes then it adds the email to the database table:

 

public function set_patient_email_details($username, $email, $activation_token)

{

$this->load->library(‘form_validation’);

 

// Set validation rules.

// The custom rules ‘identity_available’ and ‘validate_password’ can be found in ‘../libaries/MY_Form_validation.php’.

$validation_rules = array(

array(‘field’ => ‘addEmail’,'label’ => ‘Email Address’, ‘rules’ => ‘required|valid_email|identity_available’)

);

$this->form_validation->set_rules($validation_rules);

 

// Run the validation.

if ($this->form_validation->run())

{

//search email available on secondary_email table

$this->db->select(‘email’);

$this->db->from(‘secondary_email’);

$this->db->where(‘email’, $email);

$query = $this->db->get();

$result= $query->num_rows;

if($result ==0 )

{

$data = array(

           ’username’ => $username,

           ’activation_token’ => $activation_token,

           ’email’ => $email

       );

// if found the email is available then insert the newly added email  to the corresponding table.

       return $this->db->insert(‘secondary_email’, $data);

}

}

   }

Now, send an email to the newly added email with a confirmation token,a redirective activation link and the corresponding user-id of the user. In order to do that, just add a method ‘addNewEmail_Patient’ to the ‘auth_model’ in the flexi-auth library:

 

function addNewEmail_Patient($email_to, $activation_token)

{

// The ‘update_email_via_verification()’ function generates a verification token that is then emailed to the user.

$this->flexi_auth->send_patient_email_via_verification($email_to, $activation_token);

// Save any public status or error messages (Whilst suppressing any admin messages) to CI’s flash session data.

$this->session->set_flashdata(‘message’, $this->flexi_auth->get_messages());

}

 

And now go to the flexi_auth(/libraries/flexi_auth) file and add the send_patient_email_via_verification method:

 

public function send_patient_email_via_verification($email_to, $activation_token)

{

if ($this->CI->flexi_auth_model->send_email_patient($email_to, $activation_token))

{

$this->CI->flexi_auth_model->set_status_message(‘email_activation_email_successful’, ‘config’);

return TRUE;

}

else

{

$this->CI->flexi_auth_model->set_error_message(‘email_activation_email_unsuccessful’, ‘config’);

return FALSE;

}

$this->CI->flexi_auth_model->set_error_message(‘update_unsuccessful’, ‘config’);

return FALSE;

}

After the user gets the activation email of the newly added email he/she will click the activation link provided by the mail that activates the added email.
To do this, just add another method,’activate_new_email’ in the ‘patient’ controller next to the ‘addEmail’ method given at the top:

function activate_new_email($user_id, $confirmToken)

{

//check Token the current user details

$current_user_id = $this->flexi_auth->get_user_by_id()->result();

$currentuserid= $current_user_id[0]->uacc_id;

if($user_id == $currentuserid )

{

// if current user is logged-in then then check the token  after checking it will redirect to patient home page

$this->patient_model->getToken($user_id, $confirmToken);

redirect(‘patient’);

}else

{

//it not it will redirect to login page.

redirect(‘auth/login’);

}

}

 

Now go to the ‘patient_model’ and add the following method to get the token and match it with the database table,if it has been matched successfully then ‘active’ field of the database table will be updated with the value ‘1’ and otherwise it’ll be redirected to the corresponding homepage. :

function getToken($user_id, $confirmToken)

{

$this->db->select(‘*’);

$this->db->from(‘secondary_email’);

$this->db->where(‘activation_token’, $confirmToken);

    $query = $this->db->get();

foreach($query->result_array() as $row) {

$result= $row['activation_token'];}

if(!empty($result))

{

$tableToken= $result;

if ($confirmToken == $tableToken)

{

$data = array(

              ’active’ => ’1′

           );

 

$this->db->where(‘activation_token’, $confirmToken);

$this->db->update(‘secondary_email’, $data);

return TRUE;

}else

{//// token does’t match

$this->session->set_flashdata(‘message’, ‘Invalid token,try again..’);

$this->data['message'] = (! isset($this->data['message'])) ? $this->session->flashdata(‘message’) : $this->data['message'];

return FALSE;

}

} else{

//if $result is empty -> invalid token.

return FALSE;

}

}

One last thing to remember that to add a new email to the user accounts you have to create an additional table other than the default flexi-auth ‘user-accounts’ table. We’ve named that as ‘secondary_email’ here. Nevertheless, we’re generating the approval token from flexi-auth and matching it with the default flexi-auth ‘user-accounts’ table data and we’re checking the email availability with flexi-auth too.

When retrieving the newly added email to show to the user on the webpage we’re getting it from the secondary_email table where the active column is set to ‘1’.

 

How to login with Windows live id into your website

To develop with Windows Live Messenger Connect, you must register and obtain a client ID.

All programmatic interaction with Windows Live requires a client ID, which uniquely identifies your application to Windows Live. Your application must include the client ID in every request that it sends to the Messenger Connect API Service.

Before you register

To get ready to register, you must:

  • Decide which application type you want.  If you are going to try both web and desktop applications, you must obtain two separate client IDs. (Sample Messenger Connect web and desktop applications are available.
  • Obtain a Windows Live ID, which you must have to be able to get a client ID for your application. If you don’t already have a Windows Live ID, the registration process guides you in creating one.
    The client ID that you obtain is associated with the specific Windows Live ID that you use during registration, and this association cannot be changed later. We recommend that you create a new Windows Live ID specifically for managing your Windows Live application.
  • To register your application
    1. Sign in to the Windows Live application management site
      • If you are a returning user, you see a page that lists your registered applications. Click Add an application on this page.
      • If you are new to the site, you see a page similar to following.
        Add application page from the Portal
  1.            Type an application name (for example, “Contoso”). This is the name that users will see in the Windows Live user interface (UI). The application name should include your company name or the name of your web site.
  2. Select an application type from the options that appear next to Application type. For more information, such as Web Application or Desktop Application
  3. Provide the following information, depending on the application type you choose:
    • Web application—Provide the domain of your site. You cannot change this domain later. Do not specify a domain that is used for redirection.
      Note that you can create a callback URL in a subdomain of the domain that you registered, for example, http://mysubdomain.contoso.com. This practice is called subdomain wildcarding, and it is enabled by default for all applications.
      If you have multiple domains, you must register separate applications—one for each domain. If you have one domain with subdomains, you can either register separate applications for each subdomain, or register one application that uses the root domain and then use the same client ID on subdomains. When you register multiple applications, each application has its own name and logo.
    • Activity feed—This application type is available only to specific Windows Live partners.
    • Desktop application—Provide the home page URL at which your users can learn more—for example, a page that contains download instructions. You cannot change the domain of the home page URL later. Do not specify a domain that is used for redirection.
  4. Click I accept to accept the Windows Live Terms of Service. This action registers your application. The next screen, shown in the following image, displays the client ID and secret key values for your application. Make a note of these values, because you will need them when you write your application.
    Add application confirmation page from the Portal
After getting Client ID and Secret Key you have to include this code
 <?php
// Begin the session// Declaring the variables required for authentication
$client_key = ‘Your Client ID’;
$client_secret = ‘Your Secret key’;
$redirect_uri = ‘Your redirect url’;

// Check if the authorization code is received or not !
// Also, if the access token is received or not
if (!isset($_REQUEST['code']) && !isset($_SESSION['access_token'])) {
// Print the below message, if the code is not received !
echo “<br/><br/>”;
echo ‘<center><a href = “https://login.live.com/oauth20_authorize.srf?client_id=’.$client_key.’&scope=wl.basic+wl.emails&response_type=code&redirect_uri=’.$redirect_uri.’”><img src=”windows.png”/></center></a>’;

}

else {
if(!isset($_SESSION['access_token'])) {
// Initialize a cURL session
$ch = curl_init();

// Set the cURL URL
curl_setopt($ch, CURLOPT_URL, “https://login.live.com/oauth20_token.srf”);

// The HTTP METHOD is set to POST
curl_setopt($ch, CURLOPT_POST, TRUE);

// This option is set to TRUE so that the response
// doesnot get printed and is stored directly in
// the variable
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

// The POST variables which need to be sent along with the HTTP request
curl_setopt($ch, CURLOPT_POSTFIELDS,”code=” . $_REQUEST['code'] . “&client_id=” . $client_key . “&client_secret=” . $client_secret . “&redirect_uri=”.$redirect_uri.”&grant_type=authorization_code”);

// Execute the cURL request
$data = curl_exec($ch);

// Close the cURL connection
curl_close($ch);

// Decode the JSON request and remove the access token from it
$data = json_decode($data);

$access_token = $data->access_token;

// Set the session access token
$_SESSION['access_token'] = $data->access_token;
}
else {
// If session access token is set
$access_token = $_SESSION['access_token'];
}
// Initialize another cURL session
$ch = curl_init();

// Set all the options and execute the session
curl_setopt($ch, CURLOPT_URL, “https://apis.live.net/v5.0/me?access_token=” . $access_token);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($ch);
curl_close($ch);

// Get the data from the JSON response
$data = json_decode($data,true);

}

?>

File to Large / Convert FAT to NFTS without loosing data

Amit posted http://blogs.technicise.com/how-to-solve-file-is-too-large-for-the-destination-file-system-error-in-windows/ which is a working solution. There is a better solution for converting an external drive FAT32-16 to NFTS in which no data is lost on the external hard drive.

The youtube video tutorial https://www.youtube.com/watch?v=rj4HVsQlT00 explains the conversion process clearly and precisely.

 

Astrid is going to close service

Those who have been using Astrid for long time like me, it is obviously a bad news for them. Astrid is going to close there service from 5th August 2013.

Today i got an EMail from Jon Paris & the Astrid Team, 660 4th Street #259, San Francisco, CA, 94107 and shocked after reading the content. They are suggesting to download the user data from Export Astrid before 5th August.

Email from Astrid

Email from Astrid

Here they suggest four links Wrike,WunderlistSandglaz, and Any.do where the user can easily import their Astrid data.

If you are an Astrid user and want to get your old data from Astrid, immediately Export your data before 5th August 2013 otherwise you will loose your all previous data.

 

How to change Android launcher activity from AndroidMainfest file

While creating a new activity, we are given a check box to make it the launcher activity. The first activity on an Android project by default becomes the launcher activity. But, to change the launcher activity manually ? To do that, we need to open the AndroidMainfest.xml file located in the root folder of the project.

AndroidMainfest

 

First, download an example. My example project contains two activities. See the AndroidMainfest.xml file of the project:

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”com.example.buttonclicktutorial”
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.example.buttonclicktutorial.LayoutOneActivity”
android:label=”@string/app_name” >
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
<activity
android:name=”com.example.buttonclicktutorial.LayoutTwoActivity”
android:label=”@string/title_activity_layout_two” >
</activity>
</application>

</manifest>

 

As you can see, there are two activity tags. Whenever a new activity gets created, some information on that activity is stored inside the AndroidMainfest.xml file. Out of them, only one contains the categoty_launcher intent filter that makes that particular activity the launcher activity. The code is highlighted above.

To change your launcher activity, you can simply cut and paste the highlighted code inside the activity tag want to make the launcher activity. If no activity contains that code, the project will not get launched and you will get the following error:

No launcher activity

How to open a new Android activity from another activity on clicking a button

Go through my previous post on Android to learn how to create Android activity. After that, create an new Android project along with the launcher activity. Name the layout of the activity, layout_one. See the following image:

layout one

 

Take a button inside the layout_one. To do that, copy the following code in your layout:

<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=”.LayoutOneActivity” >

<Button
android:text=”Click Me”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:onClick=”openNewActivity”/>

</RelativeLayout>

See the bold line in the button’s xml code, you must give a new and meaningful name to the android:onClick property. That name is the same name of the method which will be executed when the button is clicked. Now, open the activity of the layout and copy the below code just after the onCreate method (you can delete the onCreateOptionsMenu method as we do not need that in this tutorial)

public void openNewActivity(View view) {
// Do something in response to button

}

As, you can see, the name of the method is same as mentioned earlier. Now, whatever logic we write inside this method will be executed when the button is clicked. In this case, we want to open or start a new activity when the button is clicked. So, we need to create a new activity first. Create a new Android activity and name the activity and layout the following:

layout two

 

Take a TextView inside the activity and make its text, “Layout two“. After that, you have to add two lines inside the openNewActivity method to start the newly created activity:

public void openNewActivity(View view) {
// Do something in response to button
Intent intent = new Intent(this, LayoutTwoActivity.class);
startActivity(intent);

}

The two lines are highlighted in bold. Intent is an object that most of the times is used to start a new activity. I have mentioned the name of the activity that should be started at the first line. Now run the project and click on the button and you will see that the second activity gets launched.

layout one test

layout two test

Download the source code of this Android tutorial.

Source: http://developer.android.com/

How to set music timer in Windows 08 Phone

I have installed a new application in my Nokia Lumia 520 Windows 08 Phone that allows users to set music timer. It could be quite handy when we listen to music after going to bed. We often go to sleep and forget to stop music in our mobile phones. So, we could decide how long the music player will keep on playing music. To do that, you need to install an application called Ultra Tool. Open the application and select the inbuilt music player of the application, (marked by arrow in the left top row of the below screenshot ) then start a new song.

wp_ss_20130703_0001

wp_ss_20130703_0002

 

Then, you can click on stop music tile to stop the music immediately. Or you could open music timer and then provide a number (minutes) to make the music stop exactly after that time.

wp_ss_20130703_0003

 

You need to keep the option on foreground to keep it working. You could lock the screen as well. The inbuilt music player or Nokia Music could also be stopped by this application.

wp_ss_20130703_0004

Ultra Tool contains other cool features as well, I will provide a complete review of those features in my next post on Windows 08 Phone applications.

Facebook updates its app for Windows Phone 8

Facebook changed its general user interface for windows phone 8 with some new feature, which is really better then previous.

They enlarge the news feed,with high resolution picture. It added three shortcuts for posting new status, posting a photo and checking in.

Large News Feed with High resolution picture

Large News Feed with High resolution picture

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

You can see your online friend through this updated app, which was missing in previous version.

Online friends

Online friends

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

You can get your pages, group etc. in one place.

Favourite pages, groups apps etc.

Favourite pages, groups apps etc.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

You will feel like your PC’s Facebook environment. Windows has updated this only for Windows Phone 8 interface and not for Windows Phone 7 and Windows Phone 7.5.

For manual update go to store and find the Facebook app and start updating. Or you can download the XAP file from the Windows Store.

To know how to install XAP file you can visit How to install XAP.

So, start facebooking and be social :)

Working with Android activity

This post shows how to create a new activity and how to change its content. An activity is a .java file which has a layout as its content, in other words, when an activity is launched, it simply shows its layout to the user. While creating a new project, we can create a new activity and its layout as well. Create a new Android project and do not change the default name of the activity and its layout.

Now, see the package explorer: there is one activity (launcher activity) inside the src folder and one layout (activity_main.xml) inside the res/layout folder.

Android activity 1

 

Inside the layout (Android xml file) I have taken a TextView that contains “Layout activity_main.xml” as its android:text.

Inside the MainActivity.java, see the following lines:

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

The onCreate method is a system defined method which contains all the codes to be executed when the activity gets created or launched. The bold line in the code sets the content of the page, in this case that is activity_main.

Now, if you launch the application, you will see the following output:

Android activity 2

 

Now, add a new layout by right clicking on the layout folder selecting, NewAndroid XML File.

Then, name it,  second_layout. and click Finish. The newly created xml file appears in the layout folder. Take a TextView inside it with some text (I gave Layout second_layout).

Android activity 3

 

Replace the following line inside the MainActivity.java

setContentView(R.layout.activity_main);

with the below line:

setContentView(R.layout.second_layout);

You can launch the project and you will see that the output is changed and it is showing: Layout second_layout

Android activity 4

 

You can add a new activity that will create its layout or xml file automatically. To do that, Right click on the project name and from there, choose: New – Others – Android – Android Activity.

Or you can create a .xml file and a Java class differently in the layout folder (xml file) and inside a package at src folder (.java file). Then, inside the java file, you can add the onCreate method containing a setContentView method that points to your newly created xml file.

My next post on Android shows how to open a new Android activity from another activity on clicking a button.

Source: http://developer.android.com/

Draw different types of diagrams using DIA

Dia is a very useful tool for various type of diagram.

To download free and open source Dia Diagram Editor visit the site.

Install it and open to draw your diagram. You can draw the UML, Flow Chart, Logic diagram, ER diagram and what not.

Items you can draw

Items you can draw

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Select from the left drop down and you will get all the shape related with your diagram.

Drag the shape from the left panel to the main area and place it according to your requirement. You can easily re size your shape and move it to everywhere in the canvas.

You can also customize your drawings element’s shape. Just right click on the shape and select Properties to change various properties like font, font size, line color, text color etc.

Properties of shape

Properties of shape

If you added your shape properly to each other then you can move the part of your design without changing the connection. The line will set itself according the position of shape.

After completing your design you have to save your creation. You can export your design in various format apart with the default .dia like .pdf, .png, .bmp etc.

Available export format for Dia

Available export format for Dia

Use it and keep drawing.