Related
In my project I download all the data of my project from a json.I download title and description as text and also download my icon and the file of games.
I can download them and also save in database and show in listview easily.
My QUESTION is about how to save that my file for game is beinng download or not?
I have two buttons. first is download button when user click it , it starts to download file.when download finish, my download button disappear and my play button appears.
I want to save this, when user for second time run the application,i save for example my second position downloaded before. and I have just my play button.
my database:
public class DatabaseHandler extends SQLiteOpenHelper {
public SQLiteDatabase sqLiteDatabase;
int tedad;
public DatabaseHandler(Context context) {
super(context, "EmployeeDatabase.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String tableEmp = "create table emp(PersianTitle text,Description text,icon text,downloadlink text,dl integer)";
db.execSQL(tableEmp);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insertData(ArrayList<String> id, ArrayList<String> name, ArrayList<String> salary, ArrayList<String> roms,String
dl) {
int size = id.size();
tedad = size;
sqLiteDatabase = this.getWritableDatabase();
try {
for (int i = 0; i < size; i++) {
ContentValues values = new ContentValues();
values.put("PersianTitle", id.get(i));
values.put("Description", name.get(i));
values.put("icon", salary.get(i));
values.put("downloadlink", roms.get(i));
values.put("dl", "0");
sqLiteDatabase.insert("emp", null, values);
}
} catch (Exception e) {
Log.e("Problem", e + " ");
}
}
public ArrayList<String> Game_Info (int row, int field) {
String fetchdata = "select * from emp";
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
ArrayList<String> stringArrayList = new ArrayList<String>();
Cursor cu = sqLiteDatabase.rawQuery(fetchdata, null);
for (int i = 0; i < row + 1; i++) {
cu.moveToPosition(i);
String s = cu.getString(field);
stringArrayList.add(s);
}
return stringArrayList;
}
}
and this is my main code:
public class MainActivity2 extends Activity {
Boolean done_game = false;
ProgressDialog progressDialog;
private boolean _init = false;
ListView listView;
DatabaseHandler database;
BaseAdapter adapter;
public String path_image;
JSONObject jsonObject;
Game_Counter_Store Game_Counter_Store;
int game_counter_store;
ArrayList<String> name_array = new ArrayList<String>();
ArrayList<String> des_array = new ArrayList<String>();
ArrayList<String> icon_array = new ArrayList<String>();
ArrayList<String> roms_array = new ArrayList<String>();
ArrayList<String> fav_array = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main2);
init();
System.gc();
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "MyDirName");//make a direction
path_image = mediaStorageDir.getAbsolutePath(); // here is tha path
listView = (ListView) findViewById(R.id.listView);
database = new DatabaseHandler(MainActivity2.this);
database.getWritableDatabase();
Game_Counter_Store = new Game_Counter_Store("Games_Number", this); // number of game in first run is 0
game_counter_store = Game_Counter_Store.get_count();
if (game_counter_store == 0) {
Log.i("mhs", "game_counter_store is 0");
DownloadGames();
} else {
Log.i("mhs", "there are some games");
for (int i = 0; i < game_counter_store; i++) {
name_array = database.Game_Info(i, 0);
des_array = database.Game_Info(i, 1);
icon_array = database.Game_Info(i, 2);
roms_array = database.Game_Info(i, 3);
fav_array = database.Game_Info(i, 4);
}
adapter = new MyBaseAdapter(MainActivity2.this, name_array, des_array, icon_array, roms_array,fav_array);
listView.setAdapter(adapter);
}
}
public void DownloadGames() {
//here we download name, des, icon
MakeDocCallBack makeDocCallBack = new MakeDocCallBack() {
#Override
public void onResult(ArrayList<String> res) {
if (res.size() > 0) {
try {
Game_Counter_Store counter_store = new Game_Counter_Store("Games_Number", MainActivity2.this); // get numbrr of games
counter_store.set_count(res.size()); // store the games number
for (int i = 0; i < res.size(); i++) {
jsonObject = new JSONObject(res.get(i)); //get all the jsons
//get all the data to store in database
name_array.add(jsonObject.getString("PersianTitle"));
des_array.add(jsonObject.getString("Description"));
icon_array.add(jsonObject.getString("icon"));
roms_array.add(jsonObject.getString("downloadlink"));
GetFile fd = new GetFile(MainActivity2.this, path_image, getFileName(jsonObject.getString("icon")), jsonObject.getString("icon").toString(), null); // download the image
GetFileCallBack Image_callback = new GetFileCallBack() {
#Override
public void onStart() {
// Toast.makeText(getApplicationContext(),"start",Toast.LENGTH_LONG).show();
}
#Override
public void onProgress(long l, long l1) {
// Toast.makeText(getApplicationContext(),"onProgress",Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess() {
// Toast.makeText(getApplicationContext(),"YES",Toast.LENGTH_LONG).show();
}
#Override
public void onFailure() {
// Toast.makeText(getApplicationContext(),"NO",Toast.LENGTH_LONG).show();
}
};
if (!fd.DoesFileExist()) {
fd.Start(Image_callback); // get the data
}
//set data in adapter to show in listview
adapter = new MyBaseAdapter(MainActivity2.this, name_array, des_array, icon_array, roms_array,fav_array);
listView.setAdapter(adapter);
}
//store dada in database (name , des , icon , bin file(roms) , state)
database.insertData(name_array, des_array, icon_array, roms_array,"0");
} catch (Exception ex) {
}
}
}
};
DocMaker doc = new DocMaker();
doc.set(this, makeDocCallBack);
}
public static String getFileName(String url) {
String temp = url.substring(url.lastIndexOf('/') + 1, url.length());
if (temp.contains("?"))
temp = temp.substring(0, temp.indexOf("?"));
return temp;
}
public class MyBaseAdapter extends BaseAdapter {
private Activity activity;
private ArrayList title, desc, icon, roms,fav;
private LayoutInflater inflater = null;
public MyBaseAdapter(Activity a, ArrayList b, ArrayList c, ArrayList d, ArrayList e, ArrayList f) {
activity = a;
this.title = b;
this.desc = c;
this.icon = d;
this.roms = e;
this.fav=f;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return title.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.list_item, null);
TextView title2 = (TextView) vi.findViewById(R.id.game_name); // title
String song = title.get(position).toString();
title2.setText(song);
TextView title22 = (TextView) vi.findViewById(R.id.game_des); // desc
String song2 = desc.get(position).toString();
title22.setText(song2);
File imageFile = new File("/storage/emulated/0/MyDirName/" + getFileName(icon_array.get(position)));
ImageView imageView = (ImageView) vi.findViewById(R.id.icon); // icon
imageView.setImageBitmap(BitmapFactory.decodeFile(imageFile.getAbsolutePath()));
TextView title222 = (TextView) vi.findViewById(R.id.game_roms); // desc
String song22 = roms.get(position).toString();
title222.setText(song22);
final Button dl_btn = (Button) vi.findViewById(R.id.dl_btn); // desc
final Button run_btn = (Button) vi.findViewById(R.id.play_btn); // desc
run_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Preferences.DEFAULT_GAME_FILENAME = getFileName(roms_array.get(position));
Intent myIntent = new Intent(MainActivity2.this, FileChooser.class);
myIntent.putExtra(FileChooser.EXTRA_START_DIR, Preferences.getRomDir(MainActivity2.this));
Log.i("mhsnnn", Preferences.getTempDir(MainActivity2.this));
final int result = Preferences.MENU_ROM_SELECT;
startActivityForResult(myIntent, result);
}
});
dl_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MakeDocCallBack makeDocCallBack = new MakeDocCallBack() {
#Override
public void onResult(ArrayList<String> res) {
if (res.size() > 0) {
try {
jsonObject = new JSONObject(res.get(position));
roms_array.add(jsonObject.getString("downloadlink"));
GetFile fd1 = new GetFile(MainActivity2.this, path_image, getFileName(jsonObject.getString("downloadlink")), jsonObject.getString("downloadlink").toString(),null); //download the bin file
GetFileCallBack roms_callback = new GetFileCallBack() {
#Override
public void onStart() {
}
#Override
public void onProgress(long l, long l1) {
Log.i("nsr", "onProgress");
}
#Override
public void onSuccess() {
Log.i("nsr", "onSuccess");
dl_btn.setVisibility(View.GONE);
run_btn.setVisibility(View.VISIBLE);
}
#Override
public void onFailure() {
Log.i("nsr", "onFailure");
}
};
if (!fd1.DoesFileExist()) {
fd1.Start(roms_callback);
}
} catch (Exception ex) {
}
}
}
};
DocMaker doc = new DocMaker();
doc.set(MainActivity2.this, makeDocCallBack);
}
});
return vi;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
private boolean verifyExternalStorage() {
// check for sd card first
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// rw access
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// r access
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// no access
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
// if we do not have storage warn user with dialog
if (!mExternalStorageAvailable || !mExternalStorageWriteable) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this)
.setTitle(getString(R.string.app_name) + " Error")
.setMessage("External Storage not mounted, are you in disk mode?")
.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
init();
}
})
.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
dialog.show();
return false;
}
return true;
}
private void init() {
if (verifyExternalStorage() && !_init) {
// always try and make application dirs
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
Log.i("nsrrr1", extStorageDirectory);
// /storage/emulated/0
File myNewFolder = new File(extStorageDirectory + Preferences.DEFAULT_DIR);
Log.i("nsrrr2", extStorageDirectory + Preferences.DEFAULT_DIR);///storage/emulated/0/sega
if (!myNewFolder.exists()) {
myNewFolder.mkdir();
}
myNewFolder = new File(extStorageDirectory + Preferences.DEFAULT_DIR_ROMS);
Log.i("nsrrr3", extStorageDirectory + Preferences.DEFAULT_DIR);///storage/emulated/0/sega
if (!myNewFolder.exists()) {
myNewFolder.mkdir();
}
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list(Preferences.DEFAULT_DIR_GAME);
Log.i("nsrrr3", files + "");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(Preferences.DEFAULT_DIR_GAME + "/" + filename);
File outFile = new File(myNewFolder, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
// do first run welcome screen
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean firstRun = preferences.getBoolean(Preferences.PREF_FIRST_RUN, true);
if (firstRun) {
// remove first run flag
Editor edit = preferences.edit();
edit.putBoolean(Preferences.PREF_FIRST_RUN, false);
// default input
edit.putBoolean(Preferences.PREF_USE_DEFAULT_INPUT, true);
edit.commit();
}
// generate APK path for the native side
ApplicationInfo appInfo = null;
PackageManager packMgmr = this.getPackageManager();
try {
appInfo = packMgmr.getApplicationInfo(getString(R.string.package_name), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Unable to locate assets, aborting...");
}
String _apkPath = appInfo.sourceDir;
// init the emulator
Emulator.init(_apkPath);
Log.i("rrrr", _apkPath);
// set the paths
Emulator.setPaths(extStorageDirectory + Preferences.DEFAULT_DIR,
extStorageDirectory + Preferences.DEFAULT_DIR_ROMS,
"",
"",
"");
// load up prefs now, never again unless they change
//PreferenceFacade.loadPrefs(this, getApplicationContext());
// load gui
// Log.d(LOG_TAG, "Done init()");
setContentView(R.layout.activity_main2);
// set title
super.setTitle(getString(R.string.app_name));
_init = true;
// Log.d(LOG_TAG, "Done onCreate()");
}
}
private void copyFile(InputStream in, OutputStream out) {
byte[] buffer = new byte[1024];
int read;
try {
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
how to make method in my database to do this?
If I understood you properly, you can add a table, user_games for example with User ID, Game ID and Status, then you can update status whenever an action is completed.
For example Status 1 for downloading, status 2 for Downloaded or Finished and you can even add statuses like download failed, to add a re-download button...
you can do something like
public void update_status(UserID,GameID) {
String update = "UPDATE games set status = 1 where id="+Game_ID+" and UserID = " + UserID);
db.rawQuery(update, null);
}
I trying to add admob native ads in recyclerview that uses resourcecursoradapter adapter .. the issues is
1 - it makes app crash
2 - it replaces recyclerview data item with admob ads
that is my code
public class EntriesCursorAdapter extends ResourceCursorAdapter {
private final Uri mUri;
private final boolean mShowFeedInfo;
private int mIdPos, mTitlePos, mMainImgPos, mDatePos, mIsReadPos, mFavoritePos, mFeedIdPos, mFeedNamePos;
public static final int Ads_view_type = 11;
public EntriesCursorAdapter(Context context, Uri uri, Cursor cursor, boolean showFeedInfo) {
super(context, PrefUtils.getInt(PrefUtils.NEWS_FORMAT_int,R.layout.item_entry_list2), cursor, 0);
mUri = uri;
mShowFeedInfo = showFeedInfo;
reinit(cursor);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final int position = cursor.getPosition();
final int viewtype = getItemViewType(position);
View itemView ;
if(viewtype == Ads_view_type) {
final LayoutInflater inflater = LayoutInflater.from(context);
itemView = inflater.inflate(R.layout.native_ads, parent, false);
if (itemView.getTag(R.id.holder) == null) {
AdsHolder ads_holder = new AdsHolder();
ads_holder.adView = (NativeExpressAdView) itemView.findViewById(R.id.adView2);
itemView.setTag(R.id.holder, ads_holder);
} return itemView;
}
else {
final LayoutInflater inflater = LayoutInflater.from(context);
itemView = inflater.inflate(PrefUtils.getInt(PrefUtils.NEWS_FORMAT_int, R.layout.item_entry_list2), parent, false);
if (itemView.getTag(R.id.holder) == null) {
ViewHolder holder = new ViewHolder();
holder.titleTextView = (TextView) itemView.findViewById(android.R.id.text1);
holder.dateTextView = (TextView) itemView.findViewById(android.R.id.text2);
holder.mainImgView = (ImageView) itemView.findViewById(R.id.main_icon);
holder.starImgView = (ImageView) itemView.findViewById(R.id.favorite_icon);
itemView.setTag(R.id.holder, holder);
}
return itemView;
}
}
#Override
public int getItemViewType(int position) {
if(position % 6 ==0)
{return Ads_view_type;}
else {
return super.getItemViewType(position);
}
}
#Override
public void bindView(View view, final Context context, Cursor cursor) {
final int position = cursor.getPosition();
final int viewtype = getItemViewType(position);
if (viewtype == Ads_view_type) {
try {
AdsHolder adsHolder = (AdsHolder) view.getTag(R.id.holder);
AdRequest request = new AdRequest.Builder()
.addTestDevice("ca-app-pub-5647351014779121/8591922893")
.build();
adsHolder.adView.loadAd(request);
} catch (Exception e) {
}
} else {
try {
ViewHolder holder = (ViewHolder) view.getTag(R.id.holder);
String titleText = cursor.getString(mTitlePos);
holder.titleTextView.setText(titleText);
final long feedId = cursor.getLong(mFeedIdPos);
String feedName = cursor.getString(mFeedNamePos);
String mainImgUrl = cursor.getString(mMainImgPos);
mainImgUrl = TextUtils.isEmpty(mainImgUrl) ? null : NetworkUtils.getDownloadedOrDistantImageUrl(cursor.getLong(mIdPos), mainImgUrl);
ColorGenerator generator = ColorGenerator.DEFAULT;
int color = generator.getColor(feedId); // The color is specific to the feedId (which shouldn't change)
String lettersForName = feedName != null ? (feedName.length() < 2 ? feedName.toUpperCase() : feedName.substring(0, 2).toUpperCase()) : "";
TextDrawable letterDrawable = TextDrawable.builder().buildRect(lettersForName, color);
if (mainImgUrl != null) {
Glide.with(context).load(mainImgUrl).centerCrop().placeholder(letterDrawable).error(letterDrawable).into(holder.mainImgView);
} else {
Glide.clear(holder.mainImgView);
holder.mainImgView.setImageDrawable(letterDrawable);
}
holder.isFavorite = cursor.getInt(mFavoritePos) == 1;
holder.starImgView.setVisibility(holder.isFavorite ? View.VISIBLE : View.INVISIBLE);
if (mShowFeedInfo && mFeedNamePos > -1) {
if (feedName != null) {
holder.dateTextView.setText(Html.fromHtml("<font color='#247ab0'>" + feedName + "</font>" + Constants.COMMA_SPACE + StringUtils.getDateTimeString(cursor.getLong(mDatePos))));
} else {
holder.dateTextView.setText(StringUtils.getDateTimeString(cursor.getLong(mDatePos)));
}
} else {
holder.dateTextView.setText(StringUtils.getDateTimeString(cursor.getLong(mDatePos)));
}
if (cursor.isNull(mIsReadPos)) {
holder.titleTextView.setEnabled(true);
holder.dateTextView.setEnabled(true);
holder.isRead = false;
} else {
holder.titleTextView.setEnabled(false);
holder.dateTextView.setEnabled(false);
holder.isRead = true;
}
} catch (Exception e) {}
}
}
public void toggleReadState(final long id, View view) {
final ViewHolder holder = (ViewHolder) view.getTag(R.id.holder);
if (holder != null) { // should not happen, but I had a crash with this on PlayStore...
holder.isRead = !holder.isRead;
if (holder.isRead) {
holder.titleTextView.setEnabled(false);
holder.dateTextView.setEnabled(false);
} else {
holder.titleTextView.setEnabled(true);
holder.dateTextView.setEnabled(true);
}
new Thread() {
#Override
public void run() {
ContentResolver cr = MainApplication.getContext().getContentResolver();
Uri entryUri = ContentUris.withAppendedId(mUri, id);
cr.update(entryUri, holder.isRead ? FeedData.getReadContentValues() : FeedData.getUnreadContentValues(), null, null);
}
}.start();
}
}
public void toggleFavoriteState(final long id, View view) {
final ViewHolder holder = (ViewHolder) view.getTag(R.id.holder);
if (holder != null) { // should not happen, but I had a crash with this on PlayStore...
holder.isFavorite = !holder.isFavorite;
if (holder.isFavorite) {
holder.starImgView.setVisibility(View.VISIBLE);
} else {
holder.starImgView.setVisibility(View.INVISIBLE);
}
new Thread() {
#Override
public void run() {
ContentValues values = new ContentValues();
values.put(EntryColumns.IS_FAVORITE, holder.isFavorite ? 1 : 0);
ContentResolver cr = MainApplication.getContext().getContentResolver();
Uri entryUri = ContentUris.withAppendedId(mUri, id);
cr.update(entryUri, values, null, null);
}
}.start();
}
}
#Override
public void changeCursor(Cursor cursor) {
reinit(cursor);
super.changeCursor(cursor);
}
#Override
public Cursor swapCursor(Cursor newCursor) {
reinit(newCursor);
return super.swapCursor(newCursor);
}
#Override
public void notifyDataSetChanged() {
reinit(null);
super.notifyDataSetChanged();
}
#Override
public void notifyDataSetInvalidated() {
reinit(null);
super.notifyDataSetInvalidated();
}
private void reinit(Cursor cursor) {
if (cursor != null && cursor.getCount() > 0) {
mIdPos = cursor.getColumnIndex(EntryColumns._ID);
mTitlePos = cursor.getColumnIndex(EntryColumns.TITLE);
mMainImgPos = cursor.getColumnIndex(EntryColumns.IMAGE_URL);
mDatePos = cursor.getColumnIndex(EntryColumns.DATE);
mIsReadPos = cursor.getColumnIndex(EntryColumns.IS_READ);
mFavoritePos = cursor.getColumnIndex(EntryColumns.IS_FAVORITE);
mFeedNamePos = cursor.getColumnIndex(FeedColumns.NAME);
mFeedIdPos = cursor.getColumnIndex(EntryColumns.FEED_ID);
}
}
private static class ViewHolder {
public TextView titleTextView;
public TextView dateTextView;
public ImageView mainImgView;
public ImageView starImgView;
public boolean isRead, isFavorite;
}
private static class AdsHolder {
NativeExpressAdView adView;
}
}
how can I solve this problem.
In the file explorer, when I hit a video file. something else appears in alertdialog. It theoretically should occur, the file pressed.
How can I solve?
Thank you.
I added 2 photos to better understand the error.
public class file_explorer_fragment extends ListFragment {
private List<String> item = null;
private List<String> path = null;
private String root;
private TextView myPath;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_file_explorer_fragment, container, false);
myPath = (TextView)v.findViewById(R.id.path);
root = Environment.getExternalStorageDirectory().getPath();
getDir(root);
return v;
}
private void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if(!dirPath.equals(root))
{
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for(int i=0; i < files.length; i++)
{
File file = files[i];
if(!file.isHidden() && file.canRead()) {
path.add(file.getPath());
if(file.isDirectory()){
item.add(file.getName() + "/");
}else{
if(isVideo(file)){
item.add(file.getName());
}
}
}
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(getActivity(), R.layout.row_file_explorer, item);
setListAdapter(fileList);
}
public static boolean isVideo(File file){
//merge perfect codul asta
/*{
if (file.getName().toLowerCase().endsWith(".avi")) return true;
if (file.getName().toLowerCase().endsWith(".m3u8")) return true;
if (file.getName().toLowerCase().endsWith(".3gp")) return true;
if (file.getName().toLowerCase().endsWith(".mpg")) return true;
if (file.getName().toLowerCase().endsWith(".mp4")) return true;
return false;
}*/
String extension = "";
String filename = file.getName().toLowerCase();
int i = filename.lastIndexOf('.');
if (i >= 0) {
extension = filename.substring(i);
}
/* String ext = null;
String s = file.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
ext = s.substring(i).toLowerCase();
}*/
switch (extension) {
case ".3gp":
case ".mpg":
case ".mpeg":
case ".mpe":
case ".mp4":
case ".avi":
case ".m3u8":
return true;
default:
return false;
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
File file = new File(path.get(position));
Context context = getActivity().getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, path.get(position), duration);
toast.show();
if (file.isDirectory())
{
if(file.canRead()){
getDir(path.get(position));
}else{
new android.app.AlertDialog.Builder(getActivity())
.setIcon(R.drawable.ic_folder_open_black_24dp)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK", null).show();
}
}else {
new android.app.AlertDialog.Builder(getActivity())
.setIcon(R.drawable.ic_folder_open_black_24dp)
.setTitle(file.getName())
.setPositiveButton("OK", null).show();
//Intent intent = new Intent(getActivity(), MainActivity.class);
//intent.putExtra("url", root+"/"+file.getName());
//startActivity(intent);
}
}
}
Photo from show 2 videos.
Photo 2 show alertdialog, and inside is wrong file.
Hello guys I'am totally new in android and I have an assignment that will output an option when a user long clicks the item that is in list view. Can you help me about this? thanks in advance. I get this code in the internet and try to tweak it but I don't know where to put the method onlongclick. please help me guys
public class MainActivity extends ListActivity{
private File mCurrentNode = null;
private File mLastNode = null;
private File mRootNode = null;
private ArrayList<File> mFiles = new ArrayList<File>();
private CustomAdapter mAdapter = null;
private String fname;
private Context context;
private ArrayList<File> objname;
File f;
String filename;
Button df;
private Bundle savedInstanceState;
ListView parent=null;
int position=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File Audio = new File(Environment.getExternalStorageDirectory() + "/Audio");
File Ebook = new File(Environment.getExternalStorageDirectory() + "/Ebook");
File Images = new File(Environment.getExternalStorageDirectory() + "/Images");
File Video = new File(Environment.getExternalStorageDirectory() + "/Video");
Audio.mkdirs();
Ebook.mkdirs();
Images.mkdirs();
Video.mkdirs();
if(!Audio.exists())
{
if(Audio.mkdir())
{
//directory is created;
}
}
if(!Ebook.exists())
{
if(Audio.mkdir())
{
//directory is created;
}
}
if(!Images.exists())
{
if(Audio.mkdir())
{
//directory is created;
}
}
if(!Video.exists())
{
if(Audio.mkdir())
{
//directory is created;
}
}
mAdapter = new CustomAdapter(this, R.layout.list_row, mFiles);
setListAdapter(mAdapter);
if (savedInstanceState != null) {
mRootNode = (File)savedInstanceState.getSerializable("root_node");
mLastNode = (File)savedInstanceState.getSerializable("last_node");
mCurrentNode = (File)savedInstanceState.getSerializable("current_node");
}
refreshFileList();
}
/* public void onLongClick(ListView parent, View v, int position, long id){
f = (File) parent.getItemAtPosition(position);
//Browser
if (position == 1) {
if (mCurrentNode.compareTo(mRootNode)!=0) {
mCurrentNode = f.getParentFile();
refreshFileList();
Toast.makeText(this, "This is postion 1 "+f.getName()+"!", Toast.LENGTH_SHORT).show();
// out();
}
} else if (f.isDirectory()) {
//f.delete();
mCurrentNode = f;
refreshFileList();
Toast.makeText(this, "This is postion 2 "+f.getName()+"!", Toast.LENGTH_SHORT).show();
//out();
} else {
Toast.makeText(this, "You selected: "+f.getName()+"!", Toast.LENGTH_SHORT).show();
//out();
}
//});
}*/
//end of bundle
private void refreshFileList() {
if (mRootNode == null) mRootNode = new File(Environment.getExternalStorageDirectory().toString());
if (mCurrentNode == null) mCurrentNode = mRootNode;
mLastNode = mCurrentNode;
File[] files = mCurrentNode.listFiles();
mFiles.clear();
mFiles.add(mRootNode);
mFiles.add(mLastNode);
if (files!=null) {
for (int i = 0; i< files.length; i++) mFiles.add(files[i]);
}
mAdapter.notifyDataSetChanged();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putSerializable("root_node", mRootNode);
outState.putSerializable("current_node", mCurrentNode);
outState.putSerializable("last_node", mLastNode);
super.onSaveInstanceState(outState);
}
/**
* Listview on click handler.
*/
#Override
public void onListItemClick(ListView parent, View v, int position, long id){
f = (File) parent.getItemAtPosition(position);
//Browser
ListView lst=null;
lst.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
// TODO Auto-generated method stub
if (position == 1) {
if (mCurrentNode.compareTo(mRootNode)!=0) {
mCurrentNode = f.getParentFile();
refreshFileList();
// Toast.makeText(this, "This is postion 1 "+f.getName()+"!", Toast.LENGTH_SHORT).show();
// out();
}
} else if (f.isDirectory()) {
//f.delete();
mCurrentNode = f;
refreshFileList();
// Toast.makeText(this, "This is postion 2 "+f.getName()+"!", Toast.LENGTH_SHORT).show();
out();
} else {
//Toast.makeText(this, "You selected: "+f.getName()+"!", Toast.LENGTH_SHORT).show();
//out();
}
return false;
}
});
}
//#Override
public void out(){
Toast.makeText(this, "You selected: "+f.getName()+"!", Toast.LENGTH_SHORT).show();
}
}
Create a setOnItemLongClickListener
My Code:
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setLongClickable(true);
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0,View arg1,int arg2, long arg3){
ListView lv = (ListView) findViewById(R.id.listView1);
// Todo
}});
you havent initialize your listview with xml listview..
ListView lst=null;
put below line after that:
lst = (ListView) findViewById(R.id.xmllistviewid);
and put your setOnItemLongClickListener method outside the onlistitemclick method.
Try this ::
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
// TODO Auto-generated method stub
Log.v("long clicked","pos"+" "+pos);
return true;
}
});
Refer this link.It is nicely explained about how to implement onItemClick() and onItemLongClick() in listview.
you can use like that
listview.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int arg2, long arg3) {
// Can't manage to remove an item here
return false;
}
});
MainMenulist.java In this class string array store all values public String[] itemcodes; i want access itemcodes to Main.java
Main.java
JSONArray json = jArray.getJSONArray("mainmenu");
list=(ListView)findViewById(R.id.mainmenulist);
adapter=new MainMenulist(this, json);
list.setAdapter(adapter);
MainMenulist.java
public class MainMenulist extends BaseAdapter {
protected static Context Context = null;
int i;
public String editnewmainmenu,menuname;
String qrimage;
Bitmap bmp, resizedbitmap;
Bitmap[] bmps;
Activity activity = null;
private LayoutInflater inflater;
private ImageView[] mImages;
String[] itemimage;
TextView[] tv;
String itemname,itemcode;
public String[] itemnames,itemcodes;
HashMap<String, String> map = new HashMap<String, String>();
public MainMenulist(Context context, JSONArray imageArrayJson) {
Context = context;
// inflater =
// (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(activity);
inflater = LayoutInflater.from(context);
this.mImages = new ImageView[imageArrayJson.length()];
this.bmps = new Bitmap[imageArrayJson.length()];
this.itemnames = new String[imageArrayJson.length()];
this.itemcodes=new String[imageArrayJson.length()];
try {
for (i = 0; i < imageArrayJson.length(); i++) {
JSONObject image = imageArrayJson.getJSONObject(i);
qrimage = image.getString("menuimage");
itemname = image.getString("menuname");
itemcode=image.getString("menucode");
itemnames[i] = itemname;
itemcodes[i]=itemcode;
byte[] qrimageBytes = Base64.decode(qrimage.getBytes());
bmp = BitmapFactory.decodeByteArray(qrimageBytes, 0,
qrimageBytes.length);
int width = 100;
int height = 100;
resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height,
true);
bmps[i] = bmp;
mImages[i] = new ImageView(context);
mImages[i].setImageBitmap(resizedbitmap);
mImages[i].setScaleType(ImageView.ScaleType.FIT_START);
// tv[i].setText(itemname);
}
System.out.println(itemnames[i]);
System.out.println(map);
} catch (Exception e) {
// TODO: handle exception
}
}
public int getCount() {
return mImages.length;
}
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;
vi = inflater.inflate(R.layout.mainmenulistview, null);
final TextView text = (TextView) vi.findViewById(R.id.menutext);
ImageView image = (ImageView) vi.findViewById(R.id.menuimage);
System.out.println(itemcodes[position]);
image.setImageBitmap(bmps[position]);
text.setText(itemnames[position]);
text.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(itemcodes[position].equals("1"))
{
Intent intent = new Intent(Context, FoodMenu.class);
System.out.println("prakash");
Context.startActivity(intent);
}
else {
Toast.makeText(Context, "This Feauture is not yet Implemented",4000).show();
}
}
});
return vi;
}
}
MainMenulist.java System.out.println(itemcodes[position]); here i print all the codes .no w i want print same result in Main.java
Write a bean which implements serlizable,write setter and getter method for your array(itemnames) as follows
class Bean implements Serializable{
String itemnames[];
public Hashtable getItemnames() {
return itemnames;
}
public void setItemnames(String itemnames[]) {
this.itemnames= itemnames;
}
}
And write foollowing code in calling activity
Bean b = new Bean();
b.setItemnames(itemnames);
Intent i=new Intent();
i.setClass(A.this,B.class);
i.putExtra("itemnames", b);
startActivity(i);
And retrieve in called activity as follows
Bean obj = (Bean) getIntent().getSerializableExtra("itemnames");// TypeCasting
String itemname[] = (Hashtable) obj.getItemnames();
There are two ways to do this:
In your code:
public String[] itemnames,itemcodes; make that arrays as static like below
public static String[] itemnames,itemcodes;
And then use `Main.java` file by calling:
System.out.println(MainMenulist.itemcodes[position]);
System.out.println(MainMenulist.itemnames[position]);
2) Parse JSON in Main.java which you have pass to MainMenulist.java
public MainMenulist(Context context, JSONArray imageArrayJson)