Saturday, March 29, 2014

List with checkbox

Here are the output screen of the application where users are able to insert their data through a textbox by clicking ok button as shown in image below. After adding the items users are able to select the items via a checkbox and the selected item are only rendered back to list when the button appearing on screen is clicked. 
Android List with checkbox
Fig: Android List with checkbox



 Get Selected Item Using Checkbox in Listview when Button is clicked
Fig:

Get Selected Item Using Checkbox in Listview when Button is clicked



ListCheckboxExampleActivity.java

 package com.rnd.action;  
 import java.util.ArrayList;  
 import android.app.Activity;  
 import android.os.Bundle;  
 import android.util.Log;  
 import android.util.SparseBooleanArray;  
 import android.view.KeyEvent;  
 import android.view.View;  
 import android.widget.ArrayAdapter;  
 import android.widget.Button;  
 import android.widget.EditText;  
 import android.widget.ListView;  
 public class ListCheckboxExampleActivity extends Activity {  
   /** Called when the activity is first created. */  
   ListView lv;  
   String[] outputStrArr;  
   ArrayAdapter<String> aa = null;  
      @Override  
   public void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.main);  
     lv = (ListView) findViewById(R.id.listView_user);  
     final EditText myEditText = (EditText) findViewById(R.id.myeditText);  
     final ArrayList<String> todoItems = new ArrayList<String>();  
     aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice,todoItems);  
     lv.setAdapter(aa);  
     myEditText.setOnKeyListener(new View.OnKeyListener() {  
                public boolean onKey(View v, int keyCode, KeyEvent event) {  
                     // TODO Auto-generated method stub  
                     if(event.getAction()== KeyEvent.ACTION_DOWN)  
                     {  
                          if(keyCode == KeyEvent.KEYCODE_DPAD_CENTER)  
                          {  
                               todoItems.add(0,myEditText.getText().toString());  
                               aa.notifyDataSetChanged();  
                               myEditText.setText("");  
                               return true;  
                          }  
                     }  
                     return false;  
                }  
           });  
     Button btn_ok = (Button) findViewById(R.id.button_ok);  
     btn_ok.setOnClickListener(new View.OnClickListener() {  
                public void onClick(View v) {  
                     SparseBooleanArray checked = lv.getCheckedItemPositions();  
               ArrayList<String> selectedItems = new ArrayList<String>();  
               for (int i = 0; i < checked.size(); i++) {  
                 // Item position in adapter  
                 int position = checked.keyAt(i);  
                 // Add sport if it is checked i.e.) == TRUE!  
                 if (checked.valueAt(i))  
                   selectedItems.add(aa.getItem(position));        
               }  
               outputStrArr = new String[selectedItems.size()];  
               aa.clear();  
               for (int i = 0; i < selectedItems.size(); i++) {  
                 outputStrArr[i] = selectedItems.get(i);  
                 Log.i("test data" + outputStrArr[i], null, null);  
                 aa.add(selectedItems.get(i));  
               }  
                }  
           });  
   }  
 }  

main.xml

 <?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" >  
   <TextView  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:text="@string/hello" />  
   <EditText  
     android:id="@+id/myeditText"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:ems="10" >  
     <requestFocus />  
   </EditText>  
   <ListView  
     android:id="@+id/listView_user"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:choiceMode="multipleChoice"  
      >  
   </ListView>  
   <Button  
     android:id="@+id/button_ok"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Button" />  
 </LinearLayout>  

AndroidManifest.xml

 <?xml version="1.0" encoding="utf-8"?>  
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
   package="com.rnd.action"  
   android:versionCode="1"  
   android:versionName="1.0" >  
   <uses-sdk android:minSdkVersion="8" />  
   <application  
     android:icon="@drawable/ic_launcher"  
     android:label="@string/app_name" >  
     <activity  
       android:name=".ListCheckboxExampleActivity"  
       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>  

Connecting Android with Php web service


In the sample tutorial below a simple login form is presented to user which is used to connect to php web service to validate user via Json.
You can download project, php web service and database. Click here to download

Application Interface

Login Screen (JsonParseExampleActivity)





MainMenuActivity (Success screen)

JsonParseExampleActivity.Class (Login Activity)

 package com.rnd.android;  
 import java.util.ArrayList;  
 import java.util.List;  
 import org.apache.http.NameValuePair;  
 import org.apache.http.message.BasicNameValuePair;  
 import org.json.JSONException;  
 import org.json.JSONObject;  
 import android.app.Activity;  
 import android.app.ProgressDialog;  
 import android.content.Intent;  
 import android.os.AsyncTask;  
 import android.os.Bundle;  
 import android.util.Log;  
 import android.view.View;  
 import android.widget.Button;  
 import android.widget.EditText;  
 import android.widget.Toast;  
 import com.rnd.service.JsonParseClass;  
 public class JsonParseExampleActivity extends Activity {  
      private ProgressDialog pDialog;  
      private final String LOG_MSG = "Log tracing";  
      JsonParseClass jsonParse = new JsonParseClass();  
      String successTag = null;  
      private static final String connectingUrl = "http://10.0.2.2/rnd_webservice/webservice.php";  
      private static final String TAG_SUCCESS = "success";  
      EditText edittextUsername, edittextPassword;  
      Button buttonLogin;  
      /** Called when the activity is first created. */  
      @Override  
      public void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.login);  
           edittextUsername = (EditText) findViewById(R.id.editText_username);  
           edittextPassword = (EditText) findViewById(R.id.editText_password);  
           buttonLogin = (Button) findViewById(R.id.Login);  
           buttonLogin.setOnClickListener(new View.OnClickListener() {  
                public void onClick(View v) {  
                     // TODO Auto-generated method stub  
                     ValidateUser validateUser = new ValidateUser();  
                     validateUser.execute();  
                }  
           });  
      }  
      // inner class  
      public class ValidateUser extends AsyncTask<String, String, String> {  
           ProgressDialog progressDialog;  
           JSONObject jObject;  
           @Override  
           protected void onPreExecute() {  
                // TODO Auto-generated method stub  
                super.onPreExecute();  
                progressDialog = new ProgressDialog(JsonParseExampleActivity.this);  
                progressDialog.setMessage("Logining please wait ...");  
                progressDialog.setIndeterminate(false);  
                progressDialog.setCancelable(true);  
                progressDialog.show();  
           }  
           @Override  
           protected String doInBackground(String... params) {  
                // TODO Auto-generated method stub  
                String username = edittextUsername.getText().toString().trim();  
                String password = edittextPassword.getText().toString().trim();  
                Log.d(LOG_MSG, "user name " + username);  
                List<NameValuePair> validateParams = new ArrayList<NameValuePair>();  
                validateParams.add(new BasicNameValuePair("username", username));  
                validateParams.add(new BasicNameValuePair("password", password));  
                System.out.println("before calling json object");  
                jObject = jsonParse.makeHttpRequest(connectingUrl, "POST",  
                          validateParams);  
                try {  
                     successTag = jObject.getString(TAG_SUCCESS);  
                     Log.d("Jeson result ", successTag);  
                } catch (JSONException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                }  
                return successTag;  
           }  
           @Override  
           protected void onPostExecute(String result) {  
                progressDialog.dismiss();  
                // TODO Auto-generated method stub  
                super.onPostExecute(result);  
                Log.d("Checking the result a post execute", result);  
                if (successTag.equalsIgnoreCase("1")) {  
                     Toast.makeText(JsonParseExampleActivity.this, "valid user",  
                               Toast.LENGTH_SHORT).show();  
                     Intent intent = new Intent(JsonParseExampleActivity.this,  
                               MainMenu.class);  
                     startActivity(intent);  
                } else {  
                     Toast.makeText(JsonParseExampleActivity.this, " invalid user",  
                               Toast.LENGTH_LONG).show();  
                }  
           }  
      }  
 }  

JsonParserClass.Class

 package com.rnd.service;  
 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 JsonParseClass {  
      DefaultHttpClient httpClient;  
      HttpPost httpPost;  
      HttpResponse httpResponse;  
      HttpEntity httpEntity;  
      static InputStream inputStream = null;  
      static JSONObject jsonObject = null;  
      static String jsonString = "";  
      public JSONObject makeHttpRequest(String url, String method,  
                List<NameValuePair> params)   
      {  
                try   
                {  
                     if(method == "POST")  
                     {  
                          //getting default http client to make request  
                          httpClient = new DefaultHttpClient();  
                          //creating http post request to the given url  
                          httpPost = new HttpPost(url);  
                     //setting inputs of android as html form inputs  
                     httpPost.setEntity(new UrlEncodedFormEntity(params));  
                     //execute http post request throuh response object with httpclient object  
                     httpResponse = httpClient.execute(httpPost);  
                     //getting entity object from response object  
                     httpEntity = httpResponse.getEntity();  
                     //getting contents of httpentity into inputstream  
                     inputStream = httpEntity.getContent();  
                     }  
                }  
                catch (UnsupportedEncodingException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                     System.out.println(e.toString());  
                } catch (ClientProtocolException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                     System.out.println(e.toString());  
                } catch (IOException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                     System.out.println(e.toString());  
                }  
                //GETTING BUFFERREADER TO READ INPUT STREAM       
                try {  
                     BufferedReader bufferReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"),8);  
                     StringBuilder sb = new StringBuilder();  
                     String line = null;  
                     while ((line = bufferReader.readLine()) != null) {  
                          sb.append(line +"\n");  
                     }  
                     inputStream.close();  
                     jsonString = sb.toString();  
                } catch (UnsupportedEncodingException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                     Log.e("Buffer Error", "Error converting result " + e.toString());  
                } catch (IOException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                }       
                //parse the string to json object  
                try {  
                     jsonObject = new JSONObject(jsonString);  
                } catch (JSONException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                      Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+ jsonString);  
                }  
           return jsonObject;  
      }  
 }  

MainMenu.Class

 package com.rnd.android;  
 import android.app.Activity;  
 import android.os.Bundle;  
 public class MainMenu extends Activity {  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           // TODO Auto-generated method stub  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.main);  
      }  
 }  

AndroidManifest.xml

 <?xml version="1.0" encoding="utf-8"?>  
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
   package="com.rnd.android"  
   android:versionCode="1"  
   android:versionName="1.0" >  
   <uses-sdk android:minSdkVersion="8" />  
   <uses-permission android:name="android.permission.INTERNET"/>  
   <application  
     android:icon="@drawable/ic_launcher"  
     android:label="@string/app_name" >  
     <activity  
       android:name=".JsonParseExampleActivity"  
       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="MainMenu"></activity>  
   </application>  
 </manifest>  

layout/login.xml

 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout 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/textView1"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Username"  
     android:textAppearance="?android:attr/textAppearanceLarge" />  
   <EditText  
     android:id="@+id/editText_username"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:ems="10" >  
     <requestFocus />  
   </EditText>  
   <TextView  
     android:id="@+id/textView2"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Password"  
     android:textAppearance="?android:attr/textAppearanceLarge" />  
   <EditText  
     android:id="@+id/editText_password"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:ems="10"  
     android:inputType="textPassword" />  
   <Button  
     android:id="@+id/Login"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:text="Login" />  
 </LinearLayout>  

layout/main.xml

 <?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" >  
   <TextView  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:text="@string/hello" />  
   <ImageView  
     android:id="@+id/imageView2"  
     android:layout_width="220dp"  
     android:layout_height="wrap_content"  
     android:layout_weight="0.19"  
     android:src="@drawable/ic_launcher" />  
   <ImageView  
     android:id="@+id/imageView1"  
     android:layout_width="212dp"  
     android:layout_height="wrap_content"  
     android:layout_weight="0.39"  
     android:src="@drawable/ic_launcher" />  
 </LinearLayout>  

 Php web service file

 <?php  
           // array for JSON response  
           $response = array();  
      if(isset($_POST['username']) And isset($_POST['password']))  
      {  
                $un=$_POST['username'];  
                $pw=$_POST['password'];  
                //connect to the db  
                $host="localhost"; // Host name   
                $user="root"; // Mysql username   
                $pswd=""; // Mysql password   
                $db="rnd_android"; // Database name   
                $tbl_name="user"; // Table name  
                $conn = mysql_connect($host, $user, $pswd);  
                mysql_select_db($db, $conn);  
                //run the query to search for the username and password the match  
                //$query = "SELECT * FROM $tbl_name WHERE first_name = '$un' AND password = '$pw'";  
                $query = "SELECT user_id FROM $tbl_name WHERE user_name = '$un' AND password = '$pw'";  
                $result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());  
                //this is where the actual verification happens  
                if(mysql_num_rows($result) > 0)  
                {  
                     // success  
                     $response["success"] = 1;  
                     // echoing JSON response  
                     echo json_encode($response);  
                     //echo mysql_result($result,0); // for correct login response  
                }                 
                else  
                {  
                     //echo 0; // for incorrect login response  
                     // no products found  
                     $response["success"] = 0;  
                     // echo no users JSON  
                     echo json_encode($response);  
                }  
      }  
      else  
      {  
                echo("no paramter found");  
      }  
 ?>  

Wednesday, March 12, 2014

Want To Learn SEO From Beginning

Ubuntu App Showdown contest

Third Ubuntu App Showdown! Contestants will have six weeks to build and publish their apps using the new Ubuntu SDK and Ubuntu platform. Both original apps and ported apps, QML and HTML 5, will qualify for this competition.

Categories and prizes


This App Showdown is going to be very special, because we will have four dedicated categories in which you can participate and win a prize.

QML: original apps written in QML or with a combination of QML and JavaScript/C++
HTML5: original apps written using web technologies, be it pure HTML (and CSS/JavaScript) or with platform access using Apache Cordova
Ported: apps ported from another platform, regardless of the technology used
Chinese apps: apps in this category will have to be original and specific to China and the Chinese culture. They will be judged by two native experts in our jury.
The set of prizes will consist of a Nexus 7 (2013) per category for QML, HTML5 and ported apps.
 Nexus 7
Fig- Prize Nexus 7 


The top two Chinese apps will receive a Meizu device each.



Meizu device
Fig- Prize Meizu Device

Click Here For More Info