[Q] Insert multiple records using webservice in android - Java for Android App Development

I have been following this forum for quite a long time now, but I have not decided to publish my questions here.
Hope anyone can help me with this:
I am developing an android app that gets the calls made in a day, and I want those calls to be inserted into a SQL server table using a webservice.
I am kind of an android begginer, since I have never worked with webservices.
So far I am able to get the information of the calls and show it in the display and to insert up to 3-4 records in the database. the problem that I am facing right now is that when I get to insert more than 3 records, the webservice inserts duplicate entries and the call duration gets set to 0 in every call. For example: I have calls to the numbers 1,2,3,4 with a duration of 5 seconds each. When I invoke the webservice, it inserts the call 1,3,3,3 with duration of 0 seconds in all of the calls.
I am adding the code of my Activity and some captions of the device and the SQL server. If you need any more code, just let me know.
Thanks everyone!
Code:
package com.trucka.llamadasdrivers;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import com.trucka.llamadasdrivers.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.CallLog;
import android.widget.TextView;
import android.telephony.*;
import android.util.Log;
import java.text.SimpleDateFormat;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
public class ActividadLlamadasDrivers extends Activity {
TextView txtInformacion = null;
TextView txtDetalles = null;
TextView tv = null;
// Comunicación con el webservice.
private final String NAMESPACE = "htt p://truckanet.com/MensajeOperador";
private final String URL = "htt p://192.168.10.94/MensajeOperador/MensajeOperador.asmx";
//private final String URL = "htt p://200.76.187.148/MensajeOperador/MensajeOperador.asmx";
private final String SOAP_ACTION = "htt p://truckanet.com/MensajeOperador/ActualizarFede";
private final String METHOD_NAME = "ActualizarFede";
private String TAG = "TRUCKA_DRIVERS";
private String resultado;
String phNumber = null;
String callType = null;
String callDate = null;
DateFormat shortFecha = null;
DateFormat shortDF = null;
Date callDayTime = null;
Date fin = null;
String fechaLlamada1 = null;
String fechaLlamada2 = null;
String callDuration = null;
String dir = null;
public String tolo = null;
String imei = null;
String comentario = null;
String fechaRegistro = null;
String insercion = null;
String fechaInicio = null;
String fechaFin = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_actividad_llamadas_drivers);
txtInformacion = (TextView) findViewById(R.id.textview_call);
txtDetalles = (TextView)findViewById(R.id.textview_call2);
getCallDetails();
}
// Obtener la fecha actual del teléfono.
public long getTodayTimestamp(){
Calendar c1 = Calendar.getInstance();
c1.setTime(new Date());
Calendar c2 = Calendar.getInstance();
c2.set(Calendar.YEAR, c1.get(Calendar.YEAR));
c2.set(Calendar.MONTH, c1.get(Calendar.MONTH));
c2.set(Calendar.DAY_OF_MONTH, c1.get(Calendar.DAY_OF_MONTH));
c2.set(Calendar.HOUR_OF_DAY, 0);
c2.set(Calendar.MINUTE, 0);
c2.set(Calendar.SECOND, 0);
return c2.getTimeInMillis();
}
//Obtener el detalle de las llamadas con la fecha actual.
@SuppressLint("SimpleDateFormat")
private void getCallDetails() {
String timestamp = String.valueOf(getTodayTimestamp());
StringBuffer sb = new StringBuffer();
@SuppressWarnings("deprecation")
Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null, CallLog.Calls.DATE + ">= ?", new String[]{timestamp}, null);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Bitácora de llamadas :");
Integer contador = 0;
while (managedCursor.moveToNext()) {
contador = contador + 1;
phNumber = managedCursor.getString(number);
callType = managedCursor.getString(type);
callDate = managedCursor.getString(date);
shortFecha = DateFormat.getDateInstance(DateFormat.SHORT);
shortDF = DateFormat.getTimeInstance(DateFormat.SHORT);
callDayTime = new Date(Long.valueOf(callDate));
fechaLlamada1 = shortDF.format(callDayTime);
fechaLlamada2 = shortFecha.format(callDayTime);
callDuration = managedCursor.getString(duration);
int dircode = Integer.parseInt(callType);
TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "Saliente";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "Entrante";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "Perdida";
break;
}
imei = mngr.getDeviceId();
comentario = dir;
fechaRegistro = fechaLlamada2;
DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
String ahorita=df.format(callDayTime);
fechaInicio = ahorita.toString();
//fechaFin = df.format(callDayTime.setSeconds(callDayTime.getSeconds()+5));
insercion = "DECLARE @claveDriver INT, @nombreDriver VARCHAR(max), @evento VARCHAR(max), @duracion int, @inicial varchar(max) "
+ "SET @claveDriver = (SELECT cve_tra FROM SISTEMA.dbo.TELEFONOS WHERE IMEI_SIM = '"+mngr.getDeviceId()+"') "
+ "SET @nombreDriver = (SELECT nombre FROM SISTEMA.dbo.TELEFONOS WHERE IMEI_SIM = '"+mngr.getDeviceId()+"') "
+ "SET @duracion = " + managedCursor.getString(duration)
+ "SET @evento = '(LOG) Llamada " + dir + ". Duración ' + CONVERT(varchar, @duracion, 103) + ' segundos al número: " + phNumber +"' "
//+ "SET @duracion = " + callDuration
+" SET @inicial = '" + fechaInicio + "'"
+ "INSERT INTO bitacora.dbo.registroDellamadasOperadores (fechacreacion,fecha_fin,fecha_inicio,idMobil,Tractor,Nom_tra,Cve_tra,FechaRegistro,Evento) "
+ " VALUES('" + fechaInicio + "', DATEADD(SECOND,@duracion,@inicial),'" + fechaInicio + "','" + mngr.getDeviceId() + "','',@nombreDriver,@claveDriver,current_timestamp,@evento)";
AsyncCallWS tareaEnviarABD = new AsyncCallWS();
tareaEnviarABD.execute();
sb.append("\nNúmero de teléfono:--- " + phNumber + " \nTipo de llamada:--- "
+ dir + " \nFecha de llamada:--- " + fechaLlamada2 + " " + fechaLlamada1
+ " \nDuración en segundos:--- " + callDuration
+ " \nDispositivo actual:--" +mngr.getDeviceId());
sb.append("\n----------------------------------");
}
txtDetalles.setText(sb);
}
private class AsyncCallWS extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
Log.i(TAG,"doInBackground");
InsertarLlamada(insercion);
return null;
}
@Override
protected void onPostExecute(Void result) {
Log.i(TAG, "onPostExecute");
txtInformacion.setText("Información enviada");
}
@Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
txtInformacion.setText("Enviando información...");
}
@Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
public void InsertarLlamada(String insercion) {
//Creamos la solicitud
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//Propiedades que contienen los valores
PropertyInfo propiedades = new PropertyInfo();
propiedades.setName("insercion");
propiedades.setValue(insercion);
propiedades.setType(String.class);
//Agregamos las propiedades
request.addProperty(propiedades);
//Creamos el envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
//ponemos la salida SOAP
envelope.setOutputSoapObject(request);
//Creamos la llamada HTTP
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
//Invocamos el servicio
androidHttpTransport.call(SOAP_ACTION, envelope);
//Obtenemos la respuesta
Object response = envelope.getResponse();
//Asignamos el resultado de la consulta
resultado = response.toString();
} catch (Exception e) {
resultado = e.getMessage();
}
}
}
}

I do not know if this is the best way to do it, but i used sql variables and only sent 2 parameters to the webservice.
Thanks

Related

Help Decrypting assets

Hi, I really need help, i want to extract some .png and .jpg from the assets of the app 'Hyperdimension Neptunia The App'
after 3 month of research i found out that the assets are probably "encrypted" i wanted the textures for the live2D model files, and wanted to replace the sounds with the English versions from the iOS app that i extracted.
Audio was .caf in iOS but in Android it says its .mp3
This Line in a class says something about the audio: localEditor.putString("alarm_voice", bw.a(str, "caf", "mp3"));
The .caf opens and runs fine so whats the problem and anyone help me decrypt it? :fingers-crossed:
Full "AlarmActivity.class"
Code:
package jp.co.ideaf.neptune.nepkamijigenapp;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.NumberPicker;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.Calendar;
import java.util.Timer;
import jp.co.ideaf.neptune.nepkamijigenapp.a.a;
import jp.co.ideaf.neptune.nepkamijigenapp.a.d;
import jp.co.ideaf.neptune.nepkamijigenapp.a.f;
import jp.co.ideaf.neptune.nepkamijigenapp.a.h;
import jp.co.ideaf.neptune.nepkamijigenapp.d.z;
public class AlarmActivity extends Activity
{
private a a = null;
private d b = null;
private Timer c = null;
private ee d = null;
private eg e = null;
private Handler f = new Handler();
private LinearLayout g = null;
private static int a(Context paramContext, a parama, long paramLong)
{
h localh = KamijigenApplication.c();
z localz = localh.b(parama.c().f());
int i = localh.a();
String str = localz.g();
Object[] arrayOfObject = new Object[1];
arrayOfObject[0] = Long.valueOf(paramLong / 1000L);
jp.co.ideaf.neptune.nepkamijigenapp.d.k.a(String.format("アラーム発生時間 : %d秒", arrayOfObject), new Object[0]);
f localf = new f(paramLong + Calendar.getInstance().getTimeInMillis());
SharedPreferences.Editor localEditor = paramContext.getSharedPreferences(bw.a(paramContext, 2131034117), 0).edit();
localEditor.putString("alarm_voice", bw.a(str, "caf", "mp3"));
localEditor.putBoolean("snooze", parama.b);
localEditor.putInt("snooze_time", parama.c);
localEditor.commit();
Intent localIntent = new Intent(paramContext, AlarmDialogActivity.class);
localIntent.addFlags(268435456);
PendingIntent localPendingIntent = PendingIntent.getActivity(paramContext, 0, localIntent, 0);
((AlarmManager)paramContext.getSystemService("alarm")).set(0, localf.b(), localPendingIntent);
return i;
}
private void a()
{
TimePicker localTimePicker = (TimePicker)findViewById(2131165202);
if (localTimePicker == null);
while (true)
{
return;
localTimePicker.setIs24HourView(Boolean.valueOf(true));
localTimePicker.setCurrentHour(Integer.valueOf(this.a.c().f()));
localTimePicker.setCurrentMinute(Integer.valueOf(this.a.c().g()));
}
}
private void a(int paramInt)
{
TextView localTextView = (TextView)findViewById(2131165196);
if (localTextView != null)
{
localTextView.setText(Integer.toString(paramInt));
localTextView.append(bw.a(this, 2131034215));
}
}
private void a(int paramInt1, int paramInt2)
{
TextView localTextView1 = (TextView)findViewById(2131165194);
if (localTextView1 != null)
{
localTextView1.setText(Integer.toString(paramInt1));
localTextView1.append(bw.a(this, 2131034211));
}
TextView localTextView2 = (TextView)findViewById(2131165195);
if (localTextView2 != null)
{
localTextView2.setText(Integer.toString(paramInt2));
localTextView2.append(bw.a(this, 2131034212));
}
}
public static void a(Context paramContext, a parama)
{
d locald = KamijigenApplication.a();
locald.b(paramContext, false);
c(paramContext, parama);
parama.a = true;
locald.p().a(parama);
locald.c(paramContext);
}
private void b()
{
CheckBox localCheckBox = (CheckBox)findViewById(2131165197);
if (localCheckBox != null)
{
if (KamijigenApplication.a().p().a)
break label38;
localCheckBox.setEnabled(false);
localCheckBox.setChecked(false);
}
while (true)
{
return;
label38: localCheckBox.setChecked(true);
}
}
private static void c(Context paramContext, a parama)
{
f localf1 = new f(Calendar.getInstance().getTimeInMillis());
int i = localf1.f();
int j = localf1.g();
int k;
int m;
int n;
f localf2;
long l;
if ((i < parama.c().f()) || ((i == parama.c().f()) && (j < parama.c().g())))
{
k = localf1.c();
m = localf1.d();
n = localf1.e();
localf2 = new f(k, m, n, parama.c().f(), parama.c().g(), 0);
jp.co.ideaf.neptune.nepkamijigenapp.d.k.a("targetDate : " + localf2.toString(), new Object[0]);
jp.co.ideaf.neptune.nepkamijigenapp.d.k.a("nowDate : " + localf1.toString(), new Object[0]);
l = localf2.b() - localf1.b();
if (parama.c <= 0)
break label300;
}
label300: for (parama.b = true; ; parama.b = false)
{
int i1 = a(paramContext, parama, l);
parama.c().a(k);
parama.c().b(m);
parama.c().c(n);
parama.d = i1;
return;
f localf3 = new f(86400000L + localf1.b());
k = localf3.c();
m = localf3.d();
n = localf3.e();
localf2 = new f(k, m, n, parama.c().f(), parama.c().g(), 0);
break;
}
}
public void onClickBackButton(View paramView)
{
finish();
}
public void onClickDecideButton(View paramView)
{
CheckBox localCheckBox = (CheckBox)findViewById(2131165197);
if (((RadioButton)findViewById(2131165199)).isChecked())
{
findViewById(2131165201).setVisibility(8);
findViewById(2131165203).setVisibility(0);
findViewById(2131165201).setVisibility(0);
findViewById(2131165203).setVisibility(8);
if (localCheckBox != null)
break label127;
}
while (true)
{
return;
findViewById(2131165201).setVisibility(0);
findViewById(2131165203).setVisibility(8);
findViewById(2131165201).setVisibility(8);
findViewById(2131165203).setVisibility(0);
break;
label127: d locald = KamijigenApplication.a();
if (!locald.p().a)
showDialog(0);
else if ((locald.p().a) && (localCheckBox.isChecked()))
showDialog(2);
else
showDialog(3);
}
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
setRequestedOrientation(1);
setContentView(2130903041);
d locald = KamijigenApplication.a();
this.a = new a();
this.a.a(locald.p());
a(this.a.c().f(), this.a.c().g());
a();
b();
TimePicker localTimePicker = (TimePicker)findViewById(2131165202);
if (localTimePicker != null)
{
localTimePicker.setVisibility(0);
localTimePicker.setOnTimeChangedListener(new j(this));
}
userNumberPicker localuserNumberPicker = (userNumberPicker)findViewById(2131165204);
a(this.a.c);
if ((Build.VERSION.SDK_INT < 11) && (localuserNumberPicker != null))
{
localuserNumberPicker.a(0, 59);
localuserNumberPicker.a(this.a.c);
localuserNumberPicker.a(new l(this));
}
if (Build.VERSION.SDK_INT >= 11)
{
FrameLayout localFrameLayout = (FrameLayout)findViewById(2131165203);
localuserNumberPicker.setEnabled(false);
localuserNumberPicker.setVisibility(8);
this.g = new LinearLayout(this);
this.g.setOrientation(0);
NumberPicker localNumberPicker = new NumberPicker(this);
localNumberPicker.setMinValue(0);
localNumberPicker.setMaxValue(59);
localNumberPicker.setValue(this.a.c);
localNumberPicker.setOnValueChangedListener(new m(this));
this.g.addView(localNumberPicker, 0, new LinearLayout.LayoutParams(-2, -2, 1.0F));
localFrameLayout.addView(this.g, new FrameLayout.LayoutParams(-2, -2, 17));
}
findViewById(2131165201).setVisibility(0);
findViewById(2131165203).setVisibility(8);
((RadioGroup)findViewById(2131165198)).setOnCheckedChangeListener(new n(this));
this.b = KamijigenApplication.a();
String str = getResources().getText(2131034115).toString();
LinearLayout localLinearLayout = (LinearLayout)findViewById(2131165191);
Button localButton = (Button)findViewById(2131165205);
if (str.equals(this.b.d(this.b.k())))
{
localLinearLayout.setBackgroundResource(2130837540);
localButton.setBackgroundResource(2130837513);
}
while (true)
{
if (locald.p().a)
showDialog(4);
return;
localLinearLayout.setBackgroundResource(2130837541);
localButton.setBackgroundResource(2130837514);
}
}
protected Dialog onCreateDialog(int paramInt)
{
AlertDialog localAlertDialog;
if (paramInt == 0)
localAlertDialog = new AlertDialog.Builder(this).setTitle(2131034216).setMessage(2131034217).setPositiveButton(2131034218, new q(this)).setNegativeButton(2131034219, null).create();
while (true)
{
return localAlertDialog;
if (paramInt == 1)
{
localAlertDialog = new AlertDialog.Builder(this).setMessage(2131034220).setPositiveButton(2131034221, new r(this)).create();
}
else if (paramInt == 2)
{
localAlertDialog = new AlertDialog.Builder(this).setTitle(2131034222).setMessage(2131034223).setPositiveButton(2131034224, new s(this)).setNegativeButton(2131034225, null).create();
}
else if (paramInt == 3)
{
localAlertDialog = new AlertDialog.Builder(this).setTitle(2131034226).setMessage(2131034227).setPositiveButton(2131034228, new t(this)).setNegativeButton(2131034229, null).create();
}
else
{
localAlertDialog = null;
if (paramInt == 4)
localAlertDialog = new AlertDialog.Builder(this).setMessage(2131034304).setPositiveButton(2131034228, new k(this)).setNegativeButton(2131034229, null).create();
}
}
}
protected void onPause()
{
super.onPause();
if (this.d != null)
this.d.b();
this.c.cancel();
this.c.purge();
}
protected void onResume()
{
super.onResume();
this.d = new ee(this);
this.d.a();
this.c = new Timer(true);
this.c.scheduleAtFixedRate(new o(this), 100L, 100L);
Display localDisplay = ((WindowManager)getSystemService("window")).getDefaultDisplay();
if (localDisplay.getWidth() > localDisplay.getHeight());
for (int i = localDisplay.getHeight(); ; i = localDisplay.getWidth())
{
float f1 = i / 480.0F;
LinearLayout localLinearLayout = (LinearLayout)findViewById(2131165193);
getResources().getDrawable(2130837742);
localLinearLayout.getLayoutParams().height = ((int)(90.0F * f1));
localLinearLayout.getLayoutParams().width = ((int)(f1 * 172.0F));
localLinearLayout.requestLayout();
this.e = new eg(this, 0);
return;
}
}
}
well if it is encrypted, what type ? and if it\s something like AES CBC how do you intend to get the cypher ?
That's the problem, im kinda new to this thing so im not sure how to get the cypher and i think its AES encrypted but not 100% certain. Sorry for being a noob.

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

I'm trying to get the result of the asynctask by using an interface but when I've tried to use the methods on that interface my app keeps on crashing.
This project has 4 java files: MainActivity.java , SigninActivity.java , GetAvailableExam.java , AsyncResponse.java
I'm pretty sure the error is not on the GetAvailableExam.java because it is just an activity that prints hello world so I'm not going to post it's code here.
MainActivity.java
Code:
package com.it4.anexsysclient;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements AsyncResponse {
private EditText usernameField,passwordField;
private TextView status,role,method;
SigninActivity signinactivity = new SigninActivity();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);
status = (TextView)findViewById(R.id.textView6);
role = (TextView)findViewById(R.id.textView7);
method = (TextView)findViewById(R.id.textView9);
signinactivity.delegate = this;
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
usernameField.setText("stud");
passwordField.setText("stud");
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void login(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Get Method");
new SigninActivity(this,status,role,0).execute(username,password);
}
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Post Method");
new SigninActivity(this,status,role,1).execute(username,password);
}
public void processFinish(String output){
//Toast.makeText(getApplicationContext(), output, Toast.LENGTH_LONG).show();
}
}
SigninActivity.java
Code:
package com.it4.anexsysclient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
public class SigninActivity extends AsyncTask<String,Void,String>{
private TextView statusField,roleField;
private Context context;
private int byGetOrPost = 0;
private String server_ip;
private ProgressDialog progress;
public AsyncResponse delegate=null;
public SigninActivity() {
}
//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,
TextView roleField,int flag) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
byGetOrPost = flag;
this.progress = new ProgressDialog(context);
}
protected void onPreExecute(){
server_ip = "http://192.168.0.101/anexsys/examination-manager.php";
this.progress.setMessage("Logging in");
this.progress.show();
}
[user=439709]@override[/user]
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://myphpmysqlweb.hostei.com/login.php?username="
+username+"&password="+password;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link=server_ip;
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
[user=439709]@override[/user]
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
this.progress.dismiss();
delegate.processFinish(result);
//Log.d("ADebugTag", "Value: " + result);
//if(result.toString()=="student") {
//context.startActivity(new Intent(context, GetAvailableExam.class));
//}
}
}
AsyncResponse.java
Code:
package com.it4.anexsysclient;
public interface AsyncResponse {
void processFinish(String output);
}
Code:
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
this.progress.dismiss();
delegate.processFinish(result);
//Log.d("ADebugTag", "Value: " + result);
//if(result.toString()=="student") {
//context.startActivity(new Intent(context, GetAvailableExam.class));
//}
}
The delegate.processFinish(result) is the one causing the crash, The app works fine if I try to remove/comment out it.
Would be helpfull with some more information, for instance: what exception is it you get?
My guess is a nullpointer? Which by a quick glance i'd suspect is that you never set "delegate" in your signinactivity.
You create signinactivity during creation of mainactivity.
Code:
[B]SigninActivity signinactivity = new SigninActivity();[/B]
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);
status = (TextView)findViewById(R.id.textView6);
role = (TextView)findViewById(R.id.textView7);
method = (TextView)findViewById(R.id.textView9);
[B]signinactivity.delegate = this;[/B]
}
However that instance is later never used from what i can tell? You create new instances later in code when its used, where delegate won't be set.
Code:
public void login(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Get Method");
[B]new SigninActivity(this,status,role,0).execute(username,password);[/B]
}
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Post Method");
[B] new SigninActivity(this,status,role,1).execute(username,password);[/B]
}

[Q] IllegalArgumentException when calling method in database

Hello everybody. I've tried to make a suitable database for my game that will represent shop stock. The problem is when I call the purchase() method, I got that exception mentioned in the title. The problem is that I need to chceck depending on ID if I need to increment number of purchases or i just unlock the whole item. Here is my code for the database
Code:
public class MonsterTapDatabase extends SQLiteOpenHelper {
static final String dbName = "MonsterTapDb";
static final int version = 1;
static final String tTableName = "Shop";
static final String fItemID = "ItemID";
static final String fItemName = "ItemName";
static final String fItemNumberOfPurchases = "NumberOfPurchases";
static final String fItemIsLocked = "IsItemLocked";
public MonsterTapDatabase(Context context) {
super(context, dbName, null, version);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS "+tTableName+" (" +
fItemID + " INTEGER PRIMARY KEY , " +
fItemName + " TEXT , " +
fItemNumberOfPurchases + " INT, " +
fItemIsLocked + " TEXT" +
")");
ContentValues cv = new ContentValues();
cv.put(fItemID, 1);
cv.put(fItemName, "Lives");
cv.put(fItemNumberOfPurchases, 0);
cv.put(fItemIsLocked, "true");
sqLiteDatabase.insert(tTableName, null, cv);
cv.put(fItemID, 2);
cv.put(fItemName, "Hardmode");
cv.put(fItemNumberOfPurchases, 0);
cv.put(fItemIsLocked, "true");
sqLiteDatabase.insert(tTableName, null, cv);
cv.put(fItemID, 3);
cv.put(fItemName, "Reversed");
cv.put(fItemNumberOfPurchases, 0);
cv.put(fItemIsLocked, "true");
sqLiteDatabase.insert(tTableName, null, cv);
cv.put(fItemID, 4);
cv.put(fItemName, "Reversed Hardmode");
cv.put(fItemNumberOfPurchases, 0);
cv.put(fItemIsLocked, "true");
sqLiteDatabase.insert(tTableName, null, cv);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + tTableName);
onCreate(sqLiteDatabase);
}
public void purchase(int ID){
if(ID==1){
SQLiteDatabase myDB = this.getReadableDatabase();
String[] mySearch = new String[]{String.valueOf(ID)};
Cursor myCursor = myDB.rawQuery("SELECT "+ fItemNumberOfPurchases +" FROM "+ tTableName +" WHERE "+ fItemID +"=?",mySearch);
myCursor.moveToFirst();
int index = myCursor.getColumnIndex(fItemNumberOfPurchases);
if(index<5){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(fItemNumberOfPurchases, index);
db.update(tTableName,cv, fItemID, new String[]{String.valueOf(ID)});
}
else{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(fItemIsLocked, false);
db.update(tTableName,cv, fItemID, new String[]{String.valueOf(ID)});
}
myCursor.close();
}
else{
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(fItemIsLocked, false);
cv.put(fItemNumberOfPurchases, 1);
myDB.update(tTableName, cv, fItemID+"=?", new String []{String.valueOf(ID)});
}
}
public String isPurchased(int ID){
SQLiteDatabase myDB = this.getReadableDatabase();
String[] mySearch = new String[]{String.valueOf(ID)};
Cursor myCursor = myDB.rawQuery("SELECT "+ fItemIsLocked +" FROM "+ tTableName +" WHERE "+ fItemID +"=?",mySearch);
myCursor.moveToFirst();
int index = myCursor.getColumnIndex(fItemID);
String myAnswer = myCursor.getString(index);
myCursor.close();
return myAnswer;
}
public int numberOfLives(){
int ID = 1;
SQLiteDatabase myDB = this.getReadableDatabase();
String[] mySearch = new String[]{String.valueOf(ID)};
Cursor myCursor = myDB.rawQuery("SELECT "+ fItemNumberOfPurchases +" FROM "+ tTableName +" WHERE "+ fItemID +"=?",mySearch);
myCursor.moveToFirst();
int index = myCursor.getColumnIndex(fItemNumberOfPurchases);
myCursor.close();
return index;
}
}

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected an int

hello i have a problems with app
result
W/System.err﹕ com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected an int but was BOOLEAN at line 1 column 856
code:
private Boolean getCourseInfo() {
CourseSyncTask cs = new CourseSyncTask(mUrl, token, siteInfo.getId());
publishProgress(context.getString(R.string.login_prog_sync_course));
Boolean usrCourseSyncStatus = cs.syncUserCourses();
if (!usrCourseSyncStatus) {
publishProgress(cs.getError());
publishProgress("\n"
+ context.getString(R.string.login_prog_sync_failed));
}
return usrCourseSyncStatus;
}
////////////////////////////////////////////////////////////
public class CourseSyncTask {
String mUrl;
String token;
long siteid;
String error;
/**
*
* @param mUrl
* @param token
* @param siteid
*
*/
public CourseSyncTask(String mUrl, String token, long siteid) {
this.mUrl = mUrl;
this.token = token;
this.siteid = siteid;
}
/**
* Sync all the courses in the current site.
*
* @return syncStatus
*
*/
public Boolean syncAllCourses() {
MoodleRestCourse mrc = new MoodleRestCourse(mUrl, token);
ArrayList<MoodleCourse> mCourses = mrc.getAllCourses();
/** Error checking **/
// Some network or encoding issue.
if (mCourses.size() == 0) {
error = "Network issue!";
return false;
}
// Moodle exception
if (mCourses.size() == 1 && mCourses.get(0).getCourseid() == 0) {
error = "Moodle Exception: User don't have permissions!";
return false;
}
// Add siteid to all courses and update
MoodleCourse course = new MoodleCourse();
List<MoodleCourse> dbCourses;
for (int i = 0; i < mCourses.size(); i++) {
course = mCourses.get(i);
course.setSiteid(siteid);
// Update or save in database
dbCourses = MoodleCourse.find(MoodleCourse.class,
"courseid = ? and siteid = ?", course.getCourseid() + "",
course.getSiteid() + "");
if (dbCourses != null && dbCourses.size() > 0) {
// Set app specific fields explicitly
course.setId(dbCourses.get(0).getId());
course.setIsUserCourse(dbCourses.get(0).getIsUserCourse());
course.setIsFavCourse(dbCourses.get(0).getIsFavCourse());
}
course.save();
}
return true;
}
/**
* Sync all courses of logged in user in the current site.
*
* @return syncStatus
*/
public Boolean syncUserCourses() {
// Get userid
MoodleSiteInfo site = MoodleSiteInfo.findById(MoodleSiteInfo.class,
siteid);
if (site == null)
return false;
int userid = site.getUserid();
MoodleRestCourse mrc = new MoodleRestCourse(mUrl, token);
ArrayList<MoodleCourse> mCourses = mrc.getEnrolledCourses(userid + "");
/** Error checking **/
// Some network or encoding issue.
if (mCourses == null)
return false;
// Some network or encoding issue.
if (mCourses.size() == 0)
return false;
// Moodle exception
if (mCourses.size() == 1 && mCourses.get(0).getCourseid() == 0)
return false;
// Add siteid and isUserCourse to all courses and update
MoodleCourse course = new MoodleCourse();
List<MoodleCourse> dbCourses;
for (int i = 0; i < mCourses.size(); i++) {
course = mCourses.get(i);
course.setSiteid(siteid);
course.setIsUserCourse(true);
// Update or save in database
dbCourses = MoodleCourse.find(MoodleCourse.class,
"courseid = ? and siteid = ?", course.getCourseid() + "",
course.getSiteid() + "");
if (dbCourses.size() > 0) {
// Set app specific fields explicitly
course.setId(dbCourses.get(0).getId());
course.setIsFavCourse(dbCourses.get(0).getIsFavCourse());
}
course.save();
}
return true;
}
/**
* Error message from the last failed sync operation.
*
* @return error
*
*/
public String getError() {
return error;
}
}
////////////////////////////////////////////
public class MoodleRestCourse {
private final String DEBUG_TAG = "MoodleRestCourses";
private String mUrl;
private String token;
public MoodleRestCourse(String mUrl, String token) {
this.mUrl = mUrl;
this.token = token;
}
public ArrayList<MoodleCourse> getAllCourses() {
ArrayList<MoodleCourse> mCourses = new ArrayList<MoodleCourse>();
String format = MoodleRestOption.RESPONSE_FORMAT;
String function = MoodleRestOption.FUNCTION_GET_ALL_COURSES;
try {
// Adding all parameters.
String params = "" + URLEncoder.encode("", "UTF-8");
// Build a REST call url to make a call.
String restUrl = mUrl + "/webservice/rest/server.php" + "?wstoken="
+ token + "&wsfunction=" + function
+ "&moodlewsrestformat=" + format;
// Fetch content now.
MoodleRestCall mrc = new MoodleRestCall();
Reader reader = mrc.fetchContent(restUrl, params);
GsonExclude ex = new GsonExclude();
Gson gson = new GsonBuilder()
.addDeserializationExclusionStrategy(ex)
.addSerializationExclusionStrategy(ex).create();
mCourses = gson.fromJson(reader,
new TypeToken<List<MoodleCourse>>() {
}.getType());
reader.close();
} catch (Exception e) {
Log.d(DEBUG_TAG, "URL encoding failed");
e.printStackTrace();
}
return mCourses;
}
public ArrayList<MoodleCourse> getEnrolledCourses(String userId) {
ArrayList<MoodleCourse> mCourses = new ArrayList<MoodleCourse>();
String format = MoodleRestOption.RESPONSE_FORMAT;
String function = MoodleRestOption.FUNCTION_GET_ENROLLED_COURSES;
try {
// Adding all parameters.
String params = "&" + URLEncoder.encode("userid", "UTF-8") + "="
+ userId;
// Build a REST call url to make a call.
String restUrl = mUrl + "/webservice/rest/server.php" + "?wstoken="
+ token + "&wsfunction=" + function
+ "&moodlewsrestformat=" + format;
// Fetch content now.
MoodleRestCall mrc = new MoodleRestCall();
Reader reader = mrc.fetchContent(restUrl, params);
GsonExclude ex = new GsonExclude();
Gson gson = new GsonBuilder()
.addDeserializationExclusionStrategy(ex)
.addSerializationExclusionStrategy(ex).create();
mCourses = gson.fromJson(reader,
new TypeToken<List<MoodleCourse>>() {
}.getType());
reader.close();
} catch (Exception e) {
Log.d(DEBUG_TAG, "URL encoding failed");
e.printStackTrace();
}
return mCourses;
}
}

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected an int

hello i have a problems with app
result
W/System.err﹕ com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected an int but was BOOLEAN at line 1 column 856
code:
private Boolean getCourseInfo() {
CourseSyncTask cs = new CourseSyncTask(mUrl, token, siteInfo.getId());
publishProgress(context.getString(R.string.login_p rog_sync_course));
Boolean usrCourseSyncStatus = cs.syncUserCourses();
if (!usrCourseSyncStatus) {
publishProgress(cs.getError());
publishProgress("\n"
+ context.getString(R.string.login_prog_sync_failed) );
}
return usrCourseSyncStatus;
}
////////////////////////////////////////////////////////////
public class CourseSyncTask {
String mUrl;
String token;
long siteid;
String error;
/**
*
* @param mUrl
* @param token
* @param siteid
*
*/
public CourseSyncTask(String mUrl, String token, long siteid) {
this.mUrl = mUrl;
this.token = token;
this.siteid = siteid;
}
/**
* Sync all the courses in the current site.
*
* @return syncStatus
*
*/
public Boolean syncAllCourses() {
MoodleRestCourse mrc = new MoodleRestCourse(mUrl, token);
ArrayList<MoodleCourse> mCourses = mrc.getAllCourses();
/** Error checking **/
// Some network or encoding issue.
if (mCourses.size() == 0) {
error = "Network issue!";
return false;
}
// Moodle exception
if (mCourses.size() == 1 && mCourses.get(0).getCourseid() == 0) {
error = "Moodle Exception: User don't have permissions!";
return false;
}
// Add siteid to all courses and update
MoodleCourse course = new MoodleCourse();
List<MoodleCourse> dbCourses;
for (int i = 0; i < mCourses.size(); i++) {
course = mCourses.get(i);
course.setSiteid(siteid);
// Update or save in database
dbCourses = MoodleCourse.find(MoodleCourse.class,
"courseid = ? and siteid = ?", course.getCourseid() + "",
course.getSiteid() + "");
if (dbCourses != null && dbCourses.size() > 0) {
// Set app specific fields explicitly
course.setId(dbCourses.get(0).getId());
course.setIsUserCourse(dbCourses.get(0).getIsUserC ourse());
course.setIsFavCourse(dbCourses.get(0).getIsFavCou rse());
}
course.save();
}
return true;
}
/**
* Sync all courses of logged in user in the current site.
*
* @return syncStatus
*/
public Boolean syncUserCourses() {
// Get userid
MoodleSiteInfo site = MoodleSiteInfo.findById(MoodleSiteInfo.class,
siteid);
if (site == null)
return false;
int userid = site.getUserid();
MoodleRestCourse mrc = new MoodleRestCourse(mUrl, token);
ArrayList<MoodleCourse> mCourses = mrc.getEnrolledCourses(userid + "");
/** Error checking **/
// Some network or encoding issue.
if (mCourses == null)
return false;
// Some network or encoding issue.
if (mCourses.size() == 0)
return false;
// Moodle exception
if (mCourses.size() == 1 && mCourses.get(0).getCourseid() == 0)
return false;
// Add siteid and isUserCourse to all courses and update
MoodleCourse course = new MoodleCourse();
List<MoodleCourse> dbCourses;
for (int i = 0; i < mCourses.size(); i++) {
course = mCourses.get(i);
course.setSiteid(siteid);
course.setIsUserCourse(true);
// Update or save in database
dbCourses = MoodleCourse.find(MoodleCourse.class,
"courseid = ? and siteid = ?", course.getCourseid() + "",
course.getSiteid() + "");
if (dbCourses.size() > 0) {
// Set app specific fields explicitly
course.setId(dbCourses.get(0).getId());
course.setIsFavCourse(dbCourses.get(0).getIsFavCou rse());
}
course.save();
}
return true;
}
/**
* Error message from the last failed sync operation.
*
* @return error
*
*/
public String getError() {
return error;
}
}
////////////////////////////////////////////
public class MoodleRestCourse {
private final String DEBUG_TAG = "MoodleRestCourses";
private String mUrl;
private String token;
public MoodleRestCourse(String mUrl, String token) {
this.mUrl = mUrl;
this.token = token;
}
public ArrayList<MoodleCourse> getAllCourses() {
ArrayList<MoodleCourse> mCourses = new ArrayList<MoodleCourse>();
String format = MoodleRestOption.RESPONSE_FORMAT;
String function = MoodleRestOption.FUNCTION_GET_ALL_COURSES;
try {
// Adding all parameters.
String params = "" + URLEncoder.encode("", "UTF-8");
// Build a REST call url to make a call.
String restUrl = mUrl + "/webservice/rest/server.php" + "?wstoken="
+ token + "&wsfunction=" + function
+ "&moodlewsrestformat=" + format;
// Fetch content now.
MoodleRestCall mrc = new MoodleRestCall();
Reader reader = mrc.fetchContent(restUrl, params);
GsonExclude ex = new GsonExclude();
Gson gson = new GsonBuilder()
.addDeserializationExclusionStrategy(ex)
.addSerializationExclusionStrategy(ex).create();
mCourses = gson.fromJson(reader,
new TypeToken<List<MoodleCourse>>() {
}.getType());
reader.close();
} catch (Exception e) {
Log.d(DEBUG_TAG, "URL encoding failed");
e.printStackTrace();
}
return mCourses;
}
public ArrayList<MoodleCourse> getEnrolledCourses(String userId) {
ArrayList<MoodleCourse> mCourses = new ArrayList<MoodleCourse>();
String format = MoodleRestOption.RESPONSE_FORMAT;
String function = MoodleRestOption.FUNCTION_GET_ENROLLED_COURSES;
try {
// Adding all parameters.
String params = "&" + URLEncoder.encode("userid", "UTF-8") + "="
+ userId;
// Build a REST call url to make a call.
String restUrl = mUrl + "/webservice/rest/server.php" + "?wstoken="
+ token + "&wsfunction=" + function
+ "&moodlewsrestformat=" + format;
// Fetch content now.
MoodleRestCall mrc = new MoodleRestCall();
Reader reader = mrc.fetchContent(restUrl, params);
GsonExclude ex = new GsonExclude();
Gson gson = new GsonBuilder()
.addDeserializationExclusionStrategy(ex)
.addSerializationExclusionStrategy(ex).create();
mCourses = gson.fromJson(reader,
new TypeToken<List<MoodleCourse>>() {
}.getType());
reader.close();
} catch (Exception e) {
Log.d(DEBUG_TAG, "URL encoding failed");
e.printStackTrace();
}
return mCourses;
}
}

Categories

Resources