So I had a thread that was taking care of some network stuff for the app behind the scenes, but for some reason the IDE kept thinking that I was updating the UI so it wouldn't stop crashing. I changed it over to an AsyncTask and now I get an Index Out of Range error. Before I had started working with threading the app worked fine, it just was really slow. I haven't changed any of the original code that worked I've just added to it with the threads. So I know that my original code isn't the issue it's the code that creates the AsyncTask or at least it should be that code. My code is shown below along with the errors:
Main Java file
package shc_BalloonSat.namespace;
import java.text.DecimalFormat;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.widget.TextView;
import android.widget.Toast;
public class Shc_BalloonSat_Activity extends Activity
{
int historyCountFromUser;
httpAPI api;
mapAPI map;
runDialog dialog;
DecimalFormat df = new DecimalFormat("##.#####");
DecimalFormat decimalf = new DecimalFormat("##.######");
AlertDialog alert;
SharedPreferences pref;
Editor prefEditor;
String lastpacketsPHP;
// User to determine how many packet the user would like to see.
int userDefinedCount = 5;
/*
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
loadApp();
}
public boolean isNetworkConnected(Context context)
{
ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectionManager.getActiveNetworkInfo() != null && connectionManager.getActiveNetworkInfo().isAvailable() && connectionManager.getActiveNetworkInfo().isConnected())
{
return true;
}
else
{
return false;
}
}
public void showAlert()
{
alert.setTitle("Sorry!");
alert.setMessage("Please connect to the internet to access the full functionality of this app.");
alert.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
});
alert.show();
}
/* public void onResume()
{
super.onResume();
loadApp();
}
public void onRestart()
{
super.onRestart();
loadApp();
}*/
public void loadApp()
{
setContentView(shc_BalloonSat.namespace.R.layout.main);
alert = new AlertDialog.Builder(this).create();
String returned = "";
lastpacketsPHP = "";
pref = getSharedPreferences("shared_prefs", 0);
prefEditor = pref.edit();
prefEditor.putString(lastpacketsPHP, "/* PHP file URL goes here */");
prefEditor.commit();
// These next two lines are used to test the PHP files on the SHC server by determining if PHP is set up correctly.
//prefEditor.putString(lastpacketsPHP, "/* PHP file URL goes here */");
//prefEditor.commit();
if (!isNetworkConnected(this))
{
showAlert();
}
else
{
api = new httpAPI(this);
map = new mapAPI(this);
dialog = new runDialog();
try
{
returned = api.getData();
}
catch (Exception e)
{
Toast.makeText(this, "Error: Unable to receive data at this time.", Toast.LENGTH_SHORT).show();
}
TextView infoTV = (TextView)this.findViewById(shc_BalloonSat.namespace.R.id.info);
infoTV.setText(returned);
assignInfoToInfoTextView();
assignInfoToHistoryTextView();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(shc_BalloonSat.namespace.R.menu.mainmenu, menu);
SubMenu submenu = menu.addSubMenu(0, Menu.FIRST, Menu.NONE, "Preferences");
submenu.add(0, 5, Menu.NONE, "Get Last 5 Packets");
submenu.add(0, 10, Menu.NONE, "Get Last 10 Packets");
submenu.add(0, 20, Menu.NONE, "Get Last 20 Packets");
inflater.inflate(shc_BalloonSat.namespace.R.menu.mainmenu, submenu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle item selection
switch (item.getItemId())
{
case shc_BalloonSat.namespace.R.id.viewKML:
viewKML();
return true;
case 5:
viewLast5Packets();
return true;
case 10:
viewLast10Packets();
return true;
case 20:
viewLast20Packets();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void assignInfoToInfoTextView()
{
TextView infoTV = (TextView)this.findViewById(shc_BalloonSat.namespace.R.id.info);
try
{
String result = api.result.substring(1, api.result.length()-2);
JSONObject json_data = new JSONObject(result);
double altitudeData = json_data.getDouble("altitude");
double altitudeInFeet = altitudeData * 3.281;
String infoText = "Last Known Altitude: " + df.format(altitudeInFeet) + " ft\n";
Double speedData = json_data.optDouble("speed");
if (speedData.isNaN())
{
speedData = 0.00;
}
Double direction = json_data.optDouble("heading");
String directionUnits = " degrees from N";
String directionText = "";
if (direction == 0)
{
directionText = ", N";
}
else if (direction > 0 && direction < 45)
{
directionText = ", N NE";
}
else if (direction == 45)
{
directionText = ", NE";
}
else if (direction > 45 && direction < 90)
{
directionText = ", E NE";
}
else if (direction == 90)
{
directionText = ", E";
}
else if (direction > 90 && direction < 135)
{
directionText = ", E SE";
}
else if (direction == 135)
{
directionText = ", SE";
}
else if (direction > 135 && direction < 180)
{
directionText = ", S SE";
}
else if (direction == 180)
{
directionText = ", S";
}
else if (direction > 180 && direction < 225)
{
directionText = ", S SW";
}
else if (direction == 225)
{
directionText = ", SW";
}
else if (direction > 225 && direction < 270)
{
directionText = ", W SW";
}
else if (direction == 270)
{
directionText = ", W";
}
else if (direction > 270 && direction < 315)
{
directionText = ", W NW";
}
else if (direction == 315)
{
directionText = ", NW";
}
else if (direction > 315 && direction < 360)
{
directionText = ", N NW";
}
else if (direction.isNaN())
{
directionText = " Invalid direction";
}
else
{
}
infoText += "Last Known Velocity: " + df.format(speedData) + " m/s " + direction + directionUnits + directionText + "\n";
double recentLatitudeData = json_data.getDouble("latitude");
infoText += "Last Known Latitude: " + df.format(recentLatitudeData) + "\n";
double recentLongitudeData = json_data.getDouble("longitude");
infoText += "Last Known Longtitude: " + df.format(recentLongitudeData) + "\n";
infoTV.setText(infoText);
}
catch (JSONException e)
{
// TODO Auto-generated catch block
Log.e("<tag>", e.getMessage());
Toast.makeText(this,"Error in (Last Known) method!",Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Log.e("<tag>", e.getMessage());
Toast.makeText(this,"Error in (Last Known) method!",Toast.LENGTH_SHORT).show();
}
}
public void assignInfoToHistoryTextView()
{
try
{
JSONArray jArray = new JSONArray(api.result);
TextView historyTV = (TextView)this.findViewById(shc_BalloonSat.namespace.R.id.history);
for (int count = 1; count < userDefinedCount; count++)
{
JSONObject json_data = jArray.getJSONObject(count);
double altitudeData = json_data.getDouble("altitude");
double altitudeInFeet = altitudeData * 3.281;
String historyText = "Altitude: " + decimalf.format(altitudeInFeet) + " ft\n";
Double speedData = json_data.optDouble("speed");
if (speedData.isNaN())
{
speedData = 0.00;
}
Double direction = json_data.optDouble("heading");
String directionUnits = " degrees from N";
String directionText = "";
if (direction == 0)
{
directionText = ", N";
}
else if (direction > 0 && direction < 45)
{
directionText = ", N NE";
}
else if (direction == 45)
{
directionText = ", NE";
}
else if (direction > 45 && direction < 90)
{
directionText = ", E NE";
}
else if (direction == 90)
{
directionText = ", E";
}
else if (direction > 90 && direction < 135)
{
directionText = ", E SE";
}
else if (direction == 135)
{
directionText = ", SE";
}
else if (direction > 135 && direction < 180)
{
directionText = ", S SE";
}
else if (direction == 180)
{
directionText = ", S";
}
else if (direction > 180 && direction < 225)
{
directionText = ", S SW";
}
else if (direction == 225)
{
directionText = ", SW";
}
else if (direction > 225 && direction < 270)
{
directionText = ", W SW";
}
else if (direction == 270)
{
directionText = ", W";
}
else if (direction > 270 && direction < 315)
{
directionText = ", W NW";
}
else if (direction == 315)
{
directionText = ", NW";
}
else if (direction > 315 && direction < 360)
{
directionText = ", N NW";
}
else if (direction.isNaN())
{
directionText = " Invalid direction";
}
else
{
}
if (direction.isNaN())
{
historyText += "Velocity: " + df.format(speedData) + " m/s " + directionText + "\n";
}
else
{
historyText += "Velocity: " + df.format(speedData) + " m/s,\n" + direction + directionUnits + directionText + "\n";
}
double latitudeData = json_data.getDouble("latitude");
historyText += "Latitude: " + df.format(latitudeData) + "\n";
double longitudeData = json_data.getDouble("longitude");
historyText += "Longtitude: " + df.format(longitudeData) + "\n\n";
historyTV.setText(historyText);
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
Log.e("log_tag", "Error parsing data: " + e.toString());
}
catch(Exception e)
{
Log.e("log_tag", "Error parsing data: " + e.toString());
}
}
void viewLast5Packets()
{
if (!isNetworkConnected(this))
{
showAlert();
}
else
{
userDefinedCount = 5;
prefEditor.putString(lastpacketsPHP, "http://space.uah.edu/balloonsat_app/get_last_5_BS_packets.php");
prefEditor.commit();
assignInfoToInfoTextView();
assignInfoToHistoryTextView();
}
}
void viewLast10Packets()
{
if (!isNetworkConnected(this))
{
showAlert();
}
else
{
userDefinedCount = 10;
prefEditor.putString(lastpacketsPHP, "http://space.uah.edu/balloonsat_app/get_last_10_BS_packets.php");
prefEditor.commit();
assignInfoToInfoTextView();
assignInfoToHistoryTextView();
}
}
void viewLast20Packets()
{
if (!isNetworkConnected(this))
{
showAlert();
}
else
{
userDefinedCount = 20;
prefEditor.putString(lastpacketsPHP, "http://space.uah.edu/balloonsat_app/get_last_20_BS_packets.php");
prefEditor.commit();
assignInfoToInfoTextView();
assignInfoToHistoryTextView();
}
}
public void viewKML()
{
if (!isNetworkConnected(this))
{
showAlert();
}
else
{
map.openKML();
}
}
}
httpAPI.java
package shc_BalloonSat.namespace;
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 android.util.Log;
public class httpAPI
{
Shc_BalloonSat_Activity shc;
HttpClient client;
ArrayList<NameValuePair> nameValuePairs;
HttpResponse response;
HttpEntity entity;
InputStream is;
String result = "";
HttpPost httppost;
public httpAPI(Shc_BalloonSat_Activity aContext)
{
shc = aContext;
}
public String getData() throws Exception
{
try
{
client = new DefaultHttpClient();
nameValuePairs = new ArrayList<NameValuePair>();
httppost = new HttpPost(shc.pref.getString(shc.lastpacketsPHP, shc.lastpacketsPHP.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = client.execute(httppost);
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();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result: " + e.toString());
}
return result;
}
}
runDialog.java
package shc_BalloonSat.namespace;
import android.app.ProgressDialog;
import android.os.AsyncTask;
public class runDialog extends AsyncTask<String, Integer, String>
{
Shc_BalloonSat_Activity shc;
httpAPI api;
ProgressDialog progressDialog;
public void onPreExecute()
{
progressDialog = new ProgressDialog(shc);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
}
#Override
protected String doInBackground(String... params)
{
for (int count = 0; count < 20; count++)
{
publishProgress(5);
try
{
api.getData();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
progressDialog.dismiss();
return null;
}
protected void onProgressUpdate(Integer...progress)
{
progressDialog.incrementProgressBy(progress[0]);
}
protected void onPostExecute()
{
}
}
Errors:
org.json.JSONException: Index 5 out of range [0..5)
I get this error each time it tries to get the data from the URL. I can also email the apk file to anyone who would like to see what it's actually doing. I also have reason to believe that what ever the cause of this is might also be causing my ProgressDialog to not show up. Any ideas on why I could be getting this error?
Turns out that I was passing an activity, not calling the ProgressDialog correctly, and set up my AsyncTask incorrectly. Thank goodness I found someone who had the time to sort debug my project for me.
Related
I try to inject some keys in a text field with a InputMethodService.
In my Manifest everything seems alright.
Everytime when I call getCurrentInputConnection() I get null.
My class extends InputMethodService and I start the service.
Can anyone help me? Is there something else I need to do to get the currentInputConnection??
Here is the code:
Its from an open source project called WifiKeyboard
And I try to inject code with the function setText(String text)
package com.example.twolibs;
/**
* WiFi Keyboard - Remote Keyboard for Android.
* Copyright (C) 2011 Ivan Volosyuk
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import java.util.HashSet;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.hardware.input.InputManager;
import android.inputmethodservice.InputMethodService;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.RemoteException;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethod;
public class WiFiInputMethod extends InputMethodService {
public static final int KEY_HOME = -1000;
public static final int KEY_END = -1001;
public static final int KEY_CONTROL = -1002;
public static final int KEY_DEL = -1003;
#Override
public void onStartInput(EditorInfo attribute, boolean restarting) {
super.onStartInput(attribute, restarting);
// boolean multiline = (attribute.inputType & InputType.TYPE_TEXT_FLAG_MULTI_LINE) != 0;
// Log.d("ivan", "onStartInput "
// + "actionId=" + attribute.actionId + " "
// + "id=" + attribute.fieldId + " "
// + "name=" + attribute.fieldName + " "
// + "opt=" + Integer.toHexString(attribute.imeOptions) + " "
// + "inputType=" + Integer.toHexString(attribute.inputType) + " "
// + "priv=" + attribute.privateImeOptions
// + "multiline=" + multiline);
try {
String text = getText();
} catch (NullPointerException e) {
}
}
ServiceConnection serviceConnection;
#Override
public void onDestroy() {
// Debug.d("WiFiInputMethod onDestroy()");
if (serviceConnection != null)
unbindService(serviceConnection);
serviceConnection = null;
super.onDestroy();
}
PowerManager.WakeLock wakeLock;
HashSet<Integer> pressedKeys = new HashSet<Integer>();
#Override
public void onCreate() {
super.onCreate();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "wifikeyboard");
// Debug.d("WiFiInputMethod started");
serviceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
// Debug.d("WiFiInputMethod connected to HttpService.");
}
//#Override
public void onServiceDisconnected(ComponentName name) {
// Debug.d("WiFiInputMethod disconnected from HttpService.");
}
};
}
#Override
public boolean onEvaluateFullscreenMode() {
return false;
}
void receivedChar(int code) {
wakeLock.acquire();
wakeLock.release();
InputConnection conn = getCurrentInputConnection();
if (conn == null) {
// Debug.d("connection closed");
return;
}
if (pressedKeys.contains(KEY_CONTROL)) {
switch (code) {
case 'a':case 'A': selectAll(conn); return;
case 'x':case 'X': cut(conn); return;
case 'c':case 'C': copy(conn); return;
case 'v':case 'V': paste(conn); return;
}
}
String text = null;
if (code >= 0 && code <= 65535) {
text = new String(new char[] { (char) code } );
} else {
int HI_SURROGATE_START = 0xD800;
int LO_SURROGATE_START = 0xDC00;
int hi = ((code >> 10) & 0x3FF) - 0x040 | HI_SURROGATE_START;
int lo = LO_SURROGATE_START | (code & 0x3FF);
text = new String(new char[] { (char) hi, (char) lo } );
}
conn.commitText(text, 1);
}
#SuppressWarnings("unused")
void receivedKey(int code, boolean pressed) {
if (false) {
for (int key : pressedKeys) {
sendKey(key, false, false);
}
pressedKeys.clear();
resetModifiers();
return;
}
if (pressedKeys.contains(code) == pressed) {
if (pressed == false) return;
// ignore autorepeat on following keys
switch (code) {
case KeyEvent.KEYCODE_ALT_LEFT:
case KeyEvent.KEYCODE_SHIFT_LEFT:
case KeyEvent.KEYCODE_HOME:
case KeyEvent.KEYCODE_MENU: return;
}
}
if (pressed) {
pressedKeys.add(code);
System.out.println("one");
sendKey(code, pressed, false);
} else {
pressedKeys.remove(code);
sendKey(code, pressed, pressedKeys.isEmpty());
}
}
void resetModifiers() {
InputConnection conn = getCurrentInputConnection();
if (conn == null) {
return;
}
conn.clearMetaKeyStates(
KeyEvent.META_ALT_ON | KeyEvent.META_SHIFT_ON | KeyEvent.META_SYM_ON);
}
private long lastWake;
void sendKey(int code, boolean down, boolean resetModifiers) {
System.out.println("two");
/*
long time = System.currentTimeMillis();
if (time - lastWake > 5000) {
wakeLock.acquire();
wakeLock.release();
lastWake = time;
}
*/
InputConnection conn = getCurrentInputConnection();
System.out.println("three");
if (conn == null) {
System.out.println("kacke");
// Debug.d("connection closed");
return;
}
if (code < 0) {
if (down == false) return;
switch (code) {
case KEY_HOME: keyHome(conn); break;
case KEY_END: keyEnd(conn); break;
case KEY_DEL: keyDel(conn); break;
}
return;
}
if (pressedKeys.contains(KEY_CONTROL)) {
switch (code) {
case KeyEvent.KEYCODE_DPAD_LEFT:
if (!down) return;
wordLeft(conn);
return;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (!down) return;
wordRight(conn);
return;
case KeyEvent.KEYCODE_DEL:
if (!down) return;
deleteWordLeft(conn);
return;
case KeyEvent.KEYCODE_FORWARD_DEL:
deleteWordRight(conn);
return;
case KeyEvent.KEYCODE_DPAD_CENTER:
if (!down) return;
copy(conn);
return;
}
}
if (pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT)) {
switch (code) {
case KeyEvent.KEYCODE_DPAD_CENTER:
if (!down) return;
paste(conn);
return;
}
}
if (code == KeyEvent.KEYCODE_ENTER) {
if (shouldSend()) {
if (!down) return;
Log.d("ivan", "sending submit action");
conn.performEditorAction(EditorInfo.IME_ACTION_SEND);
return;
}
}
// if (pressedKeys.contains(KEY_CONTROL)) {
// if (down == false) return;
// switch (code) {
// case KeyEvent.KEYCODE_A: selectAll(conn); break;
// case KeyEvent.KEYCODE_X: cut(conn); break;
// case KeyEvent.KEYCODE_C: copy(conn); break;
// case KeyEvent.KEYCODE_V: paste(conn); break;
// }
// return;
// }
System.out.println("four");
conn.sendKeyEvent(new KeyEvent(
android.os.SystemClock.uptimeMillis(),
android.os.SystemClock.uptimeMillis(),
down ? KeyEvent.ACTION_DOWN : KeyEvent.ACTION_UP,
code,
0,
(pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT)
? KeyEvent.META_SHIFT_LEFT_ON : 0) +
(pressedKeys.contains(KEY_CONTROL)? KeyEvent.META_CTRL_ON : 0) +
(pressedKeys.contains(KeyEvent.KEYCODE_ALT_LEFT)
? KeyEvent.META_ALT_LEFT_ON : 0)
));
if (resetModifiers) {
conn.clearMetaKeyStates(
KeyEvent.META_ALT_ON | KeyEvent.META_SHIFT_ON | KeyEvent.META_SYM_ON);
}
}
private boolean shouldSend() {
if (pressedKeys.contains(KEY_CONTROL)) {
// Log.d("ivan", "Control pressed");
return true;
}
EditorInfo editorInfo = getCurrentInputEditorInfo();
if (editorInfo == null) {
// Log.d("ivan", "No editor info");
return false;
}
if ((editorInfo.inputType & InputType.TYPE_CLASS_TEXT) == 0) {
// Log.d("ivan", "Not text, sending enter");
return false;
}
if ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_MULTI_LINE) != 0) {
// Log.d("ivan", "Multi-line, sending ordinary enter");
return false;
}
int action = editorInfo.imeOptions & EditorInfo.IME_MASK_ACTION;
if (action == EditorInfo.IME_ACTION_NONE || action == EditorInfo.IME_ACTION_DONE) {
// Log.d("ivan", "No useful action, sending enter");
return false;
}
// Log.d("ivan", "Useful action to be performed");
return true;
}
private void keyDel(InputConnection conn) {
// if control key used -- delete word right
if (pressedKeys.contains(KEY_CONTROL)) {
deleteWordRight(conn);
return;
}
if (pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT)) {
cut(conn);
return;
}
conn.deleteSurroundingText(0, 1);
conn.commitText("", 0);
}
private void paste(InputConnection conn) {
conn.performContextMenuAction(android.R.id.paste);
}
private void copy(InputConnection conn) {
conn.performContextMenuAction(android.R.id.copy);
}
private void cut(InputConnection conn) {
conn.performContextMenuAction(android.R.id.cut);
}
public void selectAll(InputConnection conn) {
ExtractedText text = conn.getExtractedText(req, 0);
try {
conn.setSelection(0, text.text.length());
} catch (NullPointerException e) {
// Potentially, text or text.text can be null
}
}
ExtractedTextRequest req = new ExtractedTextRequest();
{
req.hintMaxChars = 100000;
req.hintMaxLines = 10000;
}
private void deleteWordRight(InputConnection conn) {
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end = text.selectionEnd;
String str = text.text.toString();
int len = str.length();
for (; end < len; end++) {
if (!Character.isSpace(str.charAt(end))) break;
}
for (; end < len; end++) {
if (Character.isSpace(str.charAt(end))) break;
}
conn.deleteSurroundingText(0, end - text.selectionEnd);
}
private void deleteWordLeft(InputConnection conn) {
// TODO: what is the correct word deleting policy?
// delete until next space? until next different character type?
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end = text.selectionEnd - 1;
String str = text.text.toString();
for (; end >= 0; end--) {
if (!Character.isSpace(str.charAt(end))) break;
}
for (; end >= 0; end--) {
if (Character.isSpace(str.charAt(end))) break;
}
end++;
conn.deleteSurroundingText(text.selectionEnd - end, 0);
}
private void wordRight(InputConnection conn) {
boolean shift = pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT);
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end = text.selectionEnd;
String str = text.text.toString();
int len = str.length();
for (; end < len; end++) {
if (!Character.isSpace(str.charAt(end))) break;
}
for (; end < len; end++) {
if (Character.isSpace(str.charAt(end))) break;
}
int start = shift ? text.selectionStart : end;
Log.d("wifikeyboard", "start = " + start + " end = " + end);
conn.setSelection(start, end);
}
private void wordLeft(InputConnection conn) {
boolean shift = pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT);
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end = text.selectionEnd - 1;
String str = text.text.toString();
for (; end >= 0; end--) {
if (!Character.isSpace(str.charAt(end))) break;
}
for (; end >= 0; end--) {
if (Character.isSpace(str.charAt(end))) break;
}
end++;
int start = shift ? text.selectionStart : end;
Log.d("wifikeyboard", "start = " + start + " end = " + end);
conn.setSelection(start, end);
}
private void keyEnd(InputConnection conn) {
boolean control = pressedKeys.contains(KEY_CONTROL);
boolean shift = pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT);
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end;
if (control) {
end = text.text.length();
} else {
end = text.text.toString().indexOf('\n', text.selectionEnd);
if (end == -1) end = text.text.length();
}
int start = shift ? text.selectionStart : end;
Log.d("wifikeyboard", "start = " + start + " end = " + end);
conn.setSelection(start, end);
}
private void keyHome(InputConnection conn) {
boolean control = pressedKeys.contains(KEY_CONTROL);
boolean shift = pressedKeys.contains(KeyEvent.KEYCODE_SHIFT_LEFT);
ExtractedText text = conn.getExtractedText(req, 0);
if (text == null) return;
int end;
if (control) {
end = 0;
} else {
end = text.text.toString().lastIndexOf('\n', text.selectionEnd - 1);
end++;
}
int start = shift ? text.selectionStart : end;
Log.d("wifikeyboard", "start = " + start + " end = " + end);
conn.setSelection(start, end);
}
boolean setText(String text) {
// FIXME: need feedback if the input was lost
InputConnection conn = getCurrentInputConnection();
if (conn == null) {
// Debug.d("connection closed");
return false;
}
conn.commitText(text, text.length());
conn.beginBatchEdit();
// FIXME: hack
conn.deleteSurroundingText(100000, 100000);
conn.commitText(text, text.length());
conn.endBatchEdit();
return true;
}
String getText() {
String text = "";
try {
InputConnection conn = getCurrentInputConnection();
ExtractedTextRequest req = new ExtractedTextRequest();
req.hintMaxChars = 1000000;
req.hintMaxLines = 10000;
req.flags = 0;
req.token = 1;
text = conn.getExtractedText(req, 0).text.toString();
} catch (Throwable t) {
}
return text;
}
}
Thank you
package com.example.intracollegeapp;// package name
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import LibPack.UserInfoLib;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class LoginForm extends Activity {
Button login;
TextView username;
TextView password;
UserInfoLib ui;
long msgLength;
long bitLength;
char msg[];
long requiredBits;
long requiredBytes;
int toPad[];
private static final String NAMESPACE = "link to server package on which webservices are stored";
private static final String URL = "link to wsdl file stored on server";
private static final String SOAP_ACTION = "IntraCollegeWS";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_form);
login=(Button)findViewById(R.id.butLogin);
username=(TextView)findViewById(R.id.editText1);
password=(TextView)findViewById(R.id.editText2);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ui= new UserInfoLib();
ui.userId=username.getText().toString();
ui.password=getSHA1(password.getText().toString());
ui=(UserInfoLib)callService(objectToString(ui), "UserLogin", "userInfo");
//ui=(UserInfoLib)stringToObject(temp);
if(ui.firstName.equals("")){
Toast.makeText(v.getContext(), "Please Verify User Name Or Password", Toast.LENGTH_LONG).show();
finish();
}else{
Toast.makeText(v.getContext(), "Login Successfull", Toast.LENGTH_LONG).show();
System.out.println("NAME :"+ui.firstName);
Intent i = new Intent(v.getContext(), MainForm.class);
i.putExtra("uid", ui);
startActivity(i);
finish();
}
}
});
}
public long leftRotateBy(long l, int times) {
return ((l << times) & 0xFFFFFFFFl) | ((l & 0xFFFFFFFFl) >> (32 - times));
}
public int getByteAt(int at) {
if (at < msgLength) {
return (msg[at]);
} else {
at = at - (int) msgLength;
return toPad[at];
}
}
public void padBits(String pass) {
System.out.println("\n\n\n\n");
msg = pass.toCharArray();
msgLength = msg.length;
bitLength = msgLength * 8;
System.out.println("Msg Bit Length: " + bitLength);
System.out.println("MSg Byte Length: " + msgLength);
System.out.println("Required Minimum Bits: " + (bitLength + 65));
long remainder = (bitLength + 65) % 512;
System.out.println("Mod (Bits): " + remainder);
if (remainder == 0) {
requiredBits = 65;
System.out.println("No Padding Needed.");
} else {
requiredBits = (512 - remainder) + 65;
System.out.println(requiredBits + " Bits Padding Needed.");
}
requiredBytes = requiredBits / 8;
toPad = new int[(int) requiredBytes];
System.out.println("Required Bits: " + requiredBits);
System.out.println("Required Bytes: " + requiredBytes);
// manually append 1 to start of pad bits...
toPad[0] = 0x80;
for (int i = 1; i < requiredBytes - 8; i++) {
toPad[i] = 0;
}
long temp = bitLength;
for (int i = (int) (requiredBytes - 1); i >= (int) (requiredBytes - 8); i--) {
int t = (int) (temp & 0xff);
temp = temp >> 8;
toPad[i] = t;
}
System.out.println("TO PAD: ");
for (int i = 0; i < requiredBytes; i++) {
System.out.print(Integer.toHexString(toPad[i]) + " ");
}
System.out.println();
}
public String getSHA1(String pass) {
int kconst[] = new int[]{
0x5A827999,
0x6ED9EBA1,
0x8F1BBCDC,
0xCA62C1D6};
long h0 = 0x67452301;
long h1 = 0xEFCDAB89;
long h2 = 0x98BADCFE;
long h3 = 0x10325476;
long h4 = 0xC3D2E1F0;
long a, b, c, d, e;
padBits(pass);
long totalLength = msgLength + requiredBytes;
System.out.println("TOTAL LENGTH: " + totalLength);
System.out.println("BLOCKS: " + (totalLength / 8));
long w[] = new long[80];
for (int i = 0; i < (int) totalLength; i += 64) {
for (int j = i, kk = 0; j < (i + 64); j += 4, kk++) {
w[kk] = 0xffffffffl & ((getByteAt(j) << 24) | (getByteAt(j + 1) << 16) | (getByteAt(j + 2) << 8) | (getByteAt(j + 3)));
//System.out.println("W[" + kk + "]: " + Long.toHexString(w[kk]));
}
for (int kk = 16; kk < 80; kk++) {
w[kk] = (w[kk - 3] ^ w[kk - 8] ^ w[kk - 14] ^ w[kk - 16]);
w[kk] = leftRotateBy(w[kk], 1);
//System.out.println("W[" + kk + "]: " + Long.toHexString(w[kk]));
}
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
long temp = 0;
for (int t = 0; t < 20; t++) {
temp = leftRotateBy(a, 5) + ((b & c) | ((~b) & d)) + e + w[t] + kconst[0];
temp &= 0xFFFFFFFFl;
e = d;
d = c;
c = leftRotateBy(b, 30);
b = a;
a = temp;
}
for (int t = 20; t < 40; t++) {
temp = leftRotateBy(a, 5) + (b ^ c ^ d) + e + w[t] + kconst[1];
temp &= 0xFFFFFFFFl;
e = d;
d = c;
c = leftRotateBy(b, 30);
b = a;
a = temp;
}
for (int t = 40; t < 60; t++) {
temp = leftRotateBy(a, 5) + ((b & c) | (b & d) | (c & d)) + e + w[t] + kconst[2];
temp &= 0xFFFFFFFFl;
e = d;
d = c;
c = leftRotateBy(b, 30);
b = a;
a = temp;
}
for (int t = 60; t < 80; t++) {
temp = leftRotateBy(a, 5) + (b ^ c ^ d) + e + w[t] + kconst[3];
temp &= 0xFFFFFFFFl;
e = d;
d = c;
c = leftRotateBy(b, 30);
b = a;
a = temp;
}
h0 = (h0 + a) & 0xFFFFFFFFl;
h1 = (h1 + b) & 0xFFFFFFFFl;
h2 = (h2 + c) & 0xFFFFFFFFl;
h3 = (h3 + d) & 0xFFFFFFFFl;
h4 = (h4 + e) & 0xFFFFFFFFl;
}
return Long.toHexString(h0) + Long.toHexString(h1) + Long.toHexString(h2) + Long.toHexString(h3) + Long.toHexString(h4);
}
Object callService(String INPUT_DATA, String METHOD_NAME, String PARAMETER_NAME){
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
PropertyInfo pi = new PropertyInfo();
pi.setName(PARAMETER_NAME);
pi.setValue(INPUT_DATA);
pi.setType(String.class);
request.addProperty(pi);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject resultsRequestSOAP = (SoapObject)envelope.bodyIn;
String resp = resultsRequestSOAP.getPrimitivePropertyAsString("return");
return stringToObject(resp);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Object stringToObject(String inp){
byte b[] = Base64.decode(inp);
Object ret = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(b);
ObjectInput in = new ObjectInputStream(bis);
ret = (Object) in.readObject();
bis.close();
in.close();
} catch(Exception e) {
System.out.println("NOT DE-SERIALIZABLE: " + e);
}
return ret;
}
String objectToString(Object obj){
byte[] b = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(obj);
b = bos.toByteArray();
} catch(Exception e) {
System.out.println("NOT SERIALIZABLE: " + e);
}
return Base64.encode(b);
}
}
/* i have developed an android application which connects to server for login purpose. For connection i have used ksoap2 library. Intracollege webservice is stored on server. The application works fine when connected to server using wifi. if it is not connected to wifi it displays message "application is crashed" and then application stops working.
I only want to display a simple message "Application is not connected to server" if it is not connected to server using wifi.*/
Try this........
public boolean isNet()
{
boolean status=false;
String line;
try
{
URL url = new URL("http://www.google.com");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
while(( line = reader.readLine()) != null)
{
}
status=true;
}
catch (IOException ex)
{
System.out.println("ex in isNet : "+ex.toString());
if(ex.toString().equals("java.net.UnknownHostException: www.google.com"))
status=false;
}
catch(Exception e)
{
}
return status;
}
if(status==true)
{
//Do your operation
}
else
show("No Internet Connection.");
When status is true do your login process.Otherwise show message "Application is not connected to server".
To check for the internet connection try this out
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
Check this code, this will help you :
Initialize in the class where you want to check network availability.
OtherUtils otherUtils = new OtherUtils();
if (!otherUtils.isNetworkAvailable(getApplicationContext())) {
Toast.makeText(getApplicationContext(), "No Network Available", Toast.LENGTH_LONG).show();
return;
}
Add below class:
public class OtherUtils{
Context context;
public boolean isNetworkAvailable(Context context) {
this.context = context;
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
// boitealerte(this.getString(R.string.alertNoNetwork),"getSystemService rend null");
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
This will surely help you.
I am trying to create an android application to find the phone moving direction with Text to speech.There is a lot of problems with this.ie,it working some what,and i am not getting accurate movement.this is my code
#Override
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
float [] values = event.values;
synchronized (this) {
Log.d(tag, "onSensorChanged: " + sensor + ", x: " +
values[0] + ", y: " + values[1] + ", z: " + values[2]);
if (sensor.getType() == Sensor.TYPE_ACCELEROMETER ) {
x.setText("x"+ values[0]);
y.setText("y"+ values[1]);
z.setText("z"+ values[2]);
xa=(int)values[0];// this part of code is only test to see int x and y on Activity
ya=(int)values[1];
ball.scrollBy(xa, ya);
a=Integer.toString(xa);
b=Integer.toString(ya);
ball.scrollBy(xa, ya);
xat.setText(a);
yat.setText(b);
if (trigL || trigD || trigR || trigU ) {
int ttt = TextToSpeech.QUEUE_FLUSH;
final long ACCEL_SENSOR_DELAY = 100;
long lastAccelSensorChange = 0;
long now = System.currentTimeMillis();
if ((now-ACCEL_SENSOR_DELAY) > lastAccelSensorChange) {
lastAccelSensorChange = now;
ttt = TextToSpeech.QUEUE_FLUSH;
sensore.registerListener(MainActivity.this, accelerometer,
trigL = false;
trigR = false;
trigU = false;
trigD = false;
}
}
if (values[0] < -6) {
trigL = true;
if(tts.isSpeaking())
{
return;
}
else
tts.speak("Move Left", TextToSpeech.QUEUE_FLUSH, null);
values[0]=0;
values[1]=0;
return;
} else if (values[0] > 6) {
trigR = true;
if(tts.isSpeaking())
{
return;
}
else
tts.speak("Move Right", TextToSpeech.QUEUE_FLUSH, null);
values[0]=0;
values[1]=0;
return;
}
else if (values[1] < -6) {
trigD = true;
if(tts.isSpeaking())
{
return;
}
else
tts.speak("Move Down", TextToSpeech.QUEUE_FLUSH, null);
values[1]=0;
values[0]=0;
return;
} else if (values[1] > 6) {
trigU = true;
if(tts.isSpeaking())
{
return;
}
else
tts.speak("Move Up", TextToSpeech.QUEUE_FLUSH, null);
values[1]=0;
values[0]=0;
return;
}
}
}
}
I am searching for last 2 weeks. Any suggestions can be help full for me.
I'm currently trying to debug my application, however, I'm running into some difficulties with a NullPointerException. I have a dialog box with 4 checkboxes, a save button, and a cancel button. When the user marks their choices in the dialog box then presses the save button it returns a NullPointerException and I don't understand why. Below is the XML file in case it's relevant to finding the solution:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollviewPref"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:layout_marginTop="10dip">
<LinearLayout
android:layout_width="300dip"
android:layout_height="wrap_content"
android:orientation="vertical"
android:minWidth="200dip">
<CheckBox
android:id="#+id/altitudeCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Altitude"
android:layout_gravity="left" />
<CheckBox
android:id="#+id/latitudeCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Latitude"
android:layout_gravity="left" />
<CheckBox
android:id="#+id/longitudeCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Longitude"
android:layout_gravity="left" />
<CheckBox
android:id="#+id/velocityCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Velocity"
android:layout_gravity="left" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:layout_marginBottom="10dip"
android:layout_marginTop="10dip">
<Button
android:id="#+id/saveBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Save"
android:layout_weight="1" />
<Button
android:id="#+id/cancelBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Cancel"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
</ScrollView>
The set set of code is the code that saves the user's choices to a SharedPreferences.
package shc_BalloonSat.namespace;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
public class CheckPreferences extends Dialog
{
Context shc;
private CheckBox altitudeCheckBox = null;
private CheckBox latitudeCheckbox = null;
private CheckBox longitudeCheckbox = null;
private CheckBox velocityCheckbox = null;
private CheckPreferencesListener listener;
SharedPreferences pref;
Editor prefEditor;
String userAltitudePreference = "";
String userLatitudePreference = "";
String userLongitudePreference = "";
String userVelocityPreference = "";
String userAltitudeChoice = "";
String userLatitudeChoice = "";
String userLongitudeChoice = "";
String userVelocityChoice = "";
public interface CheckPreferencesListener
{
public void onSettingsSaved();
public void onCancel();
}
public CheckPreferences(Context context, CheckPreferencesListener l)
{
super(context);
shc = context;
this.listener = l;
this.setContentView(R.layout.custompreferences);
altitudeCheckBox = (CheckBox) findViewById(R.id.altitudeCheckbox);
latitudeCheckbox = (CheckBox) findViewById(R.id.latitudeCheckbox);
longitudeCheckbox = (CheckBox) findViewById(R.id.longitudeCheckbox);
velocityCheckbox = (CheckBox) findViewById(R.id.velocityCheckbox);
this.setCancelable(false);
this.setCanceledOnTouchOutside(false);
this.setTitle("Data View Settings");
pref = shc.getSharedPreferences("shared_prefs", 1);
prefEditor = pref.edit();
initOnClick();
}
private void initOnClick()
{
View.OnClickListener click = new View.OnClickListener()
{
public void onClick(View v)
{
switch (v.getId())
{
case R.id.saveBtn:
{
saveSettings();
listener.onSettingsSaved();
dismiss();
break;
}
case R.id.cancelBtn:
{
listener.onCancel();
dismiss();
break;
}
}
}
};
// Save Button
this.findViewById(R.id.saveBtn).setOnClickListener(click);
// Cancel Button
this.findViewById(R.id.cancelBtn).setOnClickListener(click);
}
// This function is called when the user chooses the save their preferences
public void saveSettings()
{
try
{
if (altitudeCheckBox.isChecked())
{
userAltitudeChoice = "true";
prefEditor.putString(userAltitudePreference, userAltitudeChoice);
prefEditor.commit();
}
else if (latitudeCheckbox.isChecked())
{
userLatitudeChoice = "true";
prefEditor.putString(userLatitudePreference, userLatitudeChoice);
prefEditor.commit();
}
else if (longitudeCheckbox.isChecked())
{
userLongitudeChoice = "true";
prefEditor.putString(userLongitudePreference, userLongitudeChoice);
prefEditor.commit();
}
else if (velocityCheckbox.isChecked())
{
userVelocityChoice = "true";
prefEditor.putString(userVelocityPreference, userVelocityChoice);
prefEditor.commit();
}
else
{
}
}
catch (NullPointerException npe)
{
if (npe.getMessage() != null)
{
Log.e("<tag>", npe.getMessage());
}
else
{
Log.e("<tag>", "Save Settings e.getMessage() was null");
}
}
}
}
The NullPointerException happens in the savedSettings function. All that function does is put data in the SharedPreferences. Any idea why that wold cause something to be null? Thanks in advance for any help given.
Update: Below is the error log.
05-09 17:25:28.835: E/<tag>(5447): Save Settings e.getMessage() was null
05-09 17:25:28.866: E/AndroidRuntime(5447): FATAL EXCEPTION: main
05-09 17:25:28.866: E/AndroidRuntime(5447): java.lang.NullPointerException
05-09 17:25:28.866: E/AndroidRuntime(5447): at shc_BalloonSat.namespace.CheckPreferences$1.onClick(CheckPreferences.java:59)
05-09 17:25:28.866: E/AndroidRuntime(5447): at android.view.View.performClick(View.java:2408)
05-09 17:25:28.866: E/AndroidRuntime(5447): at android.view.View$PerformClick.run(View.java:8816)
05-09 17:25:28.866: E/AndroidRuntime(5447): at android.os.Handler.handleCallback(Handler.java:587)
05-09 17:25:28.866: E/AndroidRuntime(5447): at android.os.Handler.dispatchMessage(Handler.java:92)
05-09 17:25:28.866: E/AndroidRuntime(5447): at android.os.Looper.loop(Looper.java:123)
05-09 17:25:28.866: E/AndroidRuntime(5447): at android.app.ActivityThread.main(ActivityThread.java:4627)
05-09 17:25:28.866: E/AndroidRuntime(5447): at java.lang.reflect.Method.invokeNative(Native Method)
05-09 17:25:28.866: E/AndroidRuntime(5447): at java.lang.reflect.Method.invoke(Method.java:521)
05-09 17:25:28.866: E/AndroidRuntime(5447): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
05-09 17:25:28.866: E/AndroidRuntime(5447): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
05-09 17:25:28.866: E/AndroidRuntime(5447): at dalvik.system.NativeStart.main(Native Method)
Below is my main class where the listener is instantiated.
package shc_BalloonSat.namespace;
import java.text.DecimalFormat;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.widget.TextView;
import android.widget.Toast;
public class Shc_BalloonSat_Activity extends Activity
{
int historyCountFromUser;
httpAPI api;
mapAPI map;
runDialog dialog;
CheckPreferences check;
DecimalFormat df = new DecimalFormat("##.#####");
DecimalFormat decimalf = new DecimalFormat("##.######");
AlertDialog alert;
SharedPreferences pref;
Editor prefEditor;
String lastpacketsPHP;
TextView historyTV;
TextView infoTV;
// User to determine how many packet the user would like to see.
int userDefinedCount = 5;
/*
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
loadApp();
}
public boolean isNetworkConnected(Context context)
{
ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectionManager.getActiveNetworkInfo() != null && connectionManager.getActiveNetworkInfo().isAvailable() && connectionManager.getActiveNetworkInfo().isConnected())
{
return true;
}
else
{
return false;
}
}
public void showAlert()
{
alert.setTitle("Sorry!");
alert.setMessage("Please connect to the internet to access the full functionality of this app.");
alert.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
});
alert.show();
}
public void loadApp()
{
setContentView(shc_BalloonSat.namespace.R.layout.main);
alert = new AlertDialog.Builder(this).create();
lastpacketsPHP = "";
pref = getSharedPreferences("shared_prefs", 1);
prefEditor = pref.edit();
//prefEditor.putString(lastpacketsPHP, "\* PHP file location goes here. */");
//prefEditor.commit();
// These next two lines are used to test the PHP files on the SHC server by determining if PHP is set up correctly.
prefEditor.putString(lastpacketsPHP, "\* PHP file location goes here. */");
prefEditor.commit();
if (!isNetworkConnected(this))
{
showAlert();
}
else
{
api = new httpAPI(this);
map = new mapAPI(this);
dialog = new runDialog(this, api, new runDialog.OnDataLoadedListener()
{
public void dataLoaded(String textViewString)
{
infoTV = (TextView)findViewById(shc_BalloonSat.namespace.R.id.info);
infoTV.setText(textViewString);
}
});
dialog.execute();
}
CheckPreferences cp = new CheckPreferences(this, new CheckPreferences.CheckPreferencesListener()
{
public void onSettingsSaved()
{
// This function let's the activity know that the user has saved their preferences and
// that the rest of the app should be now be shown.
check.saveSettings();
assignInfoToInfoTextView();
assignInfoToHistoryTextView();
}
public void onCancel()
{
Toast.makeText(getApplicationContext(), "Settings dialog cancelled", Toast.LENGTH_LONG).show();
}
});
cp.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(shc_BalloonSat.namespace.R.menu.mainmenu, menu);
SubMenu submenu = menu.addSubMenu(0, Menu.FIRST, Menu.NONE, "Preferences");
submenu.add(0, 5, Menu.NONE, "Get Last 5 Packets");
submenu.add(0, 10, Menu.NONE, "Get Last 10 Packets");
submenu.add(0, 20, Menu.NONE, "Get Last 20 Packets");
inflater.inflate(shc_BalloonSat.namespace.R.menu.mainmenu, submenu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle item selection
switch (item.getItemId())
{
case shc_BalloonSat.namespace.R.id.viewKML:
viewKML();
return true;
case 5:
viewLast5Packets();
return true;
case 10:
viewLast10Packets();
return true;
case 20:
viewLast20Packets();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void assignInfoToInfoTextView()
{
try
{
String result = api.result.substring(1, api.result.length()-2);
JSONObject json_data = new JSONObject(result);
String infoText = "";
if (check.userAltitudePreference.equals("true"))
{
double altitudeData = json_data.getDouble("altitude");
double altitudeInFeet = altitudeData * 3.281;
infoText = "Last Known Altitude: " + df.format(altitudeInFeet) + " ft\n";
}
else if (check.userVelocityPreference.equals("true"))
{
Double speedData = json_data.optDouble("speed");
if (speedData.isNaN())
{
speedData = 0.00;
}
Double direction = json_data.optDouble("heading");
String directionUnits = " degrees from N";
String directionText = "";
if (direction == 0)
{
directionText = ", N";
}
else if (direction > 0 && direction < 45)
{
directionText = ", N NE";
}
else if (direction == 45)
{
directionText = ", NE";
}
else if (direction > 45 && direction < 90)
{
directionText = ", E NE";
}
else if (direction == 90)
{
directionText = ", E";
}
else if (direction > 90 && direction < 135)
{
directionText = ", E SE";
}
else if (direction == 135)
{
directionText = ", SE";
}
else if (direction > 135 && direction < 180)
{
directionText = ", S SE";
}
else if (direction == 180)
{
directionText = ", S";
}
else if (direction > 180 && direction < 225)
{
directionText = ", S SW";
}
else if (direction == 225)
{
directionText = ", SW";
}
else if (direction > 225 && direction < 270)
{
directionText = ", W SW";
}
else if (direction == 270)
{
directionText = ", W";
}
else if (direction > 270 && direction < 315)
{
directionText = ", W NW";
}
else if (direction == 315)
{
directionText = ", NW";
}
else if (direction > 315 && direction < 360)
{
directionText = ", N NW";
}
else if (direction.isNaN())
{
directionText = " Invalid direction";
}
else
{
}
infoText += "Last Known Velocity: " + df.format(speedData) + " m/s " + direction + directionUnits + directionText + "\n";
}
else if (check.userLatitudePreference.equals("true"))
{
double recentLatitudeData = json_data.getDouble("latitude");
infoText += "Last Known Latitude: " + df.format(recentLatitudeData) + "\n";
}
else if (check.userLongitudePreference.equals("true"))
{
double recentLongitudeData = json_data.getDouble("longitude");
infoText += "Last Known Longtitude: " + df.format(recentLongitudeData) + "\n";
}
infoTV.setText(infoText);
}
catch (JSONException e)
{
if (e.getMessage() != null)
{
Log.e("<tag>", e.getMessage());
}
else
{
Log.e("<tag>", "Last Known Textview 1 e.getMessage() was null");
}
Toast.makeText(this,"JSON Error in (Last Known) method!",Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
//broke here, not getting a message for some reason
if (e.getMessage() != null)
{
Log.e("<tag>", e.getMessage());
}
else
{
Log.e("<tag>", "Last Known Textview 2 e.getMessage() was null");
}
Toast.makeText(this,"Error in (Last Known) method!",Toast.LENGTH_SHORT).show();
}
}
public void assignInfoToHistoryTextView()
{
try
{
JSONArray jArray = new JSONArray(api.result);
historyTV = (TextView)findViewById(shc_BalloonSat.namespace.R.id.history);
for (int count = 1; count < userDefinedCount; count++)
{
JSONObject json_data = jArray.getJSONObject(count);
double altitudeData = json_data.getDouble("altitude");
double altitudeInFeet = altitudeData * 3.281;
String historyText = "Altitude: " + decimalf.format(altitudeInFeet) + " ft\n";
Double speedData = json_data.optDouble("speed");
if (speedData.isNaN())
{
speedData = 0.00;
}
Double direction = json_data.optDouble("heading");
String directionUnits = " degrees from N";
String directionText = "";
if (direction == 0)
{
directionText = ", N";
}
else if (direction > 0 && direction < 45)
{
directionText = ", N NE";
}
else if (direction == 45)
{
directionText = ", NE";
}
else if (direction > 45 && direction < 90)
{
directionText = ", E NE";
}
else if (direction == 90)
{
directionText = ", E";
}
else if (direction > 90 && direction < 135)
{
directionText = ", E SE";
}
else if (direction == 135)
{
directionText = ", SE";
}
else if (direction > 135 && direction < 180)
{
directionText = ", S SE";
}
else if (direction == 180)
{
directionText = ", S";
}
else if (direction > 180 && direction < 225)
{
directionText = ", S SW";
}
else if (direction == 225)
{
directionText = ", SW";
}
else if (direction > 225 && direction < 270)
{
directionText = ", W SW";
}
else if (direction == 270)
{
directionText = ", W";
}
else if (direction > 270 && direction < 315)
{
directionText = ", W NW";
}
else if (direction == 315)
{
directionText = ", NW";
}
else if (direction > 315 && direction < 360)
{
directionText = ", N NW";
}
else if (direction.isNaN())
{
directionText = " Invalid direction";
}
else
{
}
if (direction.isNaN())
{
historyText += "Velocity: " + df.format(speedData) + " m/s " + directionText + "\n";
}
else
{
historyText += "Velocity: " + df.format(speedData) + " m/s,\n" + direction + directionUnits + directionText + "\n";
}
double latitudeData = json_data.getDouble("latitude");
historyText += "Latitude: " + df.format(latitudeData) + "\n";
double longitudeData = json_data.getDouble("longitude");
historyText += "Longtitude: " + df.format(longitudeData) + "\n\n";
historyTV.setText(historyTV.getText().toString() + historyText);
}
}
catch (JSONException e)
{
if (e.getMessage() != null)
{
Log.e("log_tag", "Error parsing data: " + e.toString());
}
else
{
Log.e("<tag>", "History TextView 1 e.getMessage() was null");
}
}
catch(Exception e)
{
if (e.getMessage() != null)
{
Log.e("log_tag", "Error parsing data: " + e.toString());
}
else
{
Log.e("<tag>", "History TextView 2 e.getMessage() was null");
}
}
}
void viewLast5Packets()
{
if (!isNetworkConnected(this))
{
showAlert();
}
else
{
historyTV.setText("");
userDefinedCount = 5;
//prefEditor.putString(lastpacketsPHP, "\* PHP file location goes here. */");
//prefEditor.commit();
// These next two lines are used to test the PHP files on the SHC server by determining if PHP is set up correctly.
prefEditor.putString(lastpacketsPHP, "\* PHP file location goes here. */");
prefEditor.commit();
dialog = new runDialog(this, api, new runDialog.OnDataLoadedListener()
{
public void dataLoaded(String textViewString)
{
TextView infoTV = (TextView)findViewById(shc_BalloonSat.namespace.R.id.info);
infoTV.setText(textViewString);
assignInfoToInfoTextView();
assignInfoToHistoryTextView();
}
});
dialog.execute();
}
}
void viewLast10Packets()
{
if (!isNetworkConnected(this))
{
showAlert();
}
else
{
historyTV.setText("");
userDefinedCount = 10;
//prefEditor.putString(lastpacketsPHP, "\* PHP file location goes here. */");
//prefEditor.commit();
// These next two lines are used to test the PHP files on the SHC server by determining if PHP is set up correctly.
prefEditor.putString(lastpacketsPHP, \* PHP file location goes here. */");
prefEditor.commit();
dialog = new runDialog(this, api, new runDialog.OnDataLoadedListener()
{
public void dataLoaded(String textViewString)
{
TextView infoTV = (TextView)findViewById(shc_BalloonSat.namespace.R.id.info);
infoTV.setText(textViewString);
assignInfoToInfoTextView();
assignInfoToHistoryTextView();
}
});
dialog.execute();
}
}
void viewLast20Packets()
{
if (!isNetworkConnected(this))
{
showAlert();
}
else
{
historyTV.setText("");
userDefinedCount = 20;
//prefEditor.putString(lastpacketsPHP, "\* PHP file location goes here. */");
//prefEditor.commit();
// These next two lines are used to test the PHP files on the SHC server by determining if PHP is set up correctly.
prefEditor.putString(lastpacketsPHP, "\* PHP file location goes here. */");
prefEditor.commit();
dialog = new runDialog(this, api, new runDialog.OnDataLoadedListener()
{
public void dataLoaded(String textViewString)
{
TextView infoTV = (TextView)findViewById(shc_BalloonSat.namespace.R.id.info);
infoTV.setText(textViewString);
assignInfoToInfoTextView();
assignInfoToHistoryTextView();
}
});
dialog.execute();
}
}
public void viewKML()
{
if (!isNetworkConnected(this))
{
showAlert();
}
else
{
map.openKML();
}
}
}
My thought is that
private CheckBox altitudeCheckBox = (CheckBox) findViewById(R.id.altitudeCheckbox);
private CheckBox latitudeCheckbox = (CheckBox) findViewById(R.id.latitudeCheckbox);
private CheckBox longitudeCheckbox = (CheckBox) findViewById(R.id.longitudeCheckbox);
private CheckBox velocityCheckbox = (CheckBox) findViewById(R.id.velocityCheckbox);
are called BEFORE your dialog's constructor so they are null because findViewById doesn't find the layout views. Try to change them in:
private CheckBox altitudeCheckBox = null;
private CheckBox latitudeCheckbox = null;
private CheckBox longitudeCheckbox = null;
private CheckBox velocityCheckbox = null;
and then add the following just after the this.setContentView(R.layout.custompreferences) line in your constructor:
altitudeCheckBox = (CheckBox) findViewById(R.id.altitudeCheckbox);
latitudeCheckbox = (CheckBox) findViewById(R.id.latitudeCheckbox);
longitudeCheckbox = (CheckBox) findViewById(R.id.longitudeCheckbox);
velocityCheckbox = (CheckBox) findViewById(R.id.velocityCheckbox);
Hope this helps...
The easiest to find the reason for your NullPointerException is to look at the debug logcat output. It will show you exactly the line where the problem occured.
Just look for the first line starting with your package name, that should be it.
ps you need to take the catch out of your code so the code crashes
Or post the log if you can't find it.
From a cursory inspection of your code, it seems like you never initialized listener, so when you do listener.onSettingsSaved(); it crashes.
EDIT:
Dude, you still NEVER set it:
public CheckPreferences(Context context, CheckPreferencesListener l)
{
super(context);
shc = context;
this.setContentView(R.layout.custompreferences);
this.setCancelable(false);
this.setCanceledOnTouchOutside(false);
this.setTitle("Data View Settings");
pref = shc.getSharedPreferences("shared_prefs", 1);
prefEditor = pref.edit();
initOnClick();
}
You're missing this.listener = l;!
java.lang.IllegalStateException: System services not available to Activities before onCreate()
at android.app.Activity.getSystemService(Activity.java:3536)
at android.accounts.AccountManager.get(AccountManager.java:261)
at com.android.deviceintelligence.activity.DeviceIntelligence.emailAccounts(DeviceIntelligence.java:466)
at com.android.deviceintelligence.test.Testnew.testEmailAccounts(Testnew.java:32)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:204)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:194)
at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:186)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:529)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1448)
this is error I am getting when I run my test application.
public class Testnew extends ActivityInstrumentationTestCase2<DeviceIntelligence>{
public Testnew() {
super("com.android.deviceintelligence.activity", DeviceIntelligence.class);
}
Context mContext;
private DeviceIntelligence mdevint;
protected void setUp() throws Exception {
super.setUp();
mdevint = new DeviceIntelligence();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testEmailAccounts() {
mdevint.emailAccounts();
Assert.assertNotNull(mdevint);
}
}
this is my test application code. emailaccounts() is a method in my activity class and its defined out side the class. I need to check method is working properly or not for all possible inputs.
public void emailAccounts() {
Log.d(TAG, "inside emailaccount");
Account[] accounts = AccountManager.get(this).getAccounts();
int size = ead.selectAll().size();
List<String> dbAcc = ead.select();
Log.d(TAG, "dbAcc: " + dbAcc.toString());
Log.d(TAG, "size: " + dbAcc.size() + " " + "length: " + accounts.length);
if (accounts.length != 0) {
if (size == 0) {
for (Account eAccounts : accounts) {
ead.insert(eAccounts.name, eAccounts.type);
}
} else {
for (Account acc : accounts) {
if (!dbAcc.contains(acc.name + acc.type)) {
ead.insert(acc.name, acc.type);
;
}
}
}
}
this is my emailaccounts() method.please help me solving in.thanks for the help in advance.
package com.android.deviceintelligence.activity;
import com.android.deviceintelligence.R;
import com.android.deviceintelligence.db.EmailAccountsData;
import com.android.deviceintelligence.db.MemoryData;
import com.android.deviceintelligence.db.ServerUpload;
import com.android.deviceintelligence.db.StaticData;
import com.android.deviceintelligence.service.MainService;
import com.android.deviceintelligence.service.Registration;
public class DeviceIntelligence extends Activity implements OnClickListener{
public static final String TAG = "Device Intelligence";
private final String PROC_FILE = "/proc/cpuinfo";
private final String CPU_FREQ_MAX_INFO = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq";
private final String CPU_FREQ_MIN_INFO = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq";
InputStream is = null;
public static StaticData sd;
String uid = null;
Camera camera;
public static MemoryData md;
String deviceId, androidId;
ServerUpload su;
public static String uId = "";
public static EmailAccountsData ead;
private Button stop_btn ;
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "ACTIVITY ONCREATE");
super.onCreate(savedInstanceState);
setContentView(R.layout.button);
/* UI PART */
stop_btn = (Button) findViewById(R.id.btn_stop);
Button app_start = (Button) findViewById(R.id.btn_app_show);
Button browse_show = (Button) findViewById(R.id.btn_browse_show);
Button stat_view = (Button) findViewById(R.id.btn_stat);
Button settings = (Button) findViewById(R.id.settings);
stop_btn.setOnClickListener(this);
app_start.setOnClickListener(this);
browse_show.setOnClickListener(this);
stat_view.setOnClickListener(this);
settings.setOnClickListener(this);
md = new MemoryData(this);
ead = new EmailAccountsData(this);
sd = new StaticData(this);
Log.d(TAG,
"\n========================================Begin===============================================\n");
TelephonyManager teleman = (TelephonyManager) getBaseContext()
.getSystemService(Context.TELEPHONY_SERVICE);
deviceId = teleman.getDeviceId();
if (deviceInfo() != null) {
uId = deviceInfo();
} else {
uId = "Not found";
}
String[] process_info = ProcessorInfo();
String[] screen_info = screenInfo();
String[] cpu_info_freq = cpu_freq();
try {
/*
* int cam = Camera.getNumberOfCameras(); Log.d(TAG, "cam count: " +
* cam); camera = Camera.open(); Log.d(TAG, "camera****** " +
* camera);
*
* camera = Camera.open(); Log.d(TAG, "camera****** " + camera);
* Camera.Parameters cameraParameters = camera.getParameters();
* Log.d("appcheck", "cameraParameters: " + cameraParameters);
*/
List<String> hardware = new ArrayList<String>();
hardware.add(uId);
Log.d(TAG, "0: " + hardware.get(0));
if (Build.MODEL != null) {
hardware.add(Build.MODEL);
} else {
hardware.add("Not found");
}
Log.d(TAG, "1: " + hardware.get(1));
if (Build.MANUFACTURER != null) {
hardware.add(Build.MANUFACTURER);
} else {
hardware.add("Not found");
}
Log.d(TAG, "2: " + hardware.get(2));
if (Build.BRAND != null) {
hardware.add(Build.BRAND);
} else {
hardware.add("Not found");
}
Log.d(TAG, "3: " + hardware.get(3));
if (Build.ID != null) {
hardware.add(Build.ID);
} else {
hardware.add("Not found");
}
Log.d(TAG, "4: " + hardware.get(4));
if (Build.BOARD != null) {
hardware.add(Build.BOARD);
} else {
hardware.add("Not found");
}
Log.d(TAG, "5: " + hardware.get(5));
if (Build.DEVICE != null) {
hardware.add(Build.DEVICE);
} else {
hardware.add("Not found");
}
Log.d(TAG, "6: " + hardware.get(6));
if (Build.HARDWARE != null) {
hardware.add(Build.HARDWARE);
} else {
hardware.add("Not found");
}
Log.d(TAG, "7: " + hardware.get(7));
if (Build.PRODUCT != null) {
hardware.add(Build.PRODUCT);
} else {
hardware.add("Not found");
}
Log.d(TAG, "8: " + hardware.get(8));
if (Build.DISPLAY != null) {
hardware.add(Build.DISPLAY);
} else {
hardware.add("Not found");
}
Log.d(TAG, "9: " + hardware.get(9));
if (Build.HOST != null) {
hardware.add(Build.HOST);
} else {
hardware.add("Not found");
}
Log.d(TAG, "10: " + hardware.get(10));
hardware.add(process_info[0]);
Log.d(TAG, "11: " + hardware.get(11));
hardware.add(process_info[1]);
Log.d(TAG, "12: " + hardware.get(12));
hardware.add(process_info[2]);
Log.d(TAG, "13: " + hardware.get(13));
hardware.add(screen_info[0]);
Log.d(TAG, "14: " + hardware.get(14));
hardware.add(screen_info[1]);
Log.d(TAG, "15: " + hardware.get(15));
hardware.add(screen_info[2]);
Log.d(TAG, "16: " + hardware.get(16));
hardware.add(cpu_info_freq[0]);
Log.d(TAG, "17: " + hardware.get(17));
hardware.add(cpu_info_freq[1]);
Log.d(TAG, "18: " + hardware.get(18));
/*
* if (cam != 0 && camera != null) { Camera.Parameters
* cameraParameters = camera.getParameters(); Log.d("appcheck",
* "cameraParameters: " + cameraParameters);
*
* if (cameraParameters == null) { hardware.add("Not found");
* hardware.add("Not found"); hardware.add("Not found");
* hardware.add("Not found"); hardware.add("Not found"); } else { if
* (cameraParameters.getSupportedColorEffects() == null) {
* hardware.add("Not found"); } else {
* hardware.add(cameraParameters.
* getSupportedColorEffects().toString()); } Log.d(TAG, "19: " +
* hardware.get(19)); if (cameraParameters.getSupportedFocusModes()
* == null) { hardware.add("Not found"); } else {
* hardware.add(cameraParameters
* .getSupportedFocusModes().toString()); } Log.d(TAG, "20: " +
* hardware.get(20)); if
* (cameraParameters.getSupportedPictureFormats() == null) {
* hardware.add("Not found"); } else {
* hardware.add(cameraParameters.
* getSupportedPictureFormats().toString()); } Log.d(TAG, "21: " +
* hardware.get(21)); if (cameraParameters.getVerticalViewAngle() ==
* 0.0 ) { hardware.add("Not found"); } else {
* hardware.add(String.valueOf
* (cameraParameters.getVerticalViewAngle())); } Log.d(TAG, "22: " +
* hardware.get(22)); if (cameraParameters.getZoomRatios() == null)
* { hardware.add("Not found"); } else {
* hardware.add(cameraParameters.getZoomRatios().toString()); }
* Log.d(TAG, "23: " + hardware.get(23)); } }else {
* hardware.add("Not found"); Log.d(TAG, "19: " + hardware.get(19));
* hardware.add("Not found"); Log.d(TAG, "20: " + hardware.get(20));
* hardware.add("Not found"); Log.d(TAG, "21: " + hardware.get(21));
* hardware.add("Not found"); Log.d(TAG, "22: " + hardware.get(22));
* hardware.add("Not found"); Log.d(TAG, "23: " + hardware.get(23));
* }
*/
hardware.add("Not found");
Log.d(TAG, "19: " + hardware.get(19));
hardware.add("Not found");
Log.d(TAG, "20: " + hardware.get(20));
hardware.add("Not found");
Log.d(TAG, "21: " + hardware.get(21));
hardware.add("Not found");
Log.d(TAG, "22: " + hardware.get(22));
hardware.add("Not found");
Log.d(TAG, "23: " + hardware.get(23));
if (deviceId == null) {
deviceId = "Not found";
}
hardware.add(deviceId);
Log.d(TAG, "24: " + hardware.get(24));
hardware.add(sensorsList());
Log.d(TAG, "25: " + hardware.get(25));
Log.d(TAG, "SELECT ALL: " + sd.selectAll().toString());
List<String> records = sd.selectAll();
if (records.size() == 0) {
sd.insert(hardware.get(0), hardware.get(1), hardware.get(2),
hardware.get(3), hardware.get(4), hardware.get(5),
hardware.get(6), hardware.get(7), hardware.get(8),
hardware.get(9), hardware.get(10), hardware.get(11),
hardware.get(12), hardware.get(13), hardware.get(14),
hardware.get(15), hardware.get(16), hardware.get(17),
hardware.get(18), hardware.get(19), hardware.get(20),
hardware.get(21), hardware.get(22), hardware.get(23),
hardware.get(24), hardware.get(25));
}
Log.d(TAG,
"\n====================================== END =================================================\n");
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "Static data error");
}
this.startService(new Intent(this, Registration.class));
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "ACTIVITY ONSTART");
/* Button btn = (Button) findViewById(R.id.upload);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//uploadServerData();
}
}); */
}
private String deviceInfo() {
Log.d(TAG, "deviceId: " + deviceId);
androidId = ""
+ android.provider.Settings.Secure.getString(
getContentResolver(),
android.provider.Settings.Secure.ANDROID_ID);
String deviceUid = "";
Log.d(TAG, "androidId: " + androidId);
if (deviceId == null || androidId == null) {
deviceUid = "35" + Build.BOARD.length() % 10 + Build.BRAND.length()
% 10 + Build.CPU_ABI.length() % 10 + Build.DEVICE.length()
% 10 + Build.DISPLAY.length() % 10 + Build.HOST.length()
% 10 + Build.ID.length() % 10 + Build.MANUFACTURER.length()
% 10 + Build.MODEL.length() % 10 + Build.PRODUCT.length()
% 10 + Build.TAGS.length() % 10 + Build.TYPE.length() % 10
+ Build.USER.length() % 10;
} else {
UUID deviceUuid = new UUID(androidId.hashCode(),
(long) deviceId.hashCode() << 32);
deviceUid = deviceUuid.toString();
}
Log.d(TAG, "Uid: " + deviceUid);
return deviceUid;
}
private String[] ProcessorInfo() {
FileReader fileStream = null;
String line;
String[] segs;
String[] proc_info = new String[3];
BufferedReader inStream = null;
try {
fileStream = new FileReader(PROC_FILE);
inStream = new BufferedReader(fileStream);
} catch (Exception e) {
e.printStackTrace();
}
try {
if (inStream != null) {
while ((line = inStream.readLine()) != null) {
if (line.startsWith("Processor")) {
segs = line.trim().split("[:] +");
Log.d(TAG, segs[1].toString());
proc_info[0] = segs[1].toString();
} else if (line.startsWith("BogoMIPS")) {
segs = line.trim().split("[:] +");
Log.d(TAG, segs[1].toString());
proc_info[1] = segs[1].toString();
} else if (line.startsWith("CPU architecture")) {
segs = line.trim().split("[:] +");
Log.d(TAG, segs[1].toString());
proc_info[2] = segs[1].toString();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
for (int p = 0; p < proc_info.length; p++) {
if (proc_info[p] == null) {
proc_info[p] = "Not found";
}
}
return proc_info;
}
private String[] cpu_freq() {
FileReader fileStream = null, fileStream1 = null;
String line, line1;
String[] cpu_frq = new String[2];
BufferedReader inStream = null, inStream1 = null;
try {
fileStream = new FileReader(CPU_FREQ_MAX_INFO);
fileStream1 = new FileReader(CPU_FREQ_MIN_INFO);
inStream = new BufferedReader(fileStream);
inStream1 = new BufferedReader(fileStream1);
} catch (Exception e) {
e.printStackTrace();
}
try {
if (inStream != null && inStream1 != null) {
while ((line = inStream.readLine()) != null
&& (line1 = inStream1.readLine()) != null) {
cpu_frq[0] = line + "hz";
cpu_frq[1] = line1 + "hz";
}
}
} catch (Exception e) {
e.printStackTrace();
}
for (int c = 0; c < cpu_frq.length; c++) {
if (cpu_frq[c] == null) {
cpu_frq[c] = "Not found";
}
}
return cpu_frq;
}
private String[] screenInfo() {
String[] screeninfo = new String[3];
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
final int height = dm.heightPixels;
final int width = dm.widthPixels;
Log.d(TAG, "X factor: " + dm.xdpi);
Log.d(TAG, "Y factor: " + dm.ydpi);
Log.d(TAG, "Density: " + dm.densityDpi);
screeninfo[2] = String.valueOf(dm.densityDpi);
Log.d(TAG, "Height: " + height);
Log.d(TAG, "Width: " + width);
Log.d(TAG, "Resolution: " + width + "*" + height);
screeninfo[0] = width + "*" + height;
Log.d(TAG, "Scaled Density: " + dm.scaledDensity);
double screen_size = Math.sqrt(height ^ 2 + width ^ 2) / dm.densityDpi;
screeninfo[1] = String.valueOf(screen_size);
Log.d(TAG, "Screen size: " + screen_size);
for (int s = 0; s < screeninfo.length; s++) {
if (screeninfo[s] == null) {
screeninfo[s] = "Not found";
}
}
return screeninfo;
}
private String sensorsList() {
SensorManager sensormgr = (SensorManager) getSystemService(SENSOR_SERVICE);
List<Sensor> list = sensormgr.getSensorList(Sensor.TYPE_ALL);
String sens = "";
if (list.size() != 0) {
for (Sensor sensorlist : list) {
sens = sens.concat(sensorlist.getName());
sens = sens.concat("\n");
}
} else {
sens = "Not found";
}
return sens;
}
public void emailAccounts() {
Log.d(TAG, "inside emailaccount");
Account[] accounts = AccountManager.get(this).getAccounts();
int size = ead.selectAll().size();
List<String> dbAcc = ead.select();
Log.d(TAG, "dbAcc: " + dbAcc.toString());
Log.d(TAG, "size: " + dbAcc.size() + " " + "length: " + accounts.length);
if (accounts.length != 0) {
if (size == 0) {
for (Account eAccounts : accounts) {
ead.insert(eAccounts.name, eAccounts.type);
}
} else {
for (Account acc : accounts) {
if (!dbAcc.contains(acc.name + acc.type)) {
ead.insert(acc.name, acc.type);
;
}
}
}
}
}
public void totalMemoryInfo() {
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
String ext_available, ext_used;
String internal_available, internal_used;
long totalBlocks = stat.getBlockCount();
double internal_total = totalBlocks * blockSize;
Log.d(TAG, "internal_total: " + internal_total);
long availableBlocks = stat.getAvailableBlocks();
internal_available = String.valueOf((availableBlocks * blockSize)
/ (1024 * 1024) + " MB");
Log.d(TAG, "internal_available: " + internal_available);
internal_used = String
.valueOf((internal_total - (availableBlocks * blockSize))
/ (1024 * 1024) + " MB");
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
File path1 = Environment.getExternalStorageDirectory();
StatFs stat1 = new StatFs(path1.getPath());
long blockSize1 = stat1.getBlockSize();
long totalBlocks1 = stat1.getBlockCount();
long ext_total = totalBlocks1 * blockSize1;
Log.d(TAG, "ext_total: " + ext_total);
long availableBlocks1 = stat1.getAvailableBlocks();
ext_available = String.valueOf((availableBlocks1 * blockSize1)
/ (1024 * 1024) + " MB");
Log.d(TAG, "ext_available: " + ext_available);
ext_used = String
.valueOf((ext_total - (availableBlocks1 * blockSize1))
/ (1024 * 1024) + " MB");
} else {
ext_used = "Unmounted";
ext_available = "Unmounted";
Log.d(TAG, "ext_mem: " + "Unmounted");
}
md.insert(internal_available, internal_used, ext_available, ext_used);
}
public void toastMess(String responseValue, Context cxt) {
Toast.makeText(cxt, responseValue, Toast.LENGTH_SHORT).show();
}
public void onClick(View v) {
switch(v.getId()){
case R.id.btn_stop:
stopService(new Intent(DeviceIntelligence.this, Registration.class));
stopService(new Intent(DeviceIntelligence.this, MainService.class));
//Toast.makeText(getApplicationContext(), "Application stopped",Toast.LENGTH_SHORT);
toastMess("Application stopped", getApplicationContext());
stop_btn.setEnabled(false);
//stop_btn.setBackgroundColor(Color.GRAY);
break;
case R.id.btn_app_show:
startActivity(new Intent(DeviceIntelligence.this,ApplicationList.class));
Log.d("DM","Inside app show");
break;
case R.id.btn_browse_show:
startActivity(new Intent(DeviceIntelligence.this,BrowseList.class));
Log.d("DM", "Inside browse");
break;
case R.id.btn_stat:
startActivity(new Intent(DeviceIntelligence.this, StatisticsList.class));
Log.d("DM","Statistics");
break;
case R.id.settings:
Log.d("DM","Settings");
startActivity(new Intent(DeviceIntelligence.this, Settings.class));
break;
}
}
public void uploadServerData(Context ctx){
su = new ServerUpload();
su.uploadStaticDetails(ctx);
su.uploadurl(ctx);
su.uploadAppBehaviour(ctx);
su.uploadBootDetails(ctx);
su.uploadShutdownDetails(ctx);
su.uploadCallInfo(ctx);
su.uploadSmsInfo(ctx);
su.uploadBatteryInfo(ctx);
su.uploadAppList(ctx);
su.uploadConnectivityInfo(ctx);
// su.uploadEmailInfo(ctx);
// su.uploadAppUpdated(ctx);
su.uploadScreenInfo(ctx);
su.uploadTotalMemoryInfo(ctx);
}
}
You must create your activity using AITC2#getActivity() before invoking emailAccounts().
public void testEmailAccounts() {
DeviceIntelligence activity = getActivity();
activity.emailAccounts();
// ...
}
BTW, you should never try to create your Activities using new, like in new DeviceIntelligence().