Thursday 24 May 2012

JSON Parsing

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

public class PhpSqlSampleActivity extends Activity {
    InputStream is;
    String result = "";
    String data = "";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void click(View v)
    {
        EditText et=(EditText)findViewById(R.id.et1);
        String name=et.getText().toString();
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("student",name));
        
        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();

 //should specify the suitable http path.

                HttpPost httppost = new HttpPost("http://10.0.0.200/text/select.php");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
        }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
        }
       
        //convert response to string
        try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                }
                is.close();
          
                result=sb.toString();
        }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
        }
        
        //parse json data
        try{
     
           
           
              JSONArray jArray = new JSONArray(result);
               
                for(int i=0;i<jArray.length();i++){
                        JSONObject json_data = jArray.getJSONObject(i);
                        int id=json_data.getInt("id");
                        String std=json_data.getString("name");
                        String place=json_data.getString("place");
                        int rank=json_data.getInt("rank");
                        data="Student Id = "+id+"\n"+"Student name = "
                        +std+"\n"+"Place = "+place+"\n"+"Rank = "+rank;
                       
                      
                        Log.i("log_tag",data);
                       
                }
        }
       
        catch(JSONException e)
        {
                Log.e("log_tag", "Error parsing data "+e.toString());
        }
        new AlertDialog.Builder(this).setPositiveButton("Ok",new OnClickListener() {

            //@Override
            public void onClick(DialogInterface dialog, int which)
            {

            }
    }).setMessage(data).setTitle("Student Details").create().show();
    }
}

This application is used to get the details of the student while we entering the name of the student in to the edit text box.

In ubuntu the php files should be in file system->opt->lampp->htdocs->anna(folder name)

Here giving some examples of the .php files

  •  if you want to select the data from the 'department table'.

<?php
    mysql_connect("localhost","root","");
mysql_select_db("studentnew");

$q=mysql_query("SELECT * FROM department");
while($e=mysql_fetch_assoc($q))
        $output[]=$e;

print(json_encode($output));

mysql_close();
?>

  • if you want we want to get the student data from the student table according to the name of the student.

 <?php
    mysql_connect("localhost","root","");
mysql_select_db("studentnew");

$q=mysql_query("SELECT * FROM studentdata WHERE id='".$_REQUEST['student']."'");
while($e=mysql_fetch_assoc($q))
        $output[]=$e;

print(json_encode($output));

mysql_close();
?>

  •  if we want to insert data in to the table

<?php
    mysql_connect("localhost","root","");
mysql_select_db("studentnew");

$q=mysql_query("INSERT INTO staffreg (name,id,department,gender)
VALUES ('".$_REQUEST['sname']."','".$_REQUEST['sid']."','".$_REQUEST['sdep']."','".$_REQUEST['srm']."')");
while($e=mysql_fetch_assoc($q))
        $output[]=$e;

print(json_encode($output));

mysql_close();
?>

Log in page

package com.ann;

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.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class studentLogin extends Activity{
    EditText ename,epass;
    Button bsave;
    TextView txt;
    String name,pass,result;
    InputStream is;
    String nname;
   
   
   
    public void onCreate(Bundle saveInstanceState)
    {
        super.onCreate(saveInstanceState);
        setContentView(R.layout.studentlogin);
        ename=(EditText)findViewById(R.id.stnee);
    epass=(EditText)findViewById(R.id.stpee);
   
    }
    public void onclickLoginss(View v){

        bsave=(Button)findViewById(R.id.buts);
        name=ename.getText().toString();
        pass=epass.getText().toString();
                try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://10.0.0.210/anna/stul.php");
           // httppost.setEntity(new UrlEncodedFormEntity(nameval));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
    }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
    }
       
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
            }
            is.close();
      
            result=sb.toString();
            Log.e("result", ""+result);
    }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
    }
    
    //parse json data
    try{      
          JSONArray jArray = new JSONArray(result);
           
            for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                   
                   String nameva=json_data.getString("name");
                   String passva=json_data.getString("id");
                  
                    
//            }
            if(name.equalsIgnoreCase(nameva) && (pass.equalsIgnoreCase(passva)))
            {
                Intent intent=new Intent(this,studentPage.class);
                intent.putExtra("name", nameva);
                startActivity(intent);
                //break;
                //Toast.makeText(this,"name  :"+nameva+"   password:"+passva, Toast.LENGTH_LONG).show();
            }
            else {
                Toast.makeText(this,"user name or password is not correct",Toast.LENGTH_LONG).show();
                ename.setText("");
                epass.setText("");
                break;
            }
            }        
   
    }
    catch(Exception e){
        Log.e("error",""+e.getMessage());
    }
   
   
    }
      

}



Registration form

 

 


package com.ann;

import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class studentReg extends Activity {
   
    EditText ename,edep;
    EditText eid;
    RadioButton rma,rfe;
    String sname,sid,sdep,srm,srf;
    int id;
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.studentreg);
       
        ename=(EditText)findViewById(R.id.sne);
        eid=(EditText)findViewById(R.id.side);
        edep=(EditText)findViewById(R.id.sde);
        rma=(RadioButton)findViewById(R.id.male);
        rfe=(RadioButton)findViewById(R.id.female);
       
       
       

    }
    public void onClickSave(View v){
        sname=ename.getText().toString();
        sid=eid.getText().toString();
        sdep=edep.getText().toString();
        if(rma.isChecked()==true){
        srm="male";   
        }
        else if(rfe.isChecked()==true){
            srm="female";
       
        }
        ArrayList<NameValuePair> nameval=new ArrayList<NameValuePair>();
        nameval.add(new BasicNameValuePair("sname", sname));
        nameval.add(new BasicNameValuePair("sid", sid));
        nameval.add(new BasicNameValuePair("sdep", sdep));
        nameval.add(new BasicNameValuePair("srm", srm));
       
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://10.0.0.210/anna/studentregnew.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameval));
            HttpResponse response = httpclient.execute(httppost);

        Toast.makeText(this,"id"+sid+"name:"+sname+"dep:"+sdep+"gen:"+srm, Toast.LENGTH_LONG).show();

        ename.setText("");
        eid.setText("");
        edep.setText("");
    }catch (Exception e){
                 Log.e("log_tag", "Error in http connection "+e.toString());
         }
    }
   
    public void onClickHome(View v){
        Intent i=new Intent(this,home.class);
        startActivity(i);
               
    }

}



No comments:

Post a Comment