Showing posts with label Android Advanced. Show all posts
Showing posts with label Android Advanced. Show all posts

Android login with php and display data in custom listview.



This is project in Android login with php and display data in custom listview.

Processing: 

Start Login with app and if password have in database, it open new activity and display data in custom listview.

Create Database In phpmyadmin.

USE db_client2;
CREATE TABLE tbl_product(pid INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,name VARCHAR(200) NOT NULL,qty int NOT NULL,price float NOT NULL,image_url text NOT NULL);


Insert Data to tbl_product

INSERT INTO tbl_product(name, qty, price,iamge_url)VALUES('name_valuse', 'number_qty', 'price_of_qty,iamge_of_url');

connection.php

<?php
$servername = "localhost"; //replace it with your database server name
$username = "root";  //replace it with your database username
$password = "";  //replace it with your database password
$dbname = "db_client2";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
?>

login.php


<?PHP
    include_once("connection.php");
    if( isset($_POST['txtUsername']) && isset($_POST['txtPassword']) ) {
        $username = $_POST['txtUsername'];
        $password = $_POST['txtPassword'];
        $query = "SELECT username, password FROM tbl_client ".
        " WHERE username = '$username' AND password = '$password'";
        $result = mysqli_query($conn, $query);
   
        if($result->num_rows > 0){     
                echo "success";
                exit;                     
        } else{
             echo "Login Failed <br/>";
             exit;
        }
    }
?>
<html>
<head>
    <title>Login | Vichit </title>
</head>
    <body>
        <h1>Login Example|<a href="https://www.youtube.com/channel/UCkIW6gubyhq_17tUI6Qgjog">Vichit Developer Android</a></h1>
        <form action="<?PHP $_PHP_SELF ?>" method="post">
            Username <input type="text" name="txtUsername" value="" /><br/>
            Password <input type="password" name="txtPassword" value="" /><br/>
            <input type="submit" name="btnSubmit" value="Login"/>
        </form>
    </body>
</html>

In Android: need to add more Library



Go to Project >> app>>libs>>past 3 library in to libs Right click on library and than click add as library

MainActivity


 you need write some code in method onlick' button

btnLogin.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View v) {
        HashMap postData = new HashMap();

        String username = edusername.getText().toString();
        String password = edpassword.getText().toString();

        postData.put("txtUsername", username);
        postData.put("txtPassword", password);


        PostResponseAsyncTask task = new PostResponseAsyncTask(MainActivity.this, postData,
                new AsyncResponse() {

                    @Override                    public void processFinish(String s) {
                        //Log.d(LOG,s);                        if (s.contains("success")) {
                            Intent intent = new Intent(MainActivity.this,ListActivity.class);
                            startActivity(intent);
                            Toast.makeText(MainActivity.this, "Login Successfully", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MainActivity.this, "Disconnect + /n Please try again", Toast.LENGTH_SHORT).show();
                        }
                    }

                });
        task.execute("http://10.0.3.2/client/login");
    }
});


Explain:

http://localhost/client/login >> if you work in php browser, you must to declare this.
http://10.0.3.2/client/login >> if you work in Genymotion, you must to declare this.

Product Class:

This class, if in java we call it Getter and Setter but in android get data from Json we don't use getter 
and setter. We use @SerializedName

public class Product { @SerializedName("pid") public int pid;

@SerializedName("name") public String name;

@SerializedName("qty") public int qty;

@SerializedName("price") public float price;

@SerializedName("image_url") public String image_url; }

ListActivity:

declare variable:

final String LOG = "ListActivity";
private ArrayList<Product> productsList;
private ListView listProduct;





OnCreate method: 
PostResponseAsyncTask task = new PostResponseAsyncTask(ListActivity.this, this);
task.execute("http://10.0.3.2/client/product.php");


When you make PostResponseAsyncTask, It generator one method to us. 


processFinish
You can read my command my note on code

productsList = new JsonConverter<Product>().toArrayList(s, Product.class);
BindDictionary<Product> dist = new BindDictionary<>();

//Get Name from Product Class
dist.addStringField(R.id.tvName, new StringExtractor<Product>() {

@Override public String getStringValue(Product product, int position) { return product.name; } }); //Get Qty from Product Classdist.addStringField(R.id.tvQty, new StringExtractor<Product>() { @Override public String getStringValue(Product product, int position) { return product.qty + ""; } }); //Get Price from Product Classdist.addStringField(R.id.tvPrice, new StringExtractor<Product>() { @Override public String getStringValue(Product product, int position) { return product.price + "$"; } }); //Get image from Product Classdist.addDynamicImageField(R.id.imageView, new StringExtractor<Product>() { @Override public String getStringValue(Product product, int position) { return product.image_url; } }, new DynamicImageLoader() { @Override public void loadImage(String url, ImageView imageView) { Picasso.with(ListActivity.this).load(url).into(imageView); } }); FunDapter<Product> adapter = new FunDapter<>(ListActivity.this,productsList,R.layout.layout_list,dist); listProduct = (ListView) findViewById(R.id.lvListView); listProduct.setAdapter(adapter);

One of problem that we want to call Image: 
Before we call method loadImage, We must to declare: compile 'com.squareup.picasso:picasso:2.5.2'
Go to bulid.gradle and write

 

Atfer finish declare. It we show you one problem in Android Monitor. Show this problem we can fix it.
Go to AndroidManifest and add some tools:

xmlns:tools="http://schemas.android.com/tools"
tools:replace="@android:icon"


Editor by: Vichit Developer.

Android Login connect with php MySQL.


This is project connection with php using mysql database.

Create database in phpmyadmin(Mysql)





USE db_client;
CREATE TABLE tbl_client2(id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,name VARCHAR(50) NOT NULL,username VARCHAR(50) NOT NULL,password VARCHAR(50) NOT NULL);


Insert data into tbl_client2


INSERT INTO tbl_client2(name, username, password)VALUES('abc', 'abc', '123');INSERT INTO tbl_client(name, username, password)VALUES('Test', 'test', 'test');


Connection.php


<?php

$servername = "localhost"; //replace it with your database server name
$username = "root";  //replace it with your database username
$password = "";  //replace it with your database password
$dbname = "db_client2";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
?>


login.php


<?PHP 
    include_once("connection.php"); 
    if( isset($_POST['txtUsername']) && isset($_POST['txtPassword']) ) { 
        $username = $_POST['txtUsername'];
        $password = $_POST['txtPassword'];

        $query = "SELECT username, password FROM tbl_client ". 
        " WHERE username = '$username' AND password = '$password'"; 

        $result = mysqli_query($conn, $query);
        
        if($result->num_rows > 0){
            //if(isset($_POST['mobile']) && $_POST['mobile'] == "android"){ 
                echo "success"; 
                exit; 
          //  } 
            //echo "Login successful"; 
                           
        } else{ 
             echo "Login Failed <br/>";
             exit;
        } 
    }
?>
<html>
<head>

    <title>Login | Vichit </title>
</head>
    <body>
        <h1>Login Example|<a href="https://www.youtube.com/channel/UCkIW6gubyhq_17tUI6Qgjog">Vichit Developer Android</a></h1>
        <form action="<?PHP $_PHP_SELF ?>" method="post">
            Username <input type="text" name="txtUsername" value="" /><br/>
            Password <input type="password" name="txtPassword" value="" /><br/>
            <input type="submit" name="btnSubmit" value="Login"/>
        </form>
    </body>
</html>


In AndroidManifest you must add:

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





In Android you must add Jar Library:


-Go to Project -> app -> libs -> past library into libs 
-Right click on Gson.jar -> add as library 


MainActivity 

You must write some code:@Override
public void onClick(View v) {
    HashMap postData = new HashMap();
    postData.put("mobile", "android");
    postData.put("txtUsername" , edUsername.getText().toString());
    postData.put("txtPassword" , edPassword.getText().toString());

    PostResponseAsyncTask task = new PostResponseAsyncTask(this,postData);
    task.execute("http://10.0.3.2/client/login.php");

}





http://localhost/client/login.php : if you work in php bowers, you need to declare  this

http://10.0.3.2/client/login.php : if you work in Genymotion, you need to declare this.

http://10.0.3.2/client/login.php : default 


when you Make PostResponseAsyncTask, it will give you a Override one method (processFinish).
The mehtod, It mean that when the android processing, it call method to use.


@Overridepublic void processFinish(String result) {
    if (result.equals("success")){
        Intent intent = new Intent(MainActivity.this,MyAppActivity.class);
        startActivity(intent);
        //Toast.makeText(this,"Login Successfully",Toast.LENGTH_SHORT).show();    }else{
        Toast.makeText(this,"Login Failed",Toast.LENGTH_SHORT).show();
    }

}

Editor by: Vichit Pov










Simplify Adapter creation for your Android ListViews. (FunDapter Class)




FunDapter takes the pain and hassle out of creating a new Adapter class for each ListView you have in your Android app.
It is a new approach to custom adapter creation for Android apps. You get free ViewHolder pattern support, field validation so you don't get bit by trivial bugs and best of all - you get to keep it DRY!

What's new?

  1. Gradle support now only contains a JAR archive instead of AAR which wasn't needed. Just add compile 'com.github.amigold.fundapter2:library:1.01' to your dependencies in the build.gradle file in your project.

What you used to do:

  1. Subclass BaseAdapter or copy existing adapter you already wrote.
  2. Create a ViewHolder static class a define all the views in it.
  3. Write (Copy.. don't fool yourself!) the whole ViewHolder creation code from somewhere.
  4. Write all the "findViewById" lines.
  5. Start filling data in the views inside the getView method.
Well that was boring! I feel your pain!

What FunDapter lets you do:

  1. Create a new BindDictionary
  2. Add fields.
  3. Create a new FunDapter instance, supplying the BindDictionary, layout resource file and item list.

Getting Started

This is the Product class we'll create an adapter for:
public class Product {
 
 public String title;
 public String description;
 public String imageUrl;
 public double price;
}

Create a new BindDictionary instance:

BindDictionary<Product> dict = new BindDictionary<Product>();

Adding a basic text field:

dict.addStringField(R.id.description,
 new StringExtractor<Product>() {

     @Override
     public String getStringValue(Product item, int position) {
   return item.description;
     }
 });
Notice how you simply provide the id of the TextView and an implementation of the StringExtractor which will be used to get the correct String value from your Product.

Now a more complicated text field:

dict.addStringField(R.id.title,
 new StringExtractor<Product>() {

     @Override
     public String getStringValue(Product item, int position) {
   return item.title;
     }
 }).typeface(myBoldFace).visibilityIfNull(View.GONE);
Notice how you can chain calls to get some more complex behaviours out of your views. typeface() will set a typeface on the view while visibilityIfNull() will change the visibility of the field according to the value being null or not.

What about our image?? Lets add that as well:

prodDict.addDynamicImageField(R.id.productImage,
 new StringExtractor<Product>() {

     @Override
     public String getStringValue(Product item, int position) {
   return item.imageUrl;
     }
 }, new DynamicImageLoader() {
     @Override
     public void loadDynamicImage(String url, ImageView view) {
   //insert your own async image loader implementation
     }
 });
In here the StringExtractor grabs the URL from the Product item while the ImageLoader gives you a reference to the view and the URL you extracted so you can use your own custom lazy image loading implementation.

Finally, create the adapter:

FunDapter<Product> adapter = new FunDapter<Product>(getActivity(), productArrayList,
  R.layout.product_list_item, dict);

What is supported so far:

  • ViewHolder pattern and more performance optimizations
  • Switching data using funDapter.updateData()
  • Alternating background colors for the list items. Use funDapter.setAlternatingBackground()
  • Text fields:
    • typeface
    • visibility if null
    • changing textcolor based on a boolean condition - chain conditionalTextColor() when setting the field
  • Image fields (that load from the web)
  • ProgressBar fields - for showing user progress or xp.
  • Conditional visibility views - views that are shown or hidden according to some boolean value. (Good for decorations such as "sale" banners)
  • All fields support setting an OnClickListener by chaining onClick()
  • ExpandableListAdapter is supported

What next?

  • Support for ViewPagerAdapter
  • Support for Favorite toggle buttons (where you provide your own implementation for the data persistence)
  • Whatever else I can think of!

Gradle Support

Just add compile 'com.github.amigold.fundapter:library:1.0' to your dependencies in the build.gradle file in your project.

License

(The MIT License)
Copyright (c) 2012-2013 Ami Goldenberg ami.gold.dev@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.