[HELP]FATAL EXCEPTION: main java.lang.NullPointerException [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
ProductDatabase.ProductDatabaseHelper controller = new ProductDatabase.ProductDatabaseHelper(this);
EditText mBarcodeEdit;
EditText mFormatEdit;
EditText mTitleEdit;
EditText mPriceEdit;
private static final int ZBAR_SCANNER_REQUEST = 0;
private static final int ZBAR_QR_SCANNER_REQUEST = 1;
private static final ProductData mProductData = new ProductData();
Button mScanButton;
Button mAddButton;
Button mSelectButton;
Button mExportButton;
Button btnimport;
ProductDatabase mProductDb;
ListView ls;
TextView infotext;
File file = null;
// DatabaseHelper dbhelper = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ls = (ListView) findViewById(R.id.placeslist);
mBarcodeEdit = (EditText) findViewById(R.id.barcodeEdit);
mFormatEdit = (EditText) findViewById(R.id.codeFormatEdit);
mTitleEdit = (EditText) findViewById(R.id.titleEdit);
mPriceEdit = (EditText) findViewById(R.id.priceEdit);
mScanButton = (Button) findViewById(R.id.scan_btn);
mAddButton = (Button) findViewById(R.id.addButton);
mSelectButton = (Button) findViewById(R.id.selelctButton);
mProductDb = new ProductDatabase(this); // not yet shown
infotext = (TextView) findViewById(R.id.txtresulttext);
mExportButton = (Button) findViewById(R.id.exportbtn);
mSelectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, product_list.class);
startActivity(i);
}
});
mAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String barcode = mBarcodeEdit.getText().toString();
String format = mFormatEdit.getText().toString();
String title = mTitleEdit.getText().toString();
String price = mPriceEdit.getText().toString();
String errors = validateFields(barcode, format, title, price);
if (errors.length() > 0) {
showInfoDialog(MainActivity.this, "Please fix errors", errors);
} else {
mProductData.barcode = barcode;
mProductData.format = format;
mProductData.title = title;
mProductData.price = new BigDecimal(price);
mProductDb.insert(mProductData);
showInfoDialog(MainActivity.this, "Success", "Product saved successfully");
resetForm();
}
}
});
mExportButton.setOnClickListener(new View.OnClickListener() {
SQLiteDatabase sqldb = controller.getReadableDatabase(); //My Database class
Cursor c =null;
#Override
public void onClick(View view) { //main code begins here
try {
c = sqldb.rawQuery("select * from spot_pay.db", null);
int rowcount = 0;
int colcount = 0;
File sdCardDir = Environment.getExternalStorageDirectory();
String filename = "MyBackUp.csv";
// the name of the file to export with
File saveFile = new File(sdCardDir, filename);
FileWriter fw = new FileWriter(saveFile);
BufferedWriter bw = new BufferedWriter(fw);
rowcount = c.getCount();
colcount = c.getColumnCount();
if (rowcount > 0) {
c.moveToFirst();
for (int i = 0; i < colcount; i++) {
if (i != colcount - 1) {
bw.write(c.getColumnName(i) + ",");
} else {
bw.write(c.getColumnName(i));
}
}
bw.newLine();
for (int i = 0; i < rowcount; i++) {
c.moveToPosition(i);
for (int j = 0; j < colcount; j++) {
if (j != colcount - 1)
bw.write(c.getString(j) + ",");
else
bw.write(c.getString(j));
}
bw.newLine();
}
bw.flush();
infotext.setText("Exported Successfully.");
}
} catch (Exception ex) {
if (sqldb.isOpen()) {
sqldb.close();
infotext.setText(ex.getMessage().toString());
}
} finally {
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
private void showInfoDialog(Context context, String title, String information) {
new AlertDialog.Builder(context)
.setMessage(information)
.setTitle(title)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
private void resetForm() {
// TODO Auto-generated method stub
mBarcodeEdit.getText().clear();
mFormatEdit.getText().clear();
mTitleEdit.getText().clear();
mPriceEdit.getText().clear();
}
public void launchScanner(View v) {
if (isCameraAvailable()) {
Intent intent = new Intent(this, ZBarScannerActivity.class);
startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
} else {
Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
}
}
public void launchQRScanner(View v) {
if (isCameraAvailable()) {
Intent intent = new Intent(this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.QRCODE});
startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
} else {
Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
}
}
public boolean isCameraAvailable() {
PackageManager pm = getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ZBAR_SCANNER_REQUEST:
case ZBAR_QR_SCANNER_REQUEST:
if (resultCode == RESULT_OK) {
mBarcodeEdit.setText(data.getStringExtra(ZBarConstants.SCAN_RESULT));
// Toast.makeText(this, "Scan Result = " + data.getStringExtra(ZBarConstants.SCAN_RESULT), Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED && data != null) {
String error = data.getStringExtra(ZBarConstants.ERROR_INFO);
if (!TextUtils.isEmpty(error)) {
Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
}
}
break;
}
}
private static String validateFields(String barcode, String format,
String title, String price) {
StringBuilder errors = new StringBuilder();
if (barcode.matches("^\\s*$")) {
errors.append("Barcode required\n");
}
if (format.matches("^\\s*$")) {
errors.append("Format required\n");
}
if (title.matches("^\\s*$")) {
errors.append("Title required\n");
}
if (!price.matches("^-?\\d+(.\\d+)?$")) {
errors.append("Need numeric price\n");
}
return errors.toString();
}
}

I think string may be null somewhere. Please type something in textfield or check for null string.

Related

save state of my game in database

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);
}

duplicate actions in android application when going to home screen

Intro:
My client require some components across the application like navigationDrawer, toolbar. So I have a MainActivity having two toolbar(top/bottom) and two navigation drawer(left/right). All other screens consist of fragments that I change in MainActivity. I have a little problem that is some of the action are being duplicated.
Cases:
In some fragments when user perform an action i.e.
1: User press "Add To Cart" button and press home button that is in toolbar Bottom, the code of "Add To Cart" button run twice (once clicking button, once going to home screen) so my item is being added to cart twice.
2: In another fragment I have "apply coupon" checkbox when user check that checkbox an AlertDialog appear and when user go to home screen the AlertDialog again appear in the home screen.
I'm simply recreating the main activity on home button press with recreate();
I check the code but can't understand why those actions duplicate. If someone faced the same or a bit similar problem please guide me how to tackle that. Any help would be appreciated.
If I need to show code tell me which part?
Edit:
inside onCreateView of fragment Cart Detail
useCoupon.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
createAndShowCustomAlertDialog();
}
}
});
Sequence of this code is Main Activity(Main Fragment)=>Product Frag=>Cart Detail Frag.
Edit 2: MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
this.utils = new Utils(this);
utils.changeLanguage("en");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
this.context = this;
setupToolbar(this);
utils.switchFragment(new MainFrag());
setOnClickListener();
initRightMenuData();
initLeftMenuData();
listAdapter = new ExpandableListAdapter(headerListLeft, hashMapLeft,
false, loggedInIconList);
listViewExpLeft.setAdapter(listAdapter);
if (isLoggedIn()) {
listAdapterRight = new ExpandableListAdapterRight(headerListRight, hashMapRight,
loggedInIconList);
} else {
listAdapterRight = new ExpandableListAdapterRight(headerListRight, hashMapRight,
NotLoggedInIconList);
}
listViewExpRight.setAdapter(listAdapterRight);
enableSingleSelection();
setExpandableListViewClickListener();
setExpandableListViewChildClickListener();
}
private void setOnClickListener() {
myAccountTV.setOnClickListener(this);
checkoutTV.setOnClickListener(this);
discountTV.setOnClickListener(this);
homeTV.setOnClickListener(this);
searchIcon.setOnClickListener(this);
cartLayout.setOnClickListener(this);
}
private void setExpandableListViewClickListener() {
listViewExpRight.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition,
long id) {
utils.printLog("GroupClicked", " Id = " + id);
int childCount = parent.getExpandableListAdapter().getChildrenCount(groupPosition);
if (!isLoggedIn()) {
if (childCount < 1) {
if (groupPosition == 0) {
utils.switchFragment(new FragLogin());
} else if (groupPosition == 1) {
utils.switchFragment(new FragRegister());
} else if (groupPosition == 2) {
utils.switchFragment(new FragContactUs());
} else {
recreate();
}
drawer.closeDrawer(GravityCompat.END);
}
} else {
if (childCount < 1) {
changeFragment(103 + groupPosition);
drawer.closeDrawer(GravityCompat.END);
}
}
return false;
}
});
listViewExpLeft.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
int childCount = parent.getExpandableListAdapter().getChildrenCount(groupPosition);
if (childCount < 1) {
MenuCategory textChild = (MenuCategory) parent.getExpandableListAdapter()
.getGroup(groupPosition);
moveToProductFragment(textChild.getMenuCategoryId());
utils.printLog("InsideChildClick", "" + textChild.getMenuCategoryId());
}
return false;
}
});
}
private void setExpandableListViewChildClickListener() {
listViewExpLeft.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
MenuSubCategory subCategory = (MenuSubCategory) parent.getExpandableListAdapter()
.getChild(groupPosition, childPosition);
moveToProductFragment(subCategory.getMenuSubCategoryId());
utils.printLog("InsideChildClick", "" + subCategory.getMenuSubCategoryId());
return true;
}
});
listViewExpRight.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
String str = parent.getExpandableListAdapter().getGroup(groupPosition).toString();
UserSubMenu userSubMenu = (UserSubMenu) parent.getExpandableListAdapter()
.getChild(groupPosition, childPosition);
if (str.contains("Information") || str.contains("معلومات")) {
Bundle bundle = new Bundle();
bundle.putString("id", userSubMenu.getUserSubMenuCode());
utils.switchFragment(new FragShowText(), bundle);
} else if (str.contains("اللغة") || str.contains("Language")) {
recreate();
} else if (str.contains("دقة") || str.contains("Currency")) {
makeDefaultCurrencyCall(userSubMenu.getUserSubMenuCode());
}
utils.printLog("InsideChildClick", "" + userSubMenu.getUserSubMenuCode());
drawer.closeDrawer(GravityCompat.END);
return false;
}
});
}
private void setupToolbar(Context context) {
ViewCompat.setLayoutDirection(appbarBottom, ViewCompat.LAYOUT_DIRECTION_RTL);
ViewCompat.setLayoutDirection(appbarTop, ViewCompat.LAYOUT_DIRECTION_RTL);
String imgPath = Preferences
.getSharedPreferenceString(appContext, LOGO_KEY, DEFAULT_STRING_VAL);
utils.printLog("Product Image = " + imgPath);
if (!imgPath.isEmpty()) {
Picasso.with(getApplicationContext()).load(imgPath)
.into(logoIcon);
}
logoIcon.setOnClickListener(this);
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
actionbarToggle();
drawer.addDrawerListener(mDrawerToggle);
drawerIconLeft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
drawerIconLeft.setScaleX(1);
drawerIconLeft.setImageResource(R.drawable.ic_arrow_back_black);
}
}
});
drawerIconRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
drawer.openDrawer(GravityCompat.END);
}
}
});
}
private void initViews() {
drawerIconLeft = findViewById(R.id.drawer_icon_left);
drawerIconRight = findViewById(R.id.drawer_icon_right);
logoIcon = findViewById(R.id.logo_icon);
searchIcon = findViewById(R.id.search_icon);
cartLayout = findViewById(R.id.cart_layout);
counterTV = findViewById(R.id.actionbar_notification_tv);
drawer = findViewById(R.id.drawer_layout);
listViewExpLeft = findViewById(R.id.expandable_lv_left);
listViewExpRight = findViewById(R.id.expandable_lv_right);
appbarBottom = findViewById(R.id.appbar_bottom);
appbarTop = findViewById(R.id.appbar_top);
myAccountTV = findViewById(R.id.my_account_tv);
discountTV = findViewById(R.id.disc_tv);
checkoutTV = findViewById(R.id.checkout_tv);
homeTV = findViewById(R.id.home_tv);
searchView = findViewById(R.id.search_view);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
super.onBackPressed();
}
}
private void initRightMenuData() {
headerListRight = new ArrayList<>();
hashMapRight = new HashMap<>();
String[] notLoggedInMenu = {findStringByName("login_text"),
findStringByName("action_register_text"),
findStringByName("contact_us_text")};
String[] loggedInMenu = {findStringByName("account"), findStringByName("edit_account_text"),
findStringByName("action_change_pass_text"),
findStringByName("order_history_text"),
findStringByName("logout"), findStringByName("contact_us_text")};
List<UserSubMenu> userSubMenusList = new ArrayList<>();
if (isLoggedIn()) {
for (int i = 0; i < loggedInMenu.length; i++) {
headerListRight.add(loggedInMenu[i]);
hashMapRight.put(headerListRight.get(i), userSubMenusList);
}
} else {
for (int i = 0; i < notLoggedInMenu.length; i++) {
headerListRight.add(notLoggedInMenu[i]);
hashMapRight.put(headerListRight.get(i), userSubMenusList);
}
}
String responseStr = "";
if (getIntent().hasExtra(KEY_EXTRA)) {
responseStr = getIntent().getStringExtra(KEY_EXTRA);
utils.printLog("ResponseInInitData", responseStr);
try {
JSONObject responseObject = new JSONObject(responseStr);
boolean success = responseObject.optBoolean("success");
if (success) {
try {
JSONObject homeObject = responseObject.getJSONObject("home");
JSONArray slideshow = homeObject.optJSONArray("slideshow");
AppConstants.setSlideshowExtra(slideshow.toString());
JSONArray menuRight = homeObject.optJSONArray("usermenu");
for (int z = 0; z < menuRight.length(); z++) {
List<UserSubMenu> userSubMenuList = new ArrayList<>();
JSONObject object = menuRight.getJSONObject(z);
headerListRight.add(object.optString("name"));
JSONArray childArray = object.optJSONArray("children");
for (int y = 0; y < childArray.length(); y++) {
JSONObject obj = childArray.optJSONObject(y);
userSubMenuList.add(new UserSubMenu(obj.optString("code"),
obj.optString("title"), obj.optString("symbol_left"),
obj.optString("symbol_right")));
}
hashMapRight.put(headerListRight.get(headerListRight.size() - 1), userSubMenuList);
utils.printLog("AfterHashMap", "" + hashMapRight.size());
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
utils.showErrorDialog("Error Getting Data From Server");
utils.printLog("SuccessFalse", "Within getCategories");
}
} catch (JSONException e) {
e.printStackTrace();
utils.printLog("JSONObjEx_MainAct", responseStr);
}
} else {
utils.printLog("ResponseExMainActivity", responseStr);
throw new IllegalArgumentException("Activity cannot find extras " + KEY_EXTRA);
}
}
private void initLeftMenuData() {
headerListLeft = new ArrayList<>();
hashMapLeft = new HashMap<>();
String responseStr = "";
if (getIntent().hasExtra(KEY_EXTRA)) {
responseStr = getIntent().getStringExtra(KEY_EXTRA);
utils.printLog("ResponseInMainActivity", responseStr);
try {
JSONObject responseObject = new JSONObject(responseStr);
utils.printLog("JSON_Response", "" + responseObject);
boolean success = responseObject.optBoolean("success");
if (success) {
try {
JSONObject homeObject = responseObject.getJSONObject("home");
JSONArray menuCategories = homeObject.optJSONArray("categoryMenu");
utils.printLog("Categories", menuCategories.toString());
for (int i = 0; i < menuCategories.length(); i++) {
JSONObject menuCategoryObj = menuCategories.getJSONObject(i);
JSONArray menuSubCategoryArray = menuCategoryObj.optJSONArray(
"children");
List<MenuSubCategory> childMenuList = new ArrayList<>();
for (int j = 0; j < menuSubCategoryArray.length(); j++) {
JSONObject menuSubCategoryObj = menuSubCategoryArray.getJSONObject(j);
MenuSubCategory menuSubCategory = new MenuSubCategory(
menuSubCategoryObj.optString("child_id"),
menuSubCategoryObj.optString("name"));
childMenuList.add(menuSubCategory);
}
MenuCategory menuCategory = new MenuCategory(menuCategoryObj.optString(
"category_id"), menuCategoryObj.optString("name"),
menuCategoryObj.optString("icon"), childMenuList);
headerListLeft.add(menuCategory);
hashMapLeft.put(headerListLeft.get(i), menuCategory.getMenuSubCategory());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
utils.printLog("ResponseExMainActivity", responseStr);
throw new IllegalArgumentException("Activity cannot find extras " + KEY_EXTRA);
}
}
private void actionbarToggle() {
mDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawer,
R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
drawerIconLeft.setImageResource(R.drawable.ic_list_black);
drawerIconLeft.setScaleX(-1);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.logo_icon) {
recreate();
} else if (id == R.id.my_account_tv) {
utils.switchFragment(new Dashboard());
} else if (id == R.id.disc_tv) {
utils.printLog("From = Main Act");
Bundle bundle = new Bundle();
bundle.putString("from", "mainActivity");
utils.switchFragment(new FragProduct(), bundle);
} else if (id == R.id.checkout_tv) {
if (isLoggedIn()) {
utils.switchFragment(new FragCheckout());
} else {
AlertDialog alertDialog = utils.showAlertDialogReturnDialog("Continue As",
"Select the appropriate option");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,
"As Guest", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
utils.switchFragment(new FragCheckout());
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
"Login", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
utils.switchFragment(new FragLogin());
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL,
"Register", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
utils.switchFragment(new FragRegister());
}
});
alertDialog.show();
}
} else if (id == R.id.home_tv) {
recreate();
} else if (id == R.id.search_icon) {
startActivityForResult(new Intent(context, SearchActivity.class), SEARCH_REQUEST_CODE);
} else if (id == R.id.cart_layout) {
Bundle bundle = new Bundle();
bundle.putString("midFix", "cartProducts");
utils.switchFragment(new FragCartDetail(), bundle);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SEARCH_REQUEST_CODE || requestCode == CURRENCY_REQUEST_CODE
|| requestCode == LANGUAGE_REQUEST_CODE) {
if (data != null) {
String responseStr = data.getStringExtra("result");
utils.printLog("ResponseIs = " + responseStr);
if (responseStr != null) {
if (resultCode == Activity.RESULT_OK) {
JSONObject response;
if (!isJSONString(responseStr)) {
try {
response = new JSONObject(responseStr);
if (requestCode == CURRENCY_REQUEST_CODE) {
JSONObject object = response.optJSONObject("currency");
Preferences.setSharedPreferenceString(appContext
, CURRENCY_SYMBOL_KEY
, object.optString("symbol_left")
+ object.optString("symbol_right")
);
recreate();
} else if (requestCode == LANGUAGE_REQUEST_CODE) {
JSONObject object = response.optJSONObject("language");
Preferences.setSharedPreferenceString(appContext
, LANGUAGE_KEY
, object.optString("code")
);
recreate();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
if (requestCode == SEARCH_REQUEST_CODE) {
if (responseStr.isEmpty())
return;
Bundle bundle = new Bundle();
bundle.putString("id", responseStr);
bundle.putString("from", "fromSearch");
utils.switchFragment(new FragProduct(), bundle);
} else {
utils.showAlertDialog("Alert", responseStr);
}
}
} else if (resultCode == FORCED_CANCEL) {
utils.printLog("WithinSearchResult", "If Success False" + responseStr);
} else if (resultCode == Activity.RESULT_CANCELED) {
utils.printLog("WithinSearchResult", "Result Cancel" + responseStr);
}
}
}
}
}
}
MainFragment
public class MainFrag extends MyBaseFragment {
public MainFrag() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_main, container, false);
initUtils();
initViews(view);
utils.setupSlider(mPager, indicator, pb, true, true);
RecyclerView.LayoutManager mLayoutManager =
new LinearLayoutManager(getActivity()
, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
List<String> keysList = prepareData();
if (keysList.size() > 0 && !keysList.isEmpty()) {
mRecyclerView.setAdapter(new MainFragmentAdapter(keysList));
}
return view;
}
private void initViews(View view) {
mRecyclerView = view.findViewById(R.id.parent_recycler_view);
mPager = view.findViewById(R.id.pager);
indicator = view.findViewById(R.id.indicator);
pb = view.findViewById(R.id.loading);
}
private List<String> prepareData() {
String responseStr = getHomeExtra();
List<String> keysStr = new ArrayList<>();
try {
JSONObject responseObject = new JSONObject(responseStr);
utils.printLog("JSON_Response", "" + responseObject);
boolean success = responseObject.optBoolean("success");
if (success) {
JSONObject homeObject = responseObject.optJSONObject("home");
JSONObject modules = homeObject.optJSONObject("modules");
Iterator<?> keys = modules.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
keysStr.add(key);
utils.printLog("KeyStr", key);
}
utils.printLog("ModuleSize", modules.toString());
} else {
utils.printLog("SuccessFalse", "Within getCategories");
}
} catch (JSONException e) {
e.printStackTrace();
utils.printLog("JSONEx_MainFragTest", responseStr);
}
return keysStr;
}
}
I removed global variables and some method because of length.
You should not use recreate() method here, as it forces the activity to reload everything. Just use intent to call your Home activity, that should solve this issue.
From the hint of #Akash Khatri I use to switch to mainFragment and its fine now. Actually #Akash is right recreate(); everything at present But as I was setting main fragment in OnCreate of MainActivity. So, It was hard to notice that Android first recreate everything and in no time It call the main Fragment.
I do not using Intent to start the same activity again Because Switching fragment is more convenient. And also I pass Some extras to it that I will loose With new Intent.

Ussd code does not work properly

I have a ussd code on a button.I add CALL_PHONE permissions in manifest.
I use the api (23).
This code does not work properly
Basically what I should do?Thanks.
I have following error:
?E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mahdishekari.mycollectbill, PID: 31738
java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx cmp=com.android.server.telecom/.components.UserCallActivity } from ProcessRecord{4e2904f 31738:com.mahdishekari.mycollectbill/u0a109} (pid=31738, uid=10109) with revoked permission android.permission.CALL_PHONE
at android.os.Parcel.readException(Parcel.java:1620)
at android.os.Parcel.readException(Parcel.java:1573)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:2776)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1509)
at android.app.Activity.startActivityForResult(Activity.java:3958)
at android.app.Activity.startActivityForResult(Activity.java:3919)
at com.mahdishekari.mycollectbill.ActivityMain$C00661.onClick(ActivityMain.java:78)
at android.view.View.performClick(View.java:5217)
at android.view.View$PerformClick.run(View.java:21349)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5585)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
I/Process: Sending signal. PID: 31738 SIG: 9
Disconnected from the target VM, address: 'localhost:8601', transport: 'socket'
My code:
public class ActivityMain extends ActivityBase {
Button btnLink;
Button btnPayBill;
Button btnRecords;
Button btnScanner;
Button btnSupport;
boolean doubleBackToExitPressedOnce;
DatabaseHelper2 myDbHelper;
TextView tvBillType;
TextView tvPrice;
EditText txtBillID;
EditText txtPayID;
EditText txtPrice;
class C00661 implements OnClickListener {
C00661() {
}
public void onClick(View v) {
String payID = ActivityMain.this.txtPayID.getText().toString();
String billID = ActivityMain.this.txtBillID.getText().toString();
String myID = "124336";
String price = ActivityMain.this.txtPrice.getText().toString();
if (billID.length() == 0) {
ActivityMain.this.showToast("\u0634\u0646\u0627\u0633\u0647 \u0642\u0628\u0636 \u0648\u0627\u0631\u062f \u0646\u0634\u062f\u0647 \u0627\u0633\u062a");
} else if (payID.length() == 0) {
ActivityMain.this.showToast("\u0634\u0646\u0627\u0633\u0647 \u067e\u0631\u062f\u0627\u062e\u062a \u0648\u0627\u0631\u062f \u0646\u0634\u062f\u0647 \u0627\u0633\u062a");
} else if (price.length() == 0) {
ActivityMain.this.showToast("\u0645\u0628\u0644\u063a \u0648\u0627\u0631\u062f \u0646\u0634\u062f\u0647 \u0627\u0633\u062a");
} else {
int i;
int payIdLen = payID.length();
for (i = 0; i < 13 - payIdLen; i++) {
payID = "0" + payID;
}
int billIdLen = billID.length();
for (i = 0; i < 13 - billIdLen; i++) {
billID = "0" + billID;
}
Bill entityBillRercord = new Bill();
entityBillRercord.billId = billID;
entityBillRercord.createDate = Tools.getDate();
entityBillRercord.payId = payID;
entityBillRercord.refId = "";
entityBillRercord.price = Tools.toInt(price);
DbBills.insert(entityBillRercord);
String encodeHash = Uri.encode("#");
String ussd = "*733*3*2*" + billID + "*" + payID + "*" + encodeHash;
ActivityMain.this.startActivityForResult(new Intent("android.intent.action.CALL", Uri.parse("tel:" + ussd)),1);
}
}
}
class Scanner implements OnClickListener {
Scanner() {
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnReadBarcode) {
IntentIntegrator scanIntegrator = new IntentIntegrator(ActivityMain.this);
scanIntegrator.initiateScan();
}
}
}
class C00683 implements OnClickListener {
C00683() {
}
public void onClick(View v) {
Intent intent = new Intent(ActivityMain.this, ActivitySupport.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
}
class C00694 implements OnClickListener {
C00694() {
}
public void onClick(View v) {
Intent intent = new Intent("android.intent.action.SEND");
intent.setType("text/plain");
intent.putExtra("android.intent.extra.SUBJECT", "\u0646\u0631\u0645 \u0627\u0641\u0632\u0627\u0631 \u0647\u0645\u0647 \u0642\u0628\u0636");
intent.putExtra("android.intent.extra.TEXT", "\u0646\u0631\u0645 \u0627\u0641\u0632\u0627\u0631 \u0647\u0645\u0647 \u0642\u0628\u0636\n\r\u067e\u0631\u062f\u0627\u062e\u062a \u0631\u0627\u062d\u062a \u0648 \u0622\u0633\u0627\u0646 \u06a9\u0644\u06cc\u0647 \u0642\u0628\u0648\u0636 \u0645\u062c\u0647\u0632 \u0628\u0647 \u0628\u0627\u0631\u06a9\u062f \u062e\u0648\u0627\u0646\n\r http://yealame.ir/upload/allbills.apk");
ActivityMain.this.startActivity(Intent.createChooser(intent, "share"));
}
}
class C00705 implements OnClickListener {
C00705() {
}
public void onClick(View v) {
Intent intent = new Intent(ActivityMain.this, ActivityRecords.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
}
class C00716 implements TextWatcher {
C00716() {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
String payID = ActivityMain.this.txtPayID.getText().toString();
String price = "";
if (payID.length() != 0) {
int i;
int payIdLen = payID.length();
for (i = 0; i < 13 - payIdLen; i++) {
payID = "0" + payID;
}
for (i = 0; i < 8; i++) {
price = new StringBuilder(String.valueOf(price)).append(String.valueOf(payID.charAt(i))).toString();
}
price = String.valueOf(Tools.toInt(price));
ActivityMain.this.txtPrice.setText(new StringBuilder(String.valueOf(price)).append("00").toString());
ActivityMain.this.tvPrice.setText("\u0645\u0628\u0644\u063a \u0642\u0628\u0636: " + price + "00 \u062a\u0648\u0645\u0627\u0646");
}
}
}
class C00727 implements TextWatcher {
C00727() {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
String billID = ActivityMain.this.txtBillID.getText().toString();
int billIdLen = billID.length();
if (billIdLen != 0) {
for (int i = 0; i < 13 - billIdLen; i++) {
billID = "0" + billID;
}
ActivityMain.this.setBillIcon(Tools.getBillIcon(billID));
}
}
}
class C00738 implements Runnable {
C00738() {
}
public void run() {
ActivityMain.this.doubleBackToExitPressedOnce = false;
}
}
public ActivityMain() {
this.doubleBackToExitPressedOnce = false;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(1);
setContentView(R.layout.main);
setFont(findViewById(R.id.llMain));
loadDb();
this.btnPayBill = (Button) findViewById(R.id.btnPay);
this.btnScanner = (Button) findViewById(R.id.btnReadBarcode);
this.txtPayID = (EditText) findViewById(R.id.txtPayID);
this.txtPrice = (EditText) findViewById(R.id.txtPrice);
this.txtBillID = (EditText) findViewById(R.id.txtBillID);
this.tvPrice = (TextView) findViewById(R.id.tvBillPrice);
this.tvBillType = (TextView) findViewById(R.id.tvBillType);
this.btnRecords = (Button) findViewById(R.id.btnRecords);
this.btnLink = (Button) findViewById(R.id.btnLink);
this.btnSupport = (Button) findViewById(R.id.btnSupport);
setListeners();
}
private void loadDb() {
this.myDbHelper = new DatabaseHelper2(this);
try {
this.myDbHelper.createDataBase();
} catch (IOException e) {
}
try {
this.myDbHelper.openDataBase();
} catch (SQLException e2) {
}
BaseDataLayer.db = this.myDbHelper.getDB();
}
private void setListeners() {
this.btnPayBill.setOnClickListener(new C00661());
this.btnScanner.setOnClickListener(new Scanner());
this.btnSupport.setOnClickListener(new C00683());
this.btnLink.setOnClickListener(new C00694());
this.btnRecords.setOnClickListener(new C00705());
this.txtPayID.addTextChangedListener(new C00716());
this.txtBillID.addTextChangedListener(new C00727());
}
private void setBillIcon(int billType) {
switch (billType) {
case CursorAdapter.FLAG_AUTO_REQUERY /*1*/:
this.tvBillType.setBackgroundResource(R.drawable._bill_1_waterpng);
case CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER /*2*/:
this.tvBillType.setBackgroundResource(R.drawable._bill_2_electric);
case TransportMediator.FLAG_KEY_MEDIA_FAST_FORWARD /*3*/:
this.tvBillType.setBackgroundResource(R.drawable._bill_3_gas);
case TransportMediator.FLAG_KEY_MEDIA_PLAY /*4*/:
this.tvBillType.setBackgroundResource(R.drawable._bill_4_tel);
default:
this.tvBillType.setBackgroundDrawable(null);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
int contentsLen = scanContent.length();
for (int i = 0; i < 26 - contentsLen; i++) {
scanContent = "0" + scanContent;
}
if (scanContent != null) {
String txtBillID = scanContent.substring(0, 13);
String txtPayID = scanContent.substring(18);
this.txtBillID.setText(txtBillID);
this.txtPayID.setText(txtPayID);
this.btnPayBill.setActivated(true);
}
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
public void onBackPressed() {
if (this.doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "\u0628\u0631\u0627\u06cc \u062e\u0631\u0648\u062c \u062f\u0648\u0628\u0627\u0631\u0647 \u06a9\u0644\u06cc\u062f \u0628\u0627\u0632\u06af\u0634\u062a \u0631\u0627 \u0628\u0632\u0646\u06cc\u062f", Toast.LENGTH_LONG).show();
new Handler().postDelayed(new ActivityMain.C00738(), 2000);
}
In android > 23 you must check permission at runtime
Requesting Permissions at Run Time
In the Manifest you have declared that you will be requesting those permissions from the user. But, you must understand that you haven't actually obtained those permissions just by declaring them in the Manifest. You need to Request for those permissions during runtime.
Beginning with Android 6.0 (API level 23), users can revoke permissions from any app at any time, even if the app targets a lower API level. So even if the app used the camera yesterday, it can't assume it still has that permission today.
Source: Official Website
I haven't gone through your code completely. However, with regards to solving the error you have posted, the solution is pretty simple. All you need to do is to ask for android.permission.CALL_PHONE during runtime.
The best guide would probably be the official website. It's just a 10-minute read.

Global variable reset to 0

I have a global variable inext set to a random value correctly before a call to setWordsQuestion(). As soon as I enter setWordsQuestion() the value is 0. Do you know how I can debug this?
and reset to 0:
Here is the java file:
public class ExercisesWords_fragment extends Fragment {
static Context context;
String login;
String fileMenuCard = null;
InputStreamReader isr;
InputStream fIn;
BufferedReader input_card = null;
int level, lang;
int ihelp;
String fileLogin;
RadioGroup rg;
RadioButton rb1, rb2, rb3, rb4;
EditText edt;
TextView txt, question;
Button validation, next, help;
int MAXWORDS = 42;
String[] words_questions = new String[MAXWORDS];
String[] words_cb1 = new String[MAXWORDS];
String[] words_cb2 = new String[MAXWORDS];
String[] words_cb3 = new String[MAXWORDS];
String[] words_cb4 = new String[MAXWORDS];
String[] words_response = new String[MAXWORDS];
int[] words_level = new int[MAXWORDS];
int MAXTEMP = 5;
int[] tmp;
int inext_question, inext;
public ExercisesWords_fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.exercises_words_fragment, container, false);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
}
#Override
public void onPause() {
closeFileWords();
super.onPause();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
context = getActivity().getApplicationContext();
fileMenuCard = "words";
login = getArguments().getString("login");
lang = getArguments().getInt("lang");
level = getArguments().getInt("level");
fileLogin = login + "_words.txt";
initViewFind();
initExerciseWords();
nextWordsQuestion();
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
edt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_NUMPAD_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
validateResponse();
}
return false;
}
});
validation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
validateResponse();
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
nextWordsQuestion();
}
});
help.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ihelp = 1;
hideKeyboard();
helpWords();
ihelp = 0;
}
});
}
private void drawBTN() {
if(lang == 0) {
validation.setText(R.string.pro_validation);
validation.setVisibility(View.VISIBLE);
next.setText(R.string.next);
next.setVisibility(View.VISIBLE);
help.setText(R.string.help);
help.setVisibility(View.VISIBLE);
}
else {
validation.setText(R.string.pro_validation_fr);
validation.setVisibility(View.VISIBLE);
next.setText(R.string.next_fr);
next.setVisibility(View.VISIBLE);
help.setText(R.string.help_fr);
help.setVisibility(View.VISIBLE);
}
}
private void nextWordsQuestion() {
int inext;
Random r;
r = new Random();
inext = r.nextInt(MAXWORDS);
if (inext_question < MAXTEMP) {
tmp[inext_question] = inext;
inext_question++;
setWordsQuestion();
return;
}
for (int i = 0; i < MAXTEMP; i++) {
if (inext == tmp[i]) {
r = new Random();
inext = r.nextInt(MAXWORDS);
i--;
}
}
System.arraycopy(tmp, 1, tmp, 0, MAXTEMP - 1);
tmp[MAXTEMP - 1] = inext;
setWordsQuestion();
}
private void setWordsQuestion(){
question.setText(words_questions[inext]);
question.setVisibility(View.VISIBLE);
edt.setText("");
rb1.setText(words_cb1[inext]);
rb2.setText(words_cb2[inext]);
rb3.setText(words_cb3[inext]);
rb4.setText(words_cb4[inext]);
rb1.setVisibility(View.INVISIBLE);
rb2.setVisibility(View.INVISIBLE);
rb3.setVisibility(View.INVISIBLE);
rb4.setVisibility(View.INVISIBLE);
rg.clearCheck();
hideKeyboard();
}
private void validateResponse(){
String response;
if(ihelp == 1){
int sel = rg.getCheckedRadioButtonId();
if(sel < 0) return;
RadioButton rb = (RadioButton) getActivity().findViewById(sel);
response = rb.getText().toString();
}
else {
response = edt.getText().toString();
}
TextView resp = (TextView) getActivity().findViewById(R.id.resp_words);
if(response.equals(words_response[inext])) {
next.setTextColor(Color.GREEN);
next.setVisibility(View.VISIBLE);
resp.setText(R.string.resp_card);
resp.setTextColor(Color.GREEN);
resp.setVisibility(View.VISIBLE);
}
else {
resp.setText(R.string.resp_card_no);
resp.setTextColor(Color.RED);
resp.setVisibility(View.VISIBLE);
}
}
private void helpWords(){
hideKeyboard();
rb1.setText(words_cb1[inext]);
rb1.setVisibility(View.VISIBLE);
rb2.setText(words_cb2[inext]);
rb2.setVisibility(View.VISIBLE);
rb3.setText(words_cb3[inext]);
rb3.setVisibility(View.VISIBLE);
rb4.setText(words_cb4[inext]);
rb4.setVisibility(View.VISIBLE);
}
private void hideKeyboard(){
EditText e = (EditText) getActivity().findViewById(R.id.words_answer);
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(e.getWindowToken(), 0);
}
private void openWords(){
String l = null;
try {
if (lang == 0)
fIn = context.getResources().getAssets()
.open(fileMenuCard+".txt", Context.MODE_PRIVATE);
else
fIn = context.getResources().getAssets()
.open(fileMenuCard+"_fr.txt", Context.MODE_PRIVATE);
isr = new InputStreamReader(fIn);
input_card = new BufferedReader(isr);
} catch (Exception e) {
e.getMessage();
}
for(int i=0;i<MAXWORDS;i++){
try {
l = input_card.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (l != null) {
StringTokenizer tokens = new StringTokenizer(l, ";");
words_questions[i] = tokens.nextToken();
words_level[i] = Integer.valueOf(tokens.nextToken());
words_cb1[i] = tokens.nextToken();
words_cb2[i] = tokens.nextToken();
words_cb3[i] = tokens.nextToken();
words_cb4[i] = tokens.nextToken();
words_response[i] = tokens.nextToken();
}
}
}
private void closeFileWords(){
try {
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
input_card.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void initExerciseWords(){
tmp = new int[MAXTEMP];
for(int i=0;i<MAXTEMP;i++)
tmp[i] = -1;
inext_question = 0;
openWords();
}
private void initViewFind(){
edt = (EditText) getActivity().findViewById(R.id.words_answer);
txt = (TextView) getActivity().findViewById(R.id.title_words);
validation = (Button) getActivity().findViewById(R.id.validation_words);
next = (Button) getActivity().findViewById(R.id.next_words);
help = (Button) getActivity().findViewById(R.id.help_words);
question = (TextView) getActivity().findViewById(R.id.words_question);
rg = (RadioGroup) getActivity().findViewById(R.id.rg_words);
rb1 = (RadioButton) getActivity().findViewById(R.id.radio1_words);
rb2 = (RadioButton) getActivity().findViewById(R.id.radio2_words);
rb3 = (RadioButton) getActivity().findViewById(R.id.radio3_words);
rb4 = (RadioButton) getActivity().findViewById(R.id.radio4_words);
if(lang == 0)
txt.setText(R.string.words_fr);
else
txt.setText(R.string.words_title_fr);
}
}
You are setting a local variable that hides the instance member :
private void nextWordsQuestion() {
int inext; // remove this line
...
inext = r.nextInt(MAXWORDS);
...
setWordsQuestion();
...
}
Therefore setWordsQuestion, which uses the instance member, doesn't see the value you set in nextWordsQuestion.
When you assign a random value to inext, you are assigning it to a local variable, not the global one.
To fix, simply remove the local variable.
private void nextWordsQuestion() {
//int inext;
Random r;
r = new Random();
inext = r.nextInt(MAXWORDS);
if (inext_question < MAXTEMP) {
tmp[inext_question] = inext;
inext_question++;
setWordsQuestion();
return;
}

validation according to data types

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.

Categories