Friday 26 September 2014

Filling Data in list view .... Using BaseAdapter :-)


Calling Adaptor Class to fill listview



                                     DB db_obj= new DB();
                                        db_obj.open();
result1=db_obj.getUserData("select * from tbl_name");
db_obj.close();
historyclass obj_historyclass = new historyclass();
lv_history.setAdapter(obj_historyclass);


Adaptor Class



public class historyclass extends BaseAdapter{
@Override
public int getCount() {
int count=result1.size();
return count;
}

@Override
public Object getItem(int position) {
return null;
}

@Override
public long getItemId(int position) {
return 0;
}

@Override
public View getView(int position, View oldview, ViewGroup arg2) {
View currentview;
if(oldview== null)
{
LayoutInflater le= getLayoutInflater();
currentview=le.inflate(R.layout.lv_his, null);

}
else
{
currentview=oldview;
}

final TextView c_colum_one = (TextView)currentview.findViewById(R.id.c_colum_one);
final TextView c_colum_two = (TextView)currentview.findViewById(R.id.c_colum_two);
final TextView c_colum_three= (TextView)currentview.findViewById(R.id.c_colum_two);

c_colum_one.setText(result1.get(position)[0]);
c_colum_two.setText(result1.get(position)[1]);
c_colum_three.setText(result1.get(position)[2]);
return currentview;
}
}

DB Structure For Android Application

Here the Sample SqliteDB class for Android Application. 

  • Add to Application Package - 
  • Can access DB class using Application context



Click here to download DB Class

Changing value on UI thread in specific intervals







public class MainActivity extends ActionBarActivity {
String []Questions=
{"Question1",
"Question2",
"Question3",
"Question4",
"Question5"};

TextView Txt_view;
private int questionInterval = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Txt_view= (TextView)findViewById(R.id.Txt_view);


Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
runOnUiThread(new  Runnable() {
public void run() {
if(questionInterval == Questions.length) {
questionInterval = 0;
}
Txt_view.setText(""+Questions[questionInterval++]);

}
});

}
}, 1000, 1000);

}
}






Thursday 25 September 2014

Activity using webservice


Activity using webservice


1. Creating input parameters
2. Calling  web services using controls.
3. Call webservices class from background method
4. Handling result in post method.



Web Service Class




public class WS_Request {

private static final String NAMESPACE = "http://tempuri.org/";
private static final String METHOD_NAME = "Request";
private static final String SOAP_ACTION = "http://tempuri.org/methodname";
private static final String URL = "http://www.webservice.asmx";

private static final int retryCount = 7;
public String SoapAction(String[] values){

String[] data = new String[]
 {
Username",
"password",
"fromdate",
"todate",
"REQUESTID",
"DataString"};


SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
for(int i = 0; i < data.length; i++){
PropertyInfo property = new PropertyInfo();
property.setName(data[i]);
property.setNamespace(NAMESPACE);
property.setType(PropertyInfo.STRING_CLASS);
property.setValue(values[i]);
Log.i("test", data[i]+"::"+values[i]);
request.addProperty(property);
}


SoapSerializationEnvelope envelope;
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
String resultString = "";
int loopCount = 0;



while ((resultString.equalsIgnoreCase("") || resultString.equalsIgnoreCase("serverError") ||                              resultString.equalsIgnoreCase("Data Not Found")) && loopCount < retryCount) {

try{
HttpTransportSE http = new HttpTransportSE(URL);
http.debug = true;
System.setProperty("http.keepAlive", "false");
http.call(SOAP_ACTION, envelope);
//Log.v("SoapAction for index no " + values[3], "2");
}catch (IOException e1) {
e1.printStackTrace();
//Log.w("IOException for index no " + values[3], e1.toString());

resultString = "serverError";
} catch (XmlPullParserException e1) {
e1.printStackTrace();
//Log.w("XmlPullParserException for index no " + values[3], e1.toString());
resultString = "serverError";
} catch (Exception e) {
e.printStackTrace();
//Log.w("Exception for index no " + values[3], e.toString());
resultString = "serverError";

}

if(!resultString.equalsIgnoreCase("serverError")) {
SoapPrimitive soapResult = null;

try{
soapResult = (SoapPrimitive)envelope.getResponse();
}catch (SoapFault e) {
e.printStackTrace();
//Log.w("SoapFaultException for index no " + values[3], e.toString());
resultString = "serverError";
}

if(soapResult != null){
resultString = soapResult.toString();
Log.i("resultstring", resultString);
} else {

resultString = "serverError";
}
}
loopCount += 1;
}

return resultString;
}

}





Activity Class


String[] values={
et_Uname.getText().toString(),
et_upw.getText().toString().trim(),
 "01/01/2012", "01/01/2014", "110", "10055"};

Web_Req_Asyn obj_Web_Req_Asy= new Web_Req_Asyn();
obj_Web_Req_Asy.execute(values);




Asyntask Class


public class Web_Req_Asyn extends AsyncTask<String[], Void, String> {

ProgressDialog pdlg;
public String xml_result_set="";
public String str_DmanCode;


@Override
protected void onPreExecute() {
super.onPreExecute();

pdlg = new ProgressDialog(Registration_login.this);
pdlg.setTitle("Stock And Sale");
pdlg.setMessage("Validating with server...");
pdlg.show();
pdlg.setCancelable(false);
}


@Override
protected String doInBackground(String[]... params) {

if (checkNetwork()) {
WS_Request ob1 = new WS_Request();
String[] values = params[0];
Log.i("", " Sending Envolope file");
xml_result_set = ob1.SoapAction(values);
if(!xml_result_set.equalsIgnoreCase("serverError")) {

/// Wot to do ???

}
} else {
return "networkError";
}
return xml_result_set;
}

@SuppressLint("ShowToast")
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i("onPostExecute", "result : " + result);
pdlg.dismiss();
if(result.equalsIgnoreCase("serverError")) {
vibrate_alert();
new AlertDialog.Builder(Registration_login.this)
.setTitle("User Details Error")
.setMessage("Invalid User details.")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

}
}).show();

} else if(result.equalsIgnoreCase("networkError")) {


} else if(result.trim().equals("<Masters />")) {
vibrate_alert();

new AlertDialog.Builder(Registration_login.this)
.setTitle("Attention!")
.setMessage("Invalid User details.")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

}
}).show();

} else {

String[] parts = xml_result_set.split("~");

if(parts[0].equalsIgnoreCase("1")){

                                       // IF RESULT IS XML START HERE


ArrayList<HashMap<String, String>> filemaps = XMLfunctions
.ParseData(xml_result_set, new String[] { "xmlnode-1",
"xmlnode-2", "xmlnode-3", "xmlnode-3"},                                                                              "Xmlheader");

int count = filemaps.size();
int i;
for (i = 0; i < count; i++) {
String resultone = filemaps.get(i).get("xmlnode-1"");
Editor edit = pref.edit();
edit.putString("result", resultone );
edit.commit();

                                       // IF RESULT IS XML ENDS  HERE


                                        String result=parts[1];
Intent intent = new Intent(getApplicationContext(), activitytwo.class);
bundle.putString("result", result);
bundle.putString("User_ID",    et_Uname .getText().toString().trim() );
bundle.putString("User_PW",  et_upw.getText().toString().trim());
intent.putExtras(bundle);
startActivity(intent);

}
else{
vibrate_alert();
Intent intent = new Intent(getApplicationContext(), activityone.class);
startActivity(intent);
}

}
}

private void vibrate_alert() {
Vibrator vibrator;
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(500);
// TODO Auto-generated method stub

}

@SuppressLint("ShowToast")
protected boolean checkNetwork() {

try {
java.net.URL myUrl = new java.net.URL("http://www.service.asmx");
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(2000);
connection.connect();
connection_status_flag = true;
} catch (Exception e) {
Log.w("checkNetwork", e.toString());
connection_status_flag = false;
}
return connection_status_flag;
}
}





// XML parsing class (Depends on result)


public class XMLfunctions {
public final static Document XMLfromString(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) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
return doc;
}

/**
* Returns element value
*
* @param elem
*            element (it is XML tag)
* @return Element value otherwise empty String
*/
public final static String getElementValue(Node elem) {
Node kid;
if (elem != null) {
if (elem.hasChildNodes()) {
for (kid = elem.getFirstChild(); kid != null; kid = kid
.getNextSibling()) {
if (kid.getNodeType() == Node.TEXT_NODE) {
return kid.getNodeValue();
}
}
}
}
return "";
}

public static int numResults(Document doc) {
Node results = doc.getDocumentElement();
int res = -1;
try {
res = Integer.valueOf(results.getAttributes().getNamedItem("count")
.getNodeValue());
} catch (Exception e) {
res = -1;
}
return res;
}

public static String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return XMLfunctions.getElementValue(n.item(0));
}

/******** Parsing XML String to data ********/
public static String[] ParseData(String xml, String code, String header) {

org.w3c.dom.Document doc = XMLfunctions.XMLfromString(xml);

NodeList nodes = doc.getElementsByTagName(header);
String[] spin = new String[nodes.getLength()];
for (int i = 0; i < nodes.getLength(); i++) {
Element e = (Element) nodes.item(i);
spin[i] = XMLfunctions.getValue(e, code);

}
return spin;
}

/*************************************************************************************/

public static ArrayList<HashMap<String, String>> ParseData(String xml,
String[] code, String header) {

org.w3c.dom.Document doc = XMLfunctions.XMLfromString(xml);

int counter = code.length;

ArrayList<HashMap<String, String>> filemaps = new ArrayList<HashMap<String, String>>();
NodeList nodes = doc.getElementsByTagName(header);
for (int i = 0; i < nodes.getLength(); i++) {
Element e = (Element) nodes.item(i);
HashMap<String, String> map = new HashMap<String, String>();
for (int j = 0; j < counter; j++) {
map.put(code[j], XMLfunctions.getValue(e, code[j]));
//Log.i("xmlreply", XMLfunctions.getValue(e, code[j]));
}
filemaps.add(map);
}
return filemaps;
}
}




Wednesday 24 September 2014

Service in Android (GENERATING RANDOM NUMBER ON EACH 30 SEC INTERVALS)



    SERVICE

1. service is an independent process
2. Not affecting activity foreground


 CREATION OF SERVICE FOR GENERATING RANDOM NUMBER ON EACH 30 SEC  INTERVALS




public class CheckingUpdates extends  Service {
Context ctx=this;

@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.v("one", "one");
//Creating timer which executes once after 30 seconds
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TaskExampleRepeating(), 30000, 30000);
}

public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return super.onStartCommand(intent, flags, startId);
}

public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.v("one", "four");
//for test -mediaplayer.stop();
Log.v("one", "five");
}

class TaskExampleRepeating  extends TimerTask{
int randomresult1=0,
randomresult2=0,
randomresult3=0;

//This task will execute just once after seven seconds of starting the program
public void run(){

System.out.println(" displayed after " + " ->" + new Date());
Random randomGenerator = new Random();
for (int idx = 1; idx <= 1; ++idx){
randomresult1 = randomGenerator.nextInt(100);
System.out.println("after 30 seconds first-value" + " ->" + randomresult1);

}
for (int idx = 1; idx <= 1; ++idx){
randomresult2 = randomGenerator.nextInt(100);
System.out.println("after 30 seconds second-value" + " ->" + randomresult2);
}
for (int idx = 1; idx <= 1; ++idx){
randomresult3 = randomGenerator.nextInt(100);
System.out.println("after 30 seconds third-value" + " ->" + randomresult3);
}

System.out.println("value" + " ->" + "inserted all" );

}

}
}


CHANGES ON MANIFEST FILE 

       <service
            android:name="com.Packagename.services.CheckingUpdates" android:enabled="true"
            android:process=":myprocess" />
    </application>



ACTIVITY CLASS


@Override
protected void onResume() {
// TODO Auto-generated method stub
startService(new Intent(ActivityOne.this, CheckingUpdates.class));
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
super.onResume();
}


@Override
protected void onStop() {
// TODO Auto-generated method stub
stopService(new Intent(ActivityOne.this, CheckingUpdates.class));
Toast.makeText(this, "Service Stop", Toast.LENGTH_LONG).show();
super.onStop();
}






How to do text writing animation?  In Android Development we do not have the option to use any other custom font in our default Tex...