Adding ProgressBar to DetailsOverviewRow on Android TV - android

I'm trying to create a slightly modified version of the android.support.v17.leanback.widget.DetailsOverviewRow for an Android TV app. The layout I'm trying to accomplish is roughly the same as Google's default version, but with the addition of a progress bar above the actions panel. What I have now looks like this:
Current Version
What I want to create is something roughly like this:
Goal Version
I would like to add this in dynamically without having to create an entirely new layout from scratch if possible. Here's the code I'm using currently, slightly modified from the default Android TV app in Android Studio:
public class VideoDetailsFragment extends DetailsFragment {
private static final String TAG = "VideoDetailsFragment";
private static final int ACTION_UPDATE = 1;
private static final int ACTION_CHANGELOG = 2;
private static final int ACTION_INSTALLED = 3;
private static final int DETAIL_THUMB_WIDTH = 274;
private static final int DETAIL_THUMB_HEIGHT = 274;
private static final int NUM_COLS = 10;
private static final String UPDATE = "Update";
private Update mSelectedUpdate;
private Drawable mDefaultBackground;
private Target mBackgroundTarget;
private DisplayMetrics mMetrics;
private DetailsOverviewRowPresenter mDorPresenter;
private DetailRowBuilderTask mDetailRowBuilderTask;
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate DetailsFragment");
super.onCreate(savedInstanceState);
mDorPresenter =
new DetailsOverviewRowPresenter(new DetailsDescriptionPresenter());
BackgroundManager backgroundManager = BackgroundManager.getInstance(getActivity());
backgroundManager.attach(getActivity().getWindow());
mBackgroundTarget = new PicassoBackgroundManagerTarget(backgroundManager);
mDefaultBackground = getResources().getDrawable(R.drawable.default_background);
mMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(mMetrics);
List<Update> list = UpdateList.setupMovies();
mSelectedUpdate = list.get(0);//(Update) getActivity().getIntent().getSerializableExtra(MOVIE);
mDetailRowBuilderTask = (DetailRowBuilderTask) new DetailRowBuilderTask().execute(list);
mDorPresenter.setSharedElementEnterTransition(getActivity(),
DetailsActivity.SHARED_ELEMENT_NAME);
setOnItemViewClickedListener(new ItemViewClickedListener());
}
#Override
public void onStop() {
mDetailRowBuilderTask.cancel(true);
super.onStop();
}
private class DetailRowBuilderTask extends AsyncTask<List<Update>, Integer, List<DetailsOverviewRow>> {
#Override
protected List<DetailsOverviewRow> doInBackground(List<Update>... movies) {
List<DetailsOverviewRow> rows = new ArrayList<DetailsOverviewRow>();
int exampleUpdate = 0;
for (Update m: movies[0]) {
DetailsOverviewRow row = new DetailsOverviewRow(m);
try {
//String test = mSelectedUpdate.getCardImageUrl();
Bitmap poster = Picasso.with(getActivity())
.load(m.getCardImageUrl())
.resize(Utils.convertDpToPixel(getActivity().getApplicationContext(), DETAIL_THUMB_WIDTH),
Utils.convertDpToPixel(getActivity().getApplicationContext(), DETAIL_THUMB_HEIGHT))
.centerCrop()
.get();
row.setImageBitmap(getActivity(), poster);
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, e.toString(), e);
}
SparseArrayObjectAdapter adapter = new SparseArrayObjectAdapter();
if (exampleUpdate++ == 0) {
Action a1 = new Action(ACTION_UPDATE, getResources().getString(R.string.download));
Action a2 = new Action(ACTION_CHANGELOG, getResources().getString(R.string.release_notes));
adapter.set(ACTION_UPDATE, a1);
adapter.set(ACTION_CHANGELOG, a2);
row.setActionsAdapter(adapter);
}else{
Action a1 = new Action(ACTION_INSTALLED, getResources().getString(
R.string.installed));
Action a2 = new Action(ACTION_CHANGELOG, getResources().getString(R.string.release_notes));
//ProgressBar p1 = new ProgressBar(getActivity(),null, android.R.attr.progressBarStyleHorizontal);
adapter.set(1, a1);
adapter.set(2, a2);
//adapter.set(3, p1);
row.setActionsAdapter(adapter);
}
rows.add(row);
}
return rows;
}
#Override
protected void onPostExecute(List<DetailsOverviewRow> detailRows) {
ClassPresenterSelector ps = new ClassPresenterSelector();
// set detail background and style
mDorPresenter.setBackgroundColor(getResources().getColor(R.color.black_opaque));
Log.i("TEST", "Setting BG Color of Detail View");
mDorPresenter.setStyleLarge(true);
mDorPresenter.setOnActionClickedListener(new OnActionClickedListener() {
#Override
public void onActionClicked(Action action) {
if (action.getId() == ACTION_UPDATE) {
/*Intent intent = new Intent(getActivity(), PlaybackOverlayActivity.class);
intent.putExtra(getResources().getString(R.string.movie), mSelectedUpdate);
intent.putExtra(getResources().getString(R.string.should_start), true);
startActivity(intent);*/
Toast.makeText(getActivity(), "Download Update", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), action.toString(), Toast.LENGTH_SHORT).show();
}
}
});
ps.addClassPresenter(DetailsOverviewRow.class, mDorPresenter);
ps.addClassPresenter(ListRow.class,
new ListRowPresenter());
ArrayObjectAdapter adapter = new ArrayObjectAdapter(ps);
for(DetailsOverviewRow detailRow : detailRows){
adapter.add(detailRow);
}
String subcategories[] = {
getString(R.string.related_movies)
};
//HeaderItem header = new HeaderItem(0, subcategories[0]);
//adapter.add(new ListRow(header, listRowAdapter));
setAdapter(adapter);
}
}
private final class ItemViewClickedListener implements OnItemViewClickedListener {
#Override
public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item,
RowPresenter.ViewHolder rowViewHolder, Row row) {
if (item instanceof Update) {
Update update = (Update) item;
Log.d(TAG, "Item: " + item.toString());
Intent intent = new Intent(getActivity(), DetailsActivity.class);
intent.putExtra(DetailsActivity.MOVIE, update);
Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(
getActivity(),
((ImageCardView) itemViewHolder.view).getMainImageView(),
DetailsActivity.SHARED_ELEMENT_NAME).toBundle();
getActivity().startActivity(intent, bundle);
}
}
}
}
Is there a simple way to add the ProgressBar or do I need to create a completely new xml layout to do this?

I figured out a way to do it. I ended up creating a modified version of lb_details_overview.xml, which is used by the support.v17.leanback library when creating a DetailOverviewRow. I basically just added a RelativeLayout with a ProgressBar. I also had to make a modified version of DetailsOverviewRowPresenter.java in the leanback library in order to inflate the new xml layout instead of the existing one. It might not be the best or the easiest way to do this, but it works.

Related

Put ID autoincrement After Pass 2 ScreenActivity SQLite

I'm stuck for few days, and unfortunately dont know how to fix it.
I have DetailScreen.java that show data from MainScreen (one of recyclerview's list).
I tried this code but there is no effect, when i try to change use
COLUMN_NOMOR in my update function, i can change the name but
getting error when change the nomor. I guess, its right to use
COLUMN_ID in my update function because id is my PK-AI. So whether
because I didnt call COLUMN_ID in my DetailScreen? But how i can call my
id in my DetailsScreen also in my UpdateScreen?
If the data success updated, the screen will be automatically go to the DetailScreen again, but still showing old data. I had to go to MainActivity first to get the new data. Where code should i modified?
Here my Update function in my DBHandler.java
public int updateDataSiswa(Siswa siswa) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NOMOR, siswa.getNomor());
values.put(COLUMN_NAMA, siswa.getNama());
return db.update(TABLE_SISWA, values, COLUMN_ID + " = ?",
new String[]{String.valueOf(siswa.getId())});
}
Here DetailScreen.java
public class DetailScreen extends AppCompatActivity {
private TextView txt_resultnomor, txt_resultnama;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_details);
//put data
Intent i = getIntent();
final String id = i.getExtras().getString("id");
final String nomor = i.getExtras().getString("nomor");
final String nama = i.getExtras().getString("nama");
//inisialisasi
txt_resultnomor = (TextView) findViewById(R.id.txt_resultnomor);
txt_resultnama = (TextView) findViewById(R.id.txt_resultnama);
//set
txt_resultnomor.setText(nomor);
txt_resultnama.setText(nama);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_detail, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_edit) {
Intent in = new Intent(this, UpdateScreen.class);
in.putExtra("nomor", txt_resultnomor.getText().toString());
in.putExtra("nama", txt_resultnama.getText().toString());
startActivity(in);
}
if (id == R.id.action_delete) {
return true;
}
if (id == R.id.action_settings) {
// Intent i = new Intent(this, About.class);
//startActivity(i);
}
return super.onOptionsItemSelected(item);
}
}
Then here my UpdateScreen.java
public class UpdateScreen extends AppCompatActivity {
private EditText et_nomor;
private EditText et_nama;
private Button button_updatedata;
private DBHandler dbHandler;
private SiswaAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_screen);
dbHandler = new DBHandler(this);
initComponents();
}
private void initComponents(){
et_nomor = (EditText) findViewById(R.id.et_nomor);
et_nama = (EditText) findViewById(R.id.et_nama);
//ambil data
Intent in=getIntent();
final String id=in.getExtras().getString("id_siswa");
final String nomor=in.getExtras().getString("nomor");
final String nama=in.getExtras().getString("nama");
//set inisial
et_nomor.setText(nomor);
et_nama.setText(nama);
button_updatedata = (Button) findViewById(R.id.button_updatedata);
button_updatedata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validasiForm();
}
});
}
private void validasiForm() {
String form_nomor = et_nomor.getText().toString();
String form_nama = et_nama.getText().toString();
if (form_nomor.isEmpty()){
et_nomor.setError("Nomor belum diisi");
et_nomor.requestFocus();
}
else if (form_nama.isEmpty()){
et_nama.setError("Nama belum diisi");
et_nama.requestFocus();
}
else {
dbHandler.updateDataSiswa(new Siswa(form_nomor, form_nama));
List<Siswa> siswaList = dbHandler.getSemuaSiswa();
adapter = new SiswaAdapter(siswaList);
adapter.notifyDataSetChanged();
Toast.makeText(UpdateScreen.this, "Berhasil Memperbarui Data Siswa", Toast.LENGTH_SHORT).show();
MainSiswaActivity.mma.refresh();
finish();
}
}
}
I hope i tell clearly, help me please. Thanks.
where is your call to the update method you given public int updateDataSiswa(Siswa siswa)..? Also based on what you have provided...your notifyDataSetChanged() for adapter just tries to update the listview of the RecyclerView..
but it does not understand what underlying data has changed for it..you need to create a method for your Database Handler where you can fetch a List of new records..and then use this method to update your adapter with it and then set the new adapter to your listView in validasiForm() method..
please check this for more details...Android ListView not refreshing after notifyDataSetChanged

Save ArrayList of custom objects and add a new object to ArrayList

I'm having an issue with saving the instance of an ArrayList of custom objects in an Activity and then retreiving it after doing some stuff in another Activity. Inside the first Activity (which has the ArrayList), there is a button to start a second activity. Inside this second Activity the user is asked to create a new object that will be added afterwards in the ArrayList of the first Activity, so that when the second Activity finishes the first Activity is shown again with a ListView of all the objects (including the last one created). The problem I'm facing is that only the last object created is being shown in the ListView.
Here is the code of the first Activity:
public class CargasMin extends AppCompatActivity implements View.OnClickListener {
RelativeLayout rl_CargasMin;
ImageButton bt_AdDep;
Button bt_CalcCargas;
ListView listView_Dep;
ArrayList<Dependencia> listaDeDependencias = new ArrayList<Dependencia>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.min_cargas);
rl_CargasMin = (RelativeLayout) findViewById(R.id.cargasMinLayout);
bt_AdDep = (ImageButton) findViewById(R.id.bt_AdDep_CargasMin);
bt_CalcCargas = (Button) findViewById(R.id.bt_CalcCargas_CargasMin);
bt_AdDep.setOnClickListener(this);
bt_CalcCargas.setOnClickListener(this);
// This seems not to be working!
if(savedInstanceState == null) { }
else {
listaDeDependencias = savedInstanceState.getParcelableArrayList("key");
}
// Get last object created
Intent intent_de_AdDep = getIntent();
Dependencia dependenciaAAdicionar = (Dependencia) intent_de_AdDep.getParcelableExtra("novaDependencia");
if(dependenciaAAdicionar == null) { }
else {
listaDeDependencias.add(dependenciaAAdicionar);
}
//Cria Adapter pra mostrar dependencias na ListView
DependenciaAdapter adapterDeDependencias = new DependenciaAdapter(this, R.layout.adapter_dependencia, listaDeDependencias);
//Seta Adapter
listView_Dep = (ListView) findViewById(R.id.listView_Dep_CargasMin);
listView_Dep.setAdapter(adapterDeDependencias);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.bt_AdDep_CargasMin:
Intent intent_AdDep = new Intent(CargasMin.this, AdDep.class);
startActivity(intent_AdDep);
break;
case R.id.bt_CalcCargas_CargasMin:
//
break;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// Aqui se salva a listaDeDependencias quando a Atividade eh momentaneamente fechada.
outState.putParcelableArrayList("key", listaDeDependencias);
super.onSaveInstanceState(outState);
}
}
This is the code of my custom class Dependencia:
public class Dependencia implements Parcelable {
String nome;
int tipo;
float largura = 0;
float comprimento = 0;
float area = 0;
float perimetro = 0;
// Constructor da classe Dependencia.
public Dependencia(String nomeDep, int tipoDep) {
nome = nomeDep;
tipo = tipoDep;
}
private Dependencia(Parcel in) {
nome = in.readString();
tipo = in.readInt();
largura = in.readFloat();
comprimento = in.readFloat();
area = in.readFloat();
perimetro = in.readFloat();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(nome);
out.writeInt(tipo);
out.writeFloat(largura);
out.writeFloat(comprimento);
out.writeFloat(area);
out.writeFloat(perimetro);
}
public static final Parcelable.Creator<Dependencia> CREATOR = new Parcelable.Creator<Dependencia>() {
public Dependencia createFromParcel(Parcel in) {
return new Dependencia(in);
}
public Dependencia[] newArray(int size) {
return new Dependencia[size];
}
};
}
And this is the code of the second Activity:
public class AdDep extends AppCompatActivity implements View.OnClickListener {
RelativeLayout rl_AdDep;
EditText et_Nome;
EditText et_Largura;
EditText et_Comprimento;
EditText et_Area;
EditText et_Perimetro;
Spinner spinner_Tipo;
String vetorTipo[];
int tipoEscolhido;
Button bt_AdDep1;
Button bt_AdDep2;
Dependencia novaDependencia;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dep_ad);
rl_AdDep = (RelativeLayout)findViewById(R.id.adDepLayout);
et_Nome = (EditText) findViewById(R.id.et_Nome_AdDep);
et_Largura = (EditText) findViewById(R.id.et_Largura_AdDep);
et_Comprimento = (EditText) findViewById(R.id.et_Comprimento_AdDep);
et_Area = (EditText) findViewById(R.id.et_Area_AdDep);
et_Perimetro = (EditText) findViewById(R.id.et_Perimetro_AdDep);
spinner_Tipo = (Spinner) findViewById(R.id.spinner_Tipo_AdDep);
bt_AdDep1 = (Button) findViewById(R.id.bt_AdDep1);
bt_AdDep2 = (Button) findViewById(R.id.bt_AdDep2);
// Adicionando opcoes no spinner
vetorTipo = new String[5];
vetorTipo[0] = "Banheiro";
vetorTipo[1] = "Varanda";
vetorTipo[2] = "Cozinha/Copa/Serviço/etc.";
vetorTipo[3] = "Sala/Dormitório";
vetorTipo[4] = "Outro";
// Criando ArrayAdapter de strings pro spinner
ArrayAdapter<String> adapterTipo = new ArrayAdapter<String>(AdDep.this, android.R.layout.simple_spinner_item, vetorTipo);
// Setando o Adapter
spinner_Tipo.setAdapter(adapterTipo);
// Valor default do spinner (hint)
spinner_Tipo.setSelection(0);
bt_AdDep1.setOnClickListener(this);
bt_AdDep2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Banheiro"))
tipoEscolhido = 1;
else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Varanda"))
tipoEscolhido = 2;
else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Cozinha/Copa/Serviço/etc."))
tipoEscolhido = 3;
else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Sala/Dormitório"))
tipoEscolhido = 4;
else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Outro"))
tipoEscolhido = 5;
novaDependencia = new Dependencia(et_Nome.getText().toString(), tipoEscolhido);
switch(v.getId()) {
case R.id.bt_AdDep1:
novaDependencia.largura = Float.valueOf(et_Largura.getText().toString());
novaDependencia.comprimento = Float.valueOf(et_Comprimento.getText().toString());
break;
case R.id.bt_AdDep2:
novaDependencia.area = Float.valueOf(et_Area.getText().toString());
novaDependencia.perimetro = Float.valueOf(et_Perimetro.getText().toString());
break;
}
AlertDialog.Builder builder2 = new AlertDialog.Builder(v.getContext());
builder2.setMessage("Deseja adicionar T.U.E. nesta dependência?").setPositiveButton("Sim", dialogClickListener).setNegativeButton("Não", dialogClickListener).show();
}
// Objeto tipo dialog criado para perguntar se usario deseja inserir TUEs
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
break;
case DialogInterface.BUTTON_NEGATIVE:
Intent intent_NovaDep_CargasMin = new Intent(AdDep.this, CargasMin.class);
intent_NovaDep_CargasMin.putExtra("novaDependencia", novaDependencia);
startActivity(intent_NovaDep_CargasMin);
break;
}
}
};
}
If anyone knows how to solve this, please share. Thanks.
The problem is that you're starting a new instance of the CargasMin activity from AdDep activity. Your AdDep activity should just finish and return a result back to the existing instance of CargasMin activity on the back stack for you to see all the previous list data as well.
To retrieve the new list item from AdDep as a result, use startActivityForResult()
case R.id.bt_AdDep_CargasMin:
Intent intent_AdDep = new Intent(CargasMin.this, AdDep.class);
startActivityForResult(intent_AdDep, ADD_DEP_REQUEST);
break;
where ADD_DEP_REQUEST is just a request code constant
public static final int ADD_DEP_REQUEST = 1;
Now, when AdDep is done collecting data, it returns the new data item as a result.
case DialogInterface.BUTTON_NEGATIVE:
Intent result = new Intent();
result.putExtra("novaDependencia", novaDependencia);
setResult(Activity.RESULT_OK, result);
finish();
break;
Your main CargasMin activity will then receive the new data item as
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ADD_DEP_REQUEST) {
if (resultCode == RESULT_OK) {
// Get last object created
Dependencia dependenciaAAdicionar =
(Dependencia) data.getParcelableExtra("novaDependencia");
if(dependenciaAAdicionar != null){
listaDeDependencias.add(dependenciaAAdicionar);
// Refresh Adapter pra mostrar dependenciaAAdicionar na ListView
adapterDeDependencias.notifyDataSetChanged();
}
}
}
}
Note that listaDeDependencias and adapterDeDependencias have been changed to instance members of the activity.
Your current approach would have worked if you were persisting the data to some storage (like in a file or database) but creating a new instance of CargasMin is still not recommended because the one existing on the back stack would suffice.

Android: How can I make a listview wait for a variable to fill before setting?

So I have a movie trivia game that I am building. The problem I am running into is on the main user profile page I set 3 listviews. One for games where it is your turn, one for games that are waiting for your opponent, and one for completed games. These list views make calls to Parse.com to fetch the game object. In Order to fetch this info from Parse I need to provide my query with a Facebook user id. My code calls Facebook to get the ID, but the listview adapters run about 5 milliseconds before the call to Facebook returns the ID. When the user refreshes the page, the lists load properly, but when first running the app they are blank. Here is the user profile activity code:
public class UserProfileActivity extends AppCompatActivity {
ParseLogic mPl;
private WfoAdapter wfoAdapter;
private WoyAdapter woyAdapter;
private CompletedGameAdapter completedGameAdapter;
private TicketSystem mTicketsSytem;
String mMyFbId;
String mMyFbName;
int mTickets;
ListView mWfoListView;
ListView mWoyListView;
ListView mCompletedGameListView;
TextView mmTicketNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTicketsSytem = new TicketSystem();
mTickets = mTicketsSytem.getTickets();
setContentView(R.layout.activity_user_profile);
new getFbDeets().execute(); //This is where the async task is called
mPl = new ParseLogic();
mWoyListView = (ListView)findViewById(R.id.waitingForYouListView);
mWfoListView = (ListView)findViewById(R.id.waitingForOpponentListView);
mCompletedGameListView = (ListView)findViewById(R.id.completedGameListView);
mmTicketNumber = (TextView)findViewById(R.id.numberOfTickets);
mmTicketNumber.setText(String.valueOf(mTickets));
FaceBookFriends.getFaceBookFriends();
//Testing start game remove when building rest of page
Button button = (Button)findViewById(R.id.startNewGame);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UserProfileActivity.this, GameStart.class);
startActivity(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
mTickets = mTicketsSytem.getTickets();
mmTicketNumber.setText(String.valueOf(mTickets));
populateWoyListView();
populateWfoListView();
populateCompleteListView();
}
#Override
public void onBackPressed(){}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
//create the logout button in action bar
switch (item.getItemId()){
case R.id.logoutButton:
ParseUser.logOut();
ParseUser currentUser = ParseUser.getCurrentUser(); // this will now be null
Intent intent = new Intent(UserProfileActivity.this, WelcomeActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
public void populateUI() {
populateWoyListView();
populateWfoListView();
populateCompleteListView();
mWoyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String goTV = ((TextView) view.findViewById(R.id.gameObjectHiddenTextView)).getText().toString();
String score = ((TextView) view.findViewById(R.id.woyScoreNumber)).getText().toString();
Log.v("Clicked Object Id ", goTV);
Intent intent = new Intent(UserProfileActivity.this, AreYouReady.class);
intent.putExtra("Score", score);
intent.putExtra("Object Id", goTV);
startActivity(intent);
}
});
}
private void populateWoyListView() {
//mMfbId is the variable set by the facebook call
woyAdapter = new WoyAdapter(this ,mMyFbId);
woyAdapter.loadObjects();
mWoyListView.setAdapter(woyAdapter);
}
private void populateWfoListView() {
wfoAdapter = new WfoAdapter(this);
wfoAdapter.loadObjects();
mWfoListView.setAdapter(wfoAdapter);
}
private void populateCompleteListView() {
completedGameAdapter = new CompletedGameAdapter(this, mMyFbId);
completedGameAdapter.loadObjects();
mCompletedGameListView.setAdapter(completedGameAdapter);
}
protected class getFbDeets extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
mMyFbId = FaceBookFriends.getMyFbId();
mMyFbName = FaceBookFriends.getMyFbName();
Log.v("getFbDeets() ", "Is Running");
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
populateUI();
}
}
}
This is the completed gave adapter:
/**
* Created by Tom Schinler on 9/23/2015.
*/
public class CompletedGameAdapter extends ParseQueryAdapter<Game> {
String mWinnerScore;
String mWinnerName;
String mLoserScore;
String mLoserName;
String mFbName;
public CompletedGameAdapter(Context context, final String myFbId) {
super(context, new ParseQueryAdapter.QueryFactory<Game>() {
public ParseQuery<Game> create() {
ParseQuery<Game> queryCreatedBy = new ParseQuery<Game>("Game");
queryCreatedBy.whereEqualTo("Created_By", ParseUser.getCurrentUser());
ParseQuery<Game> queryOppOf = new ParseQuery<Game>("Game");
queryOppOf.whereEqualTo("Opponent_Id", myFbId);
ParseQuery<Game> query = ParseQuery.or(Arrays.asList(queryCreatedBy, queryOppOf));
query.whereNotEqualTo("Creator_Score", "");
query.whereNotEqualTo("Opponent_Score", "");
query.orderByDescending("updatedAt");
query.setLimit(4);
return query;
}
});
}
#Override
public View getItemView(Game game, View view, ViewGroup parent) {
if (view == null) {
view = View.inflate(getContext(), R.layout.completed_game_layout, null);
}
super.getItemView(game, view, parent);
mFbName = FaceBookFriends.getMyFbName();
TextView winOrLose = (TextView)view.findViewById(R.id.winOrLose);
int oppScore = Integer.parseInt(game.getOpponentScore());
int creatScore = Integer.parseInt(game.getCreatorScore());
if(oppScore > creatScore){
mWinnerScore = String.valueOf(oppScore);
mWinnerName = game.getOpponentName();
mLoserScore = String.valueOf(creatScore);
mLoserName = game.getCreatorFbName();
}
else {
mWinnerScore = String.valueOf(creatScore);
mWinnerName = game.getCreatorFbName();
mLoserScore = String.valueOf(oppScore);
mLoserName = game.getOpponentName();
}
TextView winnerName = (TextView)view.findViewById(R.id.winnerName);
winnerName.setText(mWinnerName);
TextView winnerScore = (TextView)view.findViewById(R.id.winnerScore);
winnerScore.setText(mWinnerScore);
TextView loserName = (TextView)view.findViewById(R.id.loserName);
loserName.setText(mLoserName);
TextView loserScore = (TextView)view.findViewById(R.id.loserScore);
loserScore.setText(mLoserScore);
if(mWinnerName.equals(mFbName)){
view.setBackgroundColor(Color.GREEN);
winOrLose.setText("WIN!!");
}
else {
view.setBackgroundColor(Color.RED);
winOrLose.setText("LOSER!!");
}
return view;
}
}
and here is the adapter that sets the listview for games waiting on the user:
/**
* Created by Tom Schinler on 9/22/2015.
*/
public class WoyAdapter extends ParseQueryAdapter<Game>{
public WoyAdapter(Context context, final String fbId) {
super(context, new ParseQueryAdapter.QueryFactory<Game>() {
public ParseQuery<Game> create() {
//Log.v("var fbid is ", fbId);
ParseQuery query = new ParseQuery("Game");
query.whereEqualTo("Opponent_Id", fbId);
query.whereEqualTo("Opponent_Score", "");
query.orderByDescending("updatedAt");
query.setLimit(4);
return query;
}
});
}
#Override
public View getItemView(Game game, View view, ViewGroup parent) {
if (view == null) {
view = View.inflate(getContext(), R.layout.waiting_on_you_layout, null);
Log.v("WOY is this", "running");
}
super.getItemView(game, view, parent);
ProfilePictureView friendPic = (ProfilePictureView) view.findViewById(R.id.woyFbPic);
String friendId = game.getCreatorId();
if(friendId != null){
friendPic.setProfileId(friendId);
}
TextView oppName = (TextView)view.findViewById(R.id.woyNameText);
oppName.setText(game.getCreatorFbName());
TextView oppScore = (TextView)view.findViewById(R.id.woyScoreNumber);
oppScore.setText(game.getCreatorScore());
TextView GOTV = (TextView)view.findViewById(R.id.gameObjectHiddenTextView);
GOTV.setText(game.getObjectId());
return view;
}
}
I set mMyFbId with a Facebook method like this:
mMyFbId = FaceBookFriends.getMyFbId();
but it return about 1 second after the code runs to build the lists views, since they do not have the variable, they populate nothing. Please help.

Android: Adding functionality that activty changes when game is complete

I wish to add the following functionality to my game:
-When the game is complete (no more cards are visible on screen) then move to a new activity
I am aware how to move to another activty using intents but I am not sure how to implement the functionality in this case.
I.e. what variable/info can I use to ensure the game is complete when I move before moving to the next activity?
For reference, The game is based off this open source game Images of the game are shown here to give an idea.
Current code:
public class Manager extends Activity {
private static int ROW_COUNT = -1;
private static int COL_COUNT = -1;
private Context context;
private Drawable backImage;
private int [] [] cards;
private List<Drawable> images;
private Card firstCard;
private Card seconedCard;
private ButtonListener buttonListener;
private static Object lock = new Object();
int turns;
private TableLayout mainTable;
private UpdateCardsHandler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new UpdateCardsHandler();
loadImages();
setContentView(R.layout.main);
TextView url = ((TextView)findViewById(R.id.myWebSite));
Linkify.addLinks(url, Linkify.WEB_URLS);
backImage = getResources().getDrawable(R.drawable.icon);
/*
((Button)findViewById(R.id.ButtonNew)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
newGame();
}
});*/
buttonListener = new ButtonListener();
mainTable = (TableLayout)findViewById(R.id.TableLayout03);
context = mainTable.getContext();
Spinner s = (Spinner) findViewById(R.id.Spinner01);
ArrayAdapter adapter = ArrayAdapter.createFromResource(
this, R.array.type, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
s.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(
android.widget.AdapterView<?> arg0,
View arg1, int pos, long arg3){
((Spinner) findViewById(R.id.Spinner01)).setSelection(0);
int x,y;
switch (pos) {
case 1:
x=4;y=4;
break;
case 2:
x=4;y=5;
break;
case 3:
x=4;y=6;
break;
case 4:
x=5;y=6;
break;
case 5:
x=6;y=6;
break;
default:
return;
}
newGame(x,y);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
private void newGame(int c, int r) {
ROW_COUNT = r;
COL_COUNT = c;
cards = new int [COL_COUNT] [ROW_COUNT];
mainTable.removeView(findViewById(R.id.TableRow01));
mainTable.removeView(findViewById(R.id.TableRow02));
TableRow tr = ((TableRow)findViewById(R.id.TableRow03));
tr.removeAllViews();
mainTable = new TableLayout(context);
tr.addView(mainTable);
for (int y = 0; y < ROW_COUNT; y++) {
mainTable.addView(createRow(y));
}
firstCard=null;
loadCards();
turns=0;
((TextView)findViewById(R.id.tv1)).setText("Tries: "+turns);
}
private void loadImages() {
images = new ArrayList<Drawable>();
images.add(getResources().getDrawable(R.drawable.card1));
images.add(getResources().getDrawable(R.drawable.card2));
images.add(getResources().getDrawable(R.drawable.card3));
images.add(getResources().getDrawable(R.drawable.card4));
images.add(getResources().getDrawable(R.drawable.card5));
images.add(getResources().getDrawable(R.drawable.card6));
images.add(getResources().getDrawable(R.drawable.card7));
images.add(getResources().getDrawable(R.drawable.card8));
images.add(getResources().getDrawable(R.drawable.card9));
images.add(getResources().getDrawable(R.drawable.card10));
images.add(getResources().getDrawable(R.drawable.card11));
images.add(getResources().getDrawable(R.drawable.card12));
images.add(getResources().getDrawable(R.drawable.card13));
images.add(getResources().getDrawable(R.drawable.card14));
images.add(getResources().getDrawable(R.drawable.card15));
images.add(getResources().getDrawable(R.drawable.card16));
images.add(getResources().getDrawable(R.drawable.card17));
images.add(getResources().getDrawable(R.drawable.card18));
images.add(getResources().getDrawable(R.drawable.card19));
images.add(getResources().getDrawable(R.drawable.card20));
images.add(getResources().getDrawable(R.drawable.card21));
}
private void loadCards(){
try{
int size = ROW_COUNT*COL_COUNT;
Log.i("loadCards()","size=" + size);
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0;i<size;i++){
list.add(new Integer(i));
}
Random r = new Random();
for(int i=size-1;i>=0;i--){
int t=0;
if(i>0){
t = r.nextInt(i);
}
t=list.remove(t).intValue();
cards[i%COL_COUNT][i/COL_COUNT]=t%(size/2);
Log.i("loadCards()", "card["+(i%COL_COUNT)+
"]["+(i/COL_COUNT)+"]=" + cards[i%COL_COUNT][i/COL_COUNT]);
}
}
catch (Exception e) {
Log.e("loadCards()", e+"");
}
}
private TableRow createRow(int y){
TableRow row = new TableRow(context);
row.setHorizontalGravity(Gravity.CENTER);
for (int x = 0; x < COL_COUNT; x++) {
row.addView(createImageButton(x,y));
}
return row;
}
private View createImageButton(int x, int y){
Button button = new Button(context);
button.setBackgroundDrawable(backImage);
button.setId(100*x+y);
button.setOnClickListener(buttonListener);
return button;
}
class ButtonListener implements OnClickListener {
#Override
public void onClick(View v) {
synchronized (lock) {
if(firstCard!=null && seconedCard != null){
return;
}
int id = v.getId();
int x = id/100;
int y = id%100;
turnCard((Button)v,x,y);
}
}
private void turnCard(Button button,int x, int y) {
button.setBackgroundDrawable(images.get(cards[x][y]));
if(firstCard==null){
firstCard = new Card(button,x,y);
}
else{
if(firstCard.x == x && firstCard.y == y){
return; //the user pressed the same card
}
seconedCard = new Card(button,x,y);
turns++;
((TextView)findViewById(R.id.tv1)).setText("Tries: "+turns);
TimerTask tt = new TimerTask() {
#Override
public void run() {
try{
synchronized (lock) {
handler.sendEmptyMessage(0);
}
}
catch (Exception e) {
Log.e("E1", e.getMessage());
}
}
};
Timer t = new Timer(false);
t.schedule(tt, 1300);
}
}
}
class UpdateCardsHandler extends Handler{
#Override
public void handleMessage(Message msg) {
synchronized (lock) {
checkCards();
}
}
public void checkCards(){
if(cards[seconedCard.x][seconedCard.y] == cards[firstCard.x][firstCard.y]){
firstCard.button.setVisibility(View.INVISIBLE);
seconedCard.button.setVisibility(View.INVISIBLE);
}
else {
seconedCard.button.setBackgroundDrawable(backImage);
firstCard.button.setBackgroundDrawable(backImage);
}
firstCard=null;
seconedCard=null;
}
}
}
The easiest way to do this would be to check win conditions with an if statement. This should be done in the method when a turn is actually taken which I assume happens in the turnCard() method.
if (winConditionMet) {
displayWinningScreen();
} else if (lossConditionMet) {
displayLosingScreen();
}
If conditions have been met, then call a method which handles wrapping up that screen, and then launching a new activity. For instance you could add a button to the screen with whatever text you wanted, that when pushed, would take the user to the next screen, be it your score screen, replay screen, main menu, or what have you.
Edit: Okay, since this is a game of memory, you could iterate through the cards at the end of every turn taken and check if any card still has its image set to backImage. If there are none left that are set to backImage, you can then end the game with your code inside of the if statement.
Or, instead of using an ArrayList, you could use some form of Map to keep track of if each card has been permanently turned up or not with the boolean value.

Confuse about android check list box

I would like to implement products list with checklistbox after select radio button.
And I would like to show chekclistbox as dialog box. My product list data come from sqllite.
It is need to implement adapter class to show data for checklistbox or can I directly implement for checklistbox data in alertDialog . Please clear for me.
In mainActivity
public RadioGroup.OnCheckedChangeListener setOnCheckedChangeListener = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
rdoPCode = (RadioButton) findViewById(checkedId);
switch (checkedId) {
case R.id.rdoAll:
Toast.makeText(context, rdoPCode.getText(), Toast.LENGTH_SHORT)
.show();
break;
case R.id.rdoCustom:
Intent localIntent = new Intent(MainActivity.context,
ProductListChkActivity.class);
MainActivity.context.startActivity(localIntent);
break;
}
}
};
In ProductListChkActivity
public class ProductListChkActivity extends Activity {
private static Button button_selectall;
private static Button button_unselectall;
private static CheckBox chkProductCode;
private static CashSaleProductLogic _sellProductLogic;
public static List<CashSaleProductInfo> _SaleProductInfo;
public static ListView lvlchkPrdlist;
private Button btnSelectAll, btnUnSelectAll;
// For chk productcode
private static ProductListChkAdapter _ProductListChkAdapter;
Context context;
#Override
protected void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
setContentView(R.layout.productinofchk);
context = this;
init();
ProductCodeChk();
}
private void init() {
button_selectall = (Button) this.findViewById(R.id.button_selectall);
button_unselectall = (Button) this
.findViewById(R.id.button_unselectall);
chkProductCode = (CheckBox) this.findViewById(R.id.chkProductCode);
lvlchkPrdlist = (ListView) this.findViewById(R.id.lvlchkPrdlist);
_sellProductLogic = new CashSaleProductLogic(this);
_SaleProductInfo = _sellProductLogic.getAllsellProductDataLogic();
}
protected void ProductCodeChk() {
try {
_ProductListChkAdapter = new ProductListChkAdapter(context,
_SaleProductInfo, 1);
this.lvlchkPrdlist.setAdapter(_ProductListChkAdapter);
} catch (Exception e) {
e.printStackTrace();
return;
}
}
public void OnClickbillbtncancel(View paramView) {
MainActivity.textClear();
Intent localIntent = new Intent(ProductListChkActivity.this,
MainActivity.class);
ProductListChkActivity.this.startActivity(localIntent);
}
}
I would like to show productinofchk layout as dialogbox
You need to go through floating dialogs in android. check out this documentation :
link

Categories

Resources