Monday 4 May 2015

Asynctask with insertion to server





new Insert_to_Database().execute();



class Insert_to_Database extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Upload.this);
pDialog.setMessage("Saving the data.....");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss a",
Locale.getDefault());
String timeStamp1 = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String imei = telephonyManager.getDeviceId();
String imageFileName1 = "JPEG_" + timeStamp1 + "_";
String time = sdf.format(cal.getTime());
String name = Name.getText().toString();
String image = "uploads/" + imageFileName1 + ".jpg";
String Photo = String
.valueOf(((System.currentTimeMillis() / 1000) / 60));
nvp = new ArrayList<NameValuePair>();

List<MyObject> contacts_insert = db1.getAllContacts(Name.getText()
.toString());

int rowCount = contacts_insert.size();
String[] item = new String[rowCount];
int x = 0;
for (MyObject cn : contacts_insert) {
item[x] = cn.getName();
x++;
nvp.add(new BasicNameValuePair("ID", String.valueOf(cn.getID())));
nvp.add(new BasicNameValuePair("Photo", "uploads/" + cn.getID()
+ ".jpg"));
}
Log.d("//////", "" + time);

nvp.add(new BasicNameValuePair("Name", name));
nvp.add(new BasicNameValuePair("Time", time));
nvp.add(new BasicNameValuePair("Imei", imei));

pDialog.show();
}

/**
*
* Creating product
*
* */
protected String doInBackground(String... args) {
InputStream inputStream = null;
JSONArray jArraych = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_create_product);
httpPost.setEntity(new UrlEncodedFormEntity(nvp));
Log.e("URL : ", url_create_product.toString());
Log.e("NVP : ", nvp.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// Read content & Log
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}

// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(
new InputStreamReader(inputStream, "iso-8859-1"), 8);
// BufferedReader bReader = new BufferedReader(
// new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}

inputStream.close();
String result = sBuilder.toString();

Log.e("RESULT  : ", result);

if (result.trim().equals("1")) {
                 
Log.d("Result from web : ", "SUCCESS : " + result);
} else {

Log.d("Result from web : ", "Failed : " + result);
Toast.makeText(getApplicationContext(), "Upload Failed",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader",
"Error converting result " + e.toString());
}
return null;
}

/**
*
* After completing background task Dismiss the progress dialog
*
* **/

@Override
protected void onPostExecute(String res) {

try {
pDialog.dismiss();
                         }
}




Config.php

<?php
/*
 * All database connection variables
 */
define('DB_USER', "root"); // db user  //postgres
define('DB_PASSWORD', " "); // db password (mention your db password here)
define('DB_DATABASE', "db_name"); // database name   //postgis
define('DB_SERVER', "localhost"); // db server  
?>



DbConnect.php

<?php
/**
 * A class file to connect to database
 */
class DB_CONNECT {
    // constructor
    function __construct() {
        // connecting to database
        $this->connect();
    }
    // destructor
    function __destruct() {
        // closing db connection
        $this->close();
    }
    /**
     * Function to connect with database
     */
    function connect() {
        // import database connection variables
        include 'Config.php';
        // Connecting to mysql database
        $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
        // Selecing database
        $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
        // returing connection cursor

        return $con;
    }
    /**
     * Function to close db connection
     */
    function close() {
        // closing db connection
        mysql_close();
    }
}
?>






insert.php

<?php
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);
/*
 * Following code will create a new product row
 * All product details are read from HTTP Post Request
 */
// array for JSON response
$response = array();
// check for required fields
 
    $name = $_POST['Name'];
     $description = $_POST['Description'];


    echo $name;

    echo $description;
 
    // include db connect class
    include 'db_connect.php';
    // connecting to db
    $db = new DB_CONNECT();
    // mysql inserting a new row
$query="INSERT INTO details(Name, Description) VALUES('$name',  '$description')";
echo $query;
  $result = mysql_query($query);
    // check if row inserted or not
  echo $result;
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Product successfully created.";
        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";
     
        // echoing JSON response
        echo json_encode($response);
    }

?>

Json Parsing

Fetch data from webservice

public class View_data extends Activity {

private ProgressDialog pDialog;
String returnString; // to store the result of MySQL query after decoding
// JSON
TextView RESULT, lattitude, longitude, address, time;
Button View_button;
JSONArray jArray;
String result;
StringBuilder sb;
InputStream is;
List<Item> arrayOfList;
/** Called when the activity is first created. */
String ct_name, lattitude1, longitude1, time1, address1;
Datarow objAdapter;
ListView listview;

@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.list);

listview = (ListView) findViewById(R.id.listView1);
arrayOfList = new ArrayList<Item>();

// TODO Auto-generated method stub
new task().execute();

}

@Override
public void onBackPressed() {
// TODO Auto-generated method stub
new AlertDialog.Builder(this)
.setTitle("Exit")
.setMessage("Do you want to exit?")
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// continue with delete
Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
}
})
.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// do nothing
}
}).setIcon(android.R.drawable.ic_dialog_alert).show();
}

class task extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(View_data.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}

@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Log.i("doing", "back");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// http post

try {
HttpClient httpclient = new DefaultHttpClient();


HttpPost httppost = new HttpPost(
"http://10.0.0.2/Projectjsonscript.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);
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();
Log.i("Result", "Json" + result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}

String name;
try {

jArray = new JSONArray(result);

JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);

Item objItem = new Item();
objItem.setName(json_data.getString("name"));
objItem.setlat(json_data.getString("lattitude"));
objItem.setlongi(json_data.getString("longitude"));
objItem.setdesc(json_data.getString("address"));
objItem.settime(json_data.getString("time"));
arrayOfList.add(objItem);
}

} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No Data Found",
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
return null;
}

private void setAdapterToListview() {
// TODO Auto-generated method stub
objAdapter = new Datarow(View_data.this, R.layout.list_item_card,
arrayOfList);
listview.setAdapter(objAdapter);
}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
setAdapterToListview();
if (pDialog.isShowing())
pDialog.dismiss();
}
}

}



Php Code:


<?php
mysql_connect("localhost","username","password");
mysql_select_db("DB_NAME");
$sql=mysql_query("select * from TABLE");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));// this will print the output in json
mysql_close();
?>



Monday 19 May 2014

MediaHub-TV Movie Radio

MediaHubs’ features include streaming TV and Radio channels, Videos, Live webcams from different parts of the world and lots & lots of movies according to the taste of users. Users are allowed to stream any categories of channels or videos of their choice without any registration.Download your favourite videos.





Friday 8 November 2013

MyNewscan: The news portal that can revolutionize the way you read your newspaper.

MyNewscan: Newspapers, TV News, Blogs, Social Networks. What do they have in common?
The answer is that None of them can provide us contents that we prefer . You just have to be content with what they provide.

What if we can come up with a device that can give us the news that is most appropriate?
With respect to what, where and who; Which translates to what is the category of interest, from which location it is being reported, and by whom. The platform will deliver news that you prefer based on location, Category and reporters or any of their combinations.



The presence of such an application on the internet, will result in, growing number of journalists as the system expands, whereas existing media will have only a limited number of reporters in their payroll.

Mynewscan.com.... Where your news can change the world.
Contact  information:   info@camerockstech,com


Friday 10 May 2013

Battery level Indicator in Android

Battery.java


public class Battery extends Activity {


private TextView batteryLevel;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_battery);
     batteryLevel = (TextView)findViewById(R.id.batterylevel);
     this.registerReceiver(this.myBatteryReceiver,
       new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
 }
 private BroadcastReceiver myBatteryReceiver= new BroadcastReceiver(){

 @Override
 public void onReceive(Context arg0, Intent arg1) {
  // TODO Auto-generated method stub
  int bLevel = arg1.getIntExtra("level", 0);

  batteryLevel.setText("Battery Level: "
    + String.valueOf(bLevel) + " %");
 }
 };
}


activity_battery.xml

<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=".Battery" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
      />
<TextView
 android:id="@+id/batterylevel"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Battery Level:"
 />
</RelativeLayout>



Add Battery stats permission in Manifest
<uses-permission android:name="android.permission.BATTERY_STATS"/>


Screenshot

Friday 19 April 2013

Set Alarm on specified time using Broadcast reciever in Android

Alarm.java

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class Alarm extends Activity {

    TimePicker TimePicker;
    Button Setalarm;

    TimePickerDialog timePickerDialog;

    final static int RQS_1 = 1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm);

        Setalarm = (Button) findViewById(R.id.Setalarm);
        Setalarm.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                openTimePickerDialog(false);

            }
        });

    }

    private void openTimePickerDialog(boolean is24r) {
        Calendar calendar = Calendar.getInstance();
        timePickerDialog = new TimePickerDialog(Alarm.this, onTimeSetListener,
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE), is24r);
        timePickerDialog.setTitle("Set Alarm");

        timePickerDialog.show();

    }

    OnTimeSetListener onTimeSetListener = new OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

            Calendar calNow = Calendar.getInstance();
            Calendar calSet = (Calendar) calNow.clone();

            calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
            calSet.set(Calendar.MINUTE, minute);
            calSet.set(Calendar.SECOND, 0);
            calSet.set(Calendar.MILLISECOND, 0);

            if (calSet.compareTo(calNow) <= 0) {

                calSet.add(Calendar.DATE, 1);
            }

            setAlarm(calSet);
        }
    };

    private void setAlarm(Calendar targetCal) {

        //
        Toast.makeText(Alarm.this, "Alarm is set at" + targetCal.getTime(),
                Toast.LENGTH_LONG).show();
        Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                getBaseContext(), RQS_1, intent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(),
                pendingIntent);

    }

}




AlarmReceiver.java

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        Toast.makeText(arg0, "Your Time is up!!!!!", Toast.LENGTH_LONG).show();

    }

}


activity_alarm.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" >


    <Button
        android:id="@+id/Setalarm"
        android:layout_width="117dp"
        android:layout_height="106dp"
        android:background="@drawable/alarm" />

    <TextView
        android:id="@+id/alarmprompt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>



AndroidManifest.xml

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.alarm_manager.Alarm"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="AlarmReceiver"></receiver>
    </application>

</manifest>



Screenshot