Related
Hi i'm trying to make an app to change governor and drop the cache..all things goes well and the app it's ok but when i try to inserta part of code to see the meminfo and cpu info it crash on startup.. i don't know which is the problem..here's my code:
Code:
package eu.lucazanini.swipeviews;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity {
CollectionPagerAdapter mCollectionPagerAdapter;
ViewPager mViewPager;
TextView textOut;
private TextView cpuInfo;
private TextView memoryInfo;
// Notification code
private static final int SIMPLE_NOTIFICATION_ID = 1;
NotificationManager mNotificationManager;
// fine
[user=273171]@target[/user]Api(Build.VERSION_CODES.HONEYCOMB)
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Readcpuinfo
TextView CPUinfo = (TextView) findViewById(R.id.CPUinfo);
CPUinfo.setText(getCPUinfo());
TextView Memoryinfo = (TextView) findViewById(R.id.memoryinfo);
Memoryinfo.setText(getMemoryInfo());
//fine readcpuinfo
// Notification code
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
View btnradio_hindi = findViewById(R.id.radio_hindi);
// fine
mCollectionPagerAdapter = new CollectionPagerAdapter(
getSupportFragmentManager());
// Set up action bar.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
// Set up the ViewPager, attaching the adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCollectionPagerAdapter);
}
/// Inizio creazione funzioni
private String getMemoryInfo(){
ProcessBuilder cmd;
String result = new String();
try{
String[] args = {"/system/bin/cat", "/proc/meminfo"};
cmd = new ProcessBuilder(args);
Process process = cmd.start();
InputStream in = process.getInputStream();
byte[] re = new byte[1024];
while(in.read(re) != -1){
System.out.println(new String(re));
result = result + new String(re);
}
in.close();
} catch(IOException ex){
ex.printStackTrace();
}
return result;
}
private String getCPUinfo()
{
ProcessBuilder cmd;
String result="";
try{
String[] args = {"/system/bin/cat", "/proc/cpuinfo"};
cmd = new ProcessBuilder(args);
Process process = cmd.start();
InputStream in = process.getInputStream();
byte[] re = new byte[1024];
while(in.read(re) != -1){
System.out.println(new String(re));
result = result + new String(re);
}
in.close();
} catch(IOException ex){
ex.printStackTrace();
}
return result;
}
public Boolean execCommands(String... command) {
try {
Runtime rt = Runtime.getRuntime();
Process process = rt.exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
for(int i = 0; i < command.length; i++) {
os.writeBytes(command[i] + "\n");
os.flush();
}
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (IOException e) {
return false;
} catch (InterruptedException e) {
return false;
}
return true;
}
/**
* A {@link android.support.v4.app.FragmentStatePagerAdapter} that returns a
* fragment representing an object in the collection.
*/
public class CollectionPagerAdapter extends FragmentStatePagerAdapter {
final int NUM_ITEMS = 3; // number of tabs
public CollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
[user=439709]@override[/user]
public Fragment getItem(int i) {
Fragment fragment = new TabFragment();
Bundle args = new Bundle();
args.putInt(TabFragment.ARG_OBJECT, i);
fragment.setArguments(args);
return fragment;
}
[user=439709]@override[/user]
public int getCount() {
return NUM_ITEMS;
}
[user=439709]@override[/user]
public CharSequence getPageTitle(int position) {
String tabLabel = null;
switch (position) {
case 0:
tabLabel = getString(R.string.label1);
break;
case 1:
tabLabel = getString(R.string.label2);
break;
case 2:
tabLabel = getString(R.string.label3);
break;
}
return tabLabel;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class TabFragment extends Fragment {
public static final String ARG_OBJECT = "object";
[user=439709]@override[/user]
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
int position = args.getInt(ARG_OBJECT);
int tabLayout = 0;
switch (position) {
case 0:
tabLayout = R.layout.tab1;
break;
case 1:
tabLayout = R.layout.tab2;
break;
case 2:
tabLayout = R.layout.tab3;
break;
}
View rootView = inflater.inflate(tabLayout, container, false);
return rootView;
}
}
public void onRadioButtonClicked(View view) {
((RadioButton) view).isChecked();
// Check which radio button was clicked
// switch(view.getId()) {
// case R.id.radio_hindi:
// if (checked)
switch (view.getId())
{
case R.id.radio_hindi:
String[] commands = {
"echo 3 > /proc/sys/vm/drop_caches",
"cat /proc/meminfo | awk 'NR == 2'"
};
sendSimpleNotification();
Toast.makeText(this, "Hai liberato memoria! Hai: " + Runtime.getRuntime().freeMemory() + "", Toast.LENGTH_LONG).show();
execCommands(commands);
String commandText = "echo 'foo' >> /sdcard/foo.txt\necho 'bar' >> /sdcard/foo.txt";
execCommands(commandText.split("\n"));
break;
case R.id.radio_english:
String[] commands1 = {"echo ondemand > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu1/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu2/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu3/cpufreq/scaling_governor"};
execCommands(commands1);
sendSimpleNotificationOndemand();
Toast.makeText(this, "Hai selezionato il governor Ondemand", Toast.LENGTH_LONG).show();
break;
case R.id.interactive_btn:
String[] commands2 = {"echo interactive > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu1/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu2/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu3/cpufreq/scaling_governor"};
execCommands(commands2);
sendSimpleNotificationInteractive();
Toast.makeText(this, "Hai selezionato il governor: Interactive", Toast.LENGTH_LONG).show();
break;
case R.id.conservative_btn:
String[] commands3 = {"echo conservative > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu1/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu2/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu3/cpufreq/scaling_governor"};
execCommands(commands3);
sendSimpleNotificationConservative();
Toast.makeText(this, "Hai selezionato il governor: Conservative", Toast.LENGTH_LONG).show();
break;
}
}
protected void cancelSimpleNotification() {
mNotificationManager.cancel(SIMPLE_NOTIFICATION_ID);
}
private void sendSimpleNotification() {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
MainActivity.this);
// Titolo e testo della notifica
notificationBuilder.setContentTitle("Boost RAM");
notificationBuilder.setContentText("Memoria libera: "+ Runtime.getRuntime().freeMemory() + "bytes");
// Testo che compare nella barra di stato non appena compare la notifica
notificationBuilder.setTicker("Memoria liberata con successo");
// Data e ora della notifica
notificationBuilder.setWhen(System.currentTimeMillis());
// Icona della notifica
notificationBuilder.setSmallIcon(R.drawable.ic_launcher);
// Creiamo il pending intent che verrà lanciato quando la notifica
// viene premuta
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notificationBuilder.setContentIntent(contentIntent);
// Impostiamo il suono, le luci e la vibrazione di default
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND
| Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
mNotificationManager.notify(SIMPLE_NOTIFICATION_ID,
notificationBuilder.build());
}
// Notification per il governor ondemand
private void sendSimpleNotificationOndemand() {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
MainActivity.this);
// Titolo e testo della notifica
notificationBuilder.setContentTitle("Governor Changed");
notificationBuilder.setContentText("Hai selezionato il governor Ondemand");
// Testo che compare nella barra di stato non appena compare la notifica
notificationBuilder.setTicker("Governor Ondemand settato");
// Data e ora della notifica
notificationBuilder.setWhen(System.currentTimeMillis());
// Icona della notifica
notificationBuilder.setSmallIcon(R.drawable.ic_launcher);
// Creiamo il pending intent che verrà lanciato quando la notifica
// viene premuta
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notificationBuilder.setContentIntent(contentIntent);
// Impostiamo il suono, le luci e la vibrazione di default
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND
| Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
mNotificationManager.notify(SIMPLE_NOTIFICATION_ID,
notificationBuilder.build());
}
//Notification per il governor interactive
private void sendSimpleNotificationInteractive() {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
MainActivity.this);
// Titolo e testo della notifica
notificationBuilder.setContentTitle("Governor Changed");
notificationBuilder.setContentText("Hai selezionato il governor Interactive");
// Testo che compare nella barra di stato non appena compare la notifica
notificationBuilder.setTicker("Governor Interactive settato");
// Data e ora della notifica
notificationBuilder.setWhen(System.currentTimeMillis());
// Icona della notifica
notificationBuilder.setSmallIcon(R.drawable.ic_launcher);
// Creiamo il pending intent che verrà lanciato quando la notifica
// viene premuta
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notificationBuilder.setContentIntent(contentIntent);
// Impostiamo il suono, le luci e la vibrazione di default
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND
| Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
mNotificationManager.notify(SIMPLE_NOTIFICATION_ID,
notificationBuilder.build());
}
//Notification per il governor conservative
private void sendSimpleNotificationConservative() {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
MainActivity.this);
// Titolo e testo della notifica
notificationBuilder.setContentTitle("Governor Changed");
notificationBuilder.setContentText("Hai selezionato il governor Conservative");
// Testo che compare nella barra di stato non appena compare la notifica
notificationBuilder.setTicker("Governor Conservative settato");
// Data e ora della notifica
notificationBuilder.setWhen(System.currentTimeMillis());
// Icona della notifica
notificationBuilder.setSmallIcon(R.drawable.ic_launcher);
// Creiamo il pending intent che verrà lanciato quando la notifica
// viene premuta
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notificationBuilder.setContentIntent(contentIntent);
// Impostiamo il suono, le luci e la vibrazione di default
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND
| Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
mNotificationManager.notify(SIMPLE_NOTIFICATION_ID,
notificationBuilder.build());
}
}
Any helps?Thanks:good:
Can you give us the logcat also?
sure:
Code:
05-27 00:14:09.933: E/AndroidRuntime(6243): FATAL EXCEPTION: main
05-27 00:14:09.933: E/AndroidRuntime(6243): java.lang.RuntimeException: Unable to start `activity ComponentInfo{eu.lucazanini.swipeviews/eu.lucazanini.swipeviews.MainActivity}: `java.lang.NullPointerException
05-27 00:14:09.933: E/AndroidRuntime(6243): at `android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2357)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `android.app.ActivityThread.access$600(ActivityThread.java:153)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247`)
05-27 00:14:09.933: E/AndroidRuntime(6243): at `android.os.Handler.dispatchMessage(Handler.java:99)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `android.os.Looper.loop(Looper.java:137)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `android.app.ActivityThread.main(ActivityThread.java:5226)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `java.lang.reflect.Method.invokeNative(Native Method)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `java.lang.reflect.Method.invoke(Method.java:511)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `dalvik.system.NativeStart.main(Native Method)`
05-27 00:14:09.933: E/AndroidRuntime(6243): Caused by: java.lang.NullPointerException
05-27 00:14:09.933: E/AndroidRuntime(6243): at `eu.lucazanini.swipeviews.MainActivity.onCreate(MainActivity.java:56)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `android.app.Activity.performCreate(Activity.java:5104)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2261)`
05-27 00:14:09.933: E/AndroidRuntime(6243): ... 11 mor
e
There is a problem in line 56:
MainActivity.java:56
Click to expand...
Click to collapse
Could you please highlight this line?
i've need to connect my app to an external database so i put my sqlite database on assets folder and i've follow this tutorial to make DBHelper.
now i want to show some record of database in my app but when i launch it, it give me an error like a table "linee" doesn't exists on my database but it exists!!!! this link cans proof it http://img689.imageshack.us/img689/926/ytvo.png
why???? it's a week that i can to fix this problem but i can't solve it
this is MyOpenHelper
Code:
public class MyOpenHelper extends SQLiteOpenHelper{
//The Android's default system path of your application database.
private static String DB_PATH ;
private SQLiteDatabase db;
private static String DB_NAME = "orari";
private final Context myContext;
public MyOpenHelper(Context context) {
super(context, DB_NAME, null, 1);// 1? its Database Version
if(android.os.Build.VERSION.SDK_INT >= 4.2){
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
} else {
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
}
this.myContext = context;
}
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
}else{
this.getReadableDatabase();
try{
copyDataBase();
}catch (IOException e){
throw new Error("Errore nel copiare il database");
}
}
}
private boolean checkDataBase(){
File dbFile=new File(DB_PATH+DB_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException{
InputStream myInput=myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH+DB_NAME;
OutputStream myOutput=new FileOutputStream(outFileName);
byte[] buffer = new byte [1024];
int length;
while ((length=myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{
String myPath=DB_PATH+DB_NAME;
db=SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
[user=439709]@override[/user]
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
[user=439709]@override[/user]
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
I have been following this forum for quite a long time now, but I have not decided to publish my questions here.
Hope anyone can help me with this:
I am developing an android app that gets the calls made in a day, and I want those calls to be inserted into a SQL server table using a webservice.
I am kind of an android begginer, since I have never worked with webservices.
So far I am able to get the information of the calls and show it in the display and to insert up to 3-4 records in the database. the problem that I am facing right now is that when I get to insert more than 3 records, the webservice inserts duplicate entries and the call duration gets set to 0 in every call. For example: I have calls to the numbers 1,2,3,4 with a duration of 5 seconds each. When I invoke the webservice, it inserts the call 1,3,3,3 with duration of 0 seconds in all of the calls.
I am adding the code of my Activity and some captions of the device and the SQL server. If you need any more code, just let me know.
Thanks everyone!
Code:
package com.trucka.llamadasdrivers;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import com.trucka.llamadasdrivers.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.CallLog;
import android.widget.TextView;
import android.telephony.*;
import android.util.Log;
import java.text.SimpleDateFormat;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
public class ActividadLlamadasDrivers extends Activity {
TextView txtInformacion = null;
TextView txtDetalles = null;
TextView tv = null;
// Comunicación con el webservice.
private final String NAMESPACE = "htt p://truckanet.com/MensajeOperador";
private final String URL = "htt p://192.168.10.94/MensajeOperador/MensajeOperador.asmx";
//private final String URL = "htt p://200.76.187.148/MensajeOperador/MensajeOperador.asmx";
private final String SOAP_ACTION = "htt p://truckanet.com/MensajeOperador/ActualizarFede";
private final String METHOD_NAME = "ActualizarFede";
private String TAG = "TRUCKA_DRIVERS";
private String resultado;
String phNumber = null;
String callType = null;
String callDate = null;
DateFormat shortFecha = null;
DateFormat shortDF = null;
Date callDayTime = null;
Date fin = null;
String fechaLlamada1 = null;
String fechaLlamada2 = null;
String callDuration = null;
String dir = null;
public String tolo = null;
String imei = null;
String comentario = null;
String fechaRegistro = null;
String insercion = null;
String fechaInicio = null;
String fechaFin = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_actividad_llamadas_drivers);
txtInformacion = (TextView) findViewById(R.id.textview_call);
txtDetalles = (TextView)findViewById(R.id.textview_call2);
getCallDetails();
}
// Obtener la fecha actual del teléfono.
public long getTodayTimestamp(){
Calendar c1 = Calendar.getInstance();
c1.setTime(new Date());
Calendar c2 = Calendar.getInstance();
c2.set(Calendar.YEAR, c1.get(Calendar.YEAR));
c2.set(Calendar.MONTH, c1.get(Calendar.MONTH));
c2.set(Calendar.DAY_OF_MONTH, c1.get(Calendar.DAY_OF_MONTH));
c2.set(Calendar.HOUR_OF_DAY, 0);
c2.set(Calendar.MINUTE, 0);
c2.set(Calendar.SECOND, 0);
return c2.getTimeInMillis();
}
//Obtener el detalle de las llamadas con la fecha actual.
@SuppressLint("SimpleDateFormat")
private void getCallDetails() {
String timestamp = String.valueOf(getTodayTimestamp());
StringBuffer sb = new StringBuffer();
@SuppressWarnings("deprecation")
Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null, CallLog.Calls.DATE + ">= ?", new String[]{timestamp}, null);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Bitácora de llamadas :");
Integer contador = 0;
while (managedCursor.moveToNext()) {
contador = contador + 1;
phNumber = managedCursor.getString(number);
callType = managedCursor.getString(type);
callDate = managedCursor.getString(date);
shortFecha = DateFormat.getDateInstance(DateFormat.SHORT);
shortDF = DateFormat.getTimeInstance(DateFormat.SHORT);
callDayTime = new Date(Long.valueOf(callDate));
fechaLlamada1 = shortDF.format(callDayTime);
fechaLlamada2 = shortFecha.format(callDayTime);
callDuration = managedCursor.getString(duration);
int dircode = Integer.parseInt(callType);
TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "Saliente";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "Entrante";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "Perdida";
break;
}
imei = mngr.getDeviceId();
comentario = dir;
fechaRegistro = fechaLlamada2;
DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
String ahorita=df.format(callDayTime);
fechaInicio = ahorita.toString();
//fechaFin = df.format(callDayTime.setSeconds(callDayTime.getSeconds()+5));
insercion = "DECLARE @claveDriver INT, @nombreDriver VARCHAR(max), @evento VARCHAR(max), @duracion int, @inicial varchar(max) "
+ "SET @claveDriver = (SELECT cve_tra FROM SISTEMA.dbo.TELEFONOS WHERE IMEI_SIM = '"+mngr.getDeviceId()+"') "
+ "SET @nombreDriver = (SELECT nombre FROM SISTEMA.dbo.TELEFONOS WHERE IMEI_SIM = '"+mngr.getDeviceId()+"') "
+ "SET @duracion = " + managedCursor.getString(duration)
+ "SET @evento = '(LOG) Llamada " + dir + ". Duración ' + CONVERT(varchar, @duracion, 103) + ' segundos al número: " + phNumber +"' "
//+ "SET @duracion = " + callDuration
+" SET @inicial = '" + fechaInicio + "'"
+ "INSERT INTO bitacora.dbo.registroDellamadasOperadores (fechacreacion,fecha_fin,fecha_inicio,idMobil,Tractor,Nom_tra,Cve_tra,FechaRegistro,Evento) "
+ " VALUES('" + fechaInicio + "', DATEADD(SECOND,@duracion,@inicial),'" + fechaInicio + "','" + mngr.getDeviceId() + "','',@nombreDriver,@claveDriver,current_timestamp,@evento)";
AsyncCallWS tareaEnviarABD = new AsyncCallWS();
tareaEnviarABD.execute();
sb.append("\nNúmero de teléfono:--- " + phNumber + " \nTipo de llamada:--- "
+ dir + " \nFecha de llamada:--- " + fechaLlamada2 + " " + fechaLlamada1
+ " \nDuración en segundos:--- " + callDuration
+ " \nDispositivo actual:--" +mngr.getDeviceId());
sb.append("\n----------------------------------");
}
txtDetalles.setText(sb);
}
private class AsyncCallWS extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
Log.i(TAG,"doInBackground");
InsertarLlamada(insercion);
return null;
}
@Override
protected void onPostExecute(Void result) {
Log.i(TAG, "onPostExecute");
txtInformacion.setText("Información enviada");
}
@Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
txtInformacion.setText("Enviando información...");
}
@Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
public void InsertarLlamada(String insercion) {
//Creamos la solicitud
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//Propiedades que contienen los valores
PropertyInfo propiedades = new PropertyInfo();
propiedades.setName("insercion");
propiedades.setValue(insercion);
propiedades.setType(String.class);
//Agregamos las propiedades
request.addProperty(propiedades);
//Creamos el envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
//ponemos la salida SOAP
envelope.setOutputSoapObject(request);
//Creamos la llamada HTTP
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
//Invocamos el servicio
androidHttpTransport.call(SOAP_ACTION, envelope);
//Obtenemos la respuesta
Object response = envelope.getResponse();
//Asignamos el resultado de la consulta
resultado = response.toString();
} catch (Exception e) {
resultado = e.getMessage();
}
}
}
}
I do not know if this is the best way to do it, but i used sql variables and only sent 2 parameters to the webservice.
Thanks
Hi,
I´m new here and hope you can help me.
I wrote a service for an android app.
The service should keep on a server communication with an TCP Server.
I have to use this kind of solution!
If I start the app, the service is called. I get an connection with the run()-Method (I checked it with an boolean).
But now I can´t receive and send any messanges between server and android device.
Here is the code, may it helps:
Activity:
Code:
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import com.example.obdii.OBDService.connectSocket;
public class Werkstatt_Client extends Activity {
//Variablen initalisieren
private ListView mList;
private ArrayList arrayList;
private MyCustomAdapter mAdapter;
private OBDService mTcpClient;
static String ip;
public String message;
TextView nachricht;
//SERVICE
private OBDService hallo;
private ServiceConnection serviceconntection = new ServiceConnection(){
//EDITED PART
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
hallo = ((OBDService.LocalBinder)service).getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
hallo = null;
}
};
private void doBindService() {
bindService(new Intent(Werkstatt_Client.this, OBDService.class), serviceconntection, Context.BIND_AUTO_CREATE);
}
private void doUnbindService() {
hallo.onDestroy();
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Layout ansprechen
setContentView(R.layout.activity_werkstatt__client);
//Variablen initalisieren
arrayList = new ArrayList();
final EditText eingabe = (EditText) findViewById(R.id.TfNachricht);
Button send = (Button)findViewById(R.id.BtnSenden);
//Einfügen des eigenen ListViews mit dem Namen list_item
//(Stellt den Verlauf besser dar)
mList = (ListView)findViewById(R.id.chatlist);
mAdapter = new MyCustomAdapter(this, arrayList);
mList.setAdapter(mAdapter);
/* //Binding the activity to the service to perform client-server operations
//start service on create
startService(new Intent(Werkstatt_Client.this,OBDService.class));
doBindService();*/
//OnClickListener für den Button Senden
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
message = eingabe.getText().toString();
//Nachricht zum Verlauf hinzufügen
arrayList.add("Kunde: " + message);
//Nachricht an Server senden
OBDService oc = new OBDService();
connectSocket ic = oc.new connectSocket();
if(ic.k = false){
System.out.println("ICH KANN NICHT SENDEN");
//}
if (ic.k = true) {
//System.out.println(message);
oc.sendMessage(message);
}
//aktualisiert die ListView bei neuen Nachrichten
mAdapter.notifyDataSetChanged();
eingabe.setText("");
}
}
});
}
/**Diese Methode liest die IP aus dem
* dafür vorgesehenen Textfeld aus und
* übergibt sie der Klasse TCPClient*/
public void ipsetzen (View view){
EditText IP = (EditText)findViewById(R.id.TfIP);
ip = (IP.getText().toString());
Intent ir=new Intent(this, OBDService.class);
ir.putExtra("data", ip);
this.startService(ir);
// Verbindung mit dem Server aufbauen
new connectTask().execute("");
}
/**Diese Methode äffnet einen TCPClient
* (Asynchroner Task)*/
public class connectTask extends AsyncTask<String,String,OBDService> {
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
//Empfangene Nachrichten vom Server im Verlauf hinzufügen
arrayList.add("Werkstatt: " + values[0]);
//Erkennt, dass die Daten sich geändert haben (Nachricht) und fügt sie in einer neuen Zeile hinzu
mAdapter.notifyDataSetChanged();
//Sting aus dem Verlauf abrufen
String werkstattanfrage = values[0].toString();
//Ausgabe zum Debuggen
System.out.println(werkstattanfrage);
//Relevante Zeichen aus String auslesen
}
@Override
protected OBDService doInBackground(String... arg0) {
// TODO Auto-generated method stub
return null;
}
}
public void quittung(View view){
nachricht=(TextView)findViewById(R.id.TfNachricht);
nachricht.setText("Anweisung ausgefuehrt");
}
}
Here is the service:
Code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class OBDService extends Service {
public static String SERVERIP; //Hier muss die IP stehen
public static final int SERVERPORT = 8888;
PrintWriter out;
BufferedReader in;
Socket socket;
InetAddress serverAddr;
private boolean mRun = false;
private String serverMessage;
private OnMessageReceived mMessageListener = null;
public String message;
private final IBinder mylocalbinder = new LocalBinder();
TCPClient mTcpClient = new TCPClient(null);
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
Log.e("","Client hat sich verbunden");
return mylocalbinder;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
Log.e("","OnCreat");
super.onCreate();
}
/**Diese Methode Sendet eingetippte Nachrichten
* Server
*/
public void sendMessage(String message){
if(out == null){
System.out.println(message + " ICH KANN NICHT GESENDET WERDEN");
}
if (out != null && !out.checkError()) {
out.println(message);
System.out.println(message + "ICH BIN DER SERVICE");
//Sicherstellen, dass die gesammte Nachricht erfasst wird
out.flush();
}
}
@Override
public int onStartCommand(Intent intent,int flags, int startId){
super.onStartCommand(intent, flags, startId);
sendMessage(message);
System.out.println("I am in on start");
SERVERIP= (String) intent.getExtras().get("data");
// Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show();
Runnable connect = new connectSocket();
new Thread(connect).start();
return START_STICKY;
}
class connectSocket implements Runnable {
boolean k;
/**Diese Methode handhabt die gesendeten
* und empfangenen Nachrichten*/
public void run() {
mRun = true;
try {
//IP-Adresse des Servers übergeben
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
//Sicherheitsausgabe an den Server senden
Log.e("TCP Client", "Kunde: Connecting...");
//Öffnet einen Socket, um eine Verbindung mit dem Server herzustellen
Socket socket = new Socket(serverAddr, SERVERPORT);
try {
//Sendet die Nachricht zum Server
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
//Sicherheitsausgabe an den Server
Log.e("TCP Client", "Kunde: Sent.");
Log.e("TCP Client", "Kunde: Done.");
//Empfange Nachrichen vom Server
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//Der Client achtet auf eingehende Nachrichten vom Server
while (mRun) {
serverMessage = in.readLine();
if (serverMessage != null && mMessageListener != null) {
//Ruft die Methode messageReveives von der MainActivity auf
mMessageListener.messageReceived(serverMessage);
}
serverMessage = null;
}
Log.e("RESPONSE FROM SERVER", "Werkstattserver: Received Message: '" + serverMessage + "'");
} catch (Exception e){
//Sicherheitsausgabe an den Server zum Debuggen
Log.e("TCP", "Werkstattserver: Error");
socket.close();
//Dieser Block wird ausgeführt, wenn ein Error aufgetreten ist
}
} catch (Exception e) {
//Sicherheitsausgabe an den Server zum Debuggen
Log.e("TCP", "Kunde: Error", e);
}
}
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
try {
socket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
socket = null;
}
@Override
public void onRebind(Intent intent) {
// TODO Auto-generated method stub
super.onRebind(intent);
}
@Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
return super.onUnbind(intent);
}
public void test(){
Log.e("", "test");
}
public class LocalBinder extends Binder{
public LocalBinder(){
Log.e("", "Binder erzeugt");
}
public OBDService getService(){
return OBDService.this;
}
}
//Zugriff auf die Main Activity (übergabge der Nachrichten)
public interface OnMessageReceived {
public void messageReceived(String message);
}
}
If I try it only with my TCPClient Class, the connection runs. May I call a method wrong?!
so i have been working on an app for a while now but now my code is crashing due to no empty constructor.
but i have no more idea how i should fix this.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Code:
package com.spacewizz.powersavelauncher;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class ChooserAppsSettings extends LinearLayout {
private static final int CAPACITY = 6;
private static final String KEY_LIST[] = { "1", "2", "3", "4", "5", "6"};
private static final String HENABLED_KEY = "com.spacewizz.powersavelauncher.HENABLED";
private static final String KEY_APPNAME_KEY[] = {
"com.spacewizz.powersavelauncher.APP1", "com.spacewizz.powersavelauncher.APP2",
"com.spacewizz.powersavelauncher.APP3", "com.spacewizz.powersavelauncher.APP4",
"com.spacewizz.powersavelauncher.APP5", "com.spacewizz.powersavelauncher.APP6"};
private static final String KEY_INTENTNAME_KEY[] = {
"com.spacewizz.powersavelauncher.INTENT1", "com.spacewizz.powersavelauncher.INTENT2",
"com.spacewizz.powersavelauncher.INTENT3", "com.spacewizz.powersavelauncher.INTENT4",
"com.spacewizz.powersavelauncher.INTENT5", "com.spacewizz.powersavelauncher.INTENT6"};
private static final String KEY_SETTINGS = "com.spacewizz.powersavelauncher.SETTINGS";
private static final String VIEW_MODE_KEY = "com.spacewizz.powersavelauncher.VIEW_MODE_KEY";
private static final String KEY_APPNAME[] = { "ZAPP1", "ZAPP2", "ZAPP3", "ZAPP4", "ZAPP5", "ZAPP6" };
private static final String HORIZONTAL_KEY = "com.spacewizz.powersavelauncher.HORIZONTAL";
private static final String KEY_APPINTENT[] = { "XAPP1", "XAPP2", "XAPP3", "XAPP4", "XAPP5", "XAPP6" };
private static final String KEY_INTENT_ACTION[] = { "IAPP1", "IAPP2",
"IAPP3", "IAPP4", "IAPP5", "IAPP6" };
private ArrayList<String> INSTALLED_PACKAGE = new ArrayList<String>();
private ArrayList<String> APP_NAME = new ArrayList<String>();
private ArrayList<Intent> LAUNCH_ACTIVITY = new ArrayList<Intent>();
private ArrayList<Drawable> APP_ICONS = new ArrayList<Drawable>();
private ArrayList<String> APPS_SHORTCUT = new ArrayList<String>(CAPACITY);
private ArrayAdapter<String> APPS_SHORTCUT_ADAPTER;
private String OPTIONS[] = { "Remove shortcut" };
private String APP_NAMES[] = new String[CAPACITY];
private String OLD_LIST_NAME, NEW_LIST_NAME, INTENT;
private String MODES[] = { "Icon + Label", "Icon only", "Label only",
"Icon + Label (Vertical)" };
Intent mIntent;
boolean horizontal, henabled;
SharedPreferences sp;
ArrayAdapter<String> mSpinnerAdapter;
SharedPreferences.Editor spe;
private Spinner VIEW_MODES;
private ListView APPSLISTVIEW;
private TextView ViewSettingsLabel, AppsListLabel;
private CheckBox HorizontalScroll;
private Context mContext;
int mSpinnerPos;
private LinearLayout THESETTINGS;
private Button mSettings, mDoneSettings;
private ProgressDialog dialog;
private ScrollView mSettingsView;
private Dialog mSettingsDialog;
private WindowManager.LayoutParams WMLP;
public ChooserAppsSettings(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
this.mContext = context;
dialog = new ProgressDialog(mContext);
dialog.setTitle("Please wait...");
dialog.setMessage("Loading installed applications...");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
henabled = getCBState();
setOrientation(LinearLayout.VERTICAL);
setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
LinearLayout.LayoutParams TVLP = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
TVLP.gravity = Gravity.CENTER_VERTICAL;
mSpinnerPos = getSpinnerPos();
mSettings = new Button(mContext);
mSettings.setText("Settings");
mSettings.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
mDoneSettings = new Button(mContext);
mDoneSettings.setText("Done!");
mDoneSettings.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
THESETTINGS = new LinearLayout(mContext);
THESETTINGS.setOrientation(LinearLayout.VERTICAL);
THESETTINGS.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
mSettingsView = new ScrollView(mContext);
mSettingsView.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
VIEW_MODES = new Spinner(mContext);
VIEW_MODES.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
mSpinnerAdapter = new ArrayAdapter<String>(mContext,
android.R.layout.simple_spinner_item, MODES);
mSpinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
VIEW_MODES.setAdapter(mSpinnerAdapter);
VIEW_MODES.setSelection(mSpinnerPos);
LinearLayout.LayoutParams ColorLL = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, 50);
ColorLL.bottomMargin = 30;
ColorLL.topMargin = 20;
ColorLL.leftMargin = 50;
ColorLL.rightMargin = 50;
ViewSettingsLabel = new TextView(mContext);
AppsListLabel = new TextView(mContext);
ViewSettingsLabel.setLayoutParams(TVLP);
AppsListLabel.setLayoutParams(TVLP);
ViewSettingsLabel.setText("Display Options");
AppsListLabel.setText("App Shortcuts List: ");
ViewSettingsLabel.setBackgroundResource(android.R.drawable.title_bar);
AppsListLabel.setBackgroundResource(android.R.drawable.title_bar);
ViewSettingsLabel.setGravity(Gravity.CENTER);
HorizontalScroll = new CheckBox(mContext);
HorizontalScroll.setLayoutParams(TVLP);
HorizontalScroll.setText("Horizontal Scroll (Icon only)");
HorizontalScroll.setEnabled(horizontal);
HorizontalScroll.setChecked(henabled);
APPSLISTVIEW = new ListView(mContext);
APPSLISTVIEW.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
addView(APPSLISTVIEW);
mSettingsDialog = new Dialog(mContext);
mSettingsDialog.setTitle("Settings");
mSettingsDialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
mSettingsDialog.setContentView(mSettingsView);
mSettingsDialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
android.R.drawable.ic_menu_manage);
WMLP = new WindowManager.LayoutParams();
WMLP.copyFrom(mSettingsDialog.getWindow().getAttributes());
WMLP.width = WindowManager.LayoutParams.MATCH_PARENT;
WMLP.height = WindowManager.LayoutParams.WRAP_CONTENT;
for (int i = 1; i <= CAPACITY; i++) {
APPS_SHORTCUT.add("Application " + String.valueOf(i));
}
APPS_SHORTCUT_ADAPTER = new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1, APPS_SHORTCUT);
dialog.show();
preloadInstalledApplications Preload = new preloadInstalledApplications();
Preload.execute(02, 23, 1997);
setHorizontalScrollListener();
//setViewModeOnItemSelectedListener();
setAppListViewOnClickListener();
setApplistViewOnLongClickListener();
//setmSettingsOnClickListener();
//setmDoneSettingsOnClickListener();
loadList();
refreshList();
}
private boolean getCBState() {
sp = PreferenceManager.getDefaultSharedPreferences(mContext);
return sp.getBoolean(HENABLED_KEY, false);
}
private void saveCBState(boolean state) {
openSPE();
spe.putBoolean(HENABLED_KEY, state);
commitSPE();
}
private boolean getHorizontal() {
sp = PreferenceManager.getDefaultSharedPreferences(mContext);
return sp.getBoolean(HORIZONTAL_KEY, false);
}
private void setHorizontalScrollListener() {
// TODO Auto-generated method stub
HorizontalScroll
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (HorizontalScroll.isChecked()) {
saveCBState(HorizontalScroll.isChecked());
} else {
saveCBState(HorizontalScroll.isChecked());
}
}
});
}
private void setmDoneSettingsOnClickListener() {
// TODO Auto-generated method stub
mDoneSettings.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mSettingsDialog.isShowing()) {
mSettingsDialog.dismiss();
}
}
});
}
private void setmSettingsOnClickListener() {
// TODO Auto-generated method stub
mSettings.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mSettingsDialog.show();
mSettingsDialog.getWindow().setAttributes(WMLP);
}
});
}
private void setViewModeOnItemSelectedListener() {
// TODO Auto-generated method stub
VIEW_MODES.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
mSpinnerPos = arg2;
int MODE = mSpinnerPos;
VIEW_MODES.setSelection(mSpinnerPos);
saveSpinnerPos(mSpinnerPos);
if (mSpinnerPos == 1) {
horizontal = true;
henabled = HorizontalScroll.isChecked();
if (henabled) {
MODE = 100;
} else {
MODE = mSpinnerPos;
}
} else {
horizontal = false;
henabled = false;
}
sendViewModeSettings(MODE);
HorizontalScroll.setEnabled(horizontal);
openSPE();
spe.putBoolean(HORIZONTAL_KEY, horizontal);
commitSPE();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
VIEW_MODES.setSelection(mSpinnerPos);
}
});
}
private void saveSpinnerPos(int pos) {
sp = PreferenceManager.getDefaultSharedPreferences(getContext());
spe = sp.edit();
spe.putInt(VIEW_MODE_KEY, pos);
spe.commit();
}
private int getSpinnerPos() {
sp = PreferenceManager.getDefaultSharedPreferences(getContext());
return sp.getInt(VIEW_MODE_KEY, 0);
}
private void sendViewModeSettings(int mode) {
mIntent = new Intent();
mIntent.setAction(KEY_SETTINGS);
mIntent.putExtra(VIEW_MODE_KEY, mode);
mContext.sendBroadcast(mIntent);
}
private void setApplistViewOnLongClickListener() {
// TODO Auto-generated method stub
APPSLISTVIEW.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int arg2, long arg3) {
// TODO Auto-generated method stub
final ListAdapter OPTIONSMENU = new ArrayAdapter<String>(
mContext, android.R.layout.simple_list_item_1, OPTIONS);
new AlertDialog.Builder(mContext)
.setTitle("Options")
.setIcon(android.R.drawable.ic_dialog_info)
.setAdapter(OPTIONSMENU,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
switch (which) {
case 0:
String NEW_ITEM = "Application "
+ String.valueOf(arg2 + 1)
+ " (Not on SystemUI)";
APPS_SHORTCUT.remove(arg2);
APPS_SHORTCUT.add(arg2, NEW_ITEM);
sendDeleteCommand(arg2);
APP_NAMES[arg2] = APPS_SHORTCUT
.get(arg2);
saveList(arg2);
refreshList();
break;
}
}
}).show();
return false;
}
});
}
private void setAppListViewOnClickListener() {
// TODO Auto-generated method stub
APPSLISTVIEW.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
final int arg2, long arg3) {
// TODO Auto-generated method stub
final ListAdapter ADAPTER = new ArrayAdapter<String>(mContext,
android.R.layout.simple_list_item_1, APP_NAME);
new AlertDialog.Builder(mContext)
.setTitle("Select Application")
.setIcon(android.R.drawable.ic_dialog_alert)
.setAdapter(ADAPTER,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Toast.makeText(
getContext(),
"Application "
+ String.valueOf(arg2 + 1)
+ " selected: "
+ ADAPTER
.getItem(which)
.toString(),
Toast.LENGTH_SHORT).show();
OLD_LIST_NAME = APPS_SHORTCUT.get(arg2);
NEW_LIST_NAME = ADAPTER.getItem(which)
.toString();
if (OLD_LIST_NAME != NEW_LIST_NAME) {
APPS_SHORTCUT.remove(arg2);
String NEW_ITEM = ADAPTER.getItem(
which).toString();
APPS_SHORTCUT.add(arg2, NEW_ITEM);
if (LAUNCH_ACTIVITY.get(which) != null) {
INTENT = INSTALLED_PACKAGE
.get(which);
} else {
INTENT = "null";
}
refreshToBePassed(arg2, NEW_ITEM,
INTENT);
}
saveList(arg2);
refreshList();
}
}).show();
}
});
}
private void refreshList() {
APPS_SHORTCUT_ADAPTER = new ArrayAdapter<String>(mContext,
android.R.layout.simple_list_item_1, APPS_SHORTCUT);
APPSLISTVIEW.setAdapter(APPS_SHORTCUT_ADAPTER);
}
private void refreshToBePassed(int position, String APP, String mINTENT) {
APP_NAMES[position] = APP;
KEY_APPNAME[position] = APPS_SHORTCUT_ADAPTER.getItem(position);
KEY_APPINTENT[position] = mINTENT;
mIntent = new Intent();
mIntent.setAction(KEY_INTENT_ACTION[position]);
mIntent.putExtra(KEY_APPNAME_KEY[position], KEY_APPNAME[position]);
mIntent.putExtra(KEY_INTENTNAME_KEY[position], KEY_APPINTENT[position]);
mContext.sendBroadcast(mIntent);
}
private void saveList(int position) {
sp = PreferenceManager.getDefaultSharedPreferences(getContext());
spe = sp.edit();
spe.putString(KEY_LIST[position], APP_NAMES[position]);
spe.commit();
}
private void loadList() {
// TODO Auto-generated method stub
sp = PreferenceManager.getDefaultSharedPreferences(getContext());
APPS_SHORTCUT.clear();
for (int x = 0; x < CAPACITY; x++) {
APP_NAMES[x] = sp.getString(KEY_LIST[x],
"Application " + String.valueOf((x + 1)));
APPS_SHORTCUT.add(APP_NAMES[x]);
}
}
private void sendDeleteCommand(int position) {
KEY_APPNAME[position] = "DELETE";
KEY_APPINTENT[position] = "DELETE";
mIntent = new Intent();
mIntent.setAction(KEY_INTENT_ACTION[position]);
mIntent.putExtra(KEY_APPNAME_KEY[position], KEY_APPNAME[position]);
mIntent.putExtra(KEY_INTENTNAME_KEY[position], KEY_APPINTENT[position]);
mContext.sendBroadcast(mIntent);
}
private void openSPE() {
sp = PreferenceManager.getDefaultSharedPreferences(mContext);
spe = sp.edit();
}
private void commitSPE() {
spe.commit();
}
private class preloadInstalledApplications extends
AsyncTask<Integer, Void, Void> {
@Override
protected Void doInBackground(Integer... params) {
// TODO Auto-generated method stub
final PackageManager PM = mContext.getPackageManager();
List<ApplicationInfo> PACKAGES = PM
.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo PACKAGE_INFO : PACKAGES) {
if (PM.getLaunchIntentForPackage(PACKAGE_INFO.packageName) != null) {
INSTALLED_PACKAGE.add(PACKAGE_INFO.packageName);
LAUNCH_ACTIVITY
.add(PM.getLaunchIntentForPackage(PACKAGE_INFO.packageName));
APP_ICONS.add(PM.getApplicationIcon(PACKAGE_INFO));
APP_NAME.add(PM.getApplicationLabel(PACKAGE_INFO)
.toString());
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
}
}
}
anyone knows how to fix?
thanks
This' to put it inns nutshell
haaaroldb said:
This' to put it inns nutshell
Click to expand...
Click to collapse
I am sorry i don't understand. can you explain ?
I am not sure, but your class might be missing constructor
more info: http://www.javatpoint.com/constructor
For some reason it says that it needs and Empty constructor.
Type inside ChooserAppSettings class:
Code:
public ChooserAppSettings(){
}
This may fix it. I am not sure though why it needs the empty constructor. What class is your ChooserAppSettings extending or implementing??
Can you show all the logcat messages?
@mmdeveloper said:
For some reason it says that it needs and Empty constructor.
Type inside ChooserAppSettings class:
Code:
public ChooserAppSettings(){
}
This may fix it. I am not sure though why it needs the empty constructor. What class is your ChooserAppSettings extending or implementing??
Can you show all the logcat messages?
Click to expand...
Click to collapse
Linearlayout.
Tried the above but didnt worked
Try adding these:
Code:
public ChooserAppSettings(Context context){
super(context);
}
public ChooserAppSettings(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
}
Issue solved.
was a stupid fault of myself xD
typo at launching the java file