Rss

Archives for : android

error com.android.email.permission.ACCESS_PROVIDER

I tried to read email from the emailprovider, but from StackOverflow I read that it’s impossible. The error also couldn’t be fix.

java.lang.SecurityException: Permission Denial: reading com.android.email.provider.EmailProvider uri content://com.android.email.provider/account from pid=278, uid=10003 requires com.android.email.permission.ACCESS_PROVIDER

here is the code

Cursor c = null;
Uri CONTENT_URI = Uri.parse("content://com.android.email.provider/account");
String RECORD_ID = "_id";
String[] ID_PROJECTION = new String[] {RECORD_ID };        
c = getContentResolver().query(CONTENT_URI,ID_PROJECTION,null, null, null); 

AND I also add the “permission” which is none of the permission list.


here the url I found from stackOverflow
http://stackoverflow.com/questions/5547352/how-can-i-read-inbox-in-android-mobile
http://androidbridge.blogspot.com/2011/03/reading-emails-in-android.html

I really appreciate for you who can make it happen.
please comment if you know how to fix it….

Get SMS from inbox/outbox

Now I want to show you how to show to the screen the SMS from your inbox/outbox.
In this tutorial, you should permission to read sms first on your android manifest.

 

This is the code, we use cursor to get the text.

public void readSMS() {
		String info = "";
		Uri mSmsinboxQueryUri = Uri.parse("content://sms");
		Cursor cursor1 = getContentResolver().query(
				mSmsinboxQueryUri,
				new String[] { "_id", "thread_id", "address", "person", "date",
						"body", "type" }, null, null, null);
		startManagingCursor(cursor1);
		String[] columns = new String[] { "address", "person", "date", "body",
				"type" };
		if (cursor1.getCount() > 0) {
			String count = Integer.toString(cursor1.getCount());
			Log.e("Count", count);
			while (cursor1.moveToNext()) {
				String address = cursor1.getString(cursor1
						.getColumnIndex(columns[0]));
				String name = cursor1.getString(cursor1
						.getColumnIndex(columns[1]));
				String date = cursor1.getString(cursor1
						.getColumnIndex(columns[2]));
				String msg = cursor1.getString(cursor1
						.getColumnIndex(columns[3]));
				String type = cursor1.getString(cursor1
						.getColumnIndex(columns[4]));
				info += address + "n" + name + "n" + date + "n" + msg + "n"
						+ type;
				txtInfo.setText(info);
			}
		}
	}

Get GPS Device Info

Now, I want to tell you about how get GPS Android Device Information.

Please notes that this function can be ran on class with activity extended.
the code will be like this:

GpsData gpsData = GpsData.getInstance();
	LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
	longitude = location.getLongitude();
	latitude = location.getLatitude();
	accuracy = location.getAccuracy();
	altitude = location.getAltitude();
	bearing = location.getBearing();
	hasAltitude = location.hasAltitude();
	provider = location.getProvider();
	getSpeed = location.getSpeed();
	getTime = location.getTime();

How to use getInstance() ?

getInstance is usually used to help to make just one object and without parse it.
for example, we parse parameter Object like this:

public class GpsData {
VarData vardata;
public GpsData(VarData data){
this.data = vardata;
}
}

Nah, with that situation u MUST parse one by one class that use the target class. How hard your life is.
Now, with the simple method, you can reduce it, and make your life happier than before.

public class VarData {
	private static VarData instance;
	private VarData(){}
	public static VarData getInstance() {
		if (instance == null) {
			instance = new VarData();
		}
		return instance;
	}
}

and you can call (make or use the object) like this:

VarData vardata = Vardata.getInstance();

Nah, you can make your life easier, right?
Okay, that’s all for today….
-xrv-

How to Change UI inside of thread?

now, I want to let you know how to change UI inside of thread.
You know, Android UI cannot be executed by the thread WITHOUT add an explain to execute the UI.
because the Thread is the execution program that also run while the main process is run. It would be conflict if the Thread also execute UI when the original THread (UI itself) execute the UI. so, Android prohibit it.
So, how?

you must add this:

runOnUiThread(new Runnable() {
						public void run() {
							// stuff that updates ui
							textInfo = (TextView) findViewById(R.id.txtInfo);
							textInfo.setText(someData);
						}
					});

so, the run thread will be (in this section, I used Timer for Thread)

timer.scheduleAtFixedRate(new TimerTask() {
			public void run() {
				if (running) {
					final String someData = data();
					runOnUiThread(new Runnable() {
						public void run() {
							// stuff that updates ui
							textInfo = (TextView) findViewById(R.id.txtInfo);
							textInfo.setMovementMethod(new ScrollingMovementMethod());
							textInfo.setText(someData);
						}
					});
					try {
						txtWrite = true;
						textInfo = (TextView) findViewById(R.id.txtInfo);
						// textInfo.setText(data());
						// infoActivity.writeScreen();
						// writeScreen();
						System.out.println("IF YOU READ THIS....");
						System.out.println(data());
						writeToFile(info, i); // THREAD FOR WRITE TO FILE
						SendThread(); // THREAD FOR SEND TO SERVER
						i++;
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {
					System.out.println("IT'S FINISH!");
					finish();
				}
			}
		}, delay, period);

once more, if you initialize variable to the Thread, your variable MUST be FINAL.

final String someData = data();

okay, that’s all today….

how to read a ‘strange class’

I just wonder how people know how to use the strange class.
let’s make an example.

This is the class I got from developer.android, I used Telephony Manager, but you know,,, the calling method is different.

Class Overview
Provides access to information about the telephony services on the device. Applications can use the methods in this class to determine telephony services and states, as well as to access some types of subscriber information. Applications can also register a listener to receive notification of telephony state changes.
You do not instantiate this class directly; instead, you retrieve a reference to an instance through Context.getSystemService(Context.TELEPHONY_SERVICE).
Note that access to some telephony information is permission-protected. Your application cannot access the protected information unless it has the appropriate permissions declared in its manifest file. Where permissions apply, they are noted in the the methods through which you access the protected information.

and from the forum, the way to call the class is:

TelephonyManager telephon = (TelephonyManager)	context.getSystemService(Context.TELEPHONY_SERVICE);

Show Android Device Info

Show device info is the basic to make a android interface application. Actually, you should know the data from Android device due to develop your application. For example, if you want to build memory manager application for Android, you must know the memory condition is, the heap size, the free size of memory, the applications that running and how much its use the memory.

For this post, I want to show you how to show android device info.

As you know, Android needs “listener” to get the data from the device. The listener will give all the value that you need.

package get.info;
import java.io.File;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.TextView;
public class Npp_getinfoActivity extends Activity {
	TextView textBatteryLevel = null;
	String batteryLevelInfo = "Battery Level";
	TelephonyManager Tel;
	MyPhoneStateListener MyListener;
	boolean hasSignal = false;
	int signal = 0;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		textBatteryLevel = (TextView) findViewById(R.id.batterylevel_text);
		registerBatteryLevelReceiver();
		TextView tv1 = (TextView) findViewById(R.id.device_name);
		String str = android.os.Build.MODEL;
		tv1.setText(str);
		MyListener = new MyPhoneStateListener();
		Tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		Tel.listen(MyListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
	}
	@Override
	protected void onDestroy() {
		unregisterReceiver(battery_receiver);
		super.onDestroy();
	}
	private BroadcastReceiver battery_receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			boolean isPresent = intent.getBooleanExtra("present", false);
			String technology = intent.getStringExtra("technology");
			int plugged = intent.getIntExtra("plugged", -1);
			int scale = intent.getIntExtra("scale", -1);
			int health = intent.getIntExtra("health", 0);
			int status = intent.getIntExtra("status", 0);
			int rawlevel = intent.getIntExtra("level", -1);
			int level = 0;
			// GET STORAGE DEVICE
			File path = Environment.getDataDirectory();
			StatFs stat = new StatFs(path.getPath());
			long blockSize = stat.getBlockSize();
			long availableBlocks = stat.getAvailableBlocks();
			// GET CARRIER NAME
			TelephonyManager manager = (TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE);
			String carrierName = manager.getNetworkOperatorName();
			// GET IMEI
			TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
			String imei = telephonyManager.getDeviceId();
			// GET IMSI
			TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
			String imsi = mTelephonyMgr.getSubscriberId();
			// GET PHONE NUMBER
			TelephonyManager tMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
			String mPhoneNumber = tMgr.getLine1Number();
			// GET SIGNAL STRENGTH
			MyListener = new MyPhoneStateListener();
			Tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
			Tel.listen(MyListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
			Bundle bundle = intent.getExtras();
			Log.i("BatteryLevel", bundle.toString());
			if (isPresent) {
				if (rawlevel >= 0 && scale > 0) {
					level = (rawlevel * 100) / scale;
				}
				String info = "Battery Level: " + level + "%n";
				info += ("Technology: " + technology + "n");
				info += ("Plugged: " + getPlugTypeString(plugged) + "n");
				info += ("Health: " + getHealthString(health) + "n");
				info += ("Status: " + getStatusString(status) + "n");
				info += ("n");
				info += ("Device Name: " + android.os.Build.MODEL + "n");
				info += ("Telephone Number: " + mPhoneNumber + "n");
				info += ("Android Version: " + Build.VERSION.RELEASE + "n");
				info += ("Memory Usage: " + memoryUsed() + "bytes n");
				info += ("SDCARD Usage: " + availableBlocks * blockSize + "bytes n");
				info += ("Carrier Name: " + carrierName + "n");
				info += ("IMEI : " + imei + "n");
				info += ("IMSI : " + imsi + "n");
				info += ("n Line1 : " + (tMgr.getLine1Number()));
				info += ("n Network Type : " + (networkType(tMgr.getNetworkType())));
				info += ("n Phone Type : " + (tMgr.getPhoneType()));
				info += ("n SIM COuntry Iso : " + (tMgr.getSimCountryIso()));
				info += ("n SIM serial number : " + (tMgr.getSimSerialNumber()));
				info += ("n Subscribe ID : " + (tMgr.getSubscriberId()));
				info += ("n SIM State : " + (tMgr.getSimState()));
				//info += ("n Cell Location : " + (tMgr.getCellLocation()));
				if (hasSignal) {
					info += ("Signal: " + signal + "n");
				}
				setBatteryLevelText(info);
			} else {
				setBatteryLevelText("Battery not present!!!");
			}
		}
	};
	private String getPlugTypeString(int plugged) {
		String plugType = "Unknown";
		switch (plugged) {
		case BatteryManager.BATTERY_PLUGGED_AC:
			plugType = "AC";
			break;
		case BatteryManager.BATTERY_PLUGGED_USB:
			plugType = "USB";
			break;
		}
		return plugType;
	}
	private String getHealthString(int health) {
		String healthString = "Unknown";
		switch (health) {
		case BatteryManager.BATTERY_HEALTH_DEAD:
			healthString = "Dead";
			break;
		case BatteryManager.BATTERY_HEALTH_GOOD:
			healthString = "Good";
			break;
		case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
			healthString = "Over Voltage";
			break;
		case BatteryManager.BATTERY_HEALTH_OVERHEAT:
			healthString = "Over Heat";
			break;
		case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
			healthString = "Failure";
			break;
		}
		return healthString;
	}
	private String getStatusString(int status) {
		String statusString = "Unknown";
		switch (status) {
		case BatteryManager.BATTERY_STATUS_CHARGING:
			statusString = "Charging";
			break;
		case BatteryManager.BATTERY_STATUS_DISCHARGING:
			statusString = "Discharging";
			break;
		case BatteryManager.BATTERY_STATUS_FULL:
			statusString = "Full";
			break;
		case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
			statusString = "Not Charging";
			break;
		}
		return statusString;
	}
	private void setBatteryLevelText(String text) {
		textBatteryLevel.setText(text);
	}
	private void registerBatteryLevelReceiver() {
		IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
		registerReceiver(battery_receiver, filter);
	}
	static long memoryUsed() {
		return runtime.totalMemory() - runtime.freeMemory();
	}
	static final Runtime runtime = Runtime.getRuntime();
	// get signal strength
	private class MyPhoneStateListener extends PhoneStateListener {
		@Override
		public void onSignalStrengthsChanged(SignalStrength signalStrength) {
			signal = signalStrength.getGsmSignalStrength();
			System.out.println("SIGNAL: " + signal);
			hasSignal = true;
			// }
		}
	}
	private String networkType(int network) {
		switch (network) {
		case 7:
			return ("1xRTT");
		case 4:
			return ("CDMA");
		case 2:
			return ("EDGE");
		case 14:
			return ("eHRPD");
		case 5:
			return ("EVDO rev. 0");
		case 6:
			return ("EVDO rev. A");
		case 12:
			return ("EVDO rev. B");
		case 1:
			return ("GPRS");
		case 8:
			return ("HSDPA");
		case 10:
			return ("HSPA");
		case 15:
			return ("HSPA+");
		case 9:
			return ("HSUPA");
		case 11:
			return ("iDen");
		case 13:
			return ("LTE");
		case 3:
			return ("UMTS");
		case 0:
			return ("Unknown");
		}
		return "GAGAL";
	}
}

and don’t forget to add the permission on your Android Manifest.

and the result will be like this:

JSON Java & PHP

I want to show you how to get the value of the variable from php to java using JSON. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate(wikipedia).

First, you build your database and create a table. For this example, I want to make a table named “personal”.

CREATE TABLE IF NOT EXISTS `personal` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nama` varchar(40) NOT NULL,
  `nik` varchar(40) NOT NULL,
  `jabatan` varchar(40) NOT NULL,
  `email` varchar(120) NOT NULL,
  `alamat` varchar(140) NOT NULL,
  `hp` varchar(15) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

Then, don’t forget to config the main.xml (for Android)


	
	

Then, you build your java class, for this example, I build for android. So the code will be like:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
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.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class ViewDataActivity extends Activity {
	private JSONObject jObject;
	private String xResult = "";
	private Button back;
	private String url = "http://10.0.2.2/android/datakaryawan.php";
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.datakaryawan);
		back = (Button) findViewById(R.id.back);
		back.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				goToMenu();
			}
		});
		TextView txtResult = (TextView) findViewById(R.id.TextViewResult);
		url += "?nik=" + UserData.getEmail();
		xResult = getRequest(url);
		try {
			parse(txtResult);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void parse(TextView txtResult) throws Exception {
		jObject = new JSONObject(xResult);
		JSONArray menuitemArray = jObject.getJSONArray("personal");
		String sret = "";
		int j = 0;
		for (int i = 0; i < menuitemArray.length(); i++) {
			sret += "Data Karyawan  : n n";
			sret += "Nama  : "
					+ menuitemArray.getJSONObject(i).getString("nama")
							.toString() + "n";
			sret += "NIK      : "
					+ menuitemArray.getJSONObject(i).getString("nik")
							.toString() + "n";
			sret += "E-mail : "
					+ menuitemArray.getJSONObject(i).getString("email")
							.toString() + "n";
			sret += "Alamat: "
					+ menuitemArray.getJSONObject(i).getString("alamat")
							.toString() + "n";
			sret += "No HP  : "
					+ menuitemArray.getJSONObject(i).getString("hp").toString()
					+ "n";
			sret += "Jabatan: "
					+ menuitemArray.getJSONObject(i).getString("jabatan")
							.toString() + "n";
			j = i;
		}
		txtResult.setText(sret);
	}
	/**
	 * Method untuk Mengirimkan data kes erver event by button login diklik
	 * 
	 * @param view
	 */
	public String getRequest(String Url) {
		String sret = "";
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet(Url);
		try {
			HttpResponse response = client.execute(request);
			sret = request(response);
		} catch (Exception ex) {
			Toast.makeText(this, "Gagal " + sret, Toast.LENGTH_SHORT).show();
		}
		return sret;
	}
	/**
	 * Method untuk Menenrima data dari server
	 * 
	 * @param response
	 * @return
	 */
	public static String request(HttpResponse response) {
		String result = "";
		try {
			InputStream in = response.getEntity().getContent();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(in));
			StringBuilder str = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				str.append(line + "n");
			}
			in.close();
			result = str.toString();
		} catch (Exception ex) {
			result = "Error";
		}
		return result;
	}
	public void goToMenu() {
		finish();
	}
}

Next, you build the php code.

$nik = $_GET['nik'];//get nilai user from client
$link = mysql_connect('localhost', 'root', '') or die('Cannot connect to the DB');
mysql_select_db('cuti', $link) or die('Cannot select the DB');
/* grab the posts from the db */
$query = "SELECT * FROM personal where nik='$nik'";
$result = mysql_query($query, $link) or die('Errorquery:  '.$query);
$rows = array();
while ($r = mysql_fetch_assoc($result)) {
	$rows[] = $r;
}
$data = "{personal:".json_encode($rows)."}";
echo $data;
$query2 = "SELECT * FROM cuti where nik='$nik'";
$result2 = mysql_query($query2, $link) or die('Errorquery:  '.$query2);
$rows2 = array();
while ($r2 = mysql_fetch_assoc($result2)) {
	$rows2[] = $r2;
}
$data2 = "{cuti:".json_encode($rows2)."}";
echo $data2;

the result will be like this: