[Q] java.lang.NullPointerException in Android Webservice - Java for Android App Development

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)

Related

Application crash on startup

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?

[Q] How download file in internal storage?

Hello, I want to download a xml file in local storage that I will parse.
The code is this
URL website = new URL("http://juventus.com/rss/news/ita.xml");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(c.getFilesDir()+"/eng.xml");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
This is called in doInBackground() of a AsyncTask class.
I get this error:
08-01 22:17:40.061: E/AndroidRuntime(9002): java.lang.RuntimeException: An error occured while executing doInBackground()
08-01 22:17:40.061: E/AndroidRuntime(9002): Caused by: java.lang.IllegalArgumentException: position=0 count=9223372036854775807
08-01 22:17:40.061: E/AndroidRuntime(9002): at java.nio.FileChannelImpl.transferFrom(FileChannelImpl.java:359)
What I do wrong?
I also tried this:
URL website = new URL("http://juventus.com/rss/news/ita.xml");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = c.openFileOutput("eng.xml", Context.MODE_PRIVATE);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
Hope you help me.
Thanks!
Try this...
Code:
URLConnection conn;
Log.d(TAG, "onDownload....path is: " + path);
try {
URL url = new URL(path);
conn = url.openConnection();
contentLength = conn.getContentLength();
DataInputStream in = new DataInputStream(conn.getInputStream());
Log.d(TAG, "Buffering the received stream(size=" + contentLength);
if (contentLength != -1) {
buffer = new byte[contentLength];
in.readFully(buffer);
in.close();
}else{
result = false;
return;
}
if (buffer.length > 0) {
Log.d(TAG,
"onDownload. Writing file to files dir,");
DataOutputStream out;
FileOutputStream fos = context.openFileOutput(fileName,
Context.MODE_PRIVATE);
Log.d(TAG, "Writing from buffer to the new file.." + fileName);
out = new DataOutputStream(fos);
out.write(buffer);
out.flush();
out.close();
result = true;
Edit: Here I am returning a boolean to indicate successful download.

[Q] Insert multiple records using webservice in android

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

[Q] need help im new to the app dev world

im having issues with my coding for an app im trying to develop and since im a noob i cant just identify errors i would like to post my logcat but cause of the errors it wont run .... my code is for a login and registration please just point out my errors im down to learn and understand whats going on ....
my login activity
public class LoginScreen extends Activity {
Button btnSignIn ;
TextView registerScreen;
LoginDataBaseAdapter loginDataBaseAdapter;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setting default screen to login.xml
setContentView(R.layout.login);
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(), SignUp.class);
startActivity(i);
// create a instance of SQLite Database
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
// Get The Reference Of Buttons
btnSignIn = (Button) findViewById(R.id.btnLogin);
}
// Methods to handleClick Event of Sign In Button
public void signIn(View V) {
try{
final Dialog dialog = new Dialog(LoginScreen.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the References of views
final EditText loginUsername = (EditText) dialog
.findViewById(R.id.liUsername);
final EditText loginPassword = (EditText) dialog
.findViewById(R.id.liPassword);
Button btnSignIn = (Button) dialog.findViewById(R.id.btnLogin);
}catch(Exception e){
Log.e("tag", e.getMessage());
}
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get The User name and Password
String username = loginUsername.getText().toString();
String password = loginPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword = loginDataBaseAdapter
.getSingleEntry(username);
// check if the Stored password matches with Password entered by
// user
if (password.equals(storedPassword)) {
Toast.makeText(LoginScreen.this,
"Congrats: Login Successful", Toast.LENGTH_LONG)
.show();
dialog.dismiss();
} else {
Toast.makeText(LoginScreen.this,
"User Name or Password does not match",
Toast.LENGTH_LONG).show();
dialog.show();
}
}
@override
public void startActivity(Intent intent) {
// TODO Auto-generated method stub
try{
super.startActivity(intent);
Intent mainpage = new Intent(LoginScreen.this, MainPage.class);
startActivity(mainpage);
finish();
}catch(Exception e){
Log.e("tag", e.getMessage());
}
}
@override
protected void onDestroy() {
try{
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy - Error", e.getMessage());
} }
my registration activity
public class SignUp extends Activity {
EditText reg_fullname, reg_username, reg_email, reg_password, reg_confirmpassword;
Button btnRegister;
LoginDataBaseAdapter loginDataBaseAdapter;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.signup);
TextView loginScreen = (TextView) findViewById(R.id.link_to_login);
// Listening to Login Screen link
loginScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Closing registration screen
// Switching to Login Screen/closing register screen
finish();
// get Instance of Database Adapter
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
// Get References of Views
reg_fullname = (EditText) findViewById(R.id.reg_fullname);
reg_username = (EditText) findViewById(R.id.reg_username);
reg_email = (EditText) findViewById(R.id.reg_email);
reg_password = (EditText) findViewById(R.id.reg_password);
reg_confirmpassword = (EditText) findViewById(R.id.reg_confirmpassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String fullname = reg_fullname.getText().toString();
String username = reg_username.getText().toString();
String password = reg_password.getText().toString();
String email = reg_email.getText().toString();
String confirmPassword = reg_confirmpassword.getText()
.toString();
// check if any of the fields are vacant
if (username.equals("") || password.equals("")
|| confirmPassword.equals("")) {
Toast.makeText(getApplicationContext(), "Field Vaccant",
Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if (!password.equals(confirmPassword)) {
Toast.makeText(getApplicationContext(),
"Password does not match", Toast.LENGTH_LONG)
.show();
return;
} else {
// Save the Data in Database
loginDataBaseAdapter.insertEntry(username, password);
Toast.makeText(getApplicationContext(),
"Account Successfully Created ", Toast.LENGTH_LONG)
.show();
}
}
@override
protected void onDestroy() {
// TODO Auto-generated method stub
try{
super.onDestroy();
loginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy - Error", e.getMessage());
}}
Could you please be more specific about your errors? Error output from eclipse in case of compile error or if it did compile but has runtime errors then post the logcat output for example. This would help
Edit::
Well for the first i wouldnt distribute the onclick listeners so much, instead let your activity implement OnClickListener so you have one onClick method for all, that is far more ordered. Then put a switch inside it: switch (v.getId()) { //v is the clicked button
case R.id.btnLogin:
//login button code here
case R.id. .... :
......
}
Then it is more structured
---------------------------------
Phone : Nexus 4
OS :
- KitKat 4.4.4 stock
- Xposed: 58(app_process); 54(bridge)
- SU: SuperSU
- no custom recovery
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk
Wich IDE are you using ?
If you can't run it it means that it's a compilation failure, probably a syntax error. Most of Java IDE tells you where is the error even before you run it.
updated
WaitTobi said:
*Updated*here's where im at now in regard to my register/loginscreen right at this moment i still cannot run the app and test it out at the moment my login screen seems clean no errors in and but still my register class still has a couple errors one is underlined class name saying to "add implemented methods" and the other one is at my "TextView loginScreen;" right under the ";" and it says "syntax error, insert "}" to complete
ClassBody"
and also i would like to now how to make the classes actually connect to eachother... also Im using eclipse to run my project.. and if theres anything else that just looks wrong please point it out so i the future ill notice them
my login activity
public class LoginScreen extends Activity implements OnClickListener{
Button btnLogin ;
TextView registerScreen;
LoginDataBaseAdapter LoginDataBaseAdapter;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setting default screen to login.xml
setContentView(R.layout.login);
TextView registerScreen = (TextView) this.findViewById(R.id.link_to_register);
Button btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(this);
registerScreen.setOnClickListener(new OnClickListener() {
@override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(LoginScreen.this, SignUp.class));
}
});
// create a instance of SQLite Database
LoginDataBaseAdapter = new LoginDataBaseAdapter(this);
LoginDataBaseAdapter = LoginDataBaseAdapter.open();
}
// Methods to handleClick Event of Sign In Button
public void Login(View V) {
final Dialog dialog = new Dialog(LoginScreen.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the References of views
final EditText loginUsername = (EditText) dialog
.findViewById(R.id.liUsername);
final EditText loginPassword = (EditText) dialog
.findViewById(R.id.liPassword);
// get The User name and Password
String username = loginUsername.getText().toString();
String password = loginPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword = LoginDataBaseAdapter
.getSingleEntry(username);
// check if the Stored password matches with Password entered by
// user
if (password.equals(storedPassword)) {
Toast.makeText(LoginScreen.this,
"Congrats: Login Successful", Toast.LENGTH_LONG)
.show();
dialog.dismiss();
} else {
Toast.makeText(LoginScreen.this,
"User Name or Password does not match",
Toast.LENGTH_LONG).show();
}
dialog.show();
}
@override
public void startActivity(Intent intent) {
// TODO Auto-generated method stub
try{
super.startActivity(intent);
Intent mainpage = new Intent(LoginScreen.this, MainPage.class);
startActivity(mainpage);
finish();
}catch(Exception e){
Log.e("StartActivity-Mainpage-error", e.getMessage());
}}
@override
protected void onDestroy() {
try{
super.onDestroy();
LoginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy - Error", e.getMessage());
}
}
@override
public void onClick(View v) {
// TODO Auto-generated method stub
}}
my registration activity
public class SignUp extends Activity implements OnClickListener{
EditText reg_fullname, reg_username, reg_email, reg_password, reg_confirmpassword;
Button btnRegister;
LoginDataBaseAdapter LoginDataBaseAdapter;
TextView loginScreen;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.signup);
reg_fullname = (EditText) findViewById(R.id.reg_fullname);
reg_username = (EditText) findViewById(R.id.reg_username);
reg_email = (EditText) findViewById(R.id.reg_email);
reg_password = (EditText) findViewById(R.id.reg_password);
reg_confirmpassword = (EditText) findViewById(R.id.reg_confirmpassword);
TextView loginScreen = (TextView) this.findViewById(R.id.link_to_login);
// Listening to Login Screen link
btnRegister = (Button) findViewById(R.id.btnRegister);
// Get References of Views
loginScreen.setOnClickListener(new OnClickListener() {
@override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(SignUp.this, LoginScreen.class));
finish();
}
});
// get Instance of Database Adapter
LoginDataBaseAdapter = new LoginDataBaseAdapter(this);
LoginDataBaseAdapter = LoginDataBaseAdapter.open();
String fullname = reg_fullname.getText().toString();
String username = reg_username.getText().toString();
String password = reg_password.getText().toString();
String email = reg_email.getText().toString();
String confirmPassword = reg_confirmpassword.getText()
.toString();
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// check if any of the fields are vacant
try{
if (username.equals("") || password.equals("")
|| confirmPassword.equals("")) {
Toast.makeText(getApplicationContext(), "Field Vaccant",
Toast.LENGTH_LONG).show();
return;
// check if both password matches
if (!password.equals(confirmPassword)) {
Toast.makeText(getApplicationContext(),
"Password does not match", Toast.LENGTH_LONG)
.show();
return;
} else {
// Save the Data in Database
LoginDataBaseAdapter.insertEntry(username, password);
Toast.makeText(getApplicationContext(),
"Account Successfully Created ", Toast.LENGTH_LONG)
.show();
}}
}catch(Exception e){
Log.e("onClickRegister-error", e.getMessage());
}
loginScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
try{ // Closing registration screen
// Switching to Login Screen/closing register screen
finish();
}catch(Exception e){
Log.e("onClickRegister button-error", e.getMessage());
}}
@override
protected void onDestroy() {
// TODO Auto-generated method stub
try{
super.onDestroy();
LoginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy SignUp - Error", e.getMessage());
}
}
@override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Click to expand...
Click to collapse
Hvedrung said:
Wich IDE are you using ?
If you can't run it it means that it's a compilation failure, probably a syntax error. Most of Java IDE tells you where is the error even before you run it.
Click to expand...
Click to collapse
IM using eclipse for development
I did a couple of corrections from what I see, in red.
WaitTobi said:
*Updated*here's where im at now in regard to my register/loginscreen right at this moment i still cannot run the app and test it out at the moment my login screen seems clean no errors in and but still my register class still has a couple errors one is underlined class name saying to "add implemented methods" and the other one is at my "TextView loginScreen;" right under the ";" and it says "syntax error, insert "}" to complete
ClassBody"
and also i would like to now how to make the classes actually connect to eachother... also Im using eclipse to run my project.. and if theres anything else that just looks wrong please point it out so i the future ill notice them
Code:
my login activity
public class LoginScreen extends Activity [COLOR="red"][STRIKE]implements OnClickListener[/STRIKE][/COLOR]{
[COLOR="red"]private[/COLOR] Button btnLogin ;
[COLOR="red"]private [/COLOR]TextView registerScreen;
[COLOR="red"]private [/COLOR]LoginDataBaseAdapter LoginDataBaseAdapter;
[COLOR="red"]private LoginDataBaseAdapter dataBaseAdapter; // you need it here instead of in your method so you can access it everywhere[/COLOR]
[COLOR="red"]// you don't have to make them private but it is nicer and common practice ;)[/COLOR]
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setting default screen to login.xml
setContentView(R.layout.login);
[COLOR="red"][STRIKE]TextView[/STRIKE][/COLOR] registerScreen = (TextView) this.findViewById(R.id.link_to_register);
[COLOR="red"]// you initialize a new variable in the scope of the method instead of using the instance vars you created above![/COLOR]
[COLOR="red"][STRIKE]Button[/STRIKE][/COLOR] btnLogin = (Button) findViewById(R.id.btnLogin);
[COLOR="red"]// what you were doing here is not right, set the OnClickListener only for the button: (I prefer having it locally and not the whole class)[/COLOR]
[COLOR="red"][STRIKE]btnLogin.setOnClickListener(this);[/STRIKE][/COLOR]
[COLOR="red"][STRIKE]registerScreen[/STRIKE]btnLogin[/COLOR].setOnClickListener(new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
// This is called whenever btnLogin is clicked:
startActivity(new Intent(LoginScreen.this, SignUp.class));
}
});
[COLOR="red"]// did you perhaps follow [URL="http://stackoverflow.com/questions/19152998/android-limiting-signup-for-one-user"]this question?[/URL] you should copy the LoginDataBaseAdapter class from it into your project if you don't have it already...[/COLOR]
// create a instance of SQLite Database
[COLOR="red"][STRIKE]LoginDataBaseAdapter [/STRIKE][/COLOR][COLOR="red"]dataBaseAdapter[/COLOR] = new LoginDataBaseAdapter(this);
[COLOR="red"][STRIKE]LoginDataBaseAdapter = [/STRIKE][/COLOR][COLOR="red"]dataBaseAdapter[/COLOR].open();
}
// Methods to handleClick Event of Sign In Button
public void [COLOR="red"][STRIKE]L[/STRIKE]l[/COLOR]ogin(View V) {[COLOR="red"]// method names start with lowercase![/COLOR]
[COLOR="red"]// you should use a builder for an alert dialog instead, read [URL="http://developer.android.com/guide/topics/ui/dialogs.html"]this doc about it![/URL][/COLOR]
final Dialog dialog = new Dialog(LoginScreen.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
[COLOR="red"]// again, read the doc, it [URL="http://developer.android.com/guide/topics/ui/dialogs.html#PassingEvents"]even tells you how to pass your login data back![/URL] You could also consider running this code in your dialog ;)[/COLOR]
// get the References of views
final EditText loginUsername = (EditText) dialog
.findViewById(R.id.liUsername);
final EditText loginPassword = (EditText) dialog
.findViewById(R.id.liPassword);
// get The User name and Password
String username = loginUsername.getText().toString();
String password = loginPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword = LoginDataBaseAdapter
.getSingleEntry(username);
// check if the Stored password matches with Password entered by
// user
if (password.equals(storedPassword)) {
Toast.makeText(LoginScreen.this,
"Congrats: Login Successful", Toast.LENGTH_LONG)
.show();
dialog.dismiss();
} else {
Toast.makeText(LoginScreen.this,
"User Name or Password does not match",
Toast.LENGTH_LONG).show();
}
dialog.show();
}
[COLOR="red"][STRIKE] [user=439709]@override[/user]
public void startActivity(Intent intent) {
// TODO Auto-generated method stub
try{
super.startActivity(intent);
Intent mainpage = new Intent(LoginScreen.this, MainPage.class);
startActivity(mainpage);
finish();
}catch(Exception e){
Log.e("StartActivity-Mainpage-error", e.getMessage());
}}[/STRIKE]// what the hell are you trying to do here? let android do its work alone![/COLOR]
[user=439709]@override[/user]
protected void onDestroy() {
try{
super.onDestroy();
LoginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy - Error", e.getMessage());
}
}
[COLOR="red"][STRIKE]
[user=439709]@override[/user]
public void onClick(View v) {
// TODO Auto-generated method stub
}
[/STRIKE]// ne need for that since we have our OnClickListener locally in onCreate()[/COLOR]
}
my registration activity
public class SignUp extends Activity implements OnClickListener{
[COLOR="red"]private [/COLOR]EditText reg_fullname, reg_username, reg_email, reg_password, reg_confirmpassword;
[COLOR="red"]private [/COLOR]Button btnRegister;
[COLOR="red"]private [/COLOR]LoginDataBaseAdapter [COLOR="red"][STRIKE]LoginD[/STRIKE]d[/COLOR]ataBaseAdapter; [COLOR="red"]// I prefer short names and variables are always lower case![/COLOR]
[COLOR="red"]private [/COLOR]TextView loginScreen;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.signup);
reg_fullname = (EditText) findViewById(R.id.reg_fullname);
reg_username = (EditText) findViewById(R.id.reg_username);
reg_email = (EditText) findViewById(R.id.reg_email);
reg_password = (EditText) findViewById(R.id.reg_password);
reg_confirmpassword = (EditText) findViewById(R.id.reg_confirmpassword);
[COLOR="red"][STRIKE]TextView[/STRIKE][/COLOR] loginScreen = (TextView) this.findViewById(R.id.link_to_login); // s.a.
// Listening to Login Screen link
btnRegister = (Button) findViewById(R.id.btnRegister);
// Get References of Views
[COLOR="red"][STRIKE]loginScreen[/STRIKE]btnRegister[/COLOR].setOnClickListener(new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(SignUp.this, LoginScreen.class));
[COLOR="red"][STRIKE]finish();[/STRIKE]// no need for that[/COLOR]
}
});
// get Instance of Database Adapter
[COLOR="red"][STRIKE]LoginD[/STRIKE]d[/COLOR]ataBaseAdapter = new LoginDataBaseAdapter(this);
[COLOR="red"][STRIKE]LoginDataBaseAdapter = LoginD[/STRIKE]d[/COLOR]ataBaseAdapter.open();
[COLOR="red"]final [/COLOR]String fullname = reg_fullname.getText().toString();[COLOR="red"]// I think they have to be final to be used in th onClickListener[/COLOR]
[COLOR="red"]final [/COLOR]String username = reg_username.getText().toString();
[COLOR="red"]final [/COLOR]String password = reg_password.getText().toString();
[COLOR="red"]final [/COLOR]String email = reg_email.getText().toString();
[COLOR="red"]final [/COLOR]String confirmPassword = reg_confirmpassword.getText()
.toString();
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// check if any of the fields are vacant
try{
if (username.equals("") || password.equals("")
|| confirmPassword.equals("")) {
Toast.makeText(getApplicationContext(), "Field Vaccant",
Toast.LENGTH_LONG).show();
return;
[COLOR="red"]} else// closing if(username...[/COLOR]
// check if both password matches
if (!password.equals(confirmPassword)) {
Toast.makeText(getApplicationContext(),
"Password does not match", Toast.LENGTH_LONG)
.show();
return;
} else {
// Save the Data in Database
[COLOR="red"][STRIKE]LoginD[/STRIKE]d[/COLOR]ataBaseAdapter.insertEntry(username, password);
Toast.makeText(getApplicationContext(),
"Account Successfully Created ", Toast.LENGTH_LONG)
.show();
}[COLOR="red"][STRIKE]}[/STRIKE][/COLOR]
}catch(Exception e){
Log.e("onClickRegister-error", e.getMessage());
}
[COLOR="red"]// ??? that is a text view and should not get a clicklistener... not getting where this code should go lol[/COLOR]
loginScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
try{ // Closing registration screen
// Switching to Login Screen/closing register screen
finish();
}catch(Exception e){
Log.e("onClickRegister button-error", e.getMessage());
}}
[user=439709]@override[/user]
protected void onDestroy() {
// TODO Auto-generated method stub
try{
super.onDestroy();
LoginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy SignUp - Error", e.getMessage());
}
}
[COLOR="red"][STRIKE]
[user=439709]@override[/user]
public void onClick(View v) {
// TODO Auto-generated method stub
}[/STRIKE][/COLOR]
}
Click to expand...
Click to collapse
It seems like you need a bit more practice in Java , there you go...
SimplicityApks said:
I did a couple of corrections from what I see, in red.
It seems like you need a bit more practice in Java...
Click to expand...
Click to collapse
thanks means alot helped a lot im starting to notice the errors im actually laughin at myself with a couple of the errors.... im still getting a error in regard to the last couple curly brackets "Multiple markers at this line
- Syntax error, insert ";" to complete
Statement
- Syntax error, insert "}" to complete
ClassBody
- Syntax error, insert ")" to complete
Expression"
i know it just a } somewhere or something but how can u just be able to tell where it need to be placed
WaitTobi said:
thanks means alot helped a lot im starting to notice the errors im actually laughin at myself with a couple of the errors.... im still getting a error in regard to the last couple curly brackets "Multiple markers at this line
- Syntax error, insert ";" to complete
Statement
- Syntax error, insert "}" to complete
ClassBody
- Syntax error, insert ")" to complete
Expression"
i know it just a } somewhere or something but how can u just be able to tell where it need to be placed
Click to expand...
Click to collapse
Well it tells you which line it is, take a look at it (probably where you close your second on click listener in the second activity). Remember that each bracket, curly or round has to get closed before the statement can be finished with a ; . Another thing I just noticed, you now set the onClickListener for btnRegister twice in the second activity, you can't do that. Probably the code of the first one should be executed after the code in the other click listener.
SimplicityApks said:
Well it tells you which line it is, take a look at it (probably where you close your second on click listener in the second activity). Remember that each bracket, curly or round has to get closed before the statement can be finished with a ; . Another thing I just noticed, you now set the onClickListener for btnRegister twice in the second activity, you can't do that. Probably the code of the first one should be executed after the code in the other click listener.
Click to expand...
Click to collapse
okay got it i put the first one click into the second one and i got rid of the textview onclick your were curoius about now i can finally run the app but right on the start up i get the runtime error. my logcat said"
08-19 06:49:56.201: D/AndroidRuntime(12905): Shutting down VM
08-19 06:49:56.201: W/dalvikvm(12905): threadid=1: thread exiting with uncaught exception (group=0x41a24c08)
08-19 06:49:56.206: E/AndroidRuntime(12905): FATAL EXCEPTION: main
08-19 06:49:56.206: E/AndroidRuntime(12905): Process: com.Flawed.hearmeout, PID: 12905
08-19 06:49:56.206: E/AndroidRuntime(12905): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Flawed.hearmeout/com.Flawed.hearmeout.LoginScreen}: java.lang.NullPointerException
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread.access$900(ActivityThread.java:175)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.os.Handler.dispatchMessage(Handler.java:102)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.os.Looper.loop(Looper.java:146)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread.main(ActivityThread.java:5602)
08-19 06:49:56.206: E/AndroidRuntime(12905): at java.lang.reflect.Method.invokeNative(Native Method)
08-19 06:49:56.206: E/AndroidRuntime(12905): at java.lang.reflect.Method.invoke(Method.java:515)
08-19 06:49:56.206: E/AndroidRuntime(12905): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
08-19 06:49:56.206: E/AndroidRuntime(12905): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
08-19 06:49:56.206: E/AndroidRuntime(12905): at dalvik.system.NativeStart.main(Native Method)
08-19 06:49:56.206: E/AndroidRuntime(12905): Caused by: java.lang.NullPointerException
08-19 06:49:56.206: E/AndroidRuntime(12905): at com.Flawed.hearmeout.LoginScreen.onCreate(LoginScreen.java:44)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.Activity.performCreate(Activity.java:5451)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
08-19 06:49:56.206: E/AndroidRuntime(12905): ... 11 more
"
how do i realize the issue thru logcat and solution, i know im probably bothering you by now and getting on your nerve but i apologize im just tryna to understand this a bit more
WaitTobi said:
okay got it i put the first one click into the second one and i got rid of the textview onclick your were curoius about now i can finally run the app but right on the start up i get the runtime error. my logcat said"
08-19 06:49:56.201: D/AndroidRuntime(12905): Shutting down VM
08-19 06:49:56.201: W/dalvikvm(12905): threadid=1: thread exiting with uncaught exception (group=0x41a24c08)
08-19 06:49:56.206: E/AndroidRuntime(12905): FATAL EXCEPTION: main
08-19 06:49:56.206: E/AndroidRuntime(12905): Process: com.Flawed.hearmeout, PID: 12905
08-19 06:49:56.206: E/AndroidRuntime(12905): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Flawed.hearmeout/com.Flawed.hearmeout.LoginScreen}: java.lang.NullPointerException
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread.access$900(ActivityThread.java:175)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.os.Handler.dispatchMessage(Handler.java:102)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.os.Looper.loop(Looper.java:146)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread.main(ActivityThread.java:5602)
08-19 06:49:56.206: E/AndroidRuntime(12905): at java.lang.reflect.Method.invokeNative(Native Method)
08-19 06:49:56.206: E/AndroidRuntime(12905): at java.lang.reflect.Method.invoke(Method.java:515)
08-19 06:49:56.206: E/AndroidRuntime(12905): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
08-19 06:49:56.206: E/AndroidRuntime(12905): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
08-19 06:49:56.206: E/AndroidRuntime(12905): at dalvik.system.NativeStart.main(Native Method)
08-19 06:49:56.206: E/AndroidRuntime(12905): Caused by: java.lang.NullPointerException
08-19 06:49:56.206: E/AndroidRuntime(12905): at com.Flawed.hearmeout.LoginScreen.onCreate(LoginScreen.java:44)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.Activity.performCreate(Activity.java:5451)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
08-19 06:49:56.206: E/AndroidRuntime(12905): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
08-19 06:49:56.206: E/AndroidRuntime(12905): ... 11 more
"
how do i realize the issue thru logcat and solution, i know im probably bothering you by now and getting on your nerve but i apologize im just tryna to understand this a bit more
Click to expand...
Click to collapse
Well read the whole thing, at the line in bold it tells you that you have a NullPointerException at line 44 of the Login activity. You should read nikwen's guide on logcats and debugging .
SimplicityApks said:
Well read the whole thing, at the line in bold it tells you that you have a NullPointerException at line 44 of the Login activity. You should read nikwen's guide on logcats and debugging .
Click to expand...
Click to collapse
thanks those links are really helping
SimplicityApks said:
Well read the whole thing, at the line in bold it tells you that you have a NullPointerException at line 44 of the Login activity. You should read nikwen's guide on logcats and debugging .
Click to expand...
Click to collapse
okay im having an issue with llogin button and register do you have a link or any reading i can check out to make sure my signup and login button work and actually save info and go to my main activity after it either saves the registration or logins in successfully
WaitTobi said:
okay im having an issue with llogin button and register do you have a link or any reading i can check out to make sure my signup and login button work and actually save info and go to my main activity after it either saves the registration or logins in successfully
Click to expand...
Click to collapse
If you want to check that some data is actually present then just write it to the log. Eg.
Log.V("Testing", someString);
If it is working then someString will be printed after the "Testing" tag. If its not then you should check your logcat to find out why not.

Can Someone Help Me On Finding The Cause Of Crash Of This Code

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]
}

Categories

Resources