I have an application with a listview consisting of child objects of type Product, a custom class I've created. I'm trying to set the text of a TextView object called tv_productName to the name of the object selected in the ListView. Im not sure whats going on but I get nothing whenever i click any of the ListView child objects, not even the 'Hello world!' toast.
The following code is in my onCreate() method in the main activity:
PHP:
// Instantiate AsyncTask and execute the download of products_list.xml, then set ListView
ProductListDownloadTask download = new ProductListDownloadTask();
download.execute();
//TODO populate productName, shelfLife, defaultContainer each time selection changes
productsListView = (ListView)findViewById(R.id.productsListView);
tv_productName = (TextView)findViewById(R.id.tv_productName); // product name textview
productsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int position, long mylng) {
final Product listProduct = (Product) myAdapter.getItemAtPosition(position);
tv_productName.setText(listProduct.toString()); // Product object toString() returns name
Toast.makeText(getApplicationContext(), listProduct.toString(), Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Hello world!", Toast.LENGTH_SHORT).show();
}
});
This code is outside of the onCreate method, but still within the main activity class:
PHP:
// This is called when doInBackground() is finished
protected void onPostExecute(Void result) {
//setup our ArrayAdapter using List<Product> and set it to the ListView.
mAdapter = new ProductsAdapter(MainActivity.this, -1, XMLParser.getProductsFromFile(MainActivity.this));
productsListView = (ListView)findViewById(R.id.productsListView);
productsListView.setAdapter(mAdapter);
Log.i("Products", "adapter size = " + mAdapter.getCount());
}
And here are the errors from the logcat:
PHP:
03-17 21:47:04.960 4527-4527/com.estex.kc_app D/ViewGroup﹕ addInArray been called, this = android.widget.ListView{41c9d4e8 VFED.VC. .F....ID 370,390-688,880 #7f090062 app:id/productsListView}call stack =
java.lang.Throwable: addInArray
at android.view.ViewGroup.addInArray(ViewGroup.java:3786)
at android.view.ViewGroup.addViewInner(ViewGroup.java:3740)
at android.view.ViewGroup.addViewInLayout(ViewGroup.java:3687)
at android.widget.ListView.setupChild(ListView.java:1862)
at android.widget.ListView.makeAndAddView(ListView.java:1815)
at android.widget.ListView.fillDown(ListView.java:698)
at android.widget.ListView.fillFromTop(ListView.java:759)
at android.widget.ListView.layoutChildren(ListView.java:1645)
at android.widget.AbsListView.onLayout(AbsListView.java:2149)
at android.view.View.layout(View.java:15125)
at android.view.ViewGroup.layout(ViewGroup.java:4862)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1160)
at android.view.View.layout(View.java:15125)
at android.view.ViewGroup.layout(ViewGroup.java:4862)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
at android.view.View.layout(View.java:15125)
at android.view.ViewGroup.layout(ViewGroup.java:4862)
at android.support.v7.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:502)
at android.view.View.layout(View.java:15125)
at android.view.ViewGroup.layout(ViewGroup.java:4862)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
at android.view.View.layout(View.java:15125)
at android.view.ViewGroup.layout(ViewGroup.java:4862)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1888)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1742)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1651)
at android.view.View.layout(View.java:15125)
at android.view.ViewGroup.layout(ViewGroup.java:4862)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
at android.view.View.layout(View.java:15125)
at android.view.ViewGroup.layout(ViewGroup.java:4862)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2323)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2029)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1192)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6231)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
at android.view.Choreographer.doCallbacks(Choreographer.java:591)
at android.view.Choreographer.doFrame(Choreographer.java:560)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
03-17 21:47:04.962 4527-4527/com.estex.kc_app D/ListView﹕ mSelectorRect.setEmpty in layoutChildren this=android.widget.ListView{41c9d4e8 VFED.VC. .F....ID 370,390-688,880 #7f090062 app:id/productsListView}
03-17 21:47:04.969 4527-4527/com.estex.kc_app D/OpenGLRenderer﹕ prepareDirty (0.00, 0.00, 720.00, 1280.00) opaque 1 <0x60561530>
03-17 21:47:04.979 4527-4527/com.estex.kc_app D/OpenGLRenderer﹕ finish <0x60561530>
03-17 21:47:04.981 4527-4527/com.estex.kc_app V/InputMethodManager﹕ START INPUT: android.widget.ListView{41c9d4e8 VFED.VC. .F....I. 370,390-688,880 #7f090062 app:id/productsListView} ic=null [email protected] controlFlags=#100
03-17 21:47:50.987 4527-4527/com.estex.kc_app D/ActivityThread﹕ ACT-AM_ON_PAUSE_CALLED ActivityRecord{41c3cd68 [email protected] {com.estex.kc_app/com.estex.kc_app.MainActivity}}
03-17 21:47:51.011 4527-4527/com.estex.kc_app D/ActivityThread﹕ ACT-PAUSE_ACTIVITY handled : 0 / [email protected]
03-17 21:47:51.012 4527-4527/com.estex.kc_app D/ActivityThread﹕ ACT-STOP_ACTIVITY_SHOW handled : 0 / [email protected]
03-17 21:47:51.080 4527-4527/com.estex.kc_app V/InputMethodManager﹕ START INPUT: android.widget.ListView{41c9d4e8 VFED.VC. .F....I. 370,390-688,880 #7f090062 app:id/productsListView} ic=null [email protected] controlFlags=#100
03-17 21:47:56.342 4527-4527/com.estex.kc_app D/AbsListView﹕ onWindowFocusChanged: hasWindowFocus=false, this=android.widget.ListView{41c9d4e8 VFED.VC. .F....I. 370,390-688,880 #7f090062 app:id/productsListView}
03-17 21:48:02.609 4527-4542/com.estex.kc_app D/dalvikvm﹕ threadid=12: exiting
03-17 21:48:02.609 4527-4542/com.estex.kc_app D/dalvikvm﹕ threadid=12: bye!
I should probably also mention that I am using a custom ArrayAdapter class to generate the view objects, with each object using a radio button Here is that code:
PHP:
@Override
public View getView(int pos, View convertView, ViewGroup parent){
RelativeLayout row = (RelativeLayout)convertView;
if(row == null){
//No recycled View, we have to inflate one.
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.row_product, null);
}
//Get our View Reference
RadioButton r = (RadioButton)row.findViewById(R.id.productListItem);
/* Set the relevant text in our RadioButton
* a.) When a RadioButton is checked we must call notifyDataSetChanged(), so that all views get updated.
* b.) When a RadioButton is checked we must set a selectedPosition, to keep track of which RadioButton is selected
* c.) Views are recycled inside ListViews. Therefore, their absolute position changes in the ListView.
* Therefore, inside ListAdapter#getView(), we must call setTag() on each RadioButton.
* This allows us to determine the current position of the RadioButton in the list when the RadioButton is clicked.
* RadioButton#setChecked() must be updated inside getView() for new or pre-existing Views. */
r.setText(getItem(pos).toString());
r.setChecked(pos == selectedPosition);
r.setTag(pos);
r.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
selectedPosition = (Integer)view.getTag();
notifyDataSetChanged();
}
});
It might be crashing right before Toast in onItemClick().
Related
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)
when I try to use ShowcaseView I get error
Code:
@override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final ImageButton saveButton = (ImageButton) view.findViewById(R.id.button_Save);
ViewTarget viewTarget = new ViewTarget(saveButton);
showcaseView = new ShowcaseView.Builder(getActivity())
.setTarget(viewTarget)
.setContentTitle("Reset Button")
.setContentText("This will erase all the data in the table except the line that in progress")
.build();
}
when I tried to do the same thing in my fragmentactivity and didn't work, but when I did the same thing but took a view that declared in the fragmentactivity and not in the fragment it worked.
Logcat:
Code:
FATAL EXCEPTION: main
java.lang.IllegalArgumentException: width and height must be > 0
at android.graphics.Bitmap.createBitmap(Bitmap.java:724)
at android.graphics.Bitmap.createBitmap(Bitmap.java:703)
at android.graphics.Bitmap.createBitmap(Bitmap.java:670)
at com.github.amlcurran.showcaseview.ShowcaseView.updateBitmap(ShowcaseView.java:169)
at com.github.amlcurran.showcaseview.ShowcaseView.onGlobalLayout(ShowcaseView.java:343)
at android.view.ViewTreeObserver.dispatchOnGlobalLayout(ViewTreeObserver.java:839)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2050)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1249)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6364)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
at android.view.Choreographer.doCallbacks(Choreographer.java:591)
at android.view.Choreographer.doFrame(Choreographer.java:561)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
I understand what the error said but how can I fix it?
MainActivity.java
Code:
public class MainActivity extends Activity {
private EditText usernameField,passwordField;
private TextView status,role,method;
@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);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// 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");
[B]new SigninActivity(this,status,role,1).execute(username,password);[/B]
}
}
Can someone explain to me what does this line do?
Code:
new SigninActivity(this,status,role,1).execute(username,password);
Here is the SigninActivity code.
SigninActivity.java
Code:
public class SigninActivity extends AsyncTask<String,Void,String>{
private TextView statusField,roleField;
private Context context;
private int byGetOrPost = 0;
//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;
}
protected void onPreExecute(){
}
@Override
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 = "";
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="";
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());
}
}
}
@Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
}
}
* I intentionally remove all the link from the code because I can't post any outside link yet to this account
clonedaccnt said:
MainActivity.java
Code:
public class MainActivity extends Activity {
private EditText usernameField,passwordField;
private TextView status,role,method;
@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);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// 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");
[B]new SigninActivity(this,status,role,1).execute(username,password);[/B]
}
}
Can someone explain to me what does this line do?
Code:
new SigninActivity(this,status,role,1).execute(username,password);
Here is the SigninActivity code.
SigninActivity.java
Code:
public class SigninActivity extends AsyncTask<String,Void,String>{
private TextView statusField,roleField;
private Context context;
private int byGetOrPost = 0;
//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;
}
protected void onPreExecute(){
}
@Override
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 = "";
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="";
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());
}
}
}
@Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
}
}
* I intentionally remove all the link from the code because I can't post any outside link yet to this account
Click to expand...
Click to collapse
new SigninActivity(this,status,role,1).execute(username,password);
this start a new instance of the class SigninActivity passing:
this(context)
status(textview)
role(TextView )
1(integer)
that are requested in SigninActivity(Context context,TextView statusField,TextView roleField,int flag)
and execute tha asynctask passing the variables username and password for doInBackground method
sorry for my English
Nik
nikita1977 said:
new SigninActivity(this,status,role,1).execute(username,password);
this start a new instance of the class SigninActivity passing:
this(context)
status(textview)
role(TextView )
1(integer)
that are requested in SigninActivity(Context context,TextView statusField,TextView roleField,int flag)
and execute tha asynctask passing the variables username and password for doInBackground method
sorry for my English
Nik
Click to expand...
Click to collapse
Code:
new SigninActivity(this,status,role,1).execute(username,password);
Where in the code defines how many parameters this 2 functions accepts?
clonedaccnt said:
Code:
new SigninActivity(this,status,role,1).execute(username,password);
Where in the code defines how many parameters this 2 functions accepts?
Click to expand...
Click to collapse
This is called varargs. The ... In the doInBackground method say that you can receive any number of arguments of a type. In this case string. Inside the method they are used like arrays.
Gesendet von meinem SM-N9005 mit Tapatalk
Ohh I get it! Thanks.
GalaxyInABox said:
This is called varargs. The ... In the doInBackground method say that you can receive any number of arguments of a type. In this case string. Inside the method they are used like arrays.
Gesendet von meinem SM-N9005 mit Tapatalk
Click to expand...
Click to collapse
yes for doinbackground, while for SigninActivity the requested parameters are inside the bracket:
Code:
public SigninActivity(Context context,TextView statusField,
TextView roleField,int flag)
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.
Hello everyone, I have an Android application that allows users to choose a photo for their profile as follows:
public void pickImage(View view) {
Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});
startActivityForResult(chooserIntent, 1);
}
@override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Context context = getApplicationContext();
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
if (data == null) {
//Display an error
return;
}
try {
ImageView im = findViewById(R.id.circularImageView);
uri = data.getData();
im.setImageURI(uri);
String image = uri.toString();
Log.d("ImageS", image);
SqlHelper db = new SqlHelper(this);
Intent i = getIntent();
String userid = i.getStringExtra("Name");
db.updateImage(userid, image);
}catch (Exception e){
}
//Now you can do whatever you want with your inpustream, save it as file, upload to a server, decode a bitmap...
}
}
Everything works fine and when I want to retrieve from my db the image everything works fine:
ImageView im1 = findViewById(R.id.circularImageView2);
im1.setImageURI(null);
String iS = db.getImage(name);
Log.d("ImageR", iS);
//
// Uri uri = Uri.parse(image);
//Log.d("Equals", String.valueOf(iS.equals(String.valueOf(R.drawable.imageuser))));
if(iS.equals(String.valueOf(R.drawable.imageuser))){ //Part to determine whether the user changed it or I use the default one
im1.setImageResource(Integer.parseInt(iS));
}else{
Uri uri = Uri.parse(iS);
ContentResolver contentResolver= getContentResolver();
ParcelFileDescriptor parcelFileDescriptor = null;
try {
parcelFileDescriptor = contentResolver.openFileDescriptor(uri, "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
try {
parcelFileDescriptor.close();
} catch (IOException e) {
e.printStackTrace();
}
im1.setImageBitmap(image);
}
The thing is that when I restart the application, I get the following error when going into an activity in which a user changed the image:
FATAL EXCEPTION: main
Process: com.example.arturopavon.finalproject, PID: 1445
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.arturopavon.finalproject/com.example.arturopavon.finalproject.MainActivity}: java.lang.SecurityException: Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord{47cb71a 1445:com.example.arturopavon.finalproject/u0a294} (pid=1445, uid=10294) requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6501)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.SecurityException: Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord{47cb71a 1445:com.example.arturopavon.finalproject/u0a294} (pid=1445, uid=10294) requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs
at android.os.Parcel.readException(Parcel.java:2004)
at android.os.Parcel.readException(Parcel.java:1950)
at android.app.IActivityManager$Stub$Proxy.getContentProvider(IActivityManager.java:4827)
at android.app.ActivityThread.acquireProvider(ActivityThread.java:5843)
at android.app.ContextImpl$ApplicationContentResolver.acquireUnstableProvider(ContextImpl.java:2526)
at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1783)
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1396)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1249)
at android.content.ContentResolver.openFileDescriptor(ContentResolver.java:1102)
at android.content.ContentResolver.openFileDescriptor(ContentResolver.java:1056)
at com.example.arturopavon.finalproject.MainActivity.onCreate(MainActivity.java:126)
at android.app.Activity.performCreate(Activity.java:7026)
at android.app.Activity.performCreate(Activity.java:7017)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1215)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
I have permissions set for my app to read internal storage but it is like it is not working after rebooting.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission
android:name="android.permission.MANAGE_DOCUMENTS"/>
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.MANAGE_DOCUMENTS};
for(String permission: permissions){
if (ContextCompat.checkSelfPermission(this, permission)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
permission)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(this,
permissions, 0);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
}
Any ideas on how to solve this?
I think the gallery app gives you temporary access to the photo (search FLAG_GRANT_READ_URI_PERMISSION).
As the solution, you can copy the photo into application folder and keep it there.
Your logcat says "requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs".
Have a look in the following link. It should give you an idea or possible solution...
https://stackoverflow.com/a/22178386