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);
}
This code right here is a random math questionnaire and I want to know how to be able to transfer the amount of questions answered right and wrong to a separate stats page after each time they answer a question. I want the stats page to save the numbers so that if the user exits the program and then goes back on later they can still look at their total right answered questions and wrong answered questions. Ive been looking all over the internet and cant find a good way to learn this. If anyone has some advice I would really appreciate it. btw this is pretty much all the code in the main page; I didn't add the stats page code (because it has pretty much nothing.)
Pushme1-4 are the buttons and the AdditionEasyRight and AdditionEasyWrong are the number counts that are displayed on the main page.
public class AdditionEasy extends AppCompatActivity {
int countCNumAddE = 0;
int countWNumAddE = 0;
boolean hasAnswered;
public static final String MY_PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addition);
final TextView count = (TextView) findViewById(R.id.Count);
final TextView count2 = (TextView) findViewById(R.id.Count2);
Button homeButton = (Button) findViewById(R.id.homeButton);
super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
final TextView textOne = (TextView) findViewById(R.id.textView);
final TextView textTwo = (TextView) findViewById(R.id.textView2);
final Button pushMe1 = (Button) findViewById(R.id.button1);
final Button pushMe2 = (Button) findViewById(R.id.button2);
final Button pushMe3 = (Button) findViewById(R.id.button3);
final Button pushMe4 = (Button) findViewById(R.id.button4);
final Button begin = (Button) findViewById(R.id.begin);
begin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
hasAnswered = false;
pushMe1.setEnabled(true);
pushMe2.setEnabled(true);
pushMe3.setEnabled(true);
pushMe4.setEnabled(true);
begin.setVisibility(View.INVISIBLE);
pushMe1.setVisibility(View.VISIBLE);
pushMe2.setVisibility(View.VISIBLE);
pushMe3.setVisibility(View.VISIBLE);
pushMe4.setVisibility(View.VISIBLE);
pushMe1.setTextColor(Color.BLACK);
pushMe2.setTextColor(Color.BLACK);
pushMe3.setTextColor(Color.BLACK);
pushMe4.setTextColor(Color.BLACK);
pushMe1.setTextSize(20);
pushMe2.setTextSize(20);
pushMe3.setTextSize(20);
pushMe4.setTextSize(20);
textTwo.setText("");
String randGenChoice1 = "";
String randGenChoice2 = "";
String randGenChoice3 = "";
String randGenChoice4 = "";
String randText2 = "";
String randText3 = "";
Random RandomNum = new Random();
int randChoice1 = RandomNum.nextInt(40) + 1;
int randChoice2 = RandomNum.nextInt(40) + 1;
int randChoice3 = RandomNum.nextInt(40) + 1;
int randChoice4 = RandomNum.nextInt(40) + 1;
int rando2 = RandomNum.nextInt(20) + 1;
int rando3 = RandomNum.nextInt(20) + 1;
int pick = RandomNum.nextInt(4);
randGenChoice1 = Integer.toString(randChoice1);
randGenChoice2 = Integer.toString(randChoice2);
randGenChoice3 = Integer.toString(randChoice3);
randGenChoice4 = Integer.toString(randChoice4);
randText2 = Integer.toString(rando2);
randText3 = Integer.toString(rando3);
int value1;
int value2;
value1 = Integer.parseInt(randText2);
value2 = Integer.parseInt(randText3);
final int value = value1 + value2;
String line = randText2 + " + " + randText3;
textOne.setText(line);
final String answer;
answer = Integer.toString(value);
pushMe1.setText(randGenChoice1);
pushMe2.setText(randGenChoice2);
pushMe3.setText(randGenChoice3);
pushMe4.setText(randGenChoice4);
Button[] choice = {pushMe1, pushMe2, pushMe3, pushMe4};
Button display = choice[pick];
display.setText(answer);
pushMe1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonAnswer = Integer.parseInt(pushMe1.getText().toString());
if (buttonAnswer == value) {
begin.setVisibility(View.VISIBLE);
textTwo.setText("Correct!");
textTwo.setTextColor(Color.BLACK);
pushMe1.setTextColor(Color.GREEN);
pushMe1.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyRight = Integer.toString(++countCNumAddE);
count.setText(AdditionEasyRight);
hasAnswered = true;
}
begin.setText("New Question");
begin.setTextSize(20);
pushMe2.setVisibility(View.INVISIBLE);
pushMe3.setVisibility(View.INVISIBLE);
pushMe4.setVisibility(View.INVISIBLE);
pushMe1.setEnabled(false);
pushMe2.setEnabled(false);
pushMe3.setEnabled(false);
pushMe4.setEnabled(false);
}else{
textTwo.setText("Wrong!");
textTwo.setTextColor(Color.BLACK);
pushMe1.setTextColor(Color.RED);
pushMe1.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyWrong = Integer.toString(++countWNumAddE);
count2.setText(AdditionEasyWrong);
hasAnswered = true;
}
pushMe1.setEnabled(false);
}
}
});
pushMe2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonAnswer = Integer.parseInt(pushMe2.getText().toString());
if (buttonAnswer == value) {
begin.setVisibility(View.VISIBLE);
textTwo.setText("Correct!");
textTwo.setTextColor(Color.BLACK);
pushMe2.setTextColor(Color.GREEN);
pushMe2.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyRight = Integer.toString(++countCNumAddE);
count.setText(AdditionEasyRight);
hasAnswered = true;
}
begin.setText("New Question");
begin.setTextSize(20);
pushMe1.setVisibility(View.INVISIBLE);
pushMe3.setVisibility(View.INVISIBLE);
pushMe4.setVisibility(View.INVISIBLE);
pushMe1.setEnabled(false);
pushMe2.setEnabled(false);
pushMe3.setEnabled(false);
pushMe4.setEnabled(false);
}else{
textTwo.setText("Wrong!");
textTwo.setTextColor(Color.BLACK);
pushMe2.setTextColor(Color.RED);
pushMe2.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyWrong = Integer.toString(++countWNumAddE);
count2.setText(AdditionEasyWrong);
hasAnswered = true;
}
pushMe2.setEnabled(false);
}
}
});
pushMe3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonAnswer = Integer.parseInt(pushMe3.getText().toString());
if (buttonAnswer == value) {
begin.setVisibility(View.VISIBLE);
textTwo.setText("Correct!");
textTwo.setTextColor(Color.BLACK);
pushMe3.setTextColor(Color.GREEN);
pushMe3.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyRight = Integer.toString(++countCNumAddE);
count.setText(AdditionEasyRight);
hasAnswered = true;
}
begin.setText("New Question");
begin.setTextSize(20);
pushMe1.setVisibility(View.INVISIBLE);
pushMe2.setVisibility(View.INVISIBLE);
pushMe4.setVisibility(View.INVISIBLE);
pushMe1.setEnabled(false);
pushMe2.setEnabled(false);
pushMe3.setEnabled(false);
pushMe4.setEnabled(false);
}else{
textTwo.setText("Wrong!");
textTwo.setTextColor(Color.BLACK);
pushMe3.setTextColor(Color.RED);
pushMe3.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyWrong = Integer.toString(++countWNumAddE);
count2.setText(AdditionEasyWrong);
hasAnswered = true;
}
pushMe3.setEnabled(false);
}
}
});
pushMe4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonAnswer = Integer.parseInt(pushMe4.getText().toString());
if (buttonAnswer == value) {
begin.setVisibility(View.VISIBLE);
textTwo.setText("Correct!");
textTwo.setTextColor(Color.BLACK);
pushMe4.setTextColor(Color.GREEN);
pushMe4.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyRight = Integer.toString(++countCNumAddE);
count.setText(AdditionEasyRight);
hasAnswered = true;
}
begin.setText("New Question");
begin.setTextSize(20);
pushMe1.setVisibility(View.INVISIBLE);
pushMe2.setVisibility(View.INVISIBLE);
pushMe3.setVisibility(View.INVISIBLE);
pushMe1.setEnabled(false);
pushMe2.setEnabled(false);
pushMe3.setEnabled(false);
pushMe4.setEnabled(false);
}else{
textTwo.setText("Wrong!");
textTwo.setTextColor(Color.BLACK);
pushMe4.setTextColor(Color.RED);
pushMe4.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyWrong = Integer.toString(++countWNumAddE);
count2.setText(AdditionEasyWrong);
hasAnswered = true;
}
pushMe4.setEnabled(false);
}
}
});
}
});
homeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent homepage = new Intent(AdditionEasy.this , Menu.class);
startActivity(homepage);
}
});
}
}
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.
I'm working on a To-Do List application. I want the user to add a task in the app (which gets stored in recyclerview and then displayed) and when they exit the app and remove it from Recently used and then reopen, i want the tasks that he added earlier to be present there. I've used Sharedpreferences for this task but I can't get to save or retrieve values.
This is my mainactivity.java:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private itemAdapter itemAdapter;
private RecyclerView.LayoutManager layoutManager;
Button add_item_btn;
public static final String myPreferences = "Prefs";
public static final String TaskKey = "taskKey";
SharedPreferences sharedPreferences;
ArrayList<data> myList = new ArrayList<>();
EditText editText;
String task;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
itemAdapter = new itemAdapter(myList);
final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(itemAdapter);
editText = (EditText) findViewById(R.id.edit_text);
SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences(getString(R.string.PREF_FILE), MODE_PRIVATE);
try {
myList = (ArrayList) ObjectSerializer.deserialize(sharedPreferences.getString("UserList", ObjectSerializer.serialize(new ArrayList())));
itemAdapter.notifyData(myList);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// task=sharedPreferences.getString(getString(R.string.TEXT_INFO),"");
//
// data mLog=new data();
// mLog.setTask(task);
// myList.add(mLog);
editText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
data dataList = new data();
task = editText.getText().toString();
// editor.putString(getString(R.string.TEXT_INFO), editText.getText().toString());
// editor.commit();
if (task.matches("")) {
Toast.makeText(v.getContext(), "Please enter a task", Toast.LENGTH_SHORT).show();
}
data dataForRecycler = new data();
dataForRecycler.setTask(task);
myList.add(dataForRecycler);
SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences(getString(R.string.PREF_FILE), MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
try {
editor.putString(getString(R.string.TEXT_INFO), ObjectSerializer.serialize(myList));
} catch (IOException e) {
e.printStackTrace();
}
editor.commit();
itemAdapter.notifyData(myList);
editText.setText(null);
editText.setVisibility(View.GONE);
// InputMethodManager inputManager = (InputMethodManager)
// getSystemService(Context.INPUT_METHOD_SERVICE);
// inputManager.hideSoftInputFromWindow((null == getCurrentFocus()) ? null : getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
return true;
default:
break;
}
}
return false;
}
});
add_item_btn = (Button) findViewById(R.id.add_item_button);
add_item_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editText.setVisibility(View.VISIBLE);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
});
}
}
this is my dataModel:
public class data implements Serializable {
private String task;
private boolean isChecked;
RecyclerView info;
//Default Constructor
public data()
{}
//overloaded constructor
public data (String task, boolean isChecked)
{
this.task=task;
this.isChecked=isChecked;
}
//getter to return value of String variable task
public String getTask()
{return task;}
//getter to return value of boolean isChecked
public boolean isChecked()
{return isChecked;}
//setter for string variable task
public void setTask(String task)
{
this.task=task;
}
//setter for boolean isChecked
public void setChecked(boolean isChecked)
{
this.isChecked=isChecked;
}
}
my adapter:
public class itemAdapter extends RecyclerView.Adapter<itemAdapter.RecyclerItemViewHolder> {
private ArrayList<data> myList;
int mLastPosition = 0;
public itemAdapter(ArrayList<data> myList) {
this.myList = myList;
}
public RecyclerItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
RecyclerItemViewHolder holder = new RecyclerItemViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerItemViewHolder holder, final int position) {
Log.d("onBindViewHoler ", myList.size() + "");
holder.etTaskTextView.setText(myList.get(position).getTask());
mLastPosition =position;
}
#Override
public int getItemCount() {
return(null != myList?myList.size():0);
}
public void notifyData(ArrayList<data> myList) {
Log.d("notifyData ", myList.size() + "");
this.myList = myList;
notifyDataSetChanged();
}
public class RecyclerItemViewHolder extends RecyclerView.ViewHolder {
private final TextView etTaskTextView;
private LinearLayout mainLayout;
public RecyclerItemViewHolder(final View parent) {
super(parent);
etTaskTextView = (TextView) parent.findViewById(R.id.task_text);
mainLayout = (LinearLayout) parent.findViewById(R.id.list_linear_layout);
mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(), "Position:" + Integer.toString(getPosition()), Toast.LENGTH_SHORT).show();
}
});
}
}
}
and my ObjectSerializer class:
public class ObjectSerializer {
public static String serialize(Serializable obj) throws IOException {
if (obj == null) return "";
ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
objStream.writeObject(obj);
objStream.close();
return encodeBytes(serialObj.toByteArray());
}
public static Object deserialize(String str) throws IOException, ClassNotFoundException {
if (str == null || str.length() == 0) return null;
ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
ObjectInputStream objStream = new ObjectInputStream(serialObj);
return objStream.readObject();
}
public static String encodeBytes(byte[] bytes) {
StringBuffer strBuf = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
}
return strBuf.toString();
}
public static byte[] decodeBytes(String str) {
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < str.length(); i+=2) {
char c = str.charAt(i);
bytes[i/2] = (byte) ((c - 'a') << 4);
c = str.charAt(i+1);
bytes[i/2] += (c - 'a');
}
return bytes;
}
}
You can use content provider/sqlite to easily add/read/update/delete. It is faster and suitable for list of data in persistent
I have a list of musics, so I want user to set time to play music in particular time.
here I have a list view that has a text view (is invisible at first) and a button.
when I click on the button an alert dialog open to show device time and a time picker.
I subtract these times and sent the result to the Count Down Timer, In on Tick
i set my text view visible to show time to user until to finish the time.
all things are correct
user can play music after the time which sets.
but when I scroll the list view ,my text view (show the timer )disappeared.
here is my code:
public class Main extends Activity {
public static int hour_device, minute_device;
public static int hour_user, minute_user;
Splash splash;
ListView listView;
Adaptor adaptor;
private MediaPlayer mediaPlayer;
static View lastview = null;
static MyIndexStore indexStore;
List<String> lines1 = new ArrayList<String>();
List<String> lines2 = new ArrayList<String>();
static List<String> array_audio = new ArrayList<String>();
InputStream in;
BufferedReader reader;
String line = "1";
String[] tracks;
String[] names;
String[] infos;
HashMap<Integer,String> textMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
indexStore = new MyIndexStore(getApplicationContext());
setContentView(R.layout.main_activity);
splash = new Splash(this);
splash.set_identity("1");
initiate();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.a1);
//lastview = null;
listView = (ListView) findViewById(R.id.list);
ReadText1();
names = lines1.toArray(new String[0]);// = {"track one","the seconnd track","a nice track","name name name","the seconnd track","a nice track","name name name"};
ReadText2();
infos = lines2.toArray(new String[0]);
tracks = array_audio.toArray(new String[0]);
adaptor = new Adaptor(getApplicationContext(), tracks, names, infos,textMap);
listView.setAdapter(adaptor);
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
if (lastview != null) {
ImageView play = (ImageView) lastview.findViewById(R.id.play_stop);
play.setImageResource(R.drawable.n_btn_play_unselected);
}
}
});
}
private static void initiate() {
Field[] fields = R.raw.class.getFields();
array_audio.clear();
for (int count = 0; count < fields.length; count++) {
array_audio.add("a" + (count + 1));
}
}
private void play(int index) {
mediaPlayer.release();
index++;
String s = "a" + index;
Resources resources = getResources();
final int resourceId = resources.getIdentifier(s, "raw", getPackageName());
try {
mediaPlayer = MediaPlayer.create(this, resourceId);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
mediaPlayer.release();
listView.invalidateViews();
super.onPause();
}
private void ReadText1() {
lines1.clear();
line = "1";
try {
in = this.getAssets().open("names.txt");
reader = new BufferedReader(new InputStreamReader(in));
while (line != null) {
line = reader.readLine();
if (line != null)
lines1.add(line);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void ReadText2() {
lines2.clear();
line = "1";
try {
in = this.getAssets().open("infos.txt");
reader = new BufferedReader(new InputStreamReader(in));
while (line != null) {
line = reader.readLine();
if (line != null)
lines2.add(line);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public class Adaptor extends ArrayAdapter<String> {
private final Context context;
private final String[] tracks;
private final String[] names;
private final String[] infos;
private final HashMap<Integer,String> textMap;
Typeface type_face;
public Adaptor(Context context, String[] tracks, String[] names, String[] infos,HashMap<Integer,String> textMap) {
super(context, R.layout.track, tracks);
this.context = context;
this.tracks = tracks;
this.names = names;
this.infos = infos;
type_face = Typeface.createFromAsset(context.getAssets(), "BTitrBd.ttf");
this.textMap = textMap;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.track, parent, false);
TextView name = (TextView) rowView.findViewById(R.id.track_name);
final TextView time = (TextView) rowView.findViewById(R.id.time);
//populate the textview from map
if(textMap!=null && textMap.get(new Integer(position))!=null){
time.setText(textMap.get(new Integer(position)));
}
name.setText(names[position]);
name.setTypeface(type_face);
name.setTypeface(type_face);
final ImageView ringtone = (ImageView) rowView.findViewById(R.id.ringtone);
if (position == indexStore.getindex())
ringtone.setImageResource(R.drawable.n_btn_ringtone_seted);
final ImageView play = (ImageView) rowView.findViewById(R.id.play_stop);
ringtone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater factory = LayoutInflater.from(Main.this);
final View deleteDialogView = factory.inflate(
R.layout.mylayout, null);
final AlertDialog deleteDialog = new AlertDialog.Builder(Main.this).create();
deleteDialog.setView(deleteDialogView);
TextView device_time = (TextView) deleteDialogView.findViewById(R.id.current_time);
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
hour_device = hour;
minute_device = minute;
device_time.setText(hour_device + ":" + minute_device);
deleteDialogView.findViewById(R.id.set).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TimePicker timePicker = (TimePicker) deleteDialogView.findViewById(R.id.timepicker);
timePicker.setIs24HourView(true);
hour_user = timePicker.getCurrentHour();
minute_user = timePicker.getCurrentMinute();
String time1 = hour_device + ":" + minute_device;
String time2 = hour_user + ":" + minute_user;
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date1 = null;
try {
date1 = format.parse(time1);
} catch (ParseException e) {
e.printStackTrace();
}
Date date2 = null;
try {
date2 = format.parse(time2);
} catch (ParseException e) {
e.printStackTrace();
}
long result = date2.getTime() - date1.getTime();
new CountDownTimer(result, 1000) {
public void onTick(long millisUntilFinished) {
time.setText(("seconds remaining: " + millisUntilFinished / 1000));
//create HashMap<Integer,String> textMap at the constructer of the adapter
//now fill this info into it
textMap.put(new Integer(position),"seconds remaining: " + millisUntilFinished / 1000);
//notify about the data change
notifyDataSetChanged();
}
public void onFinish() {
time.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), "finish", Toast.LENGTH_LONG).show();
if (rowView != lastview || mediaPlayer == null) {
play(position);
if (lastview != null)
lastview = rowView;
} else {
play.setImageResource(R.drawable.n_btn_play_unselected);
mediaPlayer.release();
lastview = null;
}
}
}.start();
deleteDialog.dismiss();
}
});
deleteDialog.show();
}
});
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (rowView != lastview || mediaPlayer == null) {
play(position);
if (lastview != null)
lastview = rowView;
} else {
play.setImageResource(R.drawable.n_btn_play_unselected);
mediaPlayer.release();
lastview = null;
}
}
});
return rowView;
}
}
}
I need help, any suggestion?
I'm new with android:-)
Update your countdown timer like this
new CountDownTimer(result, 1000) {
public void onTick(long millisUntilFinished) {
time.setText(("seconds remaining: " + millisUntilFinished / 1000));
//create HashMap<Integer,String> textMap at the constructer of the adapter
//whenever you want to clear a record clear the hash map
//now fill this info into it
textMap.put(new Integer(position),"seconds remaining: " + millisUntilFinished / 1000);
//notify about the data change
notifyDataSetChanged();
}
public void onFinish() {
time.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), "finish", Toast.LENGTH_LONG).show();
if (rowView != lastview || mediaPlayer == null) {
play(position);
if (lastview != null)
lastview = rowView;
} else {
play.setImageResource(R.drawable.n_btn_play_unselected);
mediaPlayer.release();
lastview = null;
}
}
}.start();
At the place where you initiate the textView text;
final TextView time = (TextView) rowView.findViewById(R.id.time);
//populate the textview from map
if(textMap!=null && textMap.get(new Integer(position))!=null){
time.setText(textMap.get(new Integer(position)));
}
This continuous update might cause lag issues.
You must use Reclyclerview for this, textview is primitive for your requirement.
https://developer.android.com/training/material/lists-cards.html