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?
Related
Hi there,
I have a Listener (for swipe) in my Main class, and I have to use some method of a second class (SecondTab).
Can I use the method of SecondTab from the Main Class without putting all the method on static?
Code:
public class Main extends TabActivity implements OnGesturePerformedListener{
public GestureLibrary mLibrary;
private String g="g";
private String d="d";
Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab);
mLibrary = GestureLibraries.fromRawResource(this, R.raw.actions);
if (!mLibrary.load()) {
finish();}
GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures);
//R.id.gestures c'est l'id dans le xml
gestures.addOnGesturePerformedListener(this);
TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost); // Le TabHost a des Tabs
TabSpec firstTabSpec = tabHost.newTabSpec("tid1"); // TabSpec: new tab - TabSpec : setContent to the tab
TabSpec secondTabSpec = tabHost.newTabSpec("tid1");
TabSpec thirdTabSpec = tabHost.newTabSpec("tid1"); // tid1 is firstTabSpec Id (used to access outside)
/** TabSpec setIndicator() indique le nom et les param -- TabSpec setContent() règle le contenu d'une tab */
firstTabSpec.setIndicator("Informations", getResources().getDrawable(R.drawable.database)).setContent(new Intent(this,FirstTab.class));
secondTabSpec.setIndicator("Graphiques", getResources().getDrawable(R.drawable.chart)).setContent(new Intent(this,SecondTab.class));
thirdTabSpec.setIndicator("Réglages", getResources().getDrawable(R.drawable.settings)).setContent(new Intent(this,ThirdTab.class));
/** Ajout des tabSpec sur le TabHost to display. */
tabHost.addTab(firstTabSpec);
tabHost.addTab(secondTabSpec);
tabHost.addTab(thirdTabSpec);
}
and the Listener with the method of the other class :
Code:
Override
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
ArrayList<Prediction> predictions = mLibrary.recognize(gesture);
// Quand y'a au moins une prédiction
if (predictions.size() > 0) {
Prediction prediction = predictions.get(0);
// On vérifie que la prédiction ressemble à un de nos modèles
if (prediction.score > 1.0) {
if (prediction.name.equals(g))
{SecondTab.setGauche();
SecondTab.refresh();}
if (prediction.name.equals(d))
{SecondTab.setDroite();
SecondTab.refresh();
}
}
}
}
}
(where setGauche(), setDroite() and refresh(); are the method of SecondTab ...)
setGauche and setDroite can be static but some variable of the refresh() cannot !!!
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
Hello everyone, me again.
I am having a little issue with my android app.
When I run the service on the phone, it starts just fine and when the call is disconnected it throws an java.lang.NullPointerException when i start the tareaEnviarABD.execute(); task.
This is the code of my service:
Code:
package com.trucka.llamadasdrivers;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
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 android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.IBinder;
import android.provider.CallLog;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class ServicioLlamadas extends Service {
TextView txtInformacion = null;
TextView txtDetalles = null;
TextView tv = null;
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;
String estadoLlamada = null;
private static ServicioLlamadas instance = null;
public static boolean isRunning() {
return instance != null;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(getApplicationContext(), "Servicio TRUCKA creado",
Toast.LENGTH_SHORT).show();
instance = this;
}
@Override
public void onDestroy() {
Toast.makeText(getApplicationContext(), "Servicio TRUCKA destruído",
Toast.LENGTH_SHORT).show();
instance = null;
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(getApplicationContext(), "Servicio TRUCKA iniciado",
Toast.LENGTH_SHORT).show();
TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
TelephonyMgr.listen(new TeleListener(),
PhoneStateListener.LISTEN_CALL_STATE);
}
class TeleListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
if (estadoLlamada == "OFFHOOK") {
insercion = null;
getCallDetails();
Toast.makeText(getApplicationContext(),
"Información enviada.", Toast.LENGTH_SHORT).show();
}
estadoLlamada = "IDLE";
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
estadoLlamada = "OFFHOOK";
Toast.makeText(getApplicationContext(),
"Enviando información...", Toast.LENGTH_SHORT).show();
break;
case TelephonyManager.CALL_STATE_RINGING:
break;
default:
break;
}
}
}
//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();
}
private void getCallDetails() {
String timestamp = String.valueOf(getTodayTimestamp());
StringBuffer sb = new StringBuffer();
Cursor managedCursor = getContentResolver().query(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 :");
//managedCursor.moveToFirst();
managedCursor.moveToLast();
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();
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: "
+ managedCursor.getString(number)
+ "' "
+ " 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)";
try
{
AsyncCallWS tareaEnviarABD = new AsyncCallWS();
tareaEnviarABD.execute();
}catch(Exception e){
Toast.makeText(getApplicationContext(),
e.toString(), Toast.LENGTH_SHORT).show();
}
}
private class AsyncCallWS extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... 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) {
Toast.makeText(getApplicationContext(),
e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
And the log cat shows this:
Code:
02-25 09:32:32.946: D/ActivityThread(8866): setTargetHeapUtilization:0.25
02-25 09:32:32.946: D/ActivityThread(8866): setTargetHeapIdealFree:8388608
02-25 09:32:32.946: D/ActivityThread(8866): setTargetHeapConcurrentStart:2097152
02-25 09:33:07.663: D/libEGL(8866): loaded /system/lib/egl/libEGL_adreno200.so
02-25 09:33:07.663: D/libEGL(8866): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
02-25 09:33:07.663: D/libEGL(8866): loaded /system/lib/egl/libGLESv2_adreno200.so
02-25 09:33:07.683: I/Adreno200-EGLSUB(8866): <ConfigWindowMatch:2087>: Format RGBA_8888.
02-25 09:33:07.693: E/(8866): <s3dReadConfigFile:75>: Can't open file for reading
02-25 09:33:07.693: E/(8866): <s3dReadConfigFile:75>: Can't open file for reading
02-25 09:33:07.693: D/OpenGLRenderer(8866): Enabling debug mode 0
02-25 09:33:13.128: I/TRUCKA_DRIVERS(8866): onPreExecute
02-25 09:33:13.128: D/AndroidRuntime(8866): Shutting down VM
02-25 09:33:13.128: W/dalvikvm(8866): threadid=1: thread exiting with uncaught exception (group=0x41e48438)
02-25 09:33:13.128: E/AndroidRuntime(8866): FATAL EXCEPTION: main
02-25 09:33:13.128: E/AndroidRuntime(8866): java.lang.NullPointerException
02-25 09:33:13.128: E/AndroidRuntime(8866): at com.trucka.llamadasdrivers.ServicioLlamadas$AsyncCallWS.onPreExecute(ServicioLlamadas.java:239)
02-25 09:33:13.128: E/AndroidRuntime(8866): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
02-25 09:33:13.128: E/AndroidRuntime(8866): at android.os.AsyncTask.execute(AsyncTask.java:534)
02-25 09:33:13.128: E/AndroidRuntime(8866): at com.trucka.llamadasdrivers.ServicioLlamadas.getCallDetails(ServicioLlamadas.java:215)
02-25 09:33:13.128: E/AndroidRuntime(8866): at com.trucka.llamadasdrivers.ServicioLlamadas.access$0(ServicioLlamadas.java:143)
02-25 09:33:13.128: E/AndroidRuntime(8866): at com.trucka.llamadasdrivers.ServicioLlamadas$TeleListener.onCallStateChanged(ServicioLlamadas.java:108)
02-25 09:33:13.128: E/AndroidRuntime(8866): at android.telephony.PhoneStateListener$2.handleMessage(PhoneStateListener.java:421)
02-25 09:33:13.128: E/AndroidRuntime(8866): at android.os.Handler.dispatchMessage(Handler.java:99)
02-25 09:33:13.128: E/AndroidRuntime(8866): at android.os.Looper.loop(Looper.java:137)
02-25 09:33:13.128: E/AndroidRuntime(8866): at android.app.ActivityThread.main(ActivityThread.java:5062)
02-25 09:33:13.128: E/AndroidRuntime(8866): at java.lang.reflect.Method.invokeNative(Native Method)
02-25 09:33:13.128: E/AndroidRuntime(8866): at java.lang.reflect.Method.invoke(Method.java:511)
02-25 09:33:13.128: E/AndroidRuntime(8866): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
02-25 09:33:13.128: E/AndroidRuntime(8866): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
02-25 09:33:13.128: E/AndroidRuntime(8866): at dalvik.system.NativeStart.main(Native Method)
02-25 09:33:14.240: I/Process(8866): Sending signal. PID: 8866 SIG: 9
Can someone please tell me what am I doing wrong?
Thanks!
FedePrado said:
Hello everyone, me again.
Code:
@Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
txtInformacion.setText("Enviando información...");
}
02-25 09:33:13.128: E/AndroidRuntime(8866): java.lang.NullPointerException
02-25 09:33:13.128: E/AndroidRuntime(8866): at com.trucka.llamadasdrivers.ServicioLlamadas$AsyncCallWS.onPreExecute(ServicioLlamadas.java:239)
Click to expand...
Click to collapse
it tells you there, note that on line 239 you are asking an object (in this case "txtInfromacion") to execute one of it's methods, but the object is actually "null" so it throws the exception
disclaimer, I only looked at it for 10 seconds cause busy but I would think there is a 99.5% chance I'm correct
EDIT : ok looked at it another 5 seconds, you never assign anything to that TextView, like associating it with the view on screen ? eg. findViewById(R.id.someID)
Hi, I really need help, i want to extract some .png and .jpg from the assets of the app 'Hyperdimension Neptunia The App'
after 3 month of research i found out that the assets are probably "encrypted" i wanted the textures for the live2D model files, and wanted to replace the sounds with the English versions from the iOS app that i extracted.
Audio was .caf in iOS but in Android it says its .mp3
This Line in a class says something about the audio: localEditor.putString("alarm_voice", bw.a(str, "caf", "mp3"));
The .caf opens and runs fine so whats the problem and anyone help me decrypt it? :fingers-crossed:
Full "AlarmActivity.class"
Code:
package jp.co.ideaf.neptune.nepkamijigenapp;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.NumberPicker;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.Calendar;
import java.util.Timer;
import jp.co.ideaf.neptune.nepkamijigenapp.a.a;
import jp.co.ideaf.neptune.nepkamijigenapp.a.d;
import jp.co.ideaf.neptune.nepkamijigenapp.a.f;
import jp.co.ideaf.neptune.nepkamijigenapp.a.h;
import jp.co.ideaf.neptune.nepkamijigenapp.d.z;
public class AlarmActivity extends Activity
{
private a a = null;
private d b = null;
private Timer c = null;
private ee d = null;
private eg e = null;
private Handler f = new Handler();
private LinearLayout g = null;
private static int a(Context paramContext, a parama, long paramLong)
{
h localh = KamijigenApplication.c();
z localz = localh.b(parama.c().f());
int i = localh.a();
String str = localz.g();
Object[] arrayOfObject = new Object[1];
arrayOfObject[0] = Long.valueOf(paramLong / 1000L);
jp.co.ideaf.neptune.nepkamijigenapp.d.k.a(String.format("アラーム発生時間 : %d秒", arrayOfObject), new Object[0]);
f localf = new f(paramLong + Calendar.getInstance().getTimeInMillis());
SharedPreferences.Editor localEditor = paramContext.getSharedPreferences(bw.a(paramContext, 2131034117), 0).edit();
localEditor.putString("alarm_voice", bw.a(str, "caf", "mp3"));
localEditor.putBoolean("snooze", parama.b);
localEditor.putInt("snooze_time", parama.c);
localEditor.commit();
Intent localIntent = new Intent(paramContext, AlarmDialogActivity.class);
localIntent.addFlags(268435456);
PendingIntent localPendingIntent = PendingIntent.getActivity(paramContext, 0, localIntent, 0);
((AlarmManager)paramContext.getSystemService("alarm")).set(0, localf.b(), localPendingIntent);
return i;
}
private void a()
{
TimePicker localTimePicker = (TimePicker)findViewById(2131165202);
if (localTimePicker == null);
while (true)
{
return;
localTimePicker.setIs24HourView(Boolean.valueOf(true));
localTimePicker.setCurrentHour(Integer.valueOf(this.a.c().f()));
localTimePicker.setCurrentMinute(Integer.valueOf(this.a.c().g()));
}
}
private void a(int paramInt)
{
TextView localTextView = (TextView)findViewById(2131165196);
if (localTextView != null)
{
localTextView.setText(Integer.toString(paramInt));
localTextView.append(bw.a(this, 2131034215));
}
}
private void a(int paramInt1, int paramInt2)
{
TextView localTextView1 = (TextView)findViewById(2131165194);
if (localTextView1 != null)
{
localTextView1.setText(Integer.toString(paramInt1));
localTextView1.append(bw.a(this, 2131034211));
}
TextView localTextView2 = (TextView)findViewById(2131165195);
if (localTextView2 != null)
{
localTextView2.setText(Integer.toString(paramInt2));
localTextView2.append(bw.a(this, 2131034212));
}
}
public static void a(Context paramContext, a parama)
{
d locald = KamijigenApplication.a();
locald.b(paramContext, false);
c(paramContext, parama);
parama.a = true;
locald.p().a(parama);
locald.c(paramContext);
}
private void b()
{
CheckBox localCheckBox = (CheckBox)findViewById(2131165197);
if (localCheckBox != null)
{
if (KamijigenApplication.a().p().a)
break label38;
localCheckBox.setEnabled(false);
localCheckBox.setChecked(false);
}
while (true)
{
return;
label38: localCheckBox.setChecked(true);
}
}
private static void c(Context paramContext, a parama)
{
f localf1 = new f(Calendar.getInstance().getTimeInMillis());
int i = localf1.f();
int j = localf1.g();
int k;
int m;
int n;
f localf2;
long l;
if ((i < parama.c().f()) || ((i == parama.c().f()) && (j < parama.c().g())))
{
k = localf1.c();
m = localf1.d();
n = localf1.e();
localf2 = new f(k, m, n, parama.c().f(), parama.c().g(), 0);
jp.co.ideaf.neptune.nepkamijigenapp.d.k.a("targetDate : " + localf2.toString(), new Object[0]);
jp.co.ideaf.neptune.nepkamijigenapp.d.k.a("nowDate : " + localf1.toString(), new Object[0]);
l = localf2.b() - localf1.b();
if (parama.c <= 0)
break label300;
}
label300: for (parama.b = true; ; parama.b = false)
{
int i1 = a(paramContext, parama, l);
parama.c().a(k);
parama.c().b(m);
parama.c().c(n);
parama.d = i1;
return;
f localf3 = new f(86400000L + localf1.b());
k = localf3.c();
m = localf3.d();
n = localf3.e();
localf2 = new f(k, m, n, parama.c().f(), parama.c().g(), 0);
break;
}
}
public void onClickBackButton(View paramView)
{
finish();
}
public void onClickDecideButton(View paramView)
{
CheckBox localCheckBox = (CheckBox)findViewById(2131165197);
if (((RadioButton)findViewById(2131165199)).isChecked())
{
findViewById(2131165201).setVisibility(8);
findViewById(2131165203).setVisibility(0);
findViewById(2131165201).setVisibility(0);
findViewById(2131165203).setVisibility(8);
if (localCheckBox != null)
break label127;
}
while (true)
{
return;
findViewById(2131165201).setVisibility(0);
findViewById(2131165203).setVisibility(8);
findViewById(2131165201).setVisibility(8);
findViewById(2131165203).setVisibility(0);
break;
label127: d locald = KamijigenApplication.a();
if (!locald.p().a)
showDialog(0);
else if ((locald.p().a) && (localCheckBox.isChecked()))
showDialog(2);
else
showDialog(3);
}
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
setRequestedOrientation(1);
setContentView(2130903041);
d locald = KamijigenApplication.a();
this.a = new a();
this.a.a(locald.p());
a(this.a.c().f(), this.a.c().g());
a();
b();
TimePicker localTimePicker = (TimePicker)findViewById(2131165202);
if (localTimePicker != null)
{
localTimePicker.setVisibility(0);
localTimePicker.setOnTimeChangedListener(new j(this));
}
userNumberPicker localuserNumberPicker = (userNumberPicker)findViewById(2131165204);
a(this.a.c);
if ((Build.VERSION.SDK_INT < 11) && (localuserNumberPicker != null))
{
localuserNumberPicker.a(0, 59);
localuserNumberPicker.a(this.a.c);
localuserNumberPicker.a(new l(this));
}
if (Build.VERSION.SDK_INT >= 11)
{
FrameLayout localFrameLayout = (FrameLayout)findViewById(2131165203);
localuserNumberPicker.setEnabled(false);
localuserNumberPicker.setVisibility(8);
this.g = new LinearLayout(this);
this.g.setOrientation(0);
NumberPicker localNumberPicker = new NumberPicker(this);
localNumberPicker.setMinValue(0);
localNumberPicker.setMaxValue(59);
localNumberPicker.setValue(this.a.c);
localNumberPicker.setOnValueChangedListener(new m(this));
this.g.addView(localNumberPicker, 0, new LinearLayout.LayoutParams(-2, -2, 1.0F));
localFrameLayout.addView(this.g, new FrameLayout.LayoutParams(-2, -2, 17));
}
findViewById(2131165201).setVisibility(0);
findViewById(2131165203).setVisibility(8);
((RadioGroup)findViewById(2131165198)).setOnCheckedChangeListener(new n(this));
this.b = KamijigenApplication.a();
String str = getResources().getText(2131034115).toString();
LinearLayout localLinearLayout = (LinearLayout)findViewById(2131165191);
Button localButton = (Button)findViewById(2131165205);
if (str.equals(this.b.d(this.b.k())))
{
localLinearLayout.setBackgroundResource(2130837540);
localButton.setBackgroundResource(2130837513);
}
while (true)
{
if (locald.p().a)
showDialog(4);
return;
localLinearLayout.setBackgroundResource(2130837541);
localButton.setBackgroundResource(2130837514);
}
}
protected Dialog onCreateDialog(int paramInt)
{
AlertDialog localAlertDialog;
if (paramInt == 0)
localAlertDialog = new AlertDialog.Builder(this).setTitle(2131034216).setMessage(2131034217).setPositiveButton(2131034218, new q(this)).setNegativeButton(2131034219, null).create();
while (true)
{
return localAlertDialog;
if (paramInt == 1)
{
localAlertDialog = new AlertDialog.Builder(this).setMessage(2131034220).setPositiveButton(2131034221, new r(this)).create();
}
else if (paramInt == 2)
{
localAlertDialog = new AlertDialog.Builder(this).setTitle(2131034222).setMessage(2131034223).setPositiveButton(2131034224, new s(this)).setNegativeButton(2131034225, null).create();
}
else if (paramInt == 3)
{
localAlertDialog = new AlertDialog.Builder(this).setTitle(2131034226).setMessage(2131034227).setPositiveButton(2131034228, new t(this)).setNegativeButton(2131034229, null).create();
}
else
{
localAlertDialog = null;
if (paramInt == 4)
localAlertDialog = new AlertDialog.Builder(this).setMessage(2131034304).setPositiveButton(2131034228, new k(this)).setNegativeButton(2131034229, null).create();
}
}
}
protected void onPause()
{
super.onPause();
if (this.d != null)
this.d.b();
this.c.cancel();
this.c.purge();
}
protected void onResume()
{
super.onResume();
this.d = new ee(this);
this.d.a();
this.c = new Timer(true);
this.c.scheduleAtFixedRate(new o(this), 100L, 100L);
Display localDisplay = ((WindowManager)getSystemService("window")).getDefaultDisplay();
if (localDisplay.getWidth() > localDisplay.getHeight());
for (int i = localDisplay.getHeight(); ; i = localDisplay.getWidth())
{
float f1 = i / 480.0F;
LinearLayout localLinearLayout = (LinearLayout)findViewById(2131165193);
getResources().getDrawable(2130837742);
localLinearLayout.getLayoutParams().height = ((int)(90.0F * f1));
localLinearLayout.getLayoutParams().width = ((int)(f1 * 172.0F));
localLinearLayout.requestLayout();
this.e = new eg(this, 0);
return;
}
}
}
well if it is encrypted, what type ? and if it\s something like AES CBC how do you intend to get the cypher ?
That's the problem, im kinda new to this thing so im not sure how to get the cypher and i think its AES encrypted but not 100% certain. Sorry for being a noob.
I'm trying to get the result of the asynctask by using an interface but when I've tried to use the methods on that interface my app keeps on crashing.
This project has 4 java files: MainActivity.java , SigninActivity.java , GetAvailableExam.java , AsyncResponse.java
I'm pretty sure the error is not on the GetAvailableExam.java because it is just an activity that prints hello world so I'm not going to post it's code here.
MainActivity.java
Code:
package com.it4.anexsysclient;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements AsyncResponse {
private EditText usernameField,passwordField;
private TextView status,role,method;
SigninActivity signinactivity = new SigninActivity();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);
status = (TextView)findViewById(R.id.textView6);
role = (TextView)findViewById(R.id.textView7);
method = (TextView)findViewById(R.id.textView9);
signinactivity.delegate = this;
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
usernameField.setText("stud");
passwordField.setText("stud");
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void login(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Get Method");
new SigninActivity(this,status,role,0).execute(username,password);
}
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Post Method");
new SigninActivity(this,status,role,1).execute(username,password);
}
public void processFinish(String output){
//Toast.makeText(getApplicationContext(), output, Toast.LENGTH_LONG).show();
}
}
SigninActivity.java
Code:
package com.it4.anexsysclient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
public class SigninActivity extends AsyncTask<String,Void,String>{
private TextView statusField,roleField;
private Context context;
private int byGetOrPost = 0;
private String server_ip;
private ProgressDialog progress;
public AsyncResponse delegate=null;
public SigninActivity() {
}
//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,
TextView roleField,int flag) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
byGetOrPost = flag;
this.progress = new ProgressDialog(context);
}
protected void onPreExecute(){
server_ip = "http://192.168.0.101/anexsys/examination-manager.php";
this.progress.setMessage("Logging in");
this.progress.show();
}
[user=439709]@override[/user]
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://myphpmysqlweb.hostei.com/login.php?username="
+username+"&password="+password;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link=server_ip;
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
[user=439709]@override[/user]
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
this.progress.dismiss();
delegate.processFinish(result);
//Log.d("ADebugTag", "Value: " + result);
//if(result.toString()=="student") {
//context.startActivity(new Intent(context, GetAvailableExam.class));
//}
}
}
AsyncResponse.java
Code:
package com.it4.anexsysclient;
public interface AsyncResponse {
void processFinish(String output);
}
Code:
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
this.progress.dismiss();
delegate.processFinish(result);
//Log.d("ADebugTag", "Value: " + result);
//if(result.toString()=="student") {
//context.startActivity(new Intent(context, GetAvailableExam.class));
//}
}
The delegate.processFinish(result) is the one causing the crash, The app works fine if I try to remove/comment out it.
Would be helpfull with some more information, for instance: what exception is it you get?
My guess is a nullpointer? Which by a quick glance i'd suspect is that you never set "delegate" in your signinactivity.
You create signinactivity during creation of mainactivity.
Code:
[B]SigninActivity signinactivity = new SigninActivity();[/B]
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);
status = (TextView)findViewById(R.id.textView6);
role = (TextView)findViewById(R.id.textView7);
method = (TextView)findViewById(R.id.textView9);
[B]signinactivity.delegate = this;[/B]
}
However that instance is later never used from what i can tell? You create new instances later in code when its used, where delegate won't be set.
Code:
public void login(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Get Method");
[B]new SigninActivity(this,status,role,0).execute(username,password);[/B]
}
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Post Method");
[B] new SigninActivity(this,status,role,1).execute(username,password);[/B]
}