Related
In my project I download all the data of my project from a json.I download title and description as text and also download my icon and the file of games.
I can download them and also save in database and show in listview easily.
My QUESTION is about how to save that my file for game is beinng download or not?
I have two buttons. first is download button when user click it , it starts to download file.when download finish, my download button disappear and my play button appears.
I want to save this, when user for second time run the application,i save for example my second position downloaded before. and I have just my play button.
my database:
public class DatabaseHandler extends SQLiteOpenHelper {
public SQLiteDatabase sqLiteDatabase;
int tedad;
public DatabaseHandler(Context context) {
super(context, "EmployeeDatabase.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String tableEmp = "create table emp(PersianTitle text,Description text,icon text,downloadlink text,dl integer)";
db.execSQL(tableEmp);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insertData(ArrayList<String> id, ArrayList<String> name, ArrayList<String> salary, ArrayList<String> roms,String
dl) {
int size = id.size();
tedad = size;
sqLiteDatabase = this.getWritableDatabase();
try {
for (int i = 0; i < size; i++) {
ContentValues values = new ContentValues();
values.put("PersianTitle", id.get(i));
values.put("Description", name.get(i));
values.put("icon", salary.get(i));
values.put("downloadlink", roms.get(i));
values.put("dl", "0");
sqLiteDatabase.insert("emp", null, values);
}
} catch (Exception e) {
Log.e("Problem", e + " ");
}
}
public ArrayList<String> Game_Info (int row, int field) {
String fetchdata = "select * from emp";
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
ArrayList<String> stringArrayList = new ArrayList<String>();
Cursor cu = sqLiteDatabase.rawQuery(fetchdata, null);
for (int i = 0; i < row + 1; i++) {
cu.moveToPosition(i);
String s = cu.getString(field);
stringArrayList.add(s);
}
return stringArrayList;
}
}
and this is my main code:
public class MainActivity2 extends Activity {
Boolean done_game = false;
ProgressDialog progressDialog;
private boolean _init = false;
ListView listView;
DatabaseHandler database;
BaseAdapter adapter;
public String path_image;
JSONObject jsonObject;
Game_Counter_Store Game_Counter_Store;
int game_counter_store;
ArrayList<String> name_array = new ArrayList<String>();
ArrayList<String> des_array = new ArrayList<String>();
ArrayList<String> icon_array = new ArrayList<String>();
ArrayList<String> roms_array = new ArrayList<String>();
ArrayList<String> fav_array = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main2);
init();
System.gc();
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "MyDirName");//make a direction
path_image = mediaStorageDir.getAbsolutePath(); // here is tha path
listView = (ListView) findViewById(R.id.listView);
database = new DatabaseHandler(MainActivity2.this);
database.getWritableDatabase();
Game_Counter_Store = new Game_Counter_Store("Games_Number", this); // number of game in first run is 0
game_counter_store = Game_Counter_Store.get_count();
if (game_counter_store == 0) {
Log.i("mhs", "game_counter_store is 0");
DownloadGames();
} else {
Log.i("mhs", "there are some games");
for (int i = 0; i < game_counter_store; i++) {
name_array = database.Game_Info(i, 0);
des_array = database.Game_Info(i, 1);
icon_array = database.Game_Info(i, 2);
roms_array = database.Game_Info(i, 3);
fav_array = database.Game_Info(i, 4);
}
adapter = new MyBaseAdapter(MainActivity2.this, name_array, des_array, icon_array, roms_array,fav_array);
listView.setAdapter(adapter);
}
}
public void DownloadGames() {
//here we download name, des, icon
MakeDocCallBack makeDocCallBack = new MakeDocCallBack() {
#Override
public void onResult(ArrayList<String> res) {
if (res.size() > 0) {
try {
Game_Counter_Store counter_store = new Game_Counter_Store("Games_Number", MainActivity2.this); // get numbrr of games
counter_store.set_count(res.size()); // store the games number
for (int i = 0; i < res.size(); i++) {
jsonObject = new JSONObject(res.get(i)); //get all the jsons
//get all the data to store in database
name_array.add(jsonObject.getString("PersianTitle"));
des_array.add(jsonObject.getString("Description"));
icon_array.add(jsonObject.getString("icon"));
roms_array.add(jsonObject.getString("downloadlink"));
GetFile fd = new GetFile(MainActivity2.this, path_image, getFileName(jsonObject.getString("icon")), jsonObject.getString("icon").toString(), null); // download the image
GetFileCallBack Image_callback = new GetFileCallBack() {
#Override
public void onStart() {
// Toast.makeText(getApplicationContext(),"start",Toast.LENGTH_LONG).show();
}
#Override
public void onProgress(long l, long l1) {
// Toast.makeText(getApplicationContext(),"onProgress",Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess() {
// Toast.makeText(getApplicationContext(),"YES",Toast.LENGTH_LONG).show();
}
#Override
public void onFailure() {
// Toast.makeText(getApplicationContext(),"NO",Toast.LENGTH_LONG).show();
}
};
if (!fd.DoesFileExist()) {
fd.Start(Image_callback); // get the data
}
//set data in adapter to show in listview
adapter = new MyBaseAdapter(MainActivity2.this, name_array, des_array, icon_array, roms_array,fav_array);
listView.setAdapter(adapter);
}
//store dada in database (name , des , icon , bin file(roms) , state)
database.insertData(name_array, des_array, icon_array, roms_array,"0");
} catch (Exception ex) {
}
}
}
};
DocMaker doc = new DocMaker();
doc.set(this, makeDocCallBack);
}
public static String getFileName(String url) {
String temp = url.substring(url.lastIndexOf('/') + 1, url.length());
if (temp.contains("?"))
temp = temp.substring(0, temp.indexOf("?"));
return temp;
}
public class MyBaseAdapter extends BaseAdapter {
private Activity activity;
private ArrayList title, desc, icon, roms,fav;
private LayoutInflater inflater = null;
public MyBaseAdapter(Activity a, ArrayList b, ArrayList c, ArrayList d, ArrayList e, ArrayList f) {
activity = a;
this.title = b;
this.desc = c;
this.icon = d;
this.roms = e;
this.fav=f;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return title.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.list_item, null);
TextView title2 = (TextView) vi.findViewById(R.id.game_name); // title
String song = title.get(position).toString();
title2.setText(song);
TextView title22 = (TextView) vi.findViewById(R.id.game_des); // desc
String song2 = desc.get(position).toString();
title22.setText(song2);
File imageFile = new File("/storage/emulated/0/MyDirName/" + getFileName(icon_array.get(position)));
ImageView imageView = (ImageView) vi.findViewById(R.id.icon); // icon
imageView.setImageBitmap(BitmapFactory.decodeFile(imageFile.getAbsolutePath()));
TextView title222 = (TextView) vi.findViewById(R.id.game_roms); // desc
String song22 = roms.get(position).toString();
title222.setText(song22);
final Button dl_btn = (Button) vi.findViewById(R.id.dl_btn); // desc
final Button run_btn = (Button) vi.findViewById(R.id.play_btn); // desc
run_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Preferences.DEFAULT_GAME_FILENAME = getFileName(roms_array.get(position));
Intent myIntent = new Intent(MainActivity2.this, FileChooser.class);
myIntent.putExtra(FileChooser.EXTRA_START_DIR, Preferences.getRomDir(MainActivity2.this));
Log.i("mhsnnn", Preferences.getTempDir(MainActivity2.this));
final int result = Preferences.MENU_ROM_SELECT;
startActivityForResult(myIntent, result);
}
});
dl_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MakeDocCallBack makeDocCallBack = new MakeDocCallBack() {
#Override
public void onResult(ArrayList<String> res) {
if (res.size() > 0) {
try {
jsonObject = new JSONObject(res.get(position));
roms_array.add(jsonObject.getString("downloadlink"));
GetFile fd1 = new GetFile(MainActivity2.this, path_image, getFileName(jsonObject.getString("downloadlink")), jsonObject.getString("downloadlink").toString(),null); //download the bin file
GetFileCallBack roms_callback = new GetFileCallBack() {
#Override
public void onStart() {
}
#Override
public void onProgress(long l, long l1) {
Log.i("nsr", "onProgress");
}
#Override
public void onSuccess() {
Log.i("nsr", "onSuccess");
dl_btn.setVisibility(View.GONE);
run_btn.setVisibility(View.VISIBLE);
}
#Override
public void onFailure() {
Log.i("nsr", "onFailure");
}
};
if (!fd1.DoesFileExist()) {
fd1.Start(roms_callback);
}
} catch (Exception ex) {
}
}
}
};
DocMaker doc = new DocMaker();
doc.set(MainActivity2.this, makeDocCallBack);
}
});
return vi;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
private boolean verifyExternalStorage() {
// check for sd card first
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// rw access
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// r access
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// no access
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
// if we do not have storage warn user with dialog
if (!mExternalStorageAvailable || !mExternalStorageWriteable) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this)
.setTitle(getString(R.string.app_name) + " Error")
.setMessage("External Storage not mounted, are you in disk mode?")
.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
init();
}
})
.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
dialog.show();
return false;
}
return true;
}
private void init() {
if (verifyExternalStorage() && !_init) {
// always try and make application dirs
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
Log.i("nsrrr1", extStorageDirectory);
// /storage/emulated/0
File myNewFolder = new File(extStorageDirectory + Preferences.DEFAULT_DIR);
Log.i("nsrrr2", extStorageDirectory + Preferences.DEFAULT_DIR);///storage/emulated/0/sega
if (!myNewFolder.exists()) {
myNewFolder.mkdir();
}
myNewFolder = new File(extStorageDirectory + Preferences.DEFAULT_DIR_ROMS);
Log.i("nsrrr3", extStorageDirectory + Preferences.DEFAULT_DIR);///storage/emulated/0/sega
if (!myNewFolder.exists()) {
myNewFolder.mkdir();
}
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list(Preferences.DEFAULT_DIR_GAME);
Log.i("nsrrr3", files + "");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(Preferences.DEFAULT_DIR_GAME + "/" + filename);
File outFile = new File(myNewFolder, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
// do first run welcome screen
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean firstRun = preferences.getBoolean(Preferences.PREF_FIRST_RUN, true);
if (firstRun) {
// remove first run flag
Editor edit = preferences.edit();
edit.putBoolean(Preferences.PREF_FIRST_RUN, false);
// default input
edit.putBoolean(Preferences.PREF_USE_DEFAULT_INPUT, true);
edit.commit();
}
// generate APK path for the native side
ApplicationInfo appInfo = null;
PackageManager packMgmr = this.getPackageManager();
try {
appInfo = packMgmr.getApplicationInfo(getString(R.string.package_name), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Unable to locate assets, aborting...");
}
String _apkPath = appInfo.sourceDir;
// init the emulator
Emulator.init(_apkPath);
Log.i("rrrr", _apkPath);
// set the paths
Emulator.setPaths(extStorageDirectory + Preferences.DEFAULT_DIR,
extStorageDirectory + Preferences.DEFAULT_DIR_ROMS,
"",
"",
"");
// load up prefs now, never again unless they change
//PreferenceFacade.loadPrefs(this, getApplicationContext());
// load gui
// Log.d(LOG_TAG, "Done init()");
setContentView(R.layout.activity_main2);
// set title
super.setTitle(getString(R.string.app_name));
_init = true;
// Log.d(LOG_TAG, "Done onCreate()");
}
}
private void copyFile(InputStream in, OutputStream out) {
byte[] buffer = new byte[1024];
int read;
try {
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
how to make method in my database to do this?
If I understood you properly, you can add a table, user_games for example with User ID, Game ID and Status, then you can update status whenever an action is completed.
For example Status 1 for downloading, status 2 for Downloaded or Finished and you can even add statuses like download failed, to add a re-download button...
you can do something like
public void update_status(UserID,GameID) {
String update = "UPDATE games set status = 1 where id="+Game_ID+" and UserID = " + UserID);
db.rawQuery(update, null);
}
I have a problem with creating two tables in sqlite and display them in RecyclerView and more specifically with one table. I add to the question a screenshot of the application so that you can understand what the problem is.
I have 3 activities: FirstActivity, in which there are two buttons (Monday and Tuesday) -> from this activity we go to MainActivity, on the button selection (Monday) -> save data in table_MON and after selection button (Tuesday) in the table_Tue. The problem is that everything works correctly, when we press the button (Monday) we can save the training, edit and delete it. However, when we go to the button (Tuesday) we can only add training, but we can't edit or delete them. However, I have no idea why? I am already looking at this problem for a week and I have no idea what is going on, maybe a fresh look will help solve the problem.
My database consists of two tables: tableMon and tableTue, but I use the same columns in it (exercises, weight etc ..), and separate _id, and I do not know if this can be a problem. Perhaps the problem is that I use MainActivity in both cases?
Screenshot App:
FirstActivity
enter image description here
Click button Monday --> MainActivity.class
enter image description here
Click button Tuesday --> MainActivity.class
enter image description here
Button Tuesday --> DetailActivity and her is the problem I can't update and delete training.
enter image description here
FirstActivity.class
public class FirstActivity extends AppCompatActivity {
Button buttonMon, buttonTue;
public static final String BUTTON_KEY1 = "BUTTON_KEY";
public static final String BUTTON_KEY2 = "BUTTON_KEY2";
public static final String BUTTON_VALUE = "1";
public static final String BUTTON_VALUE2 = "2";
public static boolean WAS_RUNNING;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
buttonMon = (Button) findViewById(R.id.buttonMonday);
buttonTue = (Button) findViewById(R.id.buttonTuesday);
WAS_RUNNING = false;
//OPEN THE SAME MAINACTIVITY
buttonMon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WAS_RUNNING = true;
Intent intent = new Intent(FirstActivity.this, MainActivity.class);
intent.putExtra(BUTTON_KEY1, BUTTON_VALUE);
startActivity(intent);
} });
//OPEN THE SAME MAINACTIVITY
buttonTue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WAS_RUNNING = true;
Intent i = new Intent(FirstActivity.this, MainActivity.class);
i.putExtra(BUTTON_KEY2, BUTTON_VALUE2);
startActivity(i);
} });}}
MainActivity.class
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private MyAdapter myAdapter;
private ArrayList<Training> trainingArrayList = new ArrayList<Training>();
private EditText editTextExercise, editTextWeight, editTextRepeat, editTextSeries;
private Button buttonSave, buttonBack;
private Dialog dialog;
private String value;
private String value2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle bundle = getIntent().getExtras();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog();}});
if(bundle == null)
{return;}
value = bundle.getString(FirstActivity.BUTTON_KEY1);
value2 = bundle.getString(FirstActivity.BUTTON_KEY2);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
if(value != null) {
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
myAdapter = new MyAdapter(this, trainingArrayList);
//Refresh MON TABLE
refreshMonTable();
}else if(value2 != null) {
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
myAdapter = new MyAdapter(this, trainingArrayList);
//Refresh TUE TABLE
refreshTueTable(); }}
public void showDialog()
{
dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog_layout);
editTextExercise = (EditText) dialog.findViewById(editTextExerciseDialog);
editTextWeight = (EditText) dialog.findViewById(editTextWeightDialog);
editTextRepeat = (EditText) dialog.findViewById(editTextRepeatDialog);
editTextSeries = (EditText) dialog.findViewById(editTextSeriesDialog);
buttonSave = (Button) dialog.findViewById(buttonSaveDialog);
buttonBack = (Button) dialog.findViewById(buttonBackDialog);
buttonBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();}});
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(value != null) {
saveDataMon(editTextExercise.getText().toString(),
String.valueOf(editTextWeight.getText().toString()),
String.valueOf(editTextRepeat.getText().toString()),
String.valueOf(editTextSeries.getText().toString()));
} else if(value2 != null) {
saveDataTue(editTextExercise.getText().toString(),
String.valueOf(editTextWeight.getText().toString()),
String.valueOf(editTextRepeat.getText().toString()),
String.valueOf(editTextSeries.getText().toString()));
}}});
dialog.show();}
private void saveDataMon(String exercise, String weight, String repeat, String series)
{
DBAdapter adapter = new DBAdapter(this);
adapter.openDatabase();
long result = adapter.addMon(exercise, weight, repeat, series);
if (result > 0) {
editTextExercise.setText("");
editTextWeight.setText("");
editTextRepeat.setText("");
editTextSeries.setText("");
dialog.dismiss();
} else {
Snackbar.make(editTextExercise, "Unable to save!", Snackbar.LENGTH_SHORT).show();}
adapter.closeDB();
refreshMonTable();}
private void saveDataTue(String exercise, String weight, String repeat, String series)
{
DBAdapter adapter = new DBAdapter(this);
adapter.openDatabase();
long result = adapter.addTue(exercise, weight, repeat, series);
if (result > 0) {
editTextExercise.setText("");
editTextWeight.setText("");
editTextRepeat.setText("");
editTextSeries.setText("");
dialog.dismiss();
} else {
Snackbar.make(editTextExercise, "Unable to save!", Snackbar.LENGTH_SHORT).show();
}
adapter.closeDB();
refreshTueTable();}
private void refreshMonTable()
{
DBAdapter adapter = new DBAdapter(this);
adapter.openDatabase();
trainingArrayList.clear();
Cursor cursor = adapter.getAllTreningMon();
if(cursor != null)
{ if(cursor.moveToFirst())
{
do {
int id = cursor.getInt(0);
String cwiczenie = cursor.getString(1);
String ciezar = cursor.getString(2);
String powtorzenia = cursor.getString(3);
String serie = cursor.getString(4);
Training training = new Training(id, cwiczenie, ciezar, powtorzenia, serie);
trainingArrayList.add(training);
}while (cursor.moveToNext());}}
recyclerView.setAdapter(myAdapter);
adapter.closeDB(); }
private void refreshTueTable()
{
DBAdapter adapter = new DBAdapter(this);
adapter.openDatabase();
trainingArrayList.clear();
Cursor cursor = adapter.getAllTreningTue();
if(cursor != null)
{ if(cursor.moveToFirst())
{
do {
int id = cursor.getInt(0);
String exercise = cursor.getString(1);
String weight = cursor.getString(2);
String repeat = cursor.getString(3);
String series = cursor.getString(4);
Training training = new Training(id, exercise, weight, repeat, series);
trainingArrayList.add(training);
}while (cursor.moveToNext());}}
recyclerView.setAdapter(myAdapter);
adapter.closeDB();
}
#Override
protected void onResume() {
super.onResume();
if(value != null) {
//REFRESH
refreshMonTable();
} else if(value2 != null) {
refreshTueTable();}}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Exit?")
.setMessage("Do you want to exit?")
.setNegativeButton("No", null)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
MainActivity.super.onBackPressed();
}
}).create().show();}}
DetailActivity.class
public class DetailActivity extends AppCompatActivity {
private EditText editTextExerciseDetail, editTextWeightDetail, editTextRepeatDetail, editTextSeriesDetail;
private Button buttonUpdate;
private Button buttonDelete;
String mon;
String tue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
Bundle intent = getIntent().getExtras();
if(intent == null)
{return;}
mon = intent.getString(MyAdapter.KEY_MON);
tue = intent.getString(MyAdapter.KEY_TUE);
final int idT = intent.getInt("id");
String cwiczenie = intent.getString("exercise");
String ciezar = intent.getString("weight");
String powtorzenia = intent.getString("repeat");
String serie = intent.getString("series");
editTextExerciseDetail = (EditText) findViewById(R.id.exerciseEditTxtDetail);
editTextWeightDetail = (EditText) findViewById(R.id.weightEditTextDetail);
editTextRepeatDetail = (EditText) findViewById(R.id.repeatEditTextDetail);
editTextSeriesDetail = (EditText) findViewById(R.id.seriesEditTextDetail);
buttonUpdate = (Button) findViewById(R.id.updateBtn);
buttonDelete = (Button) findViewById(R.id.deleteBtn);
editTextExerciseDetail.setText(cwiczenie);
editTextWeightDetail.setText(ciezar);
editTextRepeatDetail.setText(powtorzenia);
editTextSeriesDetail.setText(serie);
buttonUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mon != null) {
updateMon(idT, editTextExerciseDetail.getText().toString(),
editTextWeightDetail.getText().toString(),
editTextRepeatDetail.getText().toString(),
editTextSeriesDetail.getText().toString());
} else if(tue != null) {
updateTue(idT, editTextExerciseDetail.getText().toString(),
editTextWeightDetail.getText().toString(),
editTextRepeatDetail.getText().toString(),
editTextSeriesDetail.getText().toString());}}
});
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(DetailActivity.this);
builder.setMessage("Do you want delete this training?")
.setTitle("Delete")
.create();
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(mon != null) {
deleteMon(idT);
}else if(tue != null){
deleteTue(idT);}}});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}});
builder.show();}});}
//Update MON TABLE
private void updateMon(int id, String newExercise, String newWeight, String newRepeat, String newSeries)
{
DBAdapter dbAdapter = new DBAdapter(this);
dbAdapter.openDatabase();
long result = dbAdapter.updateMon(id, newExercise, newWeight, newRepeat, newSeries);
if(result > 0)
{
editTextExerciseDetail.setText(newExercise);
editTextWeightDetail.setText(newWeight);
editTextRepeatDetail.setText(newRepeat);
editTextSeriesDetail.setText(newSeries);
this.finish();
Snackbar.make(editTextExerciseDetail, "Updated Succesfully", Snackbar.LENGTH_SHORT).show();
}else
{
Snackbar.make(editTextExerciseDetail, "Unable to updated", Snackbar.LENGTH_SHORT).show();
}
dbAdapter.closeDB();
}
//Update TUE TABLE
private void updateTue(int id, String newExercise, String newWeight, String newRepeat, String newSeries)
{
DBAdapter dbAdapter = new DBAdapter(this);
dbAdapter.openDatabase();
long result = dbAdapter.updateTue(id, newExercise, newWeight, newRepeat, newSeries);
if(result > 0)
{
editTextExerciseDetail.setText(newExercise);
editTextWeightDetail.setText(newWeight);
editTextRepeatDetail.setText(newRepeat);
editTextSeriesDetail.setText(newSeries);
this.finish();
Snackbar.make(editTextExerciseDetail, "Updated Succesfully", Snackbar.LENGTH_SHORT).show();
}else
{
Snackbar.make(editTextExerciseDetail, "Unable to updated", Snackbar.LENGTH_SHORT).show();
}
dbAdapter.closeDB();}
//DELETE MON TABLE
private void deleteMon(int id)
{
DBAdapter dbAdapter = new DBAdapter(this);
dbAdapter.openDatabase();
long result = dbAdapter.deleteMon(id);
if(result>0)
{
this.finish();
}else
{
Snackbar.make(editTextExerciseDetail, "Unable to deleted", Snackbar.LENGTH_SHORT).show();
}
dbAdapter.closeDB();
}
//DELETE TUE TABLE
private void deleteTue(int id)
{
DBAdapter dbAdapter = new DBAdapter(this);
dbAdapter.openDatabase();
long result = dbAdapter.deleteTue(id);
if(result>0)
{
this.finish();
}else
{
Snackbar.make(editTextExerciseDetail, "Unable to deleted", Snackbar.LENGTH_SHORT).show();
}
dbAdapter.closeDB();}
#Override
protected void onResume() {
super.onResume();}
#Override
protected void onRestart() {
super.onRestart();}}
DBHelper.class
public class DBHelper extends SQLiteOpenHelper {
//DB
static final String DB_NAME = "training_db";
static final int DB_VERSION = '1';
//TABLES
static final String TB_NAME_MON = "training_tb_mon";
static final String TB_NAME_TUE = "training_tb_tue";
//COLUMNS
static final String ROW_ID_MON = "id_Mon";
static final String ROW_ID_TUE = "id_Tue";
//ROW
static final String EXERCISE = "exercise";
static final String WEIGHT = "weight";
static final String REPEAT = "repeat";
static final String SERIES = "series";
static final String CREATE_TB_MON = "CREATE TABLE training_tb_mon (id_Mon INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "exercise TEXT NOT NULL, weight TEXT NOT NULL, repeat TEXT NOT NULL, series TEXT NOT NULL);";
static final String CREATE_TB_TUE = "CREATE TABLE training_tb_tue (id_Tue INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "exercise TEXT NOT NULL, weight TEXT NOT NULL, repeat TEXT NOT NULL, series TEXT NOT NULL);";
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TB_MON);
db.execSQL(CREATE_TB_TUE);
}catch (Exception e) {
e.printStackTrace();
}}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TB_NAME_MON);
db.execSQL("DROP TABLE IF EXISTS " + TB_NAME_TUE);
onCreate(db);
}}
DBAdapter.class
public class DBAdapter {
Context c;
DBHelper dbHelper;
SQLiteDatabase db;
public DBAdapter(Context c) {
this.c = c;
dbHelper = new DBHelper(c);
}
//OPEN DATABASE
public DBAdapter openDatabase() {
try {
db = dbHelper.getWritableDatabase();
}catch (SQLiteException e) {
e.printStackTrace();
}
return this;
}
//CLOSE DATABASE
public void closeDB()
{
try{
dbHelper.close();
}catch (SQLiteException e){
e.printStackTrace();
}}
//Add training Mon
public long addMon(String exercise, String weight, String repeat, String series)
{
try{
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.EXERCISE, exercise);
contentValues.put(DBHelper.WEIGHT, weight);
contentValues.put(DBHelper.REPEAT, repeat);
contentValues.put(DBHelper.SERIES, series);
return db.insert(DBHelper.TB_NAME_MON, DBHelper.ROW_ID_MON, contentValues);
}catch (SQLiteException e) {
e.printStackTrace(); }
return 0;}
//Add training Tue
public long addTue(String exercise, String weight, String repeat, String series)
{
try{
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.EXERCISE, exercise);
contentValues.put(DBHelper.WEIGHT, weight);
contentValues.put(DBHelper.REPEAT, repeat);
contentValues.put(DBHelper.SERIES, series);
return db.insert(DBHelper.TB_NAME_TUE, DBHelper.ROW_ID_TUE, contentValues);
}catch (SQLiteException e) {
e.printStackTrace();
}
return 0;
}
//REFRESH TABLE MON
public long updateMon(int id, String exercise, String weight, String repeat, String series)
{
try{
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.EXERCISE, exercise);
contentValues.put(DBHelper.WEIGHT, weight);
contentValues.put(DBHelper.REPEAT, repeat);
contentValues.put(DBHelper.SERIES, series);
contentValues.put(DBHelper.ROW_ID_MON, id);
return db.update(DBHelper.TB_NAME_MON, contentValues, DBHelper.ROW_ID_MON + " =?", new String[]{String.valueOf(id)});
}catch (SQLiteException e) {
e.printStackTrace(); }
return 0;
}
//REFRESH TABLE TUE
public long updateTue(int id, String exercise, String weight, String repeat, String series)
{
try{
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.EXERCISE, exercise);
contentValues.put(DBHelper.WEIGHT, weight);
contentValues.put(DBHelper.REPEAT, repeat);
contentValues.put(DBHelper.SERIES, series);
contentValues.put(DBHelper.ROW_ID_TUE, id);
return db.update(DBHelper.TB_NAME_TUE, contentValues, DBHelper.ROW_ID_TUE + " =?", new String[]{String.valueOf(id)});
}catch (SQLiteException e) {
e.printStackTrace();
}
return 0;
}
//DELETE ROW TABLE MON
public long deleteMon(int id)
{
try{
return db.delete(DBHelper.TB_NAME_MON, DBHelper.ROW_ID_MON + " =?", new String[]{String.valueOf(id)});
}catch (SQLiteException e) {
e.printStackTrace();
}
return 0; }
//DELETE ROW TABLE TUE
public long deleteTue(int id)
{
try{
return db.delete(DBHelper.TB_NAME_TUE, DBHelper.ROW_ID_TUE + " =?", new String[]{String.valueOf(id)});
}catch (SQLiteException e) {
e.printStackTrace();}
return 0;}
//ALL TRAINING TABLE MON
public Cursor getAllTreningMon() {
try{
String[] columns = {DBHelper.ROW_ID_MON, DBHelper.EXERCISE, DBHelper.WEIGHT, DBHelper.REPEAT, DBHelper.SERIES};
return db.query(DBHelper.TB_NAME_MON, columns, null, null, null, null, null);
}catch (SQLiteException e)
{
e.printStackTrace();
}
return null;
}
//ALL TRAINING TABLE TUE
public Cursor getAllTreningTue() {
try{
String[] columns = {DBHelper.ROW_ID_TUE, DBHelper.EXERCISE, DBHelper.WEIGHT, DBHelper.REPEAT, DBHelper.SERIES};
return db.query(DBHelper.TB_NAME_TUE, columns, null, null, null, null, null);
}catch (SQLiteException e)
{
e.printStackTrace();
}
return null;}}
MyAdapter.class
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
ArrayList<Training> training;
public static String KEY_MON = "KEY_MON";
public static String KEY_TUE = "KEY_TUE";
public static String VALUE_MON = "10";
public static String VALUE_TUE = "20";
public <T extends Training> MyAdapter(Context c, ArrayList<Training> training) {
this.c = c;
this.training = training;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(c).inflate(R.layout.card_view_model, parent, false);
return new MyHolder(v);
}
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
holder.textViewModel.setText(training.get(position).getExercise());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v) {
if (FirstActivity.WAS_RUNNING)
{Intent intent = new Intent(c, DetailActivity.class);
intent.putExtra(KEY_MON, VALUE_MON);
intent.putExtra("id", training.get(position).getId());
intent.putExtra("exercise", training.get(position).getExercise());
intent.putExtra("weight", training.get(position).getWeight());
intent.putExtra("repeat", training.get(position).getRepeat());
intent.putExtra("series", training.get(position).getSeries());
c.startActivity(intent);
} else if (FirstActivity.WAS_RUNNING)
{Intent intent2 = new Intent(c, DetailActivity.class);
intent2.putExtra(KEY_TUE, VALUE_TUE);
intent2.putExtra("id", training.get(position).getId());
intent2.putExtra("exercise", training.get(position).getExercise());
intent2.putExtra("weight", training.get(position).getWeight());
intent2.putExtra("repeat", training.get(position).getRepeat());
intent2.putExtra("series", training.get(position).getSeries());
c.startActivity(intent2);
}}});}
#Override
public int getItemCount() {
return training.size();}}
Training.class
public class Training {
int id;
String exercise;
String weight;
String repeat;
String series;
public Training(int id, String exercise, String weight, String repeat, String series) {
this.id = id;
this.exercise = exercise;
this.weight = weight;
this.repeat = repeat;
this.series = series;
}
public int getId() {return id;}
public void setId(int id) { this.id = id;}
public String getExercise() {return exercise; }
public void setExercise(String exercise) {this.exercise = exercise;}
public String getWeight() {return weight;}
public void setWeight(String weight) {this.weight = weight; }
public String getRepeat() {return repeat;}
public void setRepeat(String repeat) { this.repeat = repeat;}
public String getSeries() {return series;}
public void setSeries(String series) {this.series = series;}}
In your MyAdapter class, in the onItemClick method, within the onBindViewHolder method, the second check, for Tue processing, would never run.
You have :-
if (FirstActivity.WAS_RUNNING) {
.......
} else if (FirstActivity.WAS_RUNNING) {
.......
}
i.e. you are saying if FirstActivity was not running and the FirstActivity was running then do your stuff.
i.e. the else will only be entered if FirstActivity were not running, in which case the if (FirstActivity.WAS_RUNNING) would never be true.
Perhaps have 2 booleans MONDAY_WAS_RUNNING and TUESDAY_WAS RUNNING (you could use just the existing boolean by setting that to false in the buttonTue listener doing the Tuesday processing in the else (without an if) ).
e.g. :-
FirstActivity class :-
public static boolean MONDAY_WAS_RUNNING;
public static boolean TUESDAY_WAS_RUNNING;
..........
buttonMon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MONDAY_WAS_RUNNING = true;
TUESDAY_WAS_RUNNING = false;
Intent intent = new Intent(FirstActivity.this, MainActivity.class);
intent.putExtra(BUTTON_KEY1, BUTTON_VALUE);
startActivity(intent);
} });
buttonTue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TUESDAY_WAS_RUNNING = true;
MONDAY_WAS_RUNNING = false;
Intent i = new Intent(FirstActivity.this, MainActivity.class);
i.putExtra(BUTTON_KEY2, BUTTON_VALUE2);
startActivity(i);
} });}}
MyAdapter :-
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
holder.textViewModel.setText(training.get(position).getExercise());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v) {
if (FirstActivity.MONDAY_WAS_RUNNING)
{Intent intent = new Intent(c, DetailActivity.class);
intent.putExtra(KEY_MON, VALUE_MON);
intent.putExtra("id", training.get(position).getId());
intent.putExtra("exercise", training.get(position).getExercise());
intent.putExtra("weight", training.get(position).getWeight());
intent.putExtra("repeat", training.get(position).getRepeat());
intent.putExtra("series", training.get(position).getSeries());
c.startActivity(intent);
} else if (FirstActivity.TUESDAY_WAS_RUNNING)
{Intent intent2 = new Intent(c, DetailActivity.class);
intent2.putExtra(KEY_TUE, VALUE_TUE);
intent2.putExtra("id", training.get(position).getId());
intent2.putExtra("exercise", training.get(position).getExercise());
intent2.putExtra("weight", training.get(position).getWeight());
intent2.putExtra("repeat", training.get(position).getRepeat());
intent2.putExtra("series", training.get(position).getSeries());
c.startActivity(intent2);
}}});}
However I'd probably go for :-
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
holder.textViewModel.setText(training.get(position).getExercise());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v) {
Intent intent = new Intent(c, DetailActivity.class);
if (FirstActivity.MONDAY_WAS_RUNNING) {
intent.putExtra(KEY_MON, VALUE_MON);
} else {
intent.putExtra(KEY_TUE, VALUE_TUE);
}
intent.putExtra("id", training.get(position).getId());
intent.putExtra("exercise", training.get(position).getExercise());
intent.putExtra("weight", training.get(position).getWeight());
intent.putExtra("repeat", training.get(position).getRepeat());
intent.putExtra("series", training.get(position).getSeries());
c.startActivity(intent);
});
}
Note! the above code has not been checked, rather it is in-principle code
I am developing an app in which i have to inform user that you are not connected to internet for further process.
I have two button accept and reject when we click on either button it should notify to connect to internet
private void initializeClickListeners() {
acceptB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int checkedOrders = checkedCheckboxArray.size();
Log.v(TAG,"size of the checked orders is: "+checkedOrders);
String msgOrdersText = "Order";
if(checkedOrders == 0)
{
Toast.makeText(getActivity(), "No Order Selected", Toast.LENGTH_SHORT).show();
}
else if(checkedOrders != 0 )
{
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
if(checkedOrders==1)
{
msgOrdersText = "Order";
}
if(checkedOrders>1)
{
msgOrdersText = "Orders";
}
adb.setTitle("Accept "+msgOrdersText);
adb.setMessage("Do you want to deliver "+checkedOrders+" "+msgOrdersText);
adb.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Log.v(TAG,"Adding orders to current list on Acceptance");
int oId;
DatabaseHelper db = new DatabaseHelper(getActivity());
db.getReadableDatabase();
Cursor cursor = db.getNewOrders();
Log.v(TAG,"Count: "+cursor.getCount());
StringBuilder orderIds = new StringBuilder();
for(int i:checkedCheckboxArray)
{
cursor.moveToPosition(i);
//oId = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.ORDER_ID));
oId = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.ORDER_ID));
db.updateOrderStatus(oId, "A");
//Log.v(TAG,"ORDER id: "+oId);
orderIds.append(oId+"$");
}
Log.v(TAG,"Selected orders in string: "+orderIds);
UpdateSelectedOrdersStatusAsyncTask updateStatus = new UpdateSelectedOrdersStatusAsyncTask();
updateStatus.execute(orderIds.toString(),"1");
cursor.close();
db.close();
Toast.makeText(getActivity(), checkedOrders+" order accepted", Toast.LENGTH_SHORT).show();
// set the selected orders to none
checkedCheckboxArray.clear();
// set the state of checkbox for all the items in list to false
for(int i=0;i<checkedState.length;i++)
{
checkedState[i] = false;
}
// refill the list adapter
fillAdapter(0);
// update the order count notification in menu bar
setNotificationCounter();
}
});
adb.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.v(TAG,"Orders not added to the current list");
//checkedCheckboxArray.clear();
}
});
AlertDialog ad = adb.create();
ad.show();
}
}
});
rejectB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int checkedOrders = checkedCheckboxArray.size();
Log.v(TAG,"size of the checked orders is: "+checkedOrders);
String msgOrdersText = "Order";
if(checkedOrders == 0)
{
Toast.makeText(getActivity(), "No Order Selected", Toast.LENGTH_SHORT).show();
}
else if(checkedOrders != 0 )
{
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
if(checkedOrders==1)
{
msgOrdersText = "Order";
}
if(checkedOrders>1)
{
msgOrdersText = "Orders";
}
adb.setTitle("Reject "+msgOrdersText);
adb.setMessage("Do you want to Reject "+checkedOrders+" "+msgOrdersText);
adb.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.v(TAG,"Adding orders to current list");
int oId;
DatabaseHelper db = new DatabaseHelper(getActivity());
db.getReadableDatabase();
Cursor cursor = db.getNewOrders();
Log.v(TAG,"Count: "+cursor.getCount());
StringBuilder orderIds = new StringBuilder("");
for(int i:checkedCheckboxArray)
{
cursor.moveToPosition(i);
oId = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.ORDER_ID));
db.updateOrderStatus(oId, "R");
orderIds.append(oId+"$");
}
cursor.close();
db.close();
Log.v(TAG,"Selected orders in string: "+orderIds);
UpdateSelectedOrdersStatusAsyncTask updateStatus = new UpdateSelectedOrdersStatusAsyncTask();
updateStatus.execute(orderIds.toString(),"2");
Toast.makeText(getActivity(), checkedOrders+" order rejected/deleted", Toast.LENGTH_SHORT).show();
checkedCheckboxArray.clear();
// set the state of checkbox for all the items in list to false
for(int i=0;i<checkedState.length;i++)
{
checkedState[i] = false;
}
fillAdapter(0);
setNotificationCounter();
}
});
adb.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.v(TAG,"Orders not added to the current list");
}
});
AlertDialog ad = adb.create();
ad.show();
}
}
});
Now i am putting my device internet status code
public class DeviceInternetStatus {
private static final String TAG = "Buzz";
private static DeviceInternetStatus instance = new DeviceInternetStatus();
static Context context;
ConnectivityManager connectivityManager;
NetworkInfo wifiInfo, mobileInfo;
boolean connected = false;
public static DeviceInternetStatus getInstance(Context ctx) {
context = ctx.getApplicationContext();
return instance;
}
public boolean isOnline() {
try {
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
Log.v(TAG,"Type of Network(Device Internet Status): "+networkInfo);
connected = networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
return connected;
} catch (Exception e) {
Log.v("Buzz","Connectivity Exception"+ e.toString());
}
return connected;
}
You need to create a constructor passing the object of OnItemClickListener
like this,
static Class<? extends OnItemClickListener> cls;
public static DeviceInternetStatus getInstance(OnItemClickListner listner) {
cls=listener.getClass();
return instance;
}
want to validate edit text according to SQLite table data types
I have one table in my SQLite database which has three data types integer,integer,text respectively. edit texts are creates dynamically according to columns present in table. now I want to give validation on each text box like if I enter string value for integer datatype then one popup should display which shows message "can't insert text value for data type integer". so what can I do now?
here is my code
public class DisplayTable_Grid extends Activity
{
TableLayout table_layout;
SQL_crud sqlcon;
TableRow rw;
TextView gettxt_onLongclik;
ArrayList<String> storeColumnNames;
EditText enter_text;
TextView set_txt;
List<EditText> allEds = new ArrayList<EditText>();
ArrayList<String> storeallEds=new ArrayList<String>();
ArrayList<String> storeEditextText=new ArrayList<String>();
List<TextView> textViewlst = new ArrayList<TextView>();
ArrayList<String> getColumnNames=new ArrayList<String>();
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.displaytable);
sqlcon = new SQL_crud(this);
table_layout = (TableLayout) findViewById(R.id.diplay_table);
BuildTable();
}
private void BuildTable()
{
sqlcon.open();
storeColumnNames=sqlcon.getColumnNames(DisaplayTables_list.getTableNameFromListView.toString());
Cursor c = sqlcon.readEntryofTable(DisaplayTables_list.getTableNameFromListView.toString());
int rows = c.getCount();
int cols = c.getColumnCount();
String colN=c.getColumnNames().toString();
arraylist=sqlcon.readColumn_Datatypes(DisaplayTables_list.getTableNameFromListView.toString ());
ArrayList<String> colName=new ArrayList<String>();
colName=sqlcon.getColumnNames(DisaplayTables_list.getTableNameFromListView.toString());
//colName.add(colN);
c.moveToFirst();
System.out.println("size of hash map:"+arraylist.size());
for(int k=0;k<1;k++)
{
TableRow rowcolumnName = new TableRow(this);
rowcolumnName.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
rowcolumnName.setBackgroundColor(Color.GRAY);
for(int a=0;a<cols/*arraylist.size()*/;a++)
{
TextView columnName = new TextView(this);
columnName.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
columnName.setGravity(Gravity.CENTER);
columnName.setTextSize(18);
columnName.setPadding(0, 5, 0, 5);
columnName.setText(colName.get(a)+" "+arraylist.get(a).toString());
rowcolumnName.addView(columnName);}
table_layout.addView(rowcolumnName);
// c.moveToNext();
}
// outer for loop
if(rows==0)
{
Toast.makeText(getApplicationContext(), "rows not found..cant build table", Toast.LENGTH_LONG);
}
else{
for (int i = 0; i < rows; i++)
{
TableRow row = new TableRow(this);
row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
// inner for loop
for (int j = 0; j < cols; j++)
{
TextView tv = new TextView(this);
tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tv.setGravity(Gravity.CENTER);
tv.setTextSize(18);
tv.setPadding(0, 5, 0, 5);
tv.setText(c.getString(j));
row.addView(tv);
}
row.setClickable(true);
row.requestFocus();
row.setOnLongClickListener(new OnLongClickListener()
{
#Override
public boolean onLongClick(View viewlong)
{
rw=(TableRow) viewlong;
gettxt_onLongclik=(TextView)rw.getChildAt(0);
Toast.makeText(getApplicationContext(),gettxt_onLongclik.getText().toString(),Toast.LENGTH_SHORT).show();
final AlertDialog.Builder alertForSelectOperation=new AlertDialog.Builder(DisplayTable_Grid.this);
final LinearLayout linear=new LinearLayout(DisplayTable_Grid.this);
linear.setOrientation(LinearLayout.VERTICAL);
//TextView update=(TextView)new TextView(DisplayTable_Grid.this);
Button update=(Button)new Button(DisplayTable_Grid.this);
//update.setBackgroundColor(Color.rgb(3,12,90));
update.setText(Html.fromHtml("<font size=10>Update</font>"));
update.setOnClickListener(new OnClickListener()
{ #Override
public void onClick(View arg0)
{
final AlertDialog.Builder alertDialogOK_CANCEL=new AlertDialog.Builder(DisplayTable_Grid.this);
final LinearLayout linearlayout=new LinearLayout(DisplayTable_Grid.this);
linearlayout.setOrientation(LinearLayout.VERTICAL);
sqlcon.open();
getColumnNames=sqlcon.getColumnNames(DisaplayTables_list.getTableNameFromListView.toString());
Cursor crs=sqlcon.readColumnCnt(DisaplayTables_list.getTableNameFromListView.toString());
int count=crs.getColumnCount();
Cursor cr=sqlcon.getSinlgeEntryof_table(DisaplayTables_list.getTableNameFromListView.toString(),getColumnNames.get(0), gettxt_onLongclik.getText().toString());
cr.moveToFirst();
for(int i=0;i<count;i++)
{ //add edittext to arralist
enter_text=new EditText(DisplayTable_Grid.this);
allEds.add(enter_text);
allEds.get(i).setText(cr.getString(cr.getColumnIndex(getColumnNames.get(i))));
linearlayout.addView(enter_text);
}
sqlcon.close();
//finish();
alertDialogOK_CANCEL.setPositiveButton("Update", new DialogInterface.OnClickListener()
{ #Override
public void onClick(DialogInterface arg0, int arg1)
{
for(int i=0;i<allEds.size();i++)
{
//System.out.println(allEds.get(i).getText().toString());
storeallEds.add(allEds.get(i).getText().toString());
String getarraylist=arraylist.get(i).toString();
String datatype_text="{datatype=text}";
String datatype_integer="{datatype=integer}";
if(getarraylist.equals(datatype_text) || getarraylist.equals(datatype_integer))
{
if(getarraylist.equals(datatype_text))
{
Toast.makeText(getApplicationContext(), "text"+storeallEds.get(i),Toast.LENGTH_LONG).show();
//enter_text.setInputType(InputType.TYPE_CLASS_TEXT);
}
else if(getarraylist.equals(datatype_integer))
{
if(storeallEds.get(i).contains("a"))//allEds.get(i).getText().toString().contains("a")||allEds.get(i).getText().toString().contains("b"))
{
Toast.makeText(getApplicationContext(), "String in integer value",Toast.LENGTH_LONG).show();
//enter_text.setInputType(InputType.TYPE_CLASS_NUMBER);
}
else
{
//storeallEds.add(allEds.get(i).getText().toString());
Toast.makeText(getApplicationContext(), "integer"+storeallEds.get(i),Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "no datatype found",Toast.LENGTH_LONG).show();
}
}
}
//System.out.println(storeallEds);
sqlcon.open();
try
{
sqlcon.updateRecord(DisaplayTables_list.getTableNameFromListView.toString(), gettxt_onLongclik.getText().toString(), storeallEds);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),"Can't Update column already exists ",Toast.LENGTH_LONG).show();
}
Intent i=new Intent(getApplicationContext(),DisplayTable_Grid.class);
startActivity(i);
sqlcon.close();
}
});
alertDialogOK_CANCEL.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{ #Override
public void onClick(DialogInterface dialog, int arg1)
{
dialog.dismiss();
}
});
alertDialogOK_CANCEL.setView(linearlayout);
alertDialogOK_CANCEL.setTitle("insert values here");
alertDialogOK_CANCEL.create();
alertDialogOK_CANCEL.show();
}
});
//TextView delete=(TextView)new TextView(DisplayTable_Grid.this);
Button delete=(Button)new Button(DisplayTable_Grid.this);
delete.setText(Html.fromHtml("<font size=10> Delete</font>"));
//delete.setBackgroundColor(Color.rgb(3,12,90));
delete.setOnClickListener(new OnClickListener()
{ #Override
public void onClick(View arg0)
{
final AlertDialog.Builder alertDialogOK_CANCEL=new AlertDialog.Builder(DisplayTable_Grid.this);
alertDialogOK_CANCEL.setMessage("Press OK to Delete this Record");
alertDialogOK_CANCEL.setPositiveButton("OK", new DialogInterface.OnClickListener()
{ #Override
public void onClick(DialogInterface arg0, int arg1)
{
sqlcon.open();
sqlcon.deleteEntry(DisaplayTables_list.getTableNameFromListView, storeColumnNames.get(0), gettxt_onLongclik.getText().toString());
sqlcon.close();
Intent i=new Intent(getApplicationContext(),DisplayTable_Grid.class);
startActivity(i);
}
});
alertDialogOK_CANCEL.setNegativeButton("CANCEL",new DialogInterface.OnClickListener()
{ #Override
public void onClick(DialogInterface dialog, int arg1)
{
dialog.dismiss();
}
});
alertDialogOK_CANCEL.create();
alertDialogOK_CANCEL.show();
}
});
//TextView insert=(TextView)new TextView(DisplayTable_Grid.this);
Button insert=(Button)new Button(DisplayTable_Grid.this);
insert.setText(Html.fromHtml("<font size=10>Insert</font>"));
//insert.setBackgroundColor(Color.rgb(3,12,90));
insert.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
final AlertDialog.Builder alertDialog=new AlertDialog.Builder(DisplayTable_Grid.this);
final LinearLayout linearlayout=new LinearLayout(DisplayTable_Grid.this);
linearlayout.setOrientation(LinearLayout.VERTICAL);
sqlcon.open();
getColumnNames=sqlcon.getColumnNames(DisaplayTables_list.getTableNameFromListView);
Cursor crs=sqlcon.readColumnCnt(DisaplayTables_list.getTableNameFromListView);
int count=crs.getColumnCount();
for(int i=0;i<count;i++)
{ //add edittext to arralist
enter_text=new EditText(DisplayTable_Grid.this);
allEds.add(enter_text);
String getarraylist=arraylist.get(i).toString();
String datatype_text="{datatype=text}";
String datatype_integer="{datatype=integer}";
if(getarraylist.equals(datatype_text))
{
Toast.makeText(getApplicationContext(), "text",Toast.LENGTH_LONG).show();
enter_text.setInputType(InputType.TYPE_CLASS_TEXT);
}
else if(getarraylist.equals(datatype_integer))
{
Toast.makeText(getApplicationContext(), "integer",Toast.LENGTH_LONG).show();
//enter_text.setInputType(InputType.TYPE_CLASS_NUMBER);
}
else
{
Toast.makeText(getApplicationContext(), "no datatype found",Toast.LENGTH_LONG).show();
}
//add textview to ayyalist
set_txt=new TextView(DisplayTable_Grid.this);
set_txt.setText(getColumnNames.get(i));
set_txt.setTextSize(15);
textViewlst.add(set_txt);
linearlayout.addView(set_txt);
linearlayout.addView(enter_text);
}
sqlcon.close();
alertDialog.setPositiveButton("Insert", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
if(allEds.size()==0)
{Toast.makeText(getApplicationContext(), "value not found",Toast.LENGTH_LONG).show();}
else
{
for(int i=0; i < allEds.size(); i++)
{ storeEditextText.add(allEds.get(i).getText().toString());
System.out.println("show gettext: "+storeEditextText.get(i).toString());
String getarraylist=arraylist.get(i).toString();
String datatype_text="{datatype=text}";
String datatype_integer="{datatype=integer}";
if(getarraylist.equals(datatype_text))
{
Toast.makeText(getApplicationContext(), "text",Toast.LENGTH_LONG).show();
}
else if(getarraylist.equals(datatype_integer))
{
Toast.makeText(getApplicationContext(), "integer",Toast.LENGTH_LONG).show();
if(storeEditextText.contains("a")||storeEditextText.contains("b"))
{
try
{
int edittxtint=Integer.parseInt(allEds.get(i).getText().toString());//enter_text.setInputType(InputType.TYPE_CLASS_NUMBER);
}
catch(Exception e)
{
System.out.println("exception....."+e);
Toast.makeText(getApplicationContext(),"value must be an integer",Toast.LENGTH_LONG).show();
}
}
}
else
{
Toast.makeText(getApplicationContext(), "no datatype found",Toast.LENGTH_LONG).show();
}
}
if(storeEditextText.size()==0)
{Toast.makeText(getApplicationContext(), "Text is empty",Toast.LENGTH_LONG).show();}
else
{
sqlcon.open();
try
{sqlcon.insert(DisaplayTables_list.getTableNameFromListView,storeEditextText);}
catch(Exception e)
{Toast.makeText(getApplicationContext(),"emp_id is Primary key", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),"column value already exists",Toast.LENGTH_LONG).show();}
System.out.println("size of storeEdittext="+storeEditextText.size());
System.out.println("size of Edit Texts: "+allEds.size());
}
Intent i=new Intent(getApplicationContext(),DisplayTable_Grid.class);
startActivity(i);
sqlcon.close();
}
}
});
alertDialog.setView(linearlayout);
alertDialog.setTitle("insert values here");
alertDialog.create();
alertDialog.show();
}
});
linear.addView(insert);
linear.addView(update);
linear.addView(delete);
alertForSelectOperation.setView(linear);
alertForSelectOperation.setTitle("perform operations here");
alertForSelectOperation.create();
alertForSelectOperation.show();
alertForSelectOperation.setCancelable(true);
return false;
}
});
row.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
TableRow rw=(TableRow) v;
TextView gettxt=(TextView)rw.getChildAt(0);
Toast.makeText(getApplicationContext(), gettxt.getText().toString(),Toast.LENGTH_SHORT).show();
}
});
c.moveToNext();
table_layout.addView(row);
}
}//end of else for null rows
sqlcon.close();
}
}
You can modify your table definition and add "CHECK" constraint, like this:
CREATE TABLE tab (
column1 INTEGER CHECK(typeof(column1) == "integer"),
column2 INTEGER CHECK(typeof(column2) == "integer"),
column3 TEXT CHECK(typeof(column3) == "text")
);
This will enable your database to enforce datatype checking for this table. This will slow down the insertions/updates on this table just a bit.
I have a database that contains level and stage of the game and the problem is every time I call method getId(), getLevel() or getStage() in my code, it's just throws CursorIndexOutOfBoundsException. I have 5 indices of my database but it tells me that only 0 indices are available. This is the code:
Database helper class:
public class DatabaseGame extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "DB2.db";
private static final int SCHEMA_VERSION = 6;
public DatabaseGame(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE save_progress (ID INTEGER PRIMARY KEY NOT NULL, LEVEL VARCHAR(3), STAGE1 VARCHAR(3), STAGE2 VARCHAR(3), STAGE3 VARCHAR(3));");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public void insert(String level, String stage1, String stage2, String stage3) {
ContentValues carry = new ContentValues();
carry.put("ID", 1);
carry.put("LEVEL", level);
carry.put("STAGE1", stage1);
carry.put("STAGE2", stage2);
carry.put("STAGE3", stage3);
getWritableDatabase().insert("save_progress", null, carry);
}
public void update(int id, String level, String stage1, String stage2,
String stage3) {
getWritableDatabase().execSQL(
"UPDATE save_progress SET LEVEL = '" + level + "', STAGE1 = '"
+ stage1 + "', STAGE2 = '" + stage2 + "', STAGE3 = '"
+ stage3 + "' WHERE ID = " + id + ";");
}
public Cursor getAll() {
return (getReadableDatabase().rawQuery("SELECT * FROM save_progress",
null));
}
public String getId(Cursor c) {
return (c.getString(0));
}
public String getLevel(Cursor c) {
return (c.getString(1));
}
public String getStage(Cursor c, int level) {
return (c.getString(level + 1));
}
}
Main class. The error occures when I access Integer.parseInt(db.getLevel(select)):
public class Level extends Activity {
DatabaseGame db = null;
Handler handlerTimer = new Handler();
ImageButton lv1, lv2, lv3;
Animation b1, b2, b3;
Cursor select = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.level);
b1 = AnimationUtils.loadAnimation(this, R.anim.button);
b2 = AnimationUtils.loadAnimation(this, R.anim.button);
b3 = AnimationUtils.loadAnimation(this, R.anim.button);
db = new DatabaseGame(this);
select = db.getAll();
if(select == null) {
db.insert("1", "1", "1", "1");
}
initAnimation();
super.onCreate(savedInstanceState);
}
#Override
protected void onPause() {
super.onPause();
db.close();
finish();
}
public void initAnimation() {
Thread animated = new Thread() {
public void run() {
try {
lv1 = (ImageButton) findViewById(R.id.level1);
lv1.setImageResource(R.drawable.level1_b);
lv1.setAnimation(b1);
lv1.startAnimation(b1);
lv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle trans = new Bundle();
trans.putInt("level", 1);
Intent change = new Intent("com.idncd.indonesiaku.STAGE");
change.putExtras(trans);
startActivity(change);
}
});
handlerTimer.postDelayed(new Runnable() {
public void run() {
if (Integer.parseInt(db.getLevel(select)) > 1) {
lv2 = (ImageButton) findViewById(R.id.level2);
lv2.setImageResource(R.drawable.level2_b);
lv2.setAnimation(b2);
lv2.startAnimation(b2);
lv2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle trans = new Bundle();
trans.putInt("level", 1);
Intent change = new Intent("com.idncd.indonesiaku.STAGE");
change.putExtras(trans);
startActivity(change);
}
});
} else {
lv2 = (ImageButton) findViewById(R.id.level2);
lv2.setImageResource(R.drawable.level2_un_b);
lv2.setAnimation(b2);
lv2.startAnimation(b2);
lv2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
}, 300);
handlerTimer.postDelayed(new Runnable() {
public void run() {
if (Integer.parseInt(db.getLevel(select)) > 2) {
lv3 = (ImageButton) findViewById(R.id.level3);
lv3.setImageResource(R.drawable.level3_b);
lv3.setAnimation(b3);
lv3.startAnimation(b3);
lv3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle trans = new Bundle();
trans.putInt("level", 1);
Intent change = new Intent("com.idncd.indonesiaku.STAGE");
change.putExtras(trans);
startActivity(change);
}
});
} else {
lv3 = (ImageButton) findViewById(R.id.level3);
lv3.setImageResource(R.drawable.level3_un_b);
lv3.setAnimation(b3);
lv3.startAnimation(b3);
lv3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
}, 600);
} catch (Exception e) {
e.printStackTrace();
}
}
};
animated.start();
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent menu = new Intent("com.idncd.indonesiaku.MAINMENU");
startActivity(menu);
return true;
} else {
return super.onKeyUp(keyCode, event);
}
}
}
Thank you for your help.
You have to firstly set location of Cursor refrence before use it , Use moveToFirsrt(), moveToLast() etc..
The question is a little unclear, but I assume you mean that SELECT * doesn't return all the columns you have in your onCreate().
You have updated SCHEMA_VERSION but your onUpgrade() is empty. Therefore the database hasn't actually been updated, though the framework thinks so since onUpgrade() returned successfully.
Clean your app data or uninstall it to remove the old database file. Then when the application is run again, your database helper onCreate() recreates it correctly.