Pages

Tuesday, May 6, 2014

xml parse

Parser Class


public class parser {

// constructor
public parser() {

}

/**
* Getting XML from URL making HTTP request
* @param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;

try {
// defaultHttpClient
 HttpClient httpClient = new DefaultHttpClient();

 HttpPost httpPost = new HttpPost(url);

HttpResponse httpResponse = httpClient.execute(httpPost);

HttpEntity httpEntity = httpResponse.getEntity();


xml = EntityUtils.toString(httpEntity);

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}

/**
* Getting XML DOM element
* @param XML string
* */
public Document getDomElement(String xml){
Document doc = null;

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {



DocumentBuilder db = dbf.newDocumentBuilder();

InputSource is = new InputSource();
     
is.setCharacterStream(new StringReader(xml));
 
doc = db.parse(is);

} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
           return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}

       return doc;
}

/** Getting node value
 * @param elem element
 */

/**
 * Getting node value
 * @param Element node
 * @param key string
 * */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
/*Node child;
for( child = n.item(0).getFirstChild(); child != null; child = child.getNextSibling() )
            {
           
            return child.getNodeValue();
             
            }*/
return n.item(0).getFirstChild().getNodeValue();

}

}

Java Class

ArrayList<HashMap<String, String>> list = new  ArrayList<HashMap<String,String>>();
String URL = "";

@SuppressLint("NewApi")
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_main);

parser parser = new parser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName("item");
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
String id = parser.getValue(e, "id");
String name = parser.getValue(e, "name");
String cost = parser.getValue(e, "cost");
map.put("A", id);
map.put("B", name);
map.put("C", cost);
list.add(map);
// Toast.makeText(MainActivity.this, ""+id.toString(), 10).show();
}
        
String from[] = {"A","B","C"};
int to[] = {R.id.a1,R.id.a2,R.id.a3};
ListAdapter adp = new SimpleAdapter(MainActivity.this, list, R.layout.abc, from, to);
setListAdapter(adp);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
HashMap<String, String> nn = (HashMap<String, String>)arg0.getItemAtPosition(arg2);
Toast.makeText(MainActivity.this, ""+nn.get("B"), 10).show();
}
});

}

Map

XML file

<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity" >

   
    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment"/>


</RelativeLayout>

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.kets"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
   
    <permission android:name="com.example.kets.permission.MAPS_RECEIVE"
         android:protectionLevel="signature"></permission>
     <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>
   
    <uses-permission android:name="com.example.kets.permission.MAPS_RECEIVE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
   
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
   
   
   

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.kets.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>
        <meta-data android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyAiRUNy8pqAE17_eLk96PwZlc45KHokiyw"/>
        <activity android:name="map"></activity>
       
    </application>


</manifest>

JAVA CLASS

try{
URL url = new URL(b.getString("flag"));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
conn.setDoInput(true);  
conn.connect();    
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch(Exception e){
e.printStackTrace();
}






android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
   SupportMapFragment mapFragment = (SupportMapFragment) fragmentManager
           .findFragmentById(R.id.map);
   map = mapFragment.getMap();
 
 
   map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
   map.setMyLocationEnabled(true);
   map.setOnMarkerClickListener(this);
   map.setOnInfoWindowClickListener(this);
 
    map.addMarker(new MarkerOptions()
    .snippet(""+b.getString("vic"))
           .position(new LatLng(Double.parseDouble(b.getString("lat")), Double.parseDouble(b.getString("long"))))
           .title(""+b.getString("name")))
         
           .setIcon(BitmapDescriptorFactory.fromBitmap(bmImg));
   
    CameraPosition cp = new CameraPosition.Builder().target(new LatLng(Double.parseDouble(b.getString("lat")), Double.parseDouble(b.getString("long")))).zoom(20).build();
    map.animateCamera(CameraUpdateFactory.newCameraPosition(cp));
   
   
   

}
@Override
public boolean onMarkerClick(Marker arg0) {
// TODO Auto-generated method stub

Toast.makeText(this, ""+arg0.getTitle(), 10).show();
return false;
}
@Override
public void onInfoWindowClick(Marker arg0) {
// TODO Auto-generated method stub
Toast.makeText(this, ""+arg0.getSnippet(), 10).show();


}

}

Json Parser



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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser
{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
Log.e("param--- is:-",""+params);
// Making HTTP request
try {

// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();


}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
Log.e("-------------------------->", paramString.toString());
HttpGet httpGet = new HttpGet(url);

HttpResponse httpResponse = httpClient.execute(httpGet);

HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

}


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

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");

}

Log.e("ANIL", "sb.toString() >>>>>"+sb.toString());




is.close();
json = sb.toString();



} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}
}

ImageDB Android

Button Click

Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
               startActivityForResult(intent, 52);



//Override

protected void onActivityResult(int requestCode, int resultCode, Intent data)
      {
          super.onActivityResult(requestCode, resultCode, data);
          
          if(resultCode == RESULT_OK && requestCode==52)
          {
          selectedImage = data.getData();    
          bmImage.setImageURI(selectedImage);
          }
       
      }

Button Click

String[] filePathColumn = { MediaStore.Images.Media.DATA };
                Cursor c = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
           if(c == null) return;            
           c.moveToFirst();
           int columnIndex = c.getColumnIndex( MediaStore.Images.Media.DATA);
           ImagePath = c.getString(columnIndex);
           c.close();
           
           
          
                 
                byte byteImage1 [] = null;
                try{ 
                FileInputStream instream = new FileInputStream(ImagePath); 
             BufferedInputStream bif = new BufferedInputStream(instream); 
             byteImage1 = new byte[bif.available()];
             bif.read(byteImage1); 
             
             Log.d("Byte Value",""+byteImage1.length); 
                }catch (IOException e) {
}
                d = h.getWritableDatabase();
                ContentValues cv =new  ContentValues();
                cv.put(h.IMAGE_DATA, byteArray);
                d.insert(h.IMAGE_TABLE, null,cv);
                d.close();
                Toast.makeText(getApplicationContext(), "Save", 6).show(); 
                

Sunday, May 5, 2013

Json Parsing


package com.rhmc.myserver;

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

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.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.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class MyServerActivity extends Activity implements OnClickListener
{
    /** Called when the activity is first created. */
    EditText username,password,e1,e2;
    Button insert,display,delete,login;
    InputStream is;
    ArrayList<NameValuePair> nameValuePairs = null;
    StringBuilder sb=null;
    String result=null;
    ArrayList<String> finaldata1 = new ArrayList<String>();
    ArrayList<String> finaldata2 = new ArrayList<String>();
    Spinner spi1,spi2;
    int j=0;
    //JSONArray jArray=null;
@Override
   
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
       
        e1 = (EditText)findViewById(R.id.e1);
        e2 = (EditText)findViewById(R.id.e2);

        username = (EditText)findViewById(R.id.txtunm);
        password = (EditText)findViewById(R.id.txtpwd);
        insert = (Button)findViewById(R.id.btnlogin);
        display = (Button)findViewById(R.id.btndisplay);
        spi1 = (Spinner)findViewById(R.id.spinner1);
        spi2 = (Spinner)findViewById(R.id.spinner2);
        delete= (Button)findViewById(R.id.delete);
        login= (Button)findViewById(R.id.lg);
       
        insert.setOnClickListener(this);
        display.setOnClickListener(this);
        delete.setOnClickListener(this);
        login.setOnClickListener(this);
}
public void onClick(View v) {
if(v == insert)
{
nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("title",username.getText().toString()));
        nameValuePairs.add(new BasicNameValuePair("details",password.getText().toString()));
       
        HttpClient httpclient = new DefaultHttpClient();
       
        HttpPost httppost = new HttpPost("http://10.0.2.2/aa/insert.php");
       
        try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
}
        catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
        try
        {
HttpResponse res = httpclient.execute(httppost);
HttpEntity entity = res.getEntity();
is = entity.getContent();
}
        catch (ClientProtocolException e)
        {
e.printStackTrace();
}
        catch (IOException e)
{
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "record successfully inserted", Toast.LENGTH_SHORT).show();
}
if(v == display)
{
try
{
finaldata1.clear();
finaldata2.clear();
HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://10.0.2.2/aa/display.php");
        HttpResponse res = httpclient.execute(httppost);
HttpEntity entity = res.getEntity();
is = entity.getContent();






BufferedReader reader = new BufferedReader(new InputStreamReader(is));
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
   
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());
}

String fd_username=null;
String fd_password=null;
try
{
      JSONArray jArray = new JSONArray(result);
      JSONObject json_data=null;
     
      for(int i=0;i<jArray.length();i++)
      {
json_data = jArray.getJSONObject(i);
fd_username=json_data.getString("title");
fd_password=json_data.getString("details");

finaldata1.add(fd_username.toString());
finaldata2.add(fd_password.toString());
Toast.makeText(getApplicationContext(), "hi"+finaldata1, 10).show();
      }
}
catch(JSONException e1)
{
Toast.makeText(getBaseContext(), "No RECORD Found", Toast.LENGTH_LONG).show();
}
catch (ParseException e1)
{
e1.printStackTrace();
}

spi1.setAdapter(new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,finaldata1));

spi1.setOnItemSelectedListener(new OnItemSelectedListener()
{

public void onItemSelected(AdapterView<?> adb, View arg1,
int pos, long arg3)
{
String user = (String)adb.getItemAtPosition(pos);
username.setText(user);

}

public void onNothingSelected(AdapterView<?> arg0)
{

}
});

spi2.setAdapter(new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,finaldata2));
spi2.setOnItemSelectedListener(new OnItemSelectedListener()
{

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String pwd = (String)arg0.getItemAtPosition(arg2);
password.setText(pwd);
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}


});
}
if(v == delete)
{
try
{
nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("unm",username.getText().toString()));
       
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://10.0.2.2/anil/delete.php");
        try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
}
        catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
        HttpResponse res = httpclient.execute(httppost);
HttpEntity entity = res.getEntity();
is = entity.getContent();
}
catch(Exception e)
{
}
}
if(v == login){

try
{
finaldata1.clear();
finaldata2.clear();
HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://10.0.2.2/anil/display.php");
        HttpResponse res = httpclient.execute(httppost);
HttpEntity entity = res.getEntity();
is = entity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(is));
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
   
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());
}

String fd_username=null;
String fd_password=null;
try
{
      JSONArray jArray = new JSONArray(result);
      JSONObject json_data=null;
     
      for(int i=0;i<jArray.length();i++)
      {
json_data = jArray.getJSONObject(i);
fd_username=json_data.getString("username");
fd_password=json_data.getString("password");

finaldata1.add(fd_username.toString());
finaldata2.add(fd_password.toString());
Toast.makeText(getApplicationContext(), "hi"+finaldata1, 10).show();
      }
}
catch(JSONException e1)
{
Toast.makeText(getBaseContext(), "No RECORD Found", Toast.LENGTH_LONG).show();
}
catch (ParseException e1)
{
e1.printStackTrace();
}



}
}
}

Wednesday, March 20, 2013

Button

Project Name : Button
Application Name : Button
Package Name : com.demo.button
Activity Name : ButtonActivity


Main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>

ButtonActivity.java


package com.demo.button;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class ButtonActivity extends Activity implements OnClickListener{

Button b;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        b = (Button)findViewById(R.id.button1);
        b.setOnClickListener(this);
    }
@Override
public void onClick(View v) {
// TODO Auto-generated method stub

Toast.makeText(getApplicationContext(), "Button pressed..", 10).show();

}
}



Friday, March 15, 2013

Android Installation

1. Download and Install Java(jdk)  Download
2. Download and Open Eclipse  Download
3. Download and Install Android sdk Download
  A pop-up will come out just after you finished installing the SDK, which is the SDK manager. If no pop-up      window comes then you can manually open it from ‘All Program’

4.Download and Install ADT plugin for Eclipse
   Start Eclipse > Help > Install New Software....
   then click on Add top Right
   when Dialog appears enter "ADT" for the NAME  and following url for LOCATION

URL : https://dl-ssl.google.com/android/eclipse/

then OK

5. Config Android sdk

  select Window> Preferences..
  select Android from Left side ..
  after you may see dialog asking whether you wants to send usage statistics to Google..
  then click on Proceed
  for sdk location  click on Browse and locate your downloaded SDK directory...
 click Apply then OK
Get it on Google Play