SQLite Java Android, not finding column to delete - java

I have a main activity where you can send a log to a database, and a log activity where you can view them and delete them. Everything works expect when I try and delete a single log, the program crashes and the error is saying that it can't find the column "identity" to delete it.
Main Activity:
package com.software.roux.diabcalc;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
public class MainActivity extends AppCompatActivity {
SharedPreferences mPrefs;
SharedPreferences logPrefs;
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
boolean rb0 = settings.getBoolean("accepted", false);
if(rb0 == true){
setTitle("MyInsulin");
mPrefs=this.getSharedPreferences("settings", 0);
logPrefs=this.getSharedPreferences("logs", 0);
final EditText a1 = (EditText) findViewById(R.id.add1);
final EditText a2 = (EditText) findViewById(R.id.add2);
final double bolusdose = Double.parseDouble(mPrefs.getString("bolus", "0"));
final double correctiondose = Double.parseDouble(mPrefs.getString("correction", "0"));
final double targetlow = Double.parseDouble(mPrefs.getString("low", "0"));
final double targethigh = Double.parseDouble(mPrefs.getString("high", "0"));
final double correctto = Double.parseDouble(mPrefs.getString("corrset", "0"));
String bolusString = mPrefs.getString("bolus", "0");
String corrString = mPrefs.getString("correction", "0");
String lowString = mPrefs.getString("low", "0");
String highString = mPrefs.getString("high", "0");
String correcttonum = mPrefs.getString("corrset", "0");
EditText b1 = (EditText)findViewById(R.id.bolus);
b1.setText(bolusString);
b1.setEnabled(false);
EditText b2 = (EditText)findViewById(R.id.correction);
b2.setText(corrString);
b2.setEnabled(false);
EditText b3 = (EditText)findViewById(R.id.targetlow);
b3.setText(lowString);
b3.setEnabled(false);
EditText b4 = (EditText)findViewById(R.id.targethigh);
b4.setText(highString);
b4.setEnabled(false);
EditText b5 = (EditText)findViewById(R.id.correcttonum);
b5.setText(correcttonum);
b5.setEnabled(false);
Button b6 = (Button)findViewById(R.id.setter);
b6.setEnabled(false);
Button b8 = (Button)findViewById(R.id.logsave);
b8.setEnabled(false);
db = openOrCreateDatabase("logDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS zlogtable('identity VARCHAR',bslevel VARCHAR,carbs VARCHAR,result VARCHAR);");
a1.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String currentlevelst = a1.getText().toString();
String carbseatenst = a2.getText().toString();
if (currentlevelst.length() >= 1) {
if (carbseatenst.length() >= 1) {
Double currentlevel = Double.parseDouble(a1.getText().toString());
Double carbseaten = Double.parseDouble(a2.getText().toString());
double firststep = 0;
if (currentlevel > targethigh) {
firststep = ((currentlevel - correctto) / correctiondose);
} else if (currentlevel < targetlow) {
firststep = ((currentlevel - targethigh) / correctiondose);
} else {
firststep = 0;
}
double secondstep = carbseaten / bolusdose;
double firstplussecond = firststep + secondstep;
BigDecimal result = new BigDecimal(firstplussecond, MathContext.DECIMAL64);
result = result.setScale(2, RoundingMode.CEILING);
if (result.compareTo(BigDecimal.ZERO) > 0) {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("Recommended Dose: " + result + " Units");
Button b8 = (Button) findViewById(R.id.logsave);
b8.setEnabled(true);
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("No Insulin Needed");
}
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("");
Button b8 = (Button)findViewById(R.id.logsave);
b8.setEnabled(false);
}
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("");
Button b8 = (Button)findViewById(R.id.logsave);
b8.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
a2.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String currentlevelst = a1.getText().toString();
String carbseatenst = a2.getText().toString();
if (currentlevelst.length() >= 1) {
if (carbseatenst.length() >= 1) {
Double currentlevel = Double.parseDouble(a1.getText().toString());
Double carbseaten = Double.parseDouble(a2.getText().toString());
double firststep = 0;
if (currentlevel > targethigh) {
firststep = ((currentlevel - correctto) / correctiondose);
} else if (currentlevel < targetlow) {
firststep = ((currentlevel - targethigh) / correctiondose);
} else {
firststep = 0;
}
double secondstep = carbseaten / bolusdose;
double firstplussecond = firststep + secondstep;
BigDecimal result = new BigDecimal(firstplussecond, MathContext.DECIMAL64);
result = result.setScale(2, RoundingMode.CEILING);
if (result.compareTo(BigDecimal.ZERO) > 0) {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("Recommended Dose: " + result + " Units");
Button b8 = (Button) findViewById(R.id.logsave);
b8.setEnabled(true);
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("No Insulin Needed");
}
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("");
Button b8 = (Button)findViewById(R.id.logsave);
b8.setEnabled(false);
}
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("");
Button b8 = (Button)findViewById(R.id.logsave);
b8.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}else{
showDialog(0);
}}
public void addclickb(View b) throws InterruptedException {
if (b.getId() == R.id.add2) {
final EditText a1 = (EditText) findViewById(R.id.add1);
final EditText a2 = (EditText) findViewById(R.id.add2);
final double bolusdose = Double.parseDouble(mPrefs.getString("bolus", "0"));
final double correctiondose = Double.parseDouble(mPrefs.getString("correction", "0"));
final double targetlow = Double.parseDouble(mPrefs.getString("low", "0"));
final double targethigh = Double.parseDouble(mPrefs.getString("high", "0"));
final double correctto = Double.parseDouble(mPrefs.getString("corrset", "0"));
a2.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String currentlevelst = a1.getText().toString();
String carbseatenst = a2.getText().toString();
if (currentlevelst.length() >= 1) {
if (carbseatenst.length() >= 1) {
Double currentlevel = Double.parseDouble(a1.getText().toString());
Double carbseaten = Double.parseDouble(a2.getText().toString());
double firststep = 0;
if (currentlevel > targethigh) {
firststep = ((currentlevel - correctto) / correctiondose);
} else if (currentlevel < targetlow) {
firststep = ((currentlevel - targethigh) / correctiondose);
} else {
firststep = 0;
}
double secondstep = carbseaten / bolusdose;
double firstplussecond = firststep + secondstep;
BigDecimal result = new BigDecimal(firstplussecond, MathContext.DECIMAL64);
result = result.setScale(2, RoundingMode.CEILING);
if (result.compareTo(BigDecimal.ZERO) > 0) {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("Recommended Dose: " + result + " Units");
Button b8 = (Button) findViewById(R.id.logsave);
b8.setEnabled(true);
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("No Insulin Needed");
}
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}
public void noweditable(View a) {
if (a.getId() == R.id.editbutton) {
EditText b1 = (EditText)findViewById(R.id.bolus);
EditText b2 = (EditText)findViewById(R.id.correction);
EditText b3 = (EditText)findViewById(R.id.targetlow);
EditText b4 = (EditText)findViewById(R.id.targethigh);
EditText b5 = (EditText)findViewById(R.id.correcttonum);
Button b6 = (Button)findViewById(R.id.setter);
Button b7 = (Button)findViewById(R.id.editbutton);
b1.setEnabled(true);
b2.setEnabled(true);
b3.setEnabled(true);
b4.setEnabled(true);
b5.setEnabled(true);
b6.setEnabled(true);
b7.setEnabled(false);
}
}
public void setclick(View b) {
if (b.getId() == R.id.setter) {
EditText b1 = (EditText)findViewById(R.id.bolus);
if (b1.length() > 0) {
String bolussave = "" + b1.getText().toString();
SharedPreferences.Editor mEditor1 = mPrefs.edit();
mEditor1.putString("bolus", bolussave).commit();
}
EditText b2 = (EditText)findViewById(R.id.correction);
if (b2.length() > 0) {
String corrsave = "" + b2.getText().toString();
SharedPreferences.Editor mEditor2 = mPrefs.edit();
mEditor2.putString("correction", corrsave).commit();
}
EditText b3 = (EditText)findViewById(R.id.targetlow);
if (b3.length() > 0) {
String lowsave = "" + b3.getText().toString();
SharedPreferences.Editor mEditor3 = mPrefs.edit();
mEditor3.putString("low", lowsave).commit();
}
EditText b4 = (EditText)findViewById(R.id.targethigh);
if (b4.length() > 0) {
String highsave = "" + b4.getText().toString();
SharedPreferences.Editor mEditor4 = mPrefs.edit();
mEditor4.putString("high", highsave).commit();
}
EditText b5 = (EditText)findViewById(R.id.correcttonum);
if (b4.length() > 0) {
String corrsetsave = "" + b5.getText().toString();
SharedPreferences.Editor mEditor5 = mPrefs.edit();
mEditor5.putString("corrset", corrsetsave).commit();
}
b1.setEnabled(false);
b2.setEnabled(false);
b3.setEnabled(false);
b4.setEnabled(false);
b5.setEnabled(false);
Button b6 = (Button)findViewById(R.id.setter);
Button b7 = (Button)findViewById(R.id.editbutton);
b6.setEnabled(false);
b7.setEnabled(true);
}
}
public void logview(View b){
if(b.getId() == R.id.logview)
{
Intent myIntent = new Intent(MainActivity.this, Settings.class);
MainActivity.this.startActivity(myIntent);
}
}
public void logsave(View b){
if(b.getId() == R.id.logsave)
{
EditText l1 = (EditText)findViewById(R.id.add1);
EditText l2 = (EditText)findViewById(R.id.add2);
TextView l3 = (TextView)findViewById(R.id.answerobj);
SharedPreferences.Editor mEditor6 = mPrefs.edit();
int incrementer = mPrefs.getInt("increment",0);
incrementer++;
mEditor6.putInt("increment", incrementer).commit();
db=openOrCreateDatabase("logDB", Context.MODE_PRIVATE, null);
db.execSQL("INSERT INTO zlogtable VALUES('"+incrementer+"','"+l2.getText()+"','"+
l1.getText()+"','"+l3.getText()+"');");
Button b8 = (Button)findViewById(R.id.logsave);
b8.setEnabled(false);
b8.setText("Saved To Log");
}
}
protected Dialog onCreateDialog(int id){
// show disclaimer....
// for example, you can show a dialog box...
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Legal Notice: The content provided through this app is for informational purposes only and does not constitute medical advice. Reliance on any information provided by this application is solely at your own risk.")
.setCancelable(false)
.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// and, if the user accept, you can execute something like this:
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("accepted", true);
// Commit the edits!
editor.commit();
}
})
.setNegativeButton("Decline", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//nm.cancel(R.notification.running); // cancel the NotificationManager (icon)
System.exit(0);
}
});
AlertDialog alert = builder.create();
return alert;
}
}
Log Activity:
package com.software.roux.diabcalc;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class Settings extends AppCompatActivity {
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
setTitle("My Logs");
db=openOrCreateDatabase("logDB", Context.MODE_PRIVATE, null);
Cursor c=db.rawQuery("SELECT * FROM zlogtable", null);
if(c.getCount()==0)
{
System.out.print("Error");
return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
final TextView logfield = new TextView(this);
final LinearLayout layout = (LinearLayout) findViewById(R.id.loghold);
final LinearLayout layout1 = new LinearLayout(this);
final int identifier = c.getInt(0);
logfield.append("Blood Sugar Level: "+c.getString(2)+"\n");
logfield.append("Carbs Eaten: "+c.getString(1)+"\n");
logfield.append(""+c.getString(3)+"\n");
final Button deleter = new Button(this);
deleter.setText("Delete");
deleter.setTextSize(12);
layout1.addView(logfield);
layout1.addView(deleter);
layout.addView(layout1);
deleter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
layout1.removeView(deleter);
layout1.removeView(logfield);
db=openOrCreateDatabase("logDB", Context.MODE_PRIVATE, null);
db.execSQL("DELETE FROM zlogtable WHERE identity = "+identifier+" ");
}
});
}
TextView log1 = (TextView) findViewById(R.id.log1);
log1.setText(buffer.toString());
}
public void switchclick(View a) {
if (a.getId() == R.id.backbutton) {
Intent myIntent = new Intent(Settings.this, MainActivity.class);
Settings.this.startActivity(myIntent);
}
}
}

Looks like there is no column named 'identity' in your database. Can you check the column name for your db table.

Rotwang commented and found an error with this statement, I removed the string markers and it worked perfectly:
This is wrong: "CREATE TABLE IF NOT EXISTS zlogtable('identity VARCHAR'. Remove the ' string markers.

Related

Unable to instantiate activity. java.lang.IllegalAccessException: void com.example.myapp.FirstActivity.<init>() is not accessible from java.lang.Class

Whenever i start the app, the apps opens but as soon as i click anyone of the button 1 or button 2 of mainactivity, i get this error :
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.example.myapp/com.example.myapp.FirstActivity}: java.lang.IllegalAccessException:
void com.example.myapp.FirstActivity.<init>() is not accessible from
java.lang.Class<android.app.AppComponentFactory>
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3341)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3595)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at
android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2147)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7814)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
Caused by: java.lang.IllegalAccessException: void com.example.myapp.FirstActivity.<init>() is
not accessible from java.lang.Class<android.app.AppComponentFactory>
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1251)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3329)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3595) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
at
android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2147) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:237) 
at android.app.ActivityThread.main(ActivityThread.java:7814) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
I am trying to make a tic-tac-toe game with a save feature in which all the data goes to SQLite database and then retrieve the data to play the saved game. Whenever i press any button, the app crashes and the get error mentioned above. I run my app in my own phone android 11.
My code :
MainActivity :
package com.example.myapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn1 = findViewById(R.id.btn1);
btn1.setOnClickListener(this);
Button btn2 = findViewById(R.id.btn2);
btn2.setOnClickListener(this);
Button btn3 = findViewById(R.id.btn3);
btn3.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.btn1 :
Intent intent1 = new Intent(this, FirstActivity.class);
intent1.putExtra("KEY1", "VALUE1");
startActivity(intent1);
break;
case R.id.btn2 :
Intent intent2 = new Intent(this, SavedgameActivity.class);
intent2.putExtra("KEY2", "VALUE2");
startActivity(intent2);
break;
case R.id.btn3 :
break;
}
}
}
FirstActivity :
package com.example.myapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
public class FirstActivity extends AppCompatActivity implements View.OnClickListener {
ArrayList<Integer> a = new ArrayList<Integer>(9);
ArrayList<Integer> b = new ArrayList<Integer>(9);
boolean chance = true;
int c=-1,d=-1;
Button btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn10, btn11;
TextView txtview4;
TextView txtview5;
int score1 = 0, score2 = 0;
String savename = "";
DBhelper db;
FirstActivity() {
}
public FirstActivity(boolean check, int score1, int score2, boolean chance, int c, int d, String btn)
{
this.chance = chance;
this.score1 = score1;
this.score2 = score2;
this.chance = chance;
this.c = c;
this.d = d;
btn1.setText(btn.charAt(0));
btn2.setText(btn.charAt(1));
btn3.setText(btn.charAt(2));
btn4.setText(btn.charAt(3));
btn5.setText(btn.charAt(4));
btn6.setText(btn.charAt(5));
btn7.setText(btn.charAt(6));
btn8.setText(btn.charAt(7));
btn9.setText(btn.charAt(8));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
txtview4 = findViewById(R.id.textView4);
txtview5 = findViewById(R.id.textView5);
btn1 = findViewById(R.id.button1);
btn2 = findViewById(R.id.button2);
btn3 = findViewById(R.id.button3);
btn4 = findViewById(R.id.button4);
btn5 = findViewById(R.id.button5);
btn6 = findViewById(R.id.button6);
btn7 = findViewById(R.id.button7);
btn8 = findViewById(R.id.button8);
btn9 = findViewById(R.id.button9);
btn10 = findViewById(R.id.button10);
btn11 = findViewById(R.id.button11);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
btn10.setOnClickListener(this);
btn11.setOnClickListener(this);
db = new DBhelper(this);
}
#Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.button1 :
if(chance == true) {
c = c+1;
a.add(c, 1);
btn1.setText("X");
}
else {
d = d+1;
b.add(d, 1);
btn1.setText("O");
}
break;
case R.id.button2 :
if(chance == true) {
c = c+1;
a.add(c, 2);
btn2.setText("X");
}
else {
d = d+1;
b.add(d, 2);
btn2.setText("O");
}
break;
case R.id.button3 :
if(chance == true) {
c = c+1;
a.add(c, 3);
btn3.setText("X");
}
else {
d = d+1;
b.add(d, 3);
btn3.setText("O");
}
break;
case R.id.button4 :
if(chance == true) {
c = c+1;
a.add(c, 4);
btn4.setText("X");
}
else {
d = d+1;
b.add(d, 4);
btn4.setText("O");
}
break;
case R.id.button5 :
if(chance == true) {
c = c+1;
a.add(c, 5);
btn5.setText("X");
}
else {
d = d+1;
b.add(d, 5);
btn5.setText("O");
}
break;
case R.id.button6 :
if(chance == true) {
c = c+1;
a.add(c, 6);
btn6.setText("X");
}
else {
d = d+1;
b.add(d, 6);
btn6.setText("O");
}
break;
case R.id.button7 :
if(chance == true) {
c = c+1;
a.add(c, 7);
btn7.setText("X");
}
else {
d = d+1;
b.add(d, 7);
btn7.setText("O");
}
break;
case R.id.button8 :
if(chance == true) {
c = c+1;
a.add(c, 8);
btn8.setText("X");
}
else {
d = d+1;
b.add(d, 8);
btn8.setText("O");
}
break;
case R.id.button9 :
if(chance == true) {
c = c+1;
a.add(c, 9);
btn9.setText("X");
}
else {
d = d+1;
b.add(d, 9);
btn9.setText("O");
}
break;
case R.id.button10 :
String btn = btn1.getText().toString() + btn2.getText().toString() +
btn3.getText().toString() + btn4.getText().toString() + btn5.getText().toString() +
btn6.getText().toString() + btn7.getText().toString() + btn8.getText().toString() +
btn9.getText().toString();
SavedgameActivity sga = new SavedgameActivity(false, score1, score2, chance, c, d, btn);
Intent intent = new Intent(FirstActivity.this, SavedgameActivity.class);
intent.putExtra("KEY3", "VALUE3");
startActivity(intent);
break;
case R.id.button11 :
finish();
break;
}
if(chance == true)
chance = false;
else
chance = true;
if((a.contains(1) && a.contains(2) && a.contains(3))||(a.contains(4) && a.contains(5) &&
a.contains(6))||((a.contains(7) && a.contains(8) && a.contains(9)))||(a.contains(1) && a.contains(4)
&& a.contains(7))||(a.contains(2) && a.contains(5) && a.contains(8))||(a.contains(3) && a.contains(6)
&& a.contains(9))||(a.contains(1) && a.contains(5) && a.contains(9))||(a.contains(3) && a.contains(5)
&& a.contains(7))) {
score1++;
txtview4.setText("" + score1);
btn1.setText("");
btn2.setText("");
btn3.setText("");
btn4.setText("");
btn5.setText("");
btn6.setText("");
btn7.setText("");
btn8.setText("");
btn9.setText("");
c = -1;
d = -1;
a.clear();
b.clear();
if((score1 + score2)%2 == 0)
chance = true;
else
chance = false;
}
else if((b.contains(1) && b.contains(2) && b.contains(3))||(b.contains(4) && b.contains(5) &&
b.contains(6))||((b.contains(7) && b.contains(8) && b.contains(9)))||(b.contains(1) && b.contains(4)
&& b.contains(7))||(b.contains(2) && b.contains(5) && b.contains(8))||(b.contains(3) && b.contains(6)
&& b.contains(9))||(b.contains(1) && b.contains(5) && b.contains(9))||(b.contains(3) && b.contains(5)
&& b.contains(7))) {
score2++;
txtview5.setText("" + score2);
btn1.setText("");
btn2.setText("");
btn3.setText("");
btn4.setText("");
btn5.setText("");
btn6.setText("");
btn7.setText("");
btn8.setText("");
btn9.setText("");
c = -1;
d = -1;
a.clear();
b.clear();
if ((score1 + score2) % 2 == 0)
chance = true;
else
chance = false;
}
}
}
SavedGameActivity :
package com.example.myapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class SavedgameActivity extends AppCompatActivity {
boolean check = true;
int score1;
int score2;
boolean chance, dialogcheck, isupdated, isinserted;
int c;
int d;
String btn;
DBhelper db = new DBhelper(this);
TextView txt6, txt7, txt8;
Button btn12, btn13, btn14;
SavedgameActivity() {
}
public SavedgameActivity(boolean check, int score1, int score2, boolean chance, int c, int d, String
btn) {
this.check = check;
this.score1 = score1;
this.score2 = score2;
this.chance = chance;
this.c = c;
this.d = d;
this.btn = btn;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_savedgame);
if(check == false) {
falsemethod();
}
else
truemethod();
}
public void falsemethod() {
btn12 = findViewById(R.id.button12);
btn13 = findViewById(R.id.button13);
btn14 = findViewById(R.id.button14);
txt6 = findViewById(R.id.textView6);
txt7 = findViewById(R.id.textView7);
txt8 = findViewById(R.id.textView8);
Cursor savegame1 = db.getgame(txt6.getText().toString());
Cursor savegame2 = db.getgame(txt7.getText().toString());
Cursor savegame3 = db.getgame(txt8.getText().toString());
ArrayList<String> itemIds1 = new ArrayList<String>();
while(savegame1.moveToNext()) {
itemIds1.add(savegame1.getString(savegame1.getColumnIndex("id")));
}
savegame1.close();
ArrayList<String> itemIds2 = new ArrayList<String>();
while(savegame2.moveToNext()) {
itemIds2.add(savegame2.getString(savegame2.getColumnIndex("id")));
}
savegame2.close();
ArrayList<String> itemIds3 = new ArrayList<String>();
while(savegame3.moveToNext()) {
itemIds3.add(savegame3.getString(savegame3.getColumnIndex("id")));
}
savegame3.close();
if(Integer.parseInt(itemIds1.get(0)) < 1)
btn12.setText("Save");
else
btn12.setText("Override and Save");
if(Integer.parseInt(itemIds2.get(0)) < 1)
btn12.setText("Save");
else
btn12.setText("Override and Save");
if(Integer.parseInt(itemIds2.get(0)) < 1)
btn12.setText("Save");
else
btn12.setText("Override and Save");
btn12.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(Integer.parseInt(itemIds1.get(0)) < 1)
isinserted = db.addgame(score1, score2, chance, c, d, btn);
else
isupdated = db.updategame(score1, score2, chance, c, d, btn,
btn12.getText().toString());
}
});
btn13.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(Integer.parseInt(itemIds2.get(0)) < 1)
isinserted = db.addgame(score1, score2, chance, c, d, btn);
else
isupdated = db.updategame(score1, score2, chance, c, d, btn,
btn13.getText().toString());
}
});
btn14.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(Integer.parseInt(itemIds3.get(0)) < 1)
isinserted = db.addgame(score1, score2, chance, c, d, btn);
else
isupdated = db.updategame(score1, score2, chance, c, d, btn,
btn14.getText().toString());
}
});
if((isinserted == true) || (isupdated == true))
Toast.makeText(SavedgameActivity.this, "Game Saved", Toast.LENGTH_LONG).show();
else
Toast.makeText(SavedgameActivity.this, "Game Not Saved", Toast.LENGTH_LONG).show();
}
public void truemethod() {
btn12.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cursor Getgame = db.getgame(txt6.getText().toString());
ArrayList<Long> itemIds = new ArrayList<Long>();
while(Getgame.moveToNext()) {
long itemId = Getgame.getLong(
Getgame.getColumnIndexOrThrow("id"));
itemIds.add(itemId);
}
Getgame.close();
if (itemIds.get(0) < 1)
Toast.makeText(SavedgameActivity.this, "Game not saved yet", Toast.LENGTH_LONG).show();
else {
FirstActivity fa = new FirstActivity(check, score1, score2, chance, c, d, btn);
Intent intent = new Intent();
intent.putExtra("KEY4", "VALUE4");
startActivity(intent);
}
}
});
}
public void setCheck(boolean check) {
this.check = check;
}
}
DBhelper class :
package com.example.myapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class DBhelper extends SQLiteOpenHelper {
SQLiteDatabase db = this.getWritableDatabase();
SQLiteDatabase db1 = this.getReadableDatabase();
public DBhelper(#Nullable Context context) {
super(context, "Database", null, 1);
SQLiteDatabase database = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE Save(id INTEGER PRIMARY KEY AUTOINCREMENT, score1 INTEGER, score2
INTEGER, chance BOOLEAN, c INTEGER, d INTEGER, btn TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public boolean addgame(int Score1, int Score2, boolean Chance, int C, int D, String Btn) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("score1", Score1);
cv.put("score2", Score2);
cv.put("chance", Chance);
cv.put("c", C);
cv.put("d", D);
cv.put("btn", Btn);
long result = db.insert("Save", null, cv);
if(result == -1)
return false;
else
return true;
}
public Cursor getgame(String a) {
Cursor res = db.query("Save", null, "id = ?", new String[]{a}, null, null, "btn DESC");
return res;
}
public boolean updategame(int Score1, int Score2, boolean Chance, int C, int D, String Btn, String
id) {
int nameid = Integer.parseInt(id);
ContentValues cv = new ContentValues();
cv.put("id", nameid);
cv.put("score1", Score1);
cv.put("score2", Score2);
cv.put("chance", Chance);
cv.put("c", C);
cv.put("d", D);
cv.put("btn", Btn);
long result = db1.update("Save", cv, "id = ?", new String[]{id});
if(result == -1)
return false;
else
return true;
}
public void closedb() {
db.close();
}
}
Mainfest file :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.MyApp">
<activity android:name=".SavedgameActivity" />
<activity android:name=".FirstActivity" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Please give me a solution. Thanks.
There's no visibility modifier for the default constructor in the FirstActivity class. When you do not specify a visibility modifier, the field or the method won't be accessible from the outside of the package. Android is trying to create that class with the empty constructor, but it can't, because it's not in the same package as your class.
You should set it as public like this:
public FirstActivity() {
}
The same thing goes with SavedGameActivity class, otherwise, you'll have the same problem in the future.
Your Activity empty constructor is protected. hence it's not accessible.
You should never make your activity empty constructor non-public.
And to pass variables that you want to pass to an Activity you can pass them in Intent as extras, which you can extract in onCreate() of your activity.
It seems to me that you are trying to instantiate activity using a custom constructor, which is not possible in Android. Try to remove constructors for your FirstActivity and SavedgameActivity. If you need to pass some data to the activities, you should pass them as a part of the intent starting the activity. Simply remove public FirstActivity(boolean check, int score1, int score2, boolean chance, int c, int d, String btn) and public SavedgameActivity(boolean check, int score1, int score2, boolean chance, int c, int d, String btn) and try again.

How to pass retrieved data to editText?

Good day everyone. Can someone tell me how can I retrieve the data from SQLite to editText? I have referred to Android::Data are not retrieving to EditText field through Database but it not working for me..
DisplayData.java
private void BuildTable(String names,String date1)
{
final String name = names;
final String date=date1;
sqlcon.open();
Cursor c = sqlcon.readEntry(name);
int rows = c.getCount();
int cols = c.getColumnCount();
c.moveToFirst();
TableRow rowDayLabels=new TableRow(this);
TextView weather=new TextView(this);
weather.setText("Weather");
weather.setTypeface(Typeface.SERIF, Typeface.BOLD);
TextView dater=new TextView(this);
dater.setText("Date");
dater.setTypeface(Typeface.SERIF, Typeface.BOLD);
TextView status=new TextView(this);
status.setText("Status");
status.setTypeface(Typeface.SERIF, Typeface.BOLD);
TextView timeIn=new TextView(this);
timeIn.setText("Time In");
timeIn.setTypeface(Typeface.SERIF, Typeface.BOLD);
TextView timeOut=new TextView(this);
timeOut.setText("Time Out");
timeOut.setTypeface(Typeface.SERIF, Typeface.BOLD);
rowDayLabels.addView(weather);
rowDayLabels.addView(dater);
rowDayLabels.addView(status);
rowDayLabels.addView(timeIn);
rowDayLabels.addView(timeOut);
table_layout.addView(rowDayLabels);
// outer for loop
for (int i = 0; i < rows; i++) {
TableRow row = new TableRow(this);
row.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
// inner for loop
for (int j = 0; j < cols; j++) {
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
// tv.setBackgroundResource(R.drawable.cell_shape);
tv.setGravity(Gravity.CENTER);
tv.setTextSize(18);
tv.setPadding(0, 5, 0, 5);
tv.setText(c.getString(j));
row.addView(tv);
row.setBackgroundColor(Color.GREEN);
row.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(DisplayData.this, UpdatePage.class);
intent.putExtra("name", name);
intent.putExtra("date",date);
startActivity(intent);
}
});
}
c.moveToNext();
table_layout.addView(row);
}
sqlcon.close();
}
}
UpdateDetails.java
package com.example.project.project;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.project.project.API.InfoAPI;
import com.example.project.project.TimeSheet.Details;
import com.example.project.project.TimeSheet.Force;
import com.example.project.project.TimeSheet.Info;
import com.example.project.project.database.MyDatabaseHelper;
public class UpdatePage extends AppCompatActivity {
InfoAPI sqlcon;
private SQLiteDatabase database;
private MyDatabaseHelper dbHelper;
private Cursor c;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbHelper = new MyDatabaseHelper(this);
setContentView(R.layout.updatepage);
final String name1 = getIntent().getExtras().getString("name");
final String date = getIntent().getExtras().getString("date");
RetrievePage(name1, date);
}
public void RetrievePage(String name, String date) {
final String name2 = name;
final String date2 = date;
final EditText name3 = (EditText) findViewById(R.id.editText9);
final EditText date3 = (EditText) findViewById(R.id.editText12);
name3.setText(name2);
date3.setText(date2);
//final Spinner weather3 = (Spinner) findViewById(R.id.spinner5);
//final Spinner status3 = (Spinner) findViewById(R.id.spinner7);
final EditText subC3 = (EditText) findViewById(R.id.editText17);
final EditText noP = (EditText) findViewById(R.id.editText18);
final EditText noH = (EditText) findViewById(R.id.editText19);
final Spinner poject3 = (Spinner) findViewById(R.id.spinner8);
database = dbHelper.getWritableDatabase();
c = database.rawQuery("SELECT w.Subcontractors, w.NumberOfPerson, w.NumberOfHours FROM Information i LEFT JOIN WorkForce w ON w.TInfo_id = i.ID WHERE i.Name = ? AND i.Date= ? ",
new String[]{String.valueOf(name2),String.valueOf(date2)}, null);
if (c != null) {
c.moveToFirst();
while (c.moveToNext()) {
Info I = new Info();
Details WD = new Details();
// String Weather = c.getString(c.getColumnIndexOrThrow(MyDatabaseHelper.Weather));
//String Status = c.getString(c.getColumnIndexOrThrow(MyDatabaseHelper.Status));
String SubC = c.getString(c.getColumnIndex(MyDatabaseHelper.Subcontractors));
String NoP = c.getString(c.getColumnIndex(MyDatabaseHelper.NumberOfPerson));
String NoH = c.getString(c.getColumnIndex(MyDatabaseHelper.NumberOfHours));
Force WF = new Force();
WF.setSubcontractors(SubC);
WF.setNoOfPerson(NoP);
WF.setNoOfHours(NoH);
subC3.setText(SubC);
noP.setText(NoP);
noH.setText(NoH);
}
}
c.close();
}
}
Force.java
public class Force {
private int id1;
private String subcontractors;
private String noOfPerson;
private String noOfHours;
public void setID(int id1)
{
this.id1=id1;
}
public int getID()
{
return this.id1;
}
public void setSubcontractors(String subcontractors)
{
this.subcontractors=subcontractors;
}
public String getSubcontractors()
{
return this.subcontractors;
}
public void setNoOfPerson(String noOfPerson)
{
this.noOfPerson=noOfPerson;
}
public String getNoOfPerson()
{
return this.noOfPerson;
}
public void setNoOfHours(String noOfHours)
{
this.noOfHours=noOfHours;
}
public String getNoOfHours()
{
return this.noOfHours;
}
}
Did I miss anything ? Please let me know! Any suggestions would be great. Thanks
If you are expecting only one row returned in the cursor you shouldn't call moveTofirst and moveToNext immediately before performing your operations. You are moving to the second row in the cursor by calling these functions immediately. My guess is that your cursor has only one row and your code in while loop is not being executed. Error might be here
if (c != null) {
c.moveToFirst();
while (c.moveToNext()) {
Info I = new Info();
}
}
You should be doing something like this
if (c != null) {
while (c.moveToNext()) {
Info I = new Info();
}
}

radiogroup.setOnCheckedListener is not working as expected .(Changing color of radio buttons)

I'm having a activity which has question and answer section with a question with 4 choices in a radio group. On choosing answer it must change the background of answer to green or red(based on right or wrong).
I have a activity which calls a BaseAdapter class which listens the setOnCheckedListener.
PreviewAdapter.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.content.Context;
import android.graphics.Color;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
import technibits.com.pme.R;
import technibits.com.pme.activity.AsyncTaskCall;
import technibits.com.pme.activity.MasterDownload;
import technibits.com.pme.activity.PreviewActivity;
import technibits.com.pme.activity.ReviewFragment;
import technibits.com.pme.data.Quizdata;
import technibits.com.pme.data.ResultData;
public class PreviewAdapter extends BaseAdapter {
private Context context;
ReviewFragment activity;
Quizdata data;
String formID;
EditText dateText;
public ViewHolderA viewHolder;
int queNo;
int size;
String select;
public ResultData resData;
String urlMark = "xx.com/mark-for-review.php";
String urlRemove = "xx.com/mark-for-review-delete.php";
public RadioButton rButton = null;
HashMap<String, String> editTextvalue = new HashMap<String, String>();
MasterDownload httpRequest;
public String ansOption;
PreviewActivity previewActivity;
public PreviewAdapter(Context conte, Quizdata form, int qNO, int device, String strSelect ) {
super();
context = conte;
data = form;
queNo = qNO + 1;
size = device;
select = strSelect;
// previewActivity=pv;
}
#Override
public int getCount() {
return 3;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (size == 7) {
row = mInflater.inflate(R.layout.quiz_layout_seven, parent, false);
} else {
row = mInflater.inflate(R.layout.quiz_layout, parent, false);
}
if (row != null) {
viewHolder = new ViewHolderA();
viewHolder.reviewLayout = (LinearLayout) row.findViewById(R.id.review);
viewHolder.questionLayout = (LinearLayout) row.findViewById(R.id.question);
viewHolder.answerLayout = (LinearLayout) row.findViewById(R.id.answer);
viewHolder.questionView = (TextView) viewHolder.questionLayout.findViewById(R.id.questionView);
viewHolder.textQno = (TextView) row.findViewById(R.id.qNo);
viewHolder.radioGroup = (RadioGroup) row.findViewById(R.id.radioGroup);
viewHolder.rButton1 = (RadioButton) row.findViewById(R.id.RadioButton01);
viewHolder.rButton2 = (RadioButton) row.findViewById(R.id.RadioButton02);
viewHolder.rButton3 = (RadioButton) row.findViewById(R.id.RadioButton03);
viewHolder.rButton4 = (RadioButton) row.findViewById(R.id.RadioButton04);
viewHolder.reviewBox = (CheckBox) row.findViewById(R.id.rCheckBox);
viewHolder.showReview = (Button) row.findViewById(R.id.showReview);
// viewHolder.infoButton = (Button) row.findViewById(R.id.info);
} else {
viewHolder = (ViewHolderA) row.getTag();
}
if (position == 0) {
viewHolder.reviewLayout.setVisibility(View.VISIBLE);
viewHolder.questionLayout.setVisibility(View.GONE);
viewHolder.answerLayout.setVisibility(View.GONE);
int check = data.getISchecked();
if (check == 1) {
viewHolder.reviewBox.setChecked(true);
} else {
viewHolder.reviewBox.setChecked(false);
}
// String review = data.getStatus();
// if (review != null) {
// if (review.equals("A")) {
viewHolder.reviewBox.setEnabled(false);
// }
// }
if (select != null) {
viewHolder.reviewLayout.setVisibility(View.GONE);
}
} else if (position == 1) {
viewHolder.questionLayout.setVisibility(View.VISIBLE);
viewHolder.reviewLayout.setVisibility(View.GONE);
viewHolder.answerLayout.setVisibility(View.GONE);
viewHolder.questionView.setText(data.getQuestion());
viewHolder.textQno.setText("Q." + String.valueOf(queNo));
} else if (position == 2) {
viewHolder.answerLayout.setVisibility(View.VISIBLE);
viewHolder.questionLayout.setVisibility(View.GONE);
viewHolder.reviewLayout.setVisibility(View.GONE);
viewHolder.radioGroup.setEnabled(true);
viewHolder.rButton1.setText(data.getOptionA());
viewHolder.rButton2.setText(data.getOptionB());
viewHolder.rButton3.setText(data.getOptionC());
viewHolder.rButton4.setText(data.getOptionD());
final View uiview = row;
// viewHolder.rButton1.setBackgroundColor(Color.YELLOW);-------> Here color changes occur
if (select != null) {
viewHolder.radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
ansOption = "yes";
data.setIsAnswer(1);
int answer = Integer.valueOf(data.getAnswer());
int selected = -1;
if (checkedId == R.id.RadioButton01) {
selected = 1;
rButton = viewHolder.rButton1;
viewHolder.rButton1.setBackgroundColor(Color.YELLOW);
} else if (checkedId == R.id.RadioButton02) {
selected = 2;
rButton = viewHolder.rButton2;
} else if (checkedId == R.id.RadioButton03) {
selected = 3;
rButton = viewHolder.rButton3;
} else if (checkedId == R.id.RadioButton04) {
selected = 4;
rButton = viewHolder.rButton4;
}
if (rButton != null) {
if (answer + 1 == selected) {
rButton.setBackgroundColor(Color.GREEN);-------> Here color changes is not working
String dd = rButton.getText().toString();
rButton.setText("Correct answer");
} else {
rButton.setBackgroundColor(Color.RED);
data.setWrongAnswer(selected);
String dd = rButton.getText().toString();
System.out.println(dd);
}
}
if (answer == 0) {
viewHolder.rButton1.setBackgroundColor(Color.GREEN);
} else if (answer == 1) {
viewHolder.rButton2.setBackgroundColor(Color.GREEN);
} else if (answer == 2) {
viewHolder.rButton3.setBackgroundColor(Color.GREEN);
} else if (answer == 3) {
viewHolder.rButton4.setBackgroundColor(Color.GREEN);
}
for (int i = 0; i < viewHolder.radioGroup.getChildCount(); i++) {
viewHolder.radioGroup.getChildAt(i).setEnabled(false);
}
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userid", "android#gmail.com"));
params.add(new BasicNameValuePair("qid", data.getQuestionID()));
AsyncTaskCall ask = new AsyncTaskCall(context, "review", params);
ask.execute(urlRemove);
}
});
} else {
System.out.println("data.getIsAnswer() " + data.getIsAnswer());
if (data.getIsAnswer() == 1) {
int wrong = data.getWrongAnswer();
int selected = -1;
if (wrong == 1) {
selected = 1;
rButton = viewHolder.rButton1;
setcolorGreen(viewHolder.rButton1);
} else if (wrong == 2) {
selected = 2;
rButton = viewHolder.rButton2;
} else if (wrong == 3) {
selected = 3;
rButton = viewHolder.rButton3;
} else if (wrong == 4) {
selected = 4;
rButton = viewHolder.rButton4;
}
int answer = Integer.valueOf(data.getAnswer());
if (rButton != null) {
if (answer + 1 == selected) {
rButton.setBackgroundColor(Color.GREEN);
} else {
rButton.setBackgroundColor(Color.RED);
}
}
if (answer == 0) {
viewHolder.rButton1.setBackgroundColor(Color.GREEN);
} else if (answer == 1) {
viewHolder.rButton2.setBackgroundColor(Color.GREEN);
} else if (answer == 2) {
viewHolder.rButton3.setBackgroundColor(Color.GREEN);
} else if (answer == 3) {
viewHolder.rButton4.setBackgroundColor(Color.GREEN);
}
for (int i = 0; i < viewHolder.radioGroup.getChildCount(); i++) {
viewHolder.radioGroup.getChildAt(i).setEnabled(false);
}
}
}
}
else
{
viewHolder.answerLayout.setVisibility(View.GONE);
viewHolder.questionLayout.setVisibility(View.GONE);
viewHolder.reviewLayout.setVisibility(View.GONE);
}
return row;
}
static class ViewHolderA {
LinearLayout reviewLayout;
LinearLayout questionLayout;
LinearLayout answerLayout;
Button showReview;
TextView questionView;
TextView textQno;
RadioGroup radioGroup;
public RadioButton rButton1;
public RadioButton rButton2;
public RadioButton rButton3;
public RadioButton rButton4;
CheckBox reviewBox;
}
void setcolorGreen(RadioButton rb){
rb.setBackgroundColor(Color.GREEN);
Toast.makeText(context,"Correct",Toast.LENGTH_SHORT).show();
}
void setcolorRed(RadioButton rb){
rb.setBackgroundColor(Color.RED);
Toast.makeText(context,"Wrong",Toast.LENGTH_SHORT).show();
}
}
The class calling this is
PreviewActivity.java
public class PreviewActivity extends Activity {
int device;
Button priv;
Button next;
boolean pCheck;
boolean nCheck;
Quizdata dataSource;
int count, position;
String select;
int iNext = 0;
ListView list;
ArrayList<Quizdata> data;
Context context;
TestAdapter adapter;
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int widthPixels = metrics.widthPixels;
int heightPixels = metrics.heightPixels;
float scaleFactor = metrics.density;
float widthDp = widthPixels / scaleFactor;
float heightDp = heightPixels / scaleFactor;
float smallestWidth = Math.min(widthDp, heightDp);
if (smallestWidth > 720) {
device = 10;
} else if (smallestWidth >= 600) {
device = 7; //Device is a 7" tablet
setContentView(R.layout.study_mode_seven);
} else {
setContentView(R.layout.study_mode);
}
// Bundle bundle = getIntent().getExtras();
list = (ListView) findViewById(R.id.listView1);
data = (ArrayList<Quizdata>) getIntent().getSerializableExtra("data");
count = getIntent().getExtras().getInt("count");
select = getIntent().getExtras().getString("review");
position = getIntent().getExtras().getInt("question_no");
// count = data.size();
if (data.size() > 0) {
dataSource = data.get(position);
adapter = new TestAdapter(context, dataSource, iNext, device, select);
// adapter.resData = resData;
list.setAdapter(adapter);
}
priv = (Button) findViewById(R.id.prev);
next = (Button) findViewById(R.id.next);
Button exp = (Button) findViewById(R.id.exp);
list = (ListView) findViewById(R.id.listView1);
priv.setEnabled(false);
if (select != null) {
priv.setVisibility(View.GONE);
exp.setVisibility(View.GONE);
next.setVisibility(View.GONE);
}
exp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Explanation");
alert.setMessage(dataSource.getDescription());
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do something with value!
}
});
alert.show();
}
});
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (next.getText().toString().equals("Next")) {
priv.setEnabled(true);
if (iNext == 0) {
iNext = 1;
pCheck = true;
}
if (nCheck) {
iNext++;
}
if (iNext < count) {
dataSource = data.get(iNext);
PreviewAdapter adapter = new PreviewAdapter(context, dataSource, iNext, device, select);
list.setAdapter(adapter);
priv.setEnabled(true);
iNext++;
pCheck = true;
nCheck = false;
}
if (iNext == count) {
// next.setEnabled(false);
next.setText("Finish");
// next.setBackgroundColor(Color.RED);
iNext = count - 1;
pCheck = false;
}
} else {
finish();
}
}
});
priv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
if (iNext == count) {
iNext = count - 1;
}
if (pCheck) {
iNext--;
}
if (iNext > 0) {
iNext--;
dataSource = data.get(iNext);
PreviewAdapter adapter = new PreviewAdapter(context, dataSource, iNext, device, select);
// adapter.resData = resData;
list.setAdapter(adapter);
next.setEnabled(true);
if (next.getText().toString().equals("Finish")) {
next.setText("Next");
// next.setBackgroundDrawable(priv.getBackground());
}
nCheck = true;
pCheck = false;
}
if (iNext == 0) {
priv.setEnabled(false);
iNext = 0;
nCheck = false;
}
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
sendMessage();
}
private void sendMessage() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", adapter.ansOption);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
The Activity calling above is
PreviewActivity.java
package technibits.com.pme.activity;
import java.util.ArrayList;
import technibits.com.pme.R;
import technibits.com.pme.adapter.PreviewAdapter;
import technibits.com.pme.adapter.TestAdapter;
import technibits.com.pme.data.Quizdata;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
public class PreviewActivity extends Activity {
int device;
Button priv;
Button next;
boolean pCheck;
boolean nCheck;
Quizdata dataSource;
int count, position;
String select;
int iNext = 0;
ListView list;
ArrayList<Quizdata> data;
Context context;
TestAdapter adapter;
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int widthPixels = metrics.widthPixels;
int heightPixels = metrics.heightPixels;
float scaleFactor = metrics.density;
float widthDp = widthPixels / scaleFactor;
float heightDp = heightPixels / scaleFactor;
float smallestWidth = Math.min(widthDp, heightDp);
if (smallestWidth > 720) {
device = 10;
} else if (smallestWidth >= 600) {
device = 7; //Device is a 7" tablet
setContentView(R.layout.study_mode_seven);
} else {
setContentView(R.layout.study_mode);
}
// Bundle bundle = getIntent().getExtras();
list = (ListView) findViewById(R.id.listView1);
data = (ArrayList<Quizdata>) getIntent().getSerializableExtra("data");
count = getIntent().getExtras().getInt("count");
select = getIntent().getExtras().getString("review");
position = getIntent().getExtras().getInt("question_no");
// count = data.size();
if (data.size() > 0) {
dataSource = data.get(position);
adapter = new TestAdapter(context, dataSource, iNext, device, select);
// adapter.resData = resData;
list.setAdapter(adapter);
}
priv = (Button) findViewById(R.id.prev);
next = (Button) findViewById(R.id.next);
Button exp = (Button) findViewById(R.id.exp);
list = (ListView) findViewById(R.id.listView1);
priv.setEnabled(false);
if (select != null) {
priv.setVisibility(View.GONE);
exp.setVisibility(View.GONE);
next.setVisibility(View.GONE);
}
exp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Explanation");
alert.setMessage(dataSource.getDescription());
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do something with value!
}
});
alert.show();
}
});
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (next.getText().toString().equals("Next")) {
priv.setEnabled(true);
if (iNext == 0) {
iNext = 1;
pCheck = true;
}
if (nCheck) {
iNext++;
}
if (iNext < count) {
dataSource = data.get(iNext);
PreviewAdapter adapter = new PreviewAdapter(context, dataSource, iNext, device, select);
list.setAdapter(adapter);
priv.setEnabled(true);
iNext++;
pCheck = true;
nCheck = false;
}
if (iNext == count) {
// next.setEnabled(false);
next.setText("Finish");
// next.setBackgroundColor(Color.RED);
iNext = count - 1;
pCheck = false;
}
} else {
finish();
}
}
});
priv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
if (iNext == count) {
iNext = count - 1;
}
if (pCheck) {
iNext--;
}
if (iNext > 0) {
iNext--;
dataSource = data.get(iNext);
PreviewAdapter adapter = new PreviewAdapter(context, dataSource, iNext, device, select);
// adapter.resData = resData;
list.setAdapter(adapter);
next.setEnabled(true);
if (next.getText().toString().equals("Finish")) {
next.setText("Next");
// next.setBackgroundDrawable(priv.getBackground());
}
nCheck = true;
pCheck = false;
}
if (iNext == 0) {
priv.setEnabled(false);
iNext = 0;
nCheck = false;
}
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
sendMessage();
}
private void sendMessage() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", adapter.ansOption);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
When i debugged the Adapter class, it perfectly goes as per logic of app. but the color alone is not changing.
What is the problem possibly occured?
The view(row) did not have scope inside the listener. so i declared that view to a final view(uiview) which did have scope inside the onChecklistener. after that it works cool. But still i didn't know the reason for not working of the previous method .

Difficulty saving and storing

I am trying to save and store data in an android app using java. At the moment the data will not save and it causes my app to crash. Can anyone make any suggestions to my code? Part of my page includes a total budget and I am difficulty storing and saving the total budget.
public class Summary extends Activity implements TextWatcher, View.OnClickListener
{
DecimalFormat df = new DecimalFormat("£0.00");
int noOfGifts, giftsPurchased;
double cost;
EditText budgetEntered;
double savedBudget = 0;
String budgetString;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.summary);
budgetEntered = (EditText) findViewById(R.id.s2TotalBudget);
budgetEntered.addTextChangedListener(this);
Button saveBudget = (Button) findViewById(R.id.s2ViewList);
saveBudget.setOnClickListener(saveButtonListener);
if(savedBudget != 0)
{
saveBudget.setText(budgetString);
}
Bundle passedInfo = getIntent().getExtras();
if (passedInfo != null)
{
cost = passedInfo.getDouble("cost");
noOfGifts = passedInfo.getInt("noOfGifts");
giftsPurchased = passedInfo.getInt("giftsPurchased");
}
Button logoutButton = (Button) findViewById(R.id.s2LogoutButton);
logoutButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(Summary.this, MainActivity.class);
startActivity(myIntent);
}
});
Button viewList = (Button) findViewById(R.id.s2ViewList);
viewList.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(Summary.this, GiftList.class);
startActivity(myIntent);
}
});
String [][] summary = {{"Number of Presents to buy: ", (noOfGifts + "")},
{"Number of Presents bought:", (giftsPurchased + "")},
{"Cost: £", (cost + "")},
{"Budget: £", "50"}};
String passedBudget=null;
//convert totalPresents to double from String
String tempPresents = summary[0][1];
int presents = Integer.parseInt(tempPresents);
//convert presentsBought to double from String
String tempBought = summary[1][1];
int presentsToBuy = Integer.parseInt(tempBought);
//Number of presents
TextView s2PresentResult = (TextView) findViewById(R.id.s2PresentsResult);
s2PresentResult.setText(summary[0][1]);
//Number of presents to buy
TextView s2PresentsBuyResult = (TextView) findViewById(R.id.s2PresntsBuyResult);
s2PresentsBuyResult.setText((noOfGifts - giftsPurchased) + "");
Bundle passedId = getIntent().getExtras();
if (passedId != null)
{
passedBudget = passedId.getString("Enter Budget");
}
//EditText s2TotalBudget = (EditText) findViewById(R.id.s2TotalBudget);
//s2TotalBudget .addTextChangedListener((android.text.TextWatcher) this);
//s2TotalBudget .setText(passedBudget, TextView.BufferType.EDITABLE);
//Number of people
//TextView s2TotalBudget = (TextView) findViewById(R.id.s2TotalBudget);
//s2TotalBudget.setText("Enter budget");
//Number of people
TextView s2TotalCost = (TextView) findViewById(R.id.s2TotalCost);
s2TotalCost.setText(df.format(Double.parseDouble(summary[2][1])));
//Output if over or under budget
TextView s2CalculateOverBudget = (TextView) findViewById(R.id.s2CalculateOverBudget);
//convert totalCost to double from String
String temp = summary[2][1];
double totalCost = Double.parseDouble(temp);
//convert totalBudget to double from String
String tempTwo = "14";
double totalBudget = Double.parseDouble(tempTwo);
if((totalCost>totalBudget)&&(totalBudget!=0))
{
s2CalculateOverBudget.setTextColor(Color.rgb(209,0,0));
s2CalculateOverBudget.setText("You are over budget");
}
else if(totalBudget==0){
s2CalculateOverBudget.setText("");
}
else {
s2CalculateOverBudget.setText("You are within budget");
}
}
public View.OnClickListener saveButtonListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(budgetEntered.getText().length()>0)
{
budgetString = budgetEntered.getText().toString();
}
}
};
public void onClick(View v)
{
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void afterTextChanged(Editable s)
{
this it the best way to store and load value in Android:
save values: (put this where you want to save the values, for example in the onStop or onPause method. Or, in your case, in the onClick method)
SharedPreferences settings = getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("testValue", value);
editor.commit();
load values:
SharedPreferences settings = getSharedPreferences("MyPref", 0);
value = settings.getInt("testValue", defValue);

A way to save Arraylist on device?

So I have this little application where you can call from.
In this application, You will be able to log in with your phone-number and get a number from our server (This is not implemented YET)
Depending on "Who you are", our server will give you a number dynamically.
This is not really relevant, but it still has some things to do with my question.
Since our server gives the number, I can't make a "Recent List" with the info I get from Android CallLogs. (It may get numbers A.E "Mom" into your professional contact list, etc etc)
So what I'm doing now, is after each call, insert the info (Name,Number,Date and Duration) Into an Array List.
recentCalls.add(new Recent(aName, aDate, aNumber, "0"));
(0 stands for Seconds, of Duration. Still not completed.)
It would "Save" in the app momentarily, and when the application is fully killed (Or Crashes), everything would be emptied out.
I have considered Saving the Array list in SharedPreferences.
But since we're going to limit the recents to 100, this will be too big.
I have read this: Android Storage Options
Either way, I AM still getting all the call logs from the phone itself, for testing purposes.
My questions are:
How could I save an ArrayList Safely and Efficiently
If I'm not going to work with an ArrayList, How could I "Format" the ACTUAL phone's call_logs to only show numbers dialed from my app. (In order to call "Through" our server, we use "ServerPhoneNumber" + "," + "Inserted PhoneNumber" - Example: 123456789,987654321)
Could I say Check if 1st 10 characters equal to "123456789"? Which is not possible, since it changes the number depending on the person.
Here's my Java Code:
package com.example.dragonphone;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.LightingColorFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.provider.BaseColumns;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;
public class Tabs extends Activity implements OnClickListener, OnLongClickListener{
TabHost th;
TabSpec specs;
TextView numberfield;
ListView recents;
public String string,number;
private List<Recent> recentCalls = new ArrayList<Recent>();
public int counter;
Button n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,nstar,nhash,sms,contact,call,clear,clearhistory,getinfo;
//ImageView call, clear;
public Vibrator vib;
//public String phoneNumber;
String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tabs);
th = (TabHost)findViewById(R.id.tabhost);
numberfield = (TextView) findViewById(R.id.etNumberField);
n1 = (Button) findViewById (R.id.bNumber1);
n2 = (Button) findViewById (R.id.bNumber2);
n3 = (Button) findViewById (R.id.bNumber3);
n4 = (Button) findViewById (R.id.bNumber4);
n5 = (Button) findViewById (R.id.bNumber5);
n6 = (Button) findViewById (R.id.bNumber6);
n7 = (Button) findViewById (R.id.bNumber7);
n8 = (Button) findViewById (R.id.bNumber8);
n9 = (Button) findViewById (R.id.bNumber9);
nstar = (Button) findViewById (R.id.bNumberStar);
n0 = (Button) findViewById (R.id.bNumber0);
nhash = (Button) findViewById (R.id.bNumberHash);
call = (Button) findViewById (R.id.bCall);
sms = (Button) findViewById (R.id.bSMS);
clear = (Button) findViewById (R.id.bClear);
contact = (Button) findViewById (R.id.bContact);
recents = (ListView) findViewById (R.id.recentList);
clearhistory = (Button) findViewById (R.id.bClearHistory);
getinfo = (Button) findViewById (R.id.bGetCallDetails);
populateRecentList();
populateListView();
registerClickCallback();
th.setBackgroundColor(Color.rgb(202, 233, 252));
//n1.getBackground().setColorFilter(new LightingColorFilter(0x000033, 0x000099));
sms.getBackground().setColorFilter(new LightingColorFilter(0xFFFF66, 0xFFFF00));
vib = (Vibrator) getSystemService(VIBRATOR_SERVICE);
n1.setOnClickListener(this);
n2.setOnClickListener(this);
n3.setOnClickListener(this);
n4.setOnClickListener(this);
n5.setOnClickListener(this);
n6.setOnClickListener(this);
n7.setOnClickListener(this);
n8.setOnClickListener(this);
n9.setOnClickListener(this);
nstar.setOnClickListener(this);
n0.setOnClickListener(this);
n0.setOnLongClickListener(this);
nhash.setOnClickListener(this);
call.setOnClickListener(this);
clear.setOnClickListener(this);
clear.setOnLongClickListener(this);
sms.setOnClickListener(this);
contact.setOnClickListener(this);
clearhistory.setOnClickListener(this);
getinfo.setOnClickListener(this);
th.setup();
specs = th.newTabSpec("tag1");
specs.setContent(R.id.Recents);
specs.setIndicator("Recent Calls");
th.addTab(specs);
specs = th.newTabSpec("tag2");
specs.setContent(R.id.Keypad);
specs.setIndicator("Keypad");
th.addTab(specs);
specs = th.newTabSpec("tag3");
specs.setContent(R.id.Sms);
specs.setIndicator("SMS");
th.addTab(specs);
specs = th.newTabSpec("tag4");
specs.setContent(R.id.Ratings);
specs.setIndicator("Rates");
th.addTab(specs);
specs = th.newTabSpec("tag5");
specs.setContent(R.id.Account);
specs.setIndicator("Account");
th.addTab(specs);
}
private void populateRecentList() {
//TODO Auto-generated method stub
recentCalls.add(new Recent("Zach", "01-12-2013", "064555246", "600"));
recentCalls.add(new Recent("Adam", "11-12-2013", "00355563315","510"));
recentCalls.add(new Recent("John", "03-12-2013", "00955587", "100"));
recentCalls.add(new Recent("Jorge", "15-10-2013" , "445559585", "60"));
}
private void populateListView() {
// TODO Auto-generated method stub
ArrayAdapter<Recent> adapter = new MyRecentAdapter();
ListView list = (ListView) findViewById(R.id.recentList);
list.setAdapter(adapter);
}
private class MyRecentAdapter extends ArrayAdapter<Recent>{
public MyRecentAdapter(){
super(Tabs.this, R.layout.recents_view, recentCalls);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
//Make sure we have a view to work with
View itemView = convertView;
if(itemView == null)
{
itemView = getLayoutInflater().inflate(R.layout.recents_view, parent,false);
}
Recent currentCall = recentCalls.get(position);
TextView nameText = (TextView) itemView.findViewById(R.id.tvRecentName);
nameText.setText(currentCall.getName());
TextView numberText = (TextView) itemView.findViewById(R.id.tvRecentNumber);
numberText.setText(currentCall.getPn());
TextView dateText = (TextView) itemView.findViewById(R.id.tvRecentDate);
dateText.setText("" + currentCall.getDate());
TextView durationText = (TextView) itemView.findViewById(R.id.tvRecentDuration);
durationText.setText("" + currentCall.getDuration());
return itemView;
// return super.getView(position, convertView, parent);
}
}
private void registerClickCallback() {
// TODO Auto-generated method stub
ListView list = (ListView) findViewById(R.id.recentList);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position,
long id) {
// TODO Auto-generated method stub
Recent clickedCall = recentCalls.get(position);
String name = clickedCall.getName();
numberfield.setText(clickedCall.getPn());
counter = numberfield.getText().toString().length();
String message = "Calling " + name;
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, message, duration);
toast.show();
call();
}
});
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId()){
case R.id.bNumber1:
numberfield.setText(numberfield.getText() + "1");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumber2:
numberfield.setText(numberfield.getText() + "2");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumber3:
numberfield.setText(numberfield.getText() + "3");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumber4:
numberfield.setText(numberfield.getText() + "4");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumber5:
numberfield.setText(numberfield.getText() + "5");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumber6:
numberfield.setText(numberfield.getText() + "6");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumber7:
numberfield.setText(numberfield.getText() + "7");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumber8:
numberfield.setText(numberfield.getText() + "8");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumber9:
numberfield.setText(numberfield.getText() + "9");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumberStar:
numberfield.setText(numberfield.getText() + "*");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumber0:
numberfield.setText(numberfield.getText() + "0");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumberHash:
numberfield.setText(numberfield.getText() + "#");
addCheck();
vib.vibrate(25);
break;
case R.id.bClear:
String number = numberfield.getText().toString();
if(number.length() > 0){
String newNumber = number.substring(0, number.length()-1);
numberfield.setText(newNumber);
deleteCheck();
vib.vibrate(25);
}else{
Context context = getApplicationContext();
CharSequence text = "The numbers are already cleared.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
break;
case R.id.bCall:
call();
break;
case R.id.bContact:
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 1);
break;
case R.id.bClearHistory:
recentCalls.clear();
CharSequence text = "Your recent list has been cleared.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(this, text, duration);
toast.show();
th.setCurrentTabByTag("tag1");
break;
case R.id.bSMS:
th.setCurrentTabByTag("tag3");
CharSequence text2 = "This function is still under construction..";
int duration2 = Toast.LENGTH_LONG;
Toast toast2 = Toast.makeText(this, text2, duration2);
toast2.show();
break;
case R.id.bGetCallDetails:
getCallDetails();
break;
}
}
private void deleteCheck() {
// TODO Auto-generated method stub
counter --;
if(counter < 14){
numberfield.setTextSize(25); //Set text size when amount goes lower.
}
if(counter >= 14 && counter < 16){
numberfield.setTextSize(20); //Set text size when amount goes lower.
}
if(counter >= 16 && counter < 18){
numberfield.setTextSize(18);
}
if(counter >= 18 && counter < 20){
numberfield.setTextSize(16);
}
}
private void addCheck() {
// TODO Auto-generated method stub
counter++;
if(counter >= 14){
numberfield.setTextSize(20); //Set text size when amount goes higher.
//numberfield.setMaxHeight(10);
}
if(counter >= 16){
numberfield.setTextSize(18); //Set text size when amount goes higher.
}
if(counter >= 18){
numberfield.setTextSize(16); //Set text size when amount goes higher.
}
if(counter >= 20){
numberfield.setTextSize(14); //Set text size when amount goes higher.
}
if(counter < 14){
numberfield.setTextSize(25); //Set text size when amount goes lower.
}
if(counter >= 14 && counter < 16){
numberfield.setTextSize(20); //Set text size when amount goes lower.
}
if(counter >= 16 && counter < 18){
numberfield.setTextSize(18);
}
if(counter >= 18 && counter < 20){
numberfield.setTextSize(16);
}
}
private void getCallDetails() {
StringBuilder sb = new StringBuilder();
Uri contacts = CallLog.Calls.CONTENT_URI;
Cursor managedCursor = this.getContentResolver().query(contacts, null, null, null,CallLog.Calls.DATE + " DESC LIMIT 100");
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("Call Details :");
while (managedCursor.moveToNext()) {
String phNumber = managedCursor.getString(number);
String callType = managedCursor.getString(type);
String callDate = managedCursor.getString(date);
String callDayTime = new Date(Long.valueOf(callDate)).toString();
// long timestamp = convertDateToTimestamp(callDayTime);
String callDuration = managedCursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- " + dir + " \nCall Date:--- " + callDayTime + " \nCall duration in sec :--- " + callDuration);
sb.append("\n----------------------------------");
}
managedCursor.close();
System.out.println(sb);
}
private void call() {
// TODO Auto-generated method stub
if(number.length() > 0){
try {
Intent callIntent = new Intent(Intent.ACTION_CALL);
String dsPhoneNumber = "+34965063314,"; // Dynamic number
//965063064
string = numberfield.getText().toString().trim();
number = "tel:" + dsPhoneNumber + string;
callIntent.setData(Uri.parse(number));
startActivity(callIntent);
//recentCalls.add(new Recent(aName, aDate, aNumber, "0"));
} catch (ActivityNotFoundException activityException) {
Log.e("helloandroid dialing example", "Call failed");
}
}else {
Context context = getApplicationContext();
CharSequence text = "Please insert a phone number or choose a contact.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
#Override
public boolean onLongClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId()){
case R.id.bClear:
if(counter != 0){
counter = 0;
numberfield.setTextSize(25);
numberfield.setText("");
vib.vibrate(100);}
else{
Context context = getApplicationContext();
CharSequence text = "The numbers are already cleared.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
break;
case R.id.bNumber0:
numberfield.setText(numberfield.getText() + "+");
addCheck();
vib.vibrate(25);
break;
}
return true;
}
public void onActivityResult(int reqCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK && data != null) {
Uri uri = data.getData();
Cursor cursor=this.getContentResolver().query(uri, null, null, null, null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts._ID));
String hasPhone = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Integer.parseInt(cursor.getString( cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// You now have the number so now query it like this
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,
null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(
phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
numberfield.setText(phoneNumber);
counter = numberfield.getText().toString().length();
/*if(counter == 0){
Context context = getApplicationContext();
//CharSequence text = counter;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, counter, duration);
toast.show();
}*/
}
phones.close();
}
}
}
}
}
Thanks in Advance!
EDIT
private void registerClickCallback() {
// TODO Auto-generated method stub
ListView list = (ListView) findViewById(R.id.recentList);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position,
long id) {
// TODO Auto-generated method stub
Recent clickedCall = recentCalls.get(position);
// String name = clickedCall.getName();
//numberfield.setText(clickedCall.getPn());
counter = numberfield.getText().toString().length();
// String message = getResources().getString(R.string.toastCalling) + " " + name + " " + getResources().getString(R.string.toastCalling2);
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
//Toast toast = Toast.makeText(context, message, duration);
//toast.show();
call();
}
});
}
This is my current call method. (Commented out stuff since it's not like the old code anymore.)
Basically whenever I click call,
case R.id.bCall:
call();
The Call function:
private void call() {
// TODO Auto-generated method stub
if(numberfield.length() > 0){
try {
Intent callIntent = new Intent(Intent.ACTION_CALL);
String dsPhoneNumber = "+34965063314,";
// Dynamic number
//965063064
String string = numberfield.getText().toString().trim();
number = "tel:" + dsPhoneNumber + string;
callIntent.setData(Uri.parse(number));
startActivity(callIntent);
//recentCalls.add(new Recent(aName, aDate, aNumber, "0"));
} catch (ActivityNotFoundException activityException) {
Log.e("helloandroid dialing example", "Call failed");
}
}else {
Context context = getApplicationContext();
CharSequence text = getResources().getText(R.string.keypadViewToastEmptyNumber);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
It needs to Insert it in the "List" and show it on the Recents tab.
I've spent a couple of hours trying to solve this, No progress. Thanks in advance!
Edit #2
public View getView(int position, View convertView, ViewGroup parent){
//Make sure we have a view to work with
View itemView = convertView;
if(itemView == null)
{
itemView = getLayoutInflater().inflate(R.layout.recents_view, parent,false);
}
Recent currentCall = recentCalls.get(position);
TextView nameText = (TextView) itemView.findViewById(R.id.tvRecentName);
nameText.setText(currentCall.getName());
TextView numberText = (TextView) itemView.findViewById(R.id.tvRecentNumber);
numberText.setText(currentCall.getPn());
TextView dateText = (TextView) itemView.findViewById(R.id.tvRecentDate);
dateText.setText("" + currentCall.getDate());
TextView durationText = (TextView) itemView.findViewById(R.id.tvRecentDuration);
durationText.setText("" + currentCall.getDuration());
return itemView;
// return super.getView(position, convertView, parent);
}
}
So this is the view of the recents tab. The .getDate/.getDuration etc are changed, What should the "new one" be? So basically read
What I would do is the following:
Get a java.io.File to a local (/data/data/f.q.c.n/files/recents) file
Open a (buffered) FileOutputStream to it
Write the elements of the ArrayList<Recent> to the file
Write the name as byte-array (String.getBytes)
Write the date as a long (since epoch)
Write the number as a string (as there can be different formats)
Write the duration as an int
Note that long and int are fixed-size and therefore can be read easily
You can prefix the byte-array with an int, indicating it's size
Then, of course, you do the same thing in reverse on startup, to rebuild that ArrayList.
Someone called this approach controlled binary serialization. Of course you can have it easier, but it's not really hard to do and you get rid of all reflection (which can have awful performance on early Android devices). This is the fastest (smoothest) approach I can think of.
I didn't choose standard Serialization because it sucks (Tons of reflection and metadata).
Note that SharedPreferences have been successfully (ab-) used to store much larger data than you have.
Example:
IO.java:
import java.io.IOException;
public interface IO {
void write(DataOutputStream out) throws IOException;
void read(DataInputStream in) throws IOException;
}
Recent.java:
import java.io.IOException;
import java.util.Date;
public class Recent implements IO {
private String name, number;
private Date date;
private int duration; // in milliseconds
public Recent(String name, String number, Date date, int duration) {
this.name = name;
this.number = number;
this.date = date;
this.duration = duration;
}
public Recent() {
this(null, null, null, 0);
}
#Override
public void write(DataOutputStream out) throws IOException {
byte[] nameData = name.getBytes("UTF-8");
out.writeInt(nameData.length);
out.write(nameData);
byte[] numberData = number.getBytes("UTF-8");
out.writeInt(numberData.length);
out.write(numberData);
out.writeLong(date.getTime());
out.writeInt(duration);
}
#Override
public void read(DataInputStream in) throws IOException {
int nameDataLength = in.readInt();
if (nameDataLength > 100000) throw new IllegalStateException("Name shouldn't be this long: " + nameDataLength);
byte[] nameData = new byte[nameDataLength];
in.readFully(nameData);
name = new String(nameData, "UTF-8");
int numberDataLength = in.readInt();
if (numberDataLength > 100000) throw new IllegalStateException("Number shouldn't be this long: " + nameDataLength);
byte[] numberData = new byte[numberDataLength];
in.readFully(numberData);
number = new String(numberData, "UTF-8");
date = new Date(in.readLong());
duration = in.readInt();
}
}
RecentsList.java:
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class RecentsList implements IO {
private List<Recent> recents;
public RecentsList() {
recents = new ArrayList<Recent>();
}
public void addRecent(Recent recent) {
recents.add(recent);
}
#Override
public void write(DataOutputStream out) throws IOException {
out.writeInt(recents.size());
for (Recent r : recents) {
r.write(out);
}
}
#Override
public void read(DataInputStream in) throws IOException {
int size = in.readInt();
recents = new ArrayList<Recent>(size);
for (int i = 0; i < size; i++) {
Recent r = new Recent();
r.read(in);
recents.add(r);
}
}
public static void main(String[] args) throws IOException {
RecentsList test = new RecentsList();
// build test data
for (int i = 0; i < 100; i++) {
String iString = Integer.toString(i);
Recent r = new Recent(iString, iString, new Date(), i);
test.addRecent(r);
}
// write
File out = new File("/home/till/recents.bin");
DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(out)));
test.write(dataOut);
dataOut.close();
// read
RecentsList read = new RecentsList();
DataInputStream dataIn = new DataInputStream(new BufferedInputStream(new FileInputStream(out)));
read.read(dataIn);
dataIn.close();
System.out.println("read now contains same data as test if everything went ok");
}
}
Note:
You will wan't to simplify writing and reading a byte-array. I do that myself but didn't include it for briefness (it's long enough already)
The imports for the Data[Input|Output]Stream are missing
You may wan't to change the size for the exception
You can shrink the ints for small numbers
If you have any problems/questions, don't hesitate to comment!

Categories

Resources