I need some help with ION and JSON PHP - Java for Android App Development

Hello, i use ION to talk to my Server and send Data with JSON over POST. And I recieve a JSON.
That is my Code.
Code:
package com.androidstudio.myapplication3.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import org.json.JSONObject;
import org.json.JSONException;
public class MainActivity extends Activity {
String games_n;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONObject json = new JSONObject();
try {
json.put("nick", "Johannes");
} catch (JSONException e) {
e.printStackTrace();
}
try {
Ion.with(getApplicationContext())
.load("http://example.com/post")
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JSONObject>() {
@Override
public void onCompleted(Exception f, JSONObject result) {
try {
games_n = result.optString("games_up");
} catch(Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception IO) {
IO.getCause();
}
}
and that is the error i get:
Code:
error: cannot access TypeToken
class file for com.google.gson.reflect.TypeToken not found
I also make a picture of the wrong Part. Please help me thx.
https://github.com/koush/ion

I changed my code to:
Code:
JsonObject json = new JsonObject();
json.addProperty("nick", nick);
Ion.with(getApplicationContext())
.load("*****")
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
@Override
public void onCompleted(Exception e, JsonObject result) {
try {
JsonArray personen = result.getAsJsonArray("user");
for (int i = 0; i < personen.size(); i++) {
JsonObject user = personen.get(i).getAsJsonObject();
mTest.setText(user.get("games_up").getAsString());
}
} catch (Exception f) {
f.printStackTrace();
}
}
});
Now there is no Error in Android Studio, but the App stops when i execute it...

Any error logs? Or is the data too huge and needs to be ran on asynctask? You need to provide an example data from your server.

frenzyboi said:
Any error logs? Or is the data too huge and needs to be ran on asynctask? You need to provide an example data from your server.
Click to expand...
Click to collapse
Ok, the php file is: (I make $nick to Johannes normaly i read this out of the POST Methode.
PHP:
<?php
/*$json = $_SERVER['HTTP_JSON'];
var_dump($json);
$data = json_decode($json);
var_dump($data);
$nick = $data->nick;*/
$nick = 'Johannes';
include 'db_connect.php';
$sql = mysql_query('SELECT * FROM user WHERE nick = "'.$nick.'"') or die(mysql_error());
while ($zeile = mysql_fetch_array($sql)) {
$id = $zeile["id"];
$games = $zeile["games"];
$games_up = $zeile["games_up"];
$coins = $zeile["coins"];
}
$user = array();
$user = NULL;
$user["games"] = $games;
$user["games_up"] = $games_up;
$user["coins"] = $coins;
echo json_encode(array('user'=>$user));
?>
That is an example for the JSON what is recieved:
HTML:
{"user":{"games":"","games_up":"14,","coins":"1500"}}
And that is the code I actually have, there is no error message in AndroidStudio and the App starts and Don't crash, but there is also no data...
Code:
package com.androidstudio.myapplication2.app;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
public class games extends Activity {
private TextView mTest;
@Override
public void onCreate(Bundle saveInstanceState) {
mTest = (TextView)findViewById(R.id.test2);
super.onCreate(saveInstanceState);
setContentView(R.layout.games);
JsonObject json = new JsonObject();
json.addProperty("nick", "Johannes");
Log.e("nick", "johannes");
Ion.with(getApplicationContext())
.load("http://kulturverein-mgh.de/test/get_user.php")
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
@Override
public void onCompleted(Exception e, JsonObject result) {
try {
JsonArray personen = result.getAsJsonArray("Spiel");
for (int i = 0; i < personen.size(); i++) {
Log.e("hallo", "as");
JsonObject user = personen.get(i).getAsJsonObject();
mTest.setText(user.get("frage1").getAsString());
}
} catch (Exception f) {
f.printStackTrace();
}
}
});
}
}
This is the LOG:
05-13 06:30:08.277 16105-16105/com.androidstudio.myapplication2.app W/InputMethodManager﹕ Bind error! start to finishInputLocked and closeCurrentInput
05-13 06:30:08.277 16105-16105/com.androidstudio.myapplication2.app W/InputMethodManager﹕ Bind error! end to finishInputLocked and closeCurrentInput
05-13 06:30:14.007 16357-16357/com.androidstudio.myapplication2.app I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:320>: EGL 1.4 QUALCOMM Build: I0404c4692afb8623f95c43aeb6d5e13ed4b30ddbDate: 11/06/13
05-13 06:30:14.027 16357-16357/com.androidstudio.myapplication2.app D/OpenGLRenderer﹕ Enabling debug mode 0
05-13 06:30:17.227 16357-16357/com.androidstudio.myapplication2.app E/nick﹕ johannes
05-13 06:30:17.447 16357-16357/com.androidstudio.myapplication2.app W/System.err﹕ java.lang.NullPointerException
05-13 06:30:17.447 16357-16357/com.androidstudio.myapplication2.app W/System.err﹕ at com.androidstudio.myapplication2.app.games$1.onCompleted(games.java:38)
05-13 06:30:17.447 16357-16357/com.androidstudio.myapplication2.app W/System.err﹕ at com.androidstudio.myapplication2.app.games$1.onCompleted(games.java:33)
05-13 06:30:17.447 16357-16357/com.androidstudio.myapplication2.app W/System.err﹕ at com.koushikdutta.async.future.SimpleFuture.handleCallbackUnlocked(SimpleFuture.java:82)
05-13 06:30:17.447 16357-16357/com.androidstudio.myapplication2.app W/System.err﹕ at com.koushikdutta.async.future.SimpleFuture.setComplete(SimpleFuture.java:118)
05-13 06:30:17.447 16357-16357/com.androidstudio.myapplication2.app W/System.err﹕ at com.koushikdutta.async.future.SimpleFuture.setComplete(SimpleFuture.java:105)
05-13 06:30:17.447 16357-16357/com.androidstudio.myapplication2.app W/System.err﹕ at com.koushikdutta.ion.IonRequestBuilder$1.run(IonRequestBuilder.java:252)
05-13 06:30:17.447 16357-16357/com.androidstudio.myapplication2.app W/System.err﹕ at com.koushikdutta.async.AsyncServer$RunnableWrapper.run(AsyncServer.java:52)
05-13 06:30:17.447 16357-16357/com.androidstudio.myapplication2.app W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:733)
05-13 06:30:17.447 16357-16357/com.androidstudio.myapplication2.app W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
05-13 06:30:17.447 16357-16357/com.androidstudio.myapplication2.app W/System.err﹕ at android.os.Looper.loop(Looper.java:136)
05-13 06:30:17.447 16357-16357/com.androidstudio.myapplication2.app W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5017)
05-13 06:30:17.447 16357-16357/com.androidstudio.myapplication2.app W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
05-13 06:30:17.447 16357-16357/com.androidstudio.myapplication2.app W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
05-13 06:30:17.447 16357-16357/com.androidstudio.myapplication2.app W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:798)
05-13 06:30:17.447 16357-16357/com.androidstudio.myapplication2.app W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:614)
05-13 06:30:17.447 16357-16357/com.androidstudio.myapplication2.app W/System.err﹕ at miui.dexspy.DexspyInstaller.main(DexspyInstaller.java:171)
05-13 06:30:17.447 16357-16357/com.androidstudio.myapplication2.app W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
Click to expand...
Click to collapse

Related

Need help with a title menu

Hey everyone,
I'm working on a minesweeper-like game for my independent project in school this semester, but I'm running into a but of trouble with the title screen. What I'm trying to do is have a seperate activity launch for MainGame.java and Options.java when their respective buttons are clicked. When I click on Start, it launches the MainGame activity, but whenever I click on Options the app force closes. It's really weird because I'm doing essentially the same thing with both buttons. Here's the code for Title.java, let me know if you need to see anything else:
Code:
package com.freekyfrogy.treasure;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Title extends Activity implements OnClickListener {
Button buttonStart, buttonScores, buttonOptions, buttonExit;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.title);
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStart.setOnClickListener(this);
buttonScores = (Button) findViewById(R.id.buttonScores);
buttonScores.setOnClickListener(this);
buttonOptions = (Button) findViewById(R.id.buttonOptions);
buttonOptions.setOnClickListener(this);
buttonExit = (Button) findViewById(R.id.buttonExit);
buttonExit.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonStart:
if(buttonStart.isPressed()){
startActivity(new Intent(getApplicationContext(),MainGame.class));
}
break;
case R.id.buttonScores:
if(buttonScores.isPressed()){
Toast.makeText(this, R.string.toastComingSoon, Toast.LENGTH_SHORT).show();
}
break;
case R.id.buttonOptions:
if(buttonOptions.isPressed()){
startActivity(new Intent(getApplicationContext(), Options.class));
}
break;
case R.id.buttonExit:
if(buttonExit.isPressed()){
finish();
}
break;
}
}
}
If i had to guess id say you didnt declare both activities in your manifest...
what does the debugger say is the problem?
I declared them both in the manifest, here's it's XML code:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.freekyfrogy.treasure"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />
<application android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar">
<activity android:name="Title"
android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="MainGame"
android:screenOrientation="portrait">
</activity>
<activity android:name="Options"
android:screenOrientation="portrait">
</activity>
</application>
</manifest>
and the Error I'm getting is this:
Code:
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): FATAL EXCEPTION: main
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.freekyfrogy.treasure/com.freekyfrogy.treasure.Options}: java.lang.NullPointerException
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1664)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1768)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.ActivityThread.access$1500(ActivityThread.java:123)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:936)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.os.Handler.dispatchMessage(Handler.java:99)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.os.Looper.loop(Looper.java:123)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.ActivityThread.main(ActivityThread.java:3812)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at java.lang.reflect.Method.invokeNative(Native Method)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at java.lang.reflect.Method.invoke(Method.java:507)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at dalvik.system.NativeStart.main(Native Method)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): Caused by: java.lang.NullPointerException
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.Activity.findViewById(Activity.java:1647)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at com.freekyfrogy.treasure.Options.<init>(Options.java:16)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at java.lang.Class.newInstanceImpl(Native Method)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at java.lang.Class.newInstance(Class.java:1409)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1656)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): ... 11 more
Can you post your Options class? It looks to me like there may be something wrong in there.
Options class:
Code:
package com.freekyfrogy.treasure;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Options extends Activity implements OnClickListener {
int intX = 5;
int intY = 5;
EditText sizeX = (EditText) findViewById(R.id.editX);
EditText sizeY = (EditText) findViewById(R.id.editY);
Button setXY = (Button) findViewById(R.id.setXY);
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
setXY.setOnClickListener(this);
}
public void onClick(View v) {
String strX = sizeX.getText().toString();
String strY = sizeY.getText().toString();
intX = Integer.parseInt(strX);
intY = Integer.parseInt(strY);
Toast.makeText(this, "this is a toast: "+ intX+ " "+ intY, Toast.LENGTH_SHORT).show();
}
}
Hi freekyfrogy,
you should declare there controls of in onCreate method of Options activity
EditText sizeX = (EditText) findViewById(R.id.editX);
EditText sizeY = (EditText) findViewById(R.id.editY);
Button setXY = (Button) findViewById(R.id.setXY);
your option activity code look like this:
package com.freekyfrogy.treasure;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Options extends Activity implements OnClickListener {
int intX = 5;
int intY = 5;
Button setXY = (Button) findViewById(R.id.setXY);
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
EditText sizeX = (EditText) findViewById(R.id.editX);
EditText sizeY = (EditText) findViewById(R.id.editY);
setXY.setOnClickListener(this);
}
public void onClick(View v) {
String strX = sizeX.getText().toString();
String strY = sizeY.getText().toString();
intX = Integer.parseInt(strX);
intY = Integer.parseInt(strY);
Toast.makeText(this, "this is a toast: "+ intX+ " "+ intY, Toast.LENGTH_SHORT).show();
}
}
Oh I see now!!! Thanks so much, now it's not force closing haha

[Q] java.lang.NullPointerException in Android Webservice

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)

[Q] Error receiving Intent from IntentService

I'm trying to make an app that displays and image which will be downloaded in background in an IntentService class. When the IntentService finishes to download it sends the intent to be catched by a BroadcastReceiver in the MainActivity but I'm getting this error:
Code:
07-17 14:27:21.003 19189-19189/com.example.matt95.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.matt95.myapplication, PID: 19189
java.lang.RuntimeException: Error receiving broadcast Intent { act=TRANSACTION_DONE flg=0x10 (has extras) } in [email protected]
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java)
at android.os.Handler.handleCallback(Handler.java)
at android.os.Handler.dispatchMessage(Handler.java)
at android.os.Looper.loop(Looper.java)
at android.app.ActivityThread.main(ActivityThread.java)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.matt95.myapplication.MyActivity$1.onReceive(MyActivity.java:74)
************at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java)
************at android.os.Handler.handleCallback(Handler.java)
************at android.os.Handler.dispatchMessage(Handler.java)
************at android.os.Looper.loop(Looper.java)
************at android.app.ActivityThread.main(ActivityThread.java)
************at java.lang.reflect.Method.invokeNative(Native Method)
************at java.lang.reflect.Method.invoke(Method.java)
This is MainActivity class:
Code:
package com.example.matt95.myapplication;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
public class MyActivity extends Activity {
ProgressDialog pd;
// Custom BroadcastReceiver for catching and showing images
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
@Override
protected void onStart() {
super.onStart();
Intent i = new Intent(this, ImageIntentService.class);
i.putExtra("url", "http://samsung-wallpapers.com/uploads/allimg/130527/1-13052F02118.jpg");
startService(i);
pd = ProgressDialog.show(this, "Fetching image", "Go intent service go!");
}
@Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ImageIntentService.TRANSACTION_DONE);
registerReceiver(imageReceiver, intentFilter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(imageReceiver);
}
private BroadcastReceiver imageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String location = intent.getExtras().getString("imageLocation");
if (location == null || location.length() == 0) {
String failedString = "Failed to download image";
Toast.makeText(context, failedString, Toast.LENGTH_LONG).show();
}
File imageFile = new File(location);
if (!imageFile.exists()) {
pd.dismiss();
String downloadFail = "Unable to download the image";
Toast.makeText(context, downloadFail, Toast.LENGTH_LONG).show();
return;
}
Bitmap image = BitmapFactory.decodeFile(location);
ImageView iv = (ImageView) findViewById(R.id.show_image);
iv.setImageBitmap(image);
pd.dismiss();
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the IntentService class:
Code:
package com.example.matt95.myapplication;
import android.app.IntentService;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageIntentService extends IntentService {
private File cacheDir;
private static final String CACHE_FOLDER = "/myapp/image_cache/";
public static String TRANSACTION_DONE = "com.example.matt95.myapplication.ImageIntentService.TRANSACTION_DONE";
//Constructor method
public ImageIntentService() {
super("ImageIntentService");
}
@Override
public void onCreate() {
super.onCreate();
String tmpLocation = Environment.getExternalStorageDirectory().getPath() + CACHE_FOLDER;
cacheDir = new File(tmpLocation);
if (!cacheDir.exists())
cacheDir.mkdirs();
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent.hasExtra("url")) {
String remoteUrl = intent.getExtras().getString("url");
String imageLocation;
String fileName = remoteUrl.substring(remoteUrl.lastIndexOf(File.separator) + 1);
File tmpImage = new File(cacheDir + "/" + fileName);
if (tmpImage.exists()) {
imageLocation = tmpImage.getAbsolutePath();
notifyFinished(imageLocation, remoteUrl);
stopSelf();
return;
}
try {
URL url = new URL(remoteUrl);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
if (httpCon.getResponseCode() != 200)
throw new Exception("Failed to connect");
InputStream is = httpCon.getInputStream();
FileOutputStream fos = new FileOutputStream(tmpImage);
writeStream(is, fos);
fos.flush();
fos.close();
is.close();
imageLocation = tmpImage.getAbsolutePath();
notifyFinished(imageLocation, remoteUrl);
} catch (Exception e) {
Log.e("Service", "Failed!", e);
}
}
}
private void writeStream(InputStream is, OutputStream fos) throws Exception {
byte buffer[] = new byte[80000];
int read = is.read(buffer);
while (read != -1) {
fos.write(buffer, 0, read);
read = is.read(buffer);
}
}
private void notifyFinished(String imageLocation, String remoteUrl) {
Intent i = new Intent(TRANSACTION_DONE);
i.putExtra("imageLocation", imageLocation);
i.putExtra("url", remoteUrl);
ImageIntentService.this.sendBroadcast(i);
}
}
And this is the Manifest file:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.matt95.myapplication" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MyActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".ImageIntentService" />
</application>
</manifest>
What am I doing wrong?
Code:
Caused by: java.lang.NullPointerException
at com.example.matt95.myapplication.MyActivity$1.onReceive(MyActivity.java:74)
tells you there, you are asking an object that is of type "x" that is NULL to do something on line 74
Why not just use the picasso library or similar to download the image asynchronously in the background?
Sent from my HTC One using Tapatalk
deanwray said:
Code:
Caused by: java.lang.NullPointerException
at com.example.matt95.myapplication.MyActivity$1.onReceive(MyActivity.java:74)
tells you there, you are asking an object that is of type "x" that is NULL to do something on line 74
Click to expand...
Click to collapse
Thanks, I knew that but I'lll take a closer look at the code again :good:
Jonny said:
Why not just use the picasso library or similar to download the image asynchronously in the background?
Sent from my HTC One using Tapatalk
Click to expand...
Click to collapse
I'm a beginner in Android application so I don't have the proper knowledge right now, thanks for the suggestion though, I'll definitely try to take a look at that library :good:
matt95 said:
Thanks, I knew that but I'lll take a closer look at the code again :good:
I'm a beginner in Android application so I don't have the proper knowledge right now, thanks for the suggestion though, I'll definitely try to take a look at that library :good:
Click to expand...
Click to collapse
Better use asynctask for loading images
Sent from my Moto G using XDA Premium 4 mobile app
arpitkh96 said:
Better use asynctask for loading images
Sent from my Moto G using XDA Premium 4 mobile app
Click to expand...
Click to collapse
Yeah but I also need to download it and then load it, and it's not good to download that amount of data on the main thread
matt95 said:
Yeah but I also need to download it and then load it, and it's not good to download that amount of data on the main thread
Click to expand...
Click to collapse
AsyncTask runs in the background on a separate thread via the doInBackground method.
Sent from my HTC One using Tapatalk
Also, when there is a possibility that one of the objects included in the intent is null you can trap the error with a try/catch around the sendBroadcast() to prevent the exception from crashing the entire app.

[Q] Webview with a longonclicklistener help request!

Hello,
I am currently trying to have a webview that listens to a long click and loads a website once longclicked.
However, it crashes and i would love to find out why, or how to fix it
I do have to state that this crash Occurs on Samsung and LG hardware, but not on the Nexus 4 or the Emulator (Nexus 7)
Code:
package com.example.homehub;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends Activity {
WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Go Fullscreen (Just in case)
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Display the layout
setContentView(R.layout.activity_main);
// Define the Web View
webView = (WebView) findViewById(R.id.webView1);
// Setup
webView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );
webView.setLongClickable(true);
// Handle Links internally
webView.setWebViewClient(new WebViewClient() { });
// Using Latest Chrome Client
webView.setWebChromeClient(new WebChromeClient());
// Browser Settings
webView.getSettings().setAllowFileAccess( true );
webView.getSettings().setAppCacheEnabled( true );
webView.getSettings().setJavaScriptEnabled( true );
// Go to Default URL
webView.loadUrl("http://google.com" );
// Long Click Listener
webView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// Grab URL
String webUrl = webView.getUrl();
// Show the URL (This works)
Toast.makeText(getApplicationContext(), webUrl, Toast.LENGTH_SHORT).show();
// This request crashes
webView.loadUrl("http://www.yahoo.com");
return true;
}
});
}
// Back Button behaviour (Either browser back, or exit)
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
WebView webView = (WebView) findViewById(R.id.webView1);
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack()){
webView.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
And my Logcat:
Code:
12-01 01:48:40.579: W/dalvikvm(15534): threadid=1: thread exiting with uncaught exception (group=0x418eac08)
12-01 01:48:40.584: E/AndroidRuntime(15534): FATAL EXCEPTION: main
12-01 01:48:40.584: E/AndroidRuntime(15534): Process: com.example.homehub, PID: 15534
12-01 01:48:40.584: E/AndroidRuntime(15534): java.lang.NullPointerException
12-01 01:48:40.584: E/AndroidRuntime(15534): at com.android.org.chromium.content.browser.LongPressDetector.dispatchLongPress(LongPressDetector.java:158)
12-01 01:48:40.584: E/AndroidRuntime(15534): at com.android.org.chromium.content.browser.LongPressDetector.access$000(LongPressDetector.java:21)
12-01 01:48:40.584: E/AndroidRuntime(15534): at com.android.org.chromium.content.browser.LongPressDetector$LongPressHandler.handleMessage(LongPressDetector.java:58)
12-01 01:48:40.584: E/AndroidRuntime(15534): at android.os.Handler.dispatchMessage(Handler.java:102)
12-01 01:48:40.584: E/AndroidRuntime(15534): at android.os.Looper.loop(Looper.java:146)
12-01 01:48:40.584: E/AndroidRuntime(15534): at android.app.ActivityThread.main(ActivityThread.java:5653)
12-01 01:48:40.584: E/AndroidRuntime(15534): at java.lang.reflect.Method.invokeNative(Native Method)
12-01 01:48:40.584: E/AndroidRuntime(15534): at java.lang.reflect.Method.invoke(Method.java:515)
12-01 01:48:40.584: E/AndroidRuntime(15534): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
12-01 01:48:40.584: E/AndroidRuntime(15534): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
12-01 01:48:40.584: E/AndroidRuntime(15534): at dalvik.system.NativeStart.main(Native Method)

Please help: strange android error i dont know further

Hello today i was trying to code a ListView and in it says data from a database and them i tested it i was sure it will work this time and them this weird error comes up my logcat:
Code:
10-09 20:53:38.166: E/AndroidRuntime(279): FATAL EXCEPTION: main
10-09 20:53:38.166: E/AndroidRuntime(279): java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
10-09 20:53:38.166: E/AndroidRuntime(279): at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:347)
10-09 20:53:38.166: E/AndroidRuntime(279): at android.widget.ArrayAdapter.getView(ArrayAdapter.java:323)
10-09 20:53:38.166: E/AndroidRuntime(279): at android.widget.AbsListView.obtainView(AbsListView.java:1315)
10-09 20:53:38.166: E/AndroidRuntime(279): at android.widget.ListView.measureHeightOfChildren(ListView.java:1198)
10-09 20:53:38.166: E/AndroidRuntime(279): at android.widget.ListView.onMeasure(ListView.java:1109)
10-09 20:53:38.166: E/AndroidRuntime(279): at android.view.View.measure(View.java:8171)
10-09 20:53:38.166: E/AndroidRuntime(279): at android.widget.RelativeLayout.measureChild(RelativeLayout.java:563)
10-09 20:53:38.166: E/AndroidRuntime(279): at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:378)
10-09 20:53:38.166: E/AndroidRuntime(279): at android.view.View.measure(View.java:8171)
10-09 20:53:38.166: E/AndroidRuntime(279): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
10-09 20:53:38.166: E/AndroidRuntime(279): at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
10-09 20:53:38.166: E/AndroidRuntime(279): at android.view.View.measure(View.java:8171)
10-09 20:53:38.166: E/AndroidRuntime(279): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
10-09 20:53:38.166: E/AndroidRuntime(279): at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
10-09 20:53:38.166: E/AndroidRuntime(279): at android.view.View.measure(View.java:8171)
10-09 20:53:38.166: E/AndroidRuntime(279): at android.view.ViewRoot.performTraversals(ViewRoot.java:801)
10-09 20:53:38.166: E/AndroidRuntime(279): at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
10-09 20:53:38.166: E/AndroidRuntime(279): at android.os.Handler.dispatchMessage(Handler.java:99)
10-09 20:53:38.166: E/AndroidRuntime(279): at android.os.Looper.loop(Looper.java:123)
10-09 20:53:38.166: E/AndroidRuntime(279): at android.app.ActivityThread.main(ActivityThread.java:4627)
10-09 20:53:38.166: E/AndroidRuntime(279): at java.lang.reflect.Method.invokeNative(Native Method)
10-09 20:53:38.166: E/AndroidRuntime(279): at java.lang.reflect.Method.invoke(Method.java:521)
10-09 20:53:38.166: E/AndroidRuntime(279): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
10-09 20:53:38.166: E/AndroidRuntime(279): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
10-09 20:53:38.166: E/AndroidRuntime(279): at dalvik.system.NativeStart.main(Native Method)
10-09 20:53:38.166: E/AndroidRuntime(279): Caused by: java.lang.ClassCastException: android.widget.RelativeLayout
10-09 20:53:38.166: E/AndroidRuntime(279): at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:340)
10-09 20:53:38.166: E/AndroidRuntime(279): ... 24 more
and my main.java code is:
Code:
package com.example.frauprinzssapp;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Main extends Activity {
private static String DDB_NAME = dbreader.FeedEntry.DB_TABLENAME;
SQLiteDatabase db;
List<String> userss = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
database Mydb = new database(Main.this);
db = Mydb.getWritableDatabase();
String[] t = null;
ListView users = (ListView) findViewById(R.id.users);
try{
String query = "SELECT * FROM "+DDB_NAME+" ORDER BY "+dbreader.FeedEntry.COL_1+" DESC";
Cursor c = db.rawQuery(query, t);
while (c.moveToNext()){
if (c.moveToLast()){
userss.add(c.toString());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Main.this, R.layout.main, userss);
users.setAdapter(adapter);
return;
}
userss.add(c.toString());
}
}catch(Exception e){
userss.add("[ERRORMSG]: "+e.getMessage());
userss.add("[ERRORCAUSE]: "+e.getCause());
userss.add("[ERRORLOC]: "+e.getLocalizedMessage());
userss.add("[CLASS]: "+e.getClass());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Main.this, R.id.users, userss);
users.setAdapter(adapter);
}
}
//-----change view voids-----
public void main(View view){
setContentView(R.layout.main);
}
public void adduser(View view){
setContentView(R.layout.adduser);
}
public void removeuser(View view){
setContentView(R.layout.removeuser);
}
//------actions------
public void add(View view){
EditText name = (EditText) findViewById(R.id.aun);
EditText clas = (EditText) findViewById(R.id.auc);
String namee = name.getText().toString();
String clase = clas.getText().toString();
if (name.toString() == null || clas.toString() == null){
Toast.makeText(Main.this, "please fill in all textfields!", Toast.LENGTH_LONG);
return;
}
ContentValues values = new ContentValues();
values.put(dbreader.FeedEntry.COL_2, namee);
values.put(dbreader.FeedEntry.COl_3, clase);
values.put(dbreader.FeedEntry.COL_4, 0);
try{
db.insert(DDB_NAME, null, values);
Toast.makeText(Main.this, "added user "+name.toString()+"!", Toast.LENGTH_LONG);
setContentView(R.layout.main);
}catch(Exception e){
Toast.makeText(Main.this, "[ERROR] Could not create user maybe its already created!", Toast.LENGTH_LONG);
e.printStackTrace();
}
}
public void remove(){
}
public void show(){
}
}
the part where this is coming from is (i tihnk):
Code:
database Mydb = new database(Main.this);
db = Mydb.getWritableDatabase();
String[] t = null;
ListView users = (ListView) findViewById(R.id.users);
try{
String query = "SELECT * FROM "+DDB_NAME+" ORDER BY "+dbreader.FeedEntry.COL_1+" DESC";
Cursor c = db.rawQuery(query, t);
while (c.moveToNext()){
if (c.moveToLast()){
userss.add(c.toString());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Main.this, R.layout.main, userss);
users.setAdapter(adapter);
return;
}
userss.add(c.toString());
}
}catch(Exception e){
userss.add("[ERRORMSG]: "+e.getMessage());
userss.add("[ERRORCAUSE]: "+e.getCause());
userss.add("[ERRORLOC]: "+e.getLocalizedMessage());
userss.add("[CLASS]: "+e.getClass());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Main.this, R.id.users, userss);
users.setAdapter(adapter);
}
and also can you tell me if the ordering and displaying to the LIstView will work and when no can you help me display it please?
The adapter is your problem.The layout file you specified is your main layout,not a ListView item layout.Try using android.R.layout.symple_list_item_1(or sort of) instead of R.layout.main.If you don't like that layout you could make a custom ListView item layout.There are plenty of tutorials on Google on how to do this.
It should look lke this:
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,listItems);
myListView.setAdapter(adapter);
Click to expand...
Click to collapse
Hope I helped!

Categories

Resources