I need help with knowing how to get dialogfragment act when entered a value then pressed okay button or cancel button.
Below are classes ActivityA.java, BasicDialogFragment.java, fragment_basic_dialog.xml and activity_a.xml.
That's all the code you need for this question. Thanks in advance.
ActivityA
package internal.android.com.helloworld;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ActivityA extends ActionBarActivity implements BasicDialogFragment.OnNameEnteredListener {
private Button dialogKnapp = null;
private TextView textA = null;
private TextView textA2 = null;
private EditText editA2 = null;
private Button buttonAB = null;
private Button buttonAC = null;
private Button buttonAD = null;
private Button buttonCancel = null;
private Button buttonOK = null;
private EditText dialog_fornavn = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
dialogKnapp = (Button) findViewById(R.id.dialog_knapp);
buttonCancel = (Button) findViewById(R.id.buttonCancel);
buttonOK = (Button) findViewById(R.id.buttonOK);
dialog_fornavn = (EditText) findViewById(R.id.dialog_fornavn);
textA = (TextView) findViewById(R.id.textA);
textA2 = (TextView) findViewById(R.id.textA2);
editA2 = (EditText) findViewById(R.id.editA2);
buttonAB = (Button) findViewById(R.id.buttonAB);
buttonAC = (Button) findViewById(R.id.buttonAC);
buttonAD = (Button) findViewById(R.id.buttonAD);
Intent intent = getIntent();
String navn = intent.getStringExtra("navnet");
textA2.setText(navn);
buttonAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAB();
}
});
buttonAC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAC();
}
});
buttonAD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAD();
}
});
dialogKnapp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startDialog();
}
});
}
private void startAB() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void startAC() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityC.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void startAD() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityD.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void startDialog() {
BasicDialogFragment bdf = new BasicDialogFragment();
bdf.show(getFragmentManager(), "basic");
}
public void OnFragmentInteractionListener(String nameEntered){
visTekst();
}
private void visTekst() {
if(buttonOK.isPressed()){
textA2.setText(dialog_fornavn.getText());
Toast melding = Toast.makeText(getApplicationContext(),
dialog_fornavn.getText(), Toast.LENGTH_SHORT);
melding.show();
} else if(buttonCancel.isPressed()){
startAB();
}
}
#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_main, menu);
return true;
}
#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.
Toast toast = Toast.makeText(getApplicationContext(), "Activity A",
Toast.LENGTH_SHORT);
switch (item.getItemId()) {
case R.id.menu_item_1:
toast.setText("Activity A");
toast.show();
return true;
case R.id.menu_item_2:
toast.setText("Activity B");
toast.show();
startAB();
return true;
case R.id.menu_item_3:
toast.setText("Activity C");
toast.show();
startAC();
return true;
case R.id.menu_item_4:
toast.setText("Activity D");
toast.show();
startAD();
return true;
case R.id.action_settings:
toast.setText("Settings");
toast.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
BasicDialogFragment.java
import android.app.Activity;
import android.app.DialogFragment;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link BasicDialogFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link BasicDialogFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class BasicDialogFragment extends DialogFragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnNameEnteredListener {
public void OnFragmentInteractionListener(String nameEntered);
}
private OnNameEnteredListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment BasicDialogFragment.
*/
// TODO: Rename and change types and number of parameters
public static BasicDialogFragment newInstance(String param1, String param2) {
BasicDialogFragment fragment = new BasicDialogFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public BasicDialogFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_basic_dialog, container, false);
this.getDialog().setTitle("First Name");
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.OnFragmentInteractionListener("uri");
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnNameEnteredListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
fragment_basic_dialog.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" tools:context="no.hit.kvisli.heiverden.BasicDialogFragment"
android:layout_width="match_parent" android:layout_height="match_parent"
android:padding="10dp" android:orientation="vertical" >
<EditText
android:id="#+id/dialog_fornavn"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:textSize="24dp" android:textColor="#android:color/holo_red_dark"
android:hint="Skriv fornavn her" android:inputType="textPersonName" />
<LinearLayout
android:layout_width="match_parent" android:layout_height="wrap_content"
android:padding="10dp" android:orientation="horizontal" >
<Button
android:id="#+id/buttonCancel" android:text="Cancel"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
<Button
android:id="#+id/buttonOK" android:text="OK"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
activity_a.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<LinearLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/farge_A"
tools:context=".ActivityA">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity A"
android:id="#+id/textA"
style="#style/Overskrift"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textA2"
style="#style/Overskrift"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editA2"
style="#style/EditTekst"
android:hint="Skriv noe her"
android:layout_marginLeft="120dp"
android:layout_marginTop="50dp"/>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:layout_marginTop="150dp"
android:layout_marginLeft="50dp"
tools:context=".ActivityA">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dialog"
android:id="#+id/dialog_knapp"
android:background="#color/dialog_knapp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to B"
android:id="#+id/buttonAB"
android:background="#color/farge_B"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to C"
android:id="#+id/buttonAC"
android:background="#color/farge_C"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to D"
android:id="#+id/buttonAD"
android:background="#color/farge_D"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
If I am reading it correctly and your BasicDialogFragment code is like this
then all you need to do is add
public void OnNameEntered(String nameEntered){
//Do Something Here
}
to your ActivityA.java
EDIT
modify the following functions as follows:
private void visTekst(String nameEntered) {
if(buttonOK.isPressed()){
textA2.setText(nameEntered);
Toast melding = Toast.makeText(getApplicationContext(),
dialog_fornavn.getText(), Toast.LENGTH_SHORT);
melding.show();
} else if(buttonCancel.isPressed()){
startAB();
}
}
and call it as
public void OnFragmentInteractionListener(String nameEntered){
visTekst(nameEntered);
}
You need to setup your listeners as it is mentioned in the code that you have used
in your BasicDialogFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_basic_dialog, container, false);
this.getDialog().setTitle("First Name");
buttonCancel = (Button) findViewById(R.id.buttonCancel);
buttonOK = (Button) findViewById(R.id.buttonOK);
buttonCancel.setOnClickListner(new View.OnClickListener(View v){
onButtonPressed(/*Your custom URI*/Uri uri);
});
buttonOK .setOnClickListner(new View.OnClickListener(View v){
onButtonPressed(/*Your custom URI*/Uri uri);
});
return v;
}
For this issue, there are two ways, one is direct cast to hosted Activity to get activity instance. Another is using one interface that defined in DialogFragment but implemented by hosted Activity.
For detail please follow my previous post Call activity from DialogFragment.
//Here is the answer. Took a while but got it to the end, thanks for your help.
//ActivityA
import android.app.FragmentManager;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ActivityA extends ActionBarActivity implements BasicDialogFragment.Communicator {
private Button dialogKnapp = null;
private TextView textA = null;
private TextView textA2 = null;
private EditText editA2 = null;
private Button buttonAB = null;
private Button buttonAC = null;
private Button buttonAD = null;
private EditText dialog_fornavn = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
dialogKnapp = (Button) findViewById(R.id.dialog_knapp);
dialog_fornavn = (EditText) findViewById(R.id.dialog_fornavn);
textA = (TextView) findViewById(R.id.textA);
textA2 = (TextView) findViewById(R.id.textA2);
editA2 = (EditText) findViewById(R.id.editA2);
buttonAB = (Button) findViewById(R.id.buttonAB);
buttonAC = (Button) findViewById(R.id.buttonAC);
buttonAD = (Button) findViewById(R.id.buttonAD);
Intent intent = getIntent();
String navn = intent.getStringExtra("navnet");
textA2.setText(navn);
buttonAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAB();
}
});
buttonAC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAC();
}
});
buttonAD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAD();
}
});
dialogKnapp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startDialog();
}
});
}
private void startAB() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void startAC() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityC.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void startAD() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityD.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
public void startDialog(){
FragmentManager manager = getFragmentManager();
BasicDialogFragment basicDialogFragment = new BasicDialogFragment();
basicDialogFragment.show(manager,"BasicDialogFragment");
}
#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_main, menu);
return true;
}
#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.
Toast toast = Toast.makeText(getApplicationContext(), "Activity A",
Toast.LENGTH_SHORT);
switch (item.getItemId()) {
case R.id.menu_item_1:
toast.setText("Activity A");
toast.show();
return true;
case R.id.menu_item_2:
toast.setText("Activity B");
toast.show();
startAB();
return true;
case R.id.menu_item_3:
toast.setText("Activity C");
toast.show();
startAC();
return true;
case R.id.menu_item_4:
toast.setText("Activity D");
toast.show();
startAD();
return true;
case R.id.action_settings:
toast.setText("Settings");
toast.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onDialogMessage(Editable message) {
textA2.setText(message);
}
}
//BasicDialogFragment
`import android.app.Activity;
import android.app.DialogFragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class BasicDialogFragment extends DialogFragment implements View.OnClickListener{
private Button buttonCancel = null;
private Button buttonOK = null;
private EditText dialog_fornavn = null;
Communicator communicator;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
communicator= (Communicator) activity;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_basic_dialog, null);
buttonCancel = (Button) v.findViewById(R.id.buttonCancel);
buttonOK = (Button) v.findViewById(R.id.buttonOK);
dialog_fornavn = (EditText) v.findViewById(R.id.dialog_fornavn);
buttonCancel.setOnClickListener(this);
buttonOK.setOnClickListener(this);
setCancelable(true);
return v;
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.buttonOK){
communicator.onDialogMessage(dialog_fornavn.getText());
dismiss();
}
else{
dismiss();
}
}
interface Communicator{
public void onDialogMessage(Editable message);
}
}`
//Thats it, nothing chaged in xml files. Not sure if its good coding but worked for me.
Related
I am using bottom navigation bar dan fragment in my project.
When it moved from one to another fragment, I dont want to lose the state or data
How can I do it?
This is activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F9FAFD">
<FrameLayout
android:id="#+id/page_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_bar"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_alignParentBottom="true"
android:background="#android:color/white"
app:labelVisibilityMode="labeled"
app:menu="#menu/bottom_menu" />
</RelativeLayout>
And this is the MainActivity.java
package com.noval.tugas_6;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.noval.tugas_6.computer.ComputerFragment;
import com.noval.tugas_6.home.HomeFragment;
import com.noval.tugas_6.home_services.HomeServicesFragment;
import com.noval.tugas_6.phone.PhoneFragment;
public class MainActivity extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
private Fragment fragment;
private long exitTime = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigationView = findViewById(R.id.bottom_bar);
getFragmentPage(new HomeFragment());
setBottomNavigationView();
}
private void setBottomNavigationView() {
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
fragment = null;
switch (item.getItemId()) {
//id yang ada di menu bottom_menu.xml
case R.id.home_menu:
fragment = new HomeFragment();
break;
case R.id.computer_menu:
fragment = new ComputerFragment();
break;
case R.id.phone_menu:
fragment = new PhoneFragment();
break;
case R.id.home_services_menu:
fragment = new HomeServicesFragment();
break;
}
return getFragmentPage(fragment);
}
});
}
private boolean getFragmentPage(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.setReorderingAllowed(true)
.addToBackStack(null)
.replace(R.id.page_fragment, fragment)
.commit();
return true;
}
return false;
}
#Override
public void onBackPressed() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
System.exit(0);
}
}
}
This is one of the fragment that I am using
PhoneFragment.java
package com.noval.tugas_6.phone;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.noval.tugas_6.R;
public class PhoneFragment extends Fragment {
public int[] imgID = new int[]{R.drawable.infinix_zero, R.drawable.realme_c35,
R.drawable.galaxy_a33, R.drawable.samsung_galaxy_a13, R.drawable.samsung_galaxy_a23};
public String[] namaHP = new String[]{"Infinix Zero 5G", "Realme C35", "Samsung Galaxy A33 5G",
"Samsung Galaxy A13", "Samsung Galaxy A23"};
public String[] hargaHP = new String[]{"Rp3.600.000", "Rp2.150.000", "Rp4.700.000", "Rp2.500.000", "Rp3.500.000"};
ImageView imgHP;
TextView txtNama, txtHarga;
Button btnNext, btnPrevious;
int position = 0;
public PhoneFragment() {
// Required empty public constructor
}
// public static PhoneFragment newInstance() {
// PhoneFragment fragment = new PhoneFragment();
// Bundle args = new Bundle();
// fragment.setArguments(args);
// return fragment;
// }
//
// #Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// if (getArguments() != null) {
//
// }
// }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_phone, container, false);
}
// method ini dipanggil sesaat setelah onCreateView di atas dipanggil
// semua pembacaan view dan penambahan listener dilakukan disini
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
imgHP = (ImageView) getActivity().findViewById(R.id.imgHP);
txtNama = (TextView) getActivity().findViewById(R.id.txtNamaHP);
txtHarga = (TextView) getActivity().findViewById(R.id.txtHargaHP);
btnNext = (Button) getActivity().findViewById(R.id.btnNextHP);
btnPrevious = (Button) getActivity().findViewById(R.id.btnPreviousHP);
imgHP.setImageResource(imgID[position]);
txtNama.setText(namaHP[position]);
txtHarga.setText(hargaHP[position]);
btnPrevious.setVisibility(View.GONE);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
position += 1;
imgHP.setImageResource(imgID[position]);
txtNama.setText(namaHP[position]);
txtHarga.setText(hargaHP[position]);
// jika posisi item yang terakhir, hilangkan tombol next
if (position == (imgID.length - 1)) {
btnNext.setVisibility(View.GONE);
} else if (position > 0) {
btnPrevious.setVisibility(View.VISIBLE);
}
}
});
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
position -= 1;
imgHP.setImageResource(imgID[position]);
txtNama.setText(namaHP[position]);
txtHarga.setText(hargaHP[position]);
if (position == 0) {
btnPrevious.setVisibility(View.GONE);
} else {
btnNext.setVisibility(View.VISIBLE);
}
}
});
}
}
Please show me how to not lose the fragment data when moving to another fragment
Thanks
because every time user click on navigation bottom u create new instance of fragment every time :
private void setBottomNavigationView() {
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
fragment = null;
switch (item.getItemId()) {
//id yang ada di menu bottom_menu.xml
case R.id.home_menu:
fragment = new HomeFragment();
break;
case R.id.computer_menu:
fragment = new ComputerFragment();
break;
case R.id.phone_menu:
fragment = new PhoneFragment();
break;
case R.id.home_services_menu:
fragment = new HomeServicesFragment();
break;
}
return getFragmentPage(fragment);
}
});
}
try this :
private homeFragment = new HomeFragment();
private computerFragment = new ComputerFragment();
private phoneFragment = new PhoneFragment();
private homeServicesFragment = new HomeServicesFragment();
private Fragment active;
private final FragmentManager fm = getSupportFragmentManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
initFragment();
...
}
private void changeFragment(Fragment fragment, Bundle bundle) {
fm.beginTransaction()
.hide(active)
.show(fragment)
.commit();
active = fragment;
active.setArguments(bundle);
}
private void initFragment() {
fm.beginTransaction().add(R.id.frameLayout, homeFragment, homeFragment.class.getSimpleName()).commit();
fm.beginTransaction().add(R.id.frameLayout, computerFragment, computerFragment.class.getSimpleName()).hide(computerFragment).commit();
fm.beginTransaction().add(R.id.frameLayout, phoneFragment, PhoneFragment.class.getSimpleName()).hide(phoneFragment).commit();
fm.beginTransaction().add(R.id.frameLayout, homeServicesFragment, HomeServicesFragment.class.getSimpleName()).hide(homeServicesFragment).commit();
active = homeFragment;
changeFragment(homeFragment, null);
}
private void setBottomNavigationView() {
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
fragment = null;
switch (item.getItemId()) {
//id yang ada di menu bottom_menu.xml
case R.id.home_menu:
changeFragment(homeFragment, null);
return true;
case R.id.computer_menu:
changeFragment(computerFragment, null);
return true;
case R.id.phone_menu:
changeFragment(phoneFragment, null);
return true;
case R.id.home_services_menu:
changeFragment(homeServicesFragment, null);
return true;
}
return homeFragment;
}
});
}
web dev trying (and struggling) to have a go at android application development here. I'm trying to implement a side navigation into a login system so make my UI look nicer and generally give my app a nicer feel. The problem that I am having is;
Currently on the MainActivity (dashboard/ homescreen) of the application, I have a button which basically logs out the user from the login system which I am using with the following code.
Button logoutBtn = findViewById(R.id.btnLogout);
logoutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
session.logoutUser();
Intent i = new Intent(MainActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
});
The UI:
The above code works as expected, by logging out the user and re-directing them to the login/ register page. Now I've start to try and implement a side navigation I've found (https://antonioleiva.com/materialize-app/) and am struggling to work out how I can give the functionality of the above button to the navigation menu item as shown below;
The side navigation example I am using has the following code which basically presents a notification to show which side navigation menu item has being selected;
private void setupDrawerLayout() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
Snackbar.make(content, menuItem.getTitle() + " pressed", Snackbar.LENGTH_LONG).show();
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
});
}
This presents the following;
If anyone could give me any points, hints, or help on how I can give the menu option the functionality of the logout button it would be thoroughly appreciated as once I know how to set on click listeners/ run parts of code for menu selections I can proceed to load different activities and proceed building my application.
Thanks in advance SO.
The full code for the homescreen (MainActivity.java) is below;
package com.antonioleiva.materializeyourapp;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements
RecyclerViewAdapter.OnItemClickListener {
private SessionHandler session;
private static List<ViewModel> items = new ArrayList<>();
private DrawerLayout drawerLayout;
private View content;
private RecyclerView recyclerView;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session = new SessionHandler(getApplicationContext());
User user = session.getUserDetails();
TextView dashboardText = findViewById(R.id.dashboardText);
dashboardText.setText("Welcome to gluca, " + user.getFullName() + "!");
initRecyclerView();
initFab();
initToolbar();
setupDrawerLayout();
Button logoutBtn = findViewById(R.id.btnLogout);
logoutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
session.logoutUser();
Intent i = new Intent(MainActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
});
content = findViewById(R.id.content);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
setRecyclerAdapter(recyclerView);
}
}
#Override
public void onEnterAnimationComplete() {
super.onEnterAnimationComplete();
setRecyclerAdapter(recyclerView);
recyclerView.scheduleLayoutAnimation();
}
private void initRecyclerView() {
recyclerView = (RecyclerView) findViewById(R.id.recycler);
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
}
private void setRecyclerAdapter(RecyclerView recyclerView) {
RecyclerViewAdapter adapter = new RecyclerViewAdapter(items);
adapter.setOnItemClickListener(this);
recyclerView.setAdapter(adapter);
}
private void initFab() {
findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Snackbar.make(content, "FAB Clicked", Snackbar.LENGTH_SHORT).show();
}
});
}
private void initToolbar() {
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_black_24dp);
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
private void setupDrawerLayout() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
Snackbar.make(content, menuItem.getTitle() + " pressed", Snackbar.LENGTH_LONG).show();
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(View view, ViewModel viewModel) {
DetailActivity.navigate(this, view.findViewById(R.id.image), viewModel);
}
}
What if you pass logout actions to a new function , let say logout() and you put inside session.logoutUser();
Intent i = new Intent(MainActivity.this, LoginActivity.class);
startActivity(i);
finish();
Then, inside onOptionsItemSelected function you add a case check case (menuItem.getTitle =="Logout") {lougout();}
Of course it's just an idea but you can elaborate it
Below is the sample code for directly logout from menu
NOTE : No need of open new Activity or fragment for logout.
Here is Code:
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
fragment = new HomeFragment();
title.setText(pref.getString(Constants.REGIS_FIRST_NAME, "")+" "+pref.getString(Constants.REGIS_LAST_NAME, ""));
}
if (id == R.id.nav_profile) {
fragment = new ProfileFragment();
title.setText("My Profile ");
}
if (id == R.id.nav_past) {
fragment = new PastFragment();
title.setText("Past Ceremony ");
}
else if (id == R.id.nav_logout) {
callLogout(); //logout here
}
Here is the Dialog code :
private void callLogout() {
final Dialog dialog1;
dialog1 = new Dialog(MainActivity.this);
dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog1.setCancelable(false);
dialog1.setContentView(R.layout.logout_dilaog);
final TextView logoutTxt, yes, no;
yes = dialog1.findViewById(R.id.yes);
no = dialog1.findViewById(R.id.no);
logoutTxt = dialog1.findViewById(R.id.logoutTxt);
Log.e("NAME", "" + pref.getString("USER_NAME_LOGIN", ""));
logoutTxt.setText("Are you sure to logout ?");
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor = pref.edit();
editor.clear();
editor.apply();
// utils.showtoast("Logout");
finish();
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog1.dismiss();
}
});
dialog1.show();
}
logout_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_marginTop="10dp"
android:gravity="center_horizontal"
android:textSize="16dp"
android:fontFamily="#font/lato_semibold"
android:id="#+id/logoutTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black" />
<LinearLayout
android:gravity="right"
android:layout_marginTop="15dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/yes"
android:layout_marginRight="15dp"
android:layout_width="90dp"
android:layout_height="30dp"
android:text="YES"
android:fontFamily="#font/lato_regular"
android:gravity="center"
android:textColor="#color/white"
android:textSize="14dp"
android:background="#drawable/ripple_btn"
/>
<TextView
android:layout_marginRight="15dp"
android:id="#+id/no"
android:layout_width="90dp"
android:layout_height="30dp"
android:text="NO"
android:fontFamily="#font/lato_regular"
android:gravity="center"
android:textColor="#color/white"
android:textSize="14dp"
android:background="#drawable/ripple_btn"
/>
</LinearLayout>
I have created a sample app using the "Master / Detail flow" activity. I have added two buttons, Next and Prev to the detail activity. How to I set programmatically the buttons actions instead having to go back and forth between the List and detail?
item_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="30dp"
android:paddingEnd="30dp"
android:weightSum="4"
android:gravity="end"
android:orientation="horizontal">
<Button
android:id="#+id/button_prev"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Prev"/>
<Button
android:id="#+id/button_next"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Next"/>
</LinearLayout>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/item_detail"
style="?android:attr/textAppearanceLarge"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:textIsSelectable="true"
tools:context="co.test.app.sample.itemapplication.ItemDetailFragment"/>
</LinearLayout>
activity_item_detail.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="co.test.app.sample.itemapplication.ItemDetailActivity"
tools:ignore="MergeRootFrame">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="#dimen/app_bar_height"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:toolbarId="#+id/toolbar">
<android.support.v7.widget.Toolbar
android:id="#+id/detail_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:id="#+id/item_detail_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
DummyContent.java
package co.test.app.sample.itemapplication.dummy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Helper class for providing sample content for user interfaces created by
* Android template wizards.
* <p>
* TODO: Replace all uses of this class before publishing your app.
*/
public class DummyContent {
/**
* An array of sample (dummy) items.
*/
public static final List<DummyItem> ITEMS = new ArrayList<DummyItem>();
/**
* A map of sample (dummy) items, by ID.
*/
public static final Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>();
private static final int COUNT = 25;
static {
// Add some sample items.
for (int i = 1; i <= COUNT; i++) {
addItem(createDummyItem(i));
}
}
private static void addItem(DummyItem item) {
ITEMS.add(item);
ITEM_MAP.put(item.id, item);
}
private static DummyItem createDummyItem(int position) {
return new DummyItem(String.valueOf(position), "Item " + position, makeDetails(position));
}
private static String makeDetails(int position) {
StringBuilder builder = new StringBuilder();
builder.append("Details about Item: ").append(position);
for (int i = 0; i < position; i++) {
builder.append("\nMore details information here.");
}
return builder.toString();
}
/**
* A dummy item representing a piece of content.
*/
public static class DummyItem {
public final String id;
public final String content;
public final String details;
public DummyItem(String id, String content, String details) {
this.id = id;
this.content = content;
this.details = details;
}
#Override
public String toString() {
return content;
}
}
}
ItemDetailActivity.java
package co.test.app.sample.itemapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBar;
import android.view.MenuItem;
/**
* An activity representing a single Item detail screen. This
* activity is only used narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a {#link ItemListActivity}.
*/
public class ItemDetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
// Show the Up button in the action bar.
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID,
getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID));
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.item_detail_container, fragment)
.commit();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
navigateUpTo(new Intent(this, ItemListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
ItemListActivity.java
package co.test.app.sample.itemapplication;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import co.test.app.sample.itemapplication.dummy.DummyContent;
import java.util.List;
/**
* An activity representing a list of Items. This activity
* has different presentations for handset and tablet-size devices. On
* handsets, the activity presents a list of items, which when touched,
* lead to a {#link ItemDetailActivity} representing
* item details. On tablets, the activity presents the list of items and
* item details side-by-side using two vertical panes.
*/
public class ItemListActivity extends AppCompatActivity {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
View recyclerView = findViewById(R.id.item_list);
assert recyclerView != null;
setupRecyclerView((RecyclerView) recyclerView);
if (findViewById(R.id.item_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
}
}
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<DummyContent.DummyItem> mValues;
public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public DummyContent.DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
}
This is the code snippet used to forward to the detail page.
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
You can forward to any page by changing the value of arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
Use the above snippets in the onClick events of next and prev buttons. cheers :)
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
I am getting a NullPointerException at line 67 while trying to set a listView with a chat adapter. Here is the class:
I have placed ** around the line I am getting the NullPointerException on. I'm not really understading why its returning as null when I'm setting messageAdapter to a new object of an inner class called ChatAdapter(this).
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MessageListActivity extends AppCompatActivity {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
ListView listView;
Button sendButton;
ArrayList<String> arrayList = new ArrayList<String>();
ChatDatabaseHelper Cdb;
private boolean mTwoPane;
ChatAdapter messageAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
listView = (ListView)findViewById(R.id.chatListView);
final EditText editText = (EditText)findViewById(R.id.messageText);
sendButton = (Button)findViewById(R.id.sendButton);
messageAdapter = new ChatAdapter(this); // chatAdapter is a built in adapater
**listView.setAdapter(messageAdapter);**
Cdb = new ChatDatabaseHelper(this);
Cursor cursor = Cdb.getMessages(); // get messages method is of type Cursor from database helper class
// cursor will move through the database to find the next text if there is any.
while (cursor.moveToNext()) { arrayList.add(cursor.getString(cursor.getColumnIndex(Cdb.KEY_MESSAGE))); }
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { // on click listener for the send button
String chatText = editText.getText().toString(); // changing editText to String
arrayList.add(chatText); // adding the string from EditTest to arrayList
boolean isInserted = Cdb.insertData(chatText); // inserting the message text into the database
if(isInserted = true)
{ Toast.makeText(MessageListActivity.this,"Message Sent",Toast.LENGTH_SHORT).show(); } // if the message inserts into the database this toast will show
else {
Toast.makeText(MessageListActivity.this,"Message not Sent",Toast.LENGTH_SHORT).show(); } // if message does not nter the database this toast will show
messageAdapter.notifyDataSetChanged(); // notifying the adapter that a message has been sent, changing from incoming to outgoing
editText.setText(" "); // set the text on the send button to blank.
} // end of onClick view
}); // end of onClickListener
if (findViewById(R.id.message_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
}
}
class ChatAdapter extends ArrayAdapter<String> { // custom adapter class // when youc all the adapter it forms the for loop for you.
public ChatAdapter(MessageListActivity ctx) {
super(ctx, 0);
} // default constructor
// method to return the number of rows that will be in your array
// will tell how many times to run a for loop
public int getCount(){ return arrayList.size(); } // will return the size of the array
public String getItem(int position){ return arrayList.get(position); } // will return the item at position
// getview method
#Override
public View getView(int position, final View convertView, ViewGroup parent) {// inner class
LayoutInflater Inflater = MessageListActivity.this.getLayoutInflater(); // an inflater inflates the xml layout into a view.
View result = null;
if(position%2 == 0){ // if position number in the array is odd do this, if number is even, do this.
result = Inflater.inflate(R.layout.chat_row_incoming, null); // depending on the position, show layout incoming
} else {
result = Inflater.inflate(R.layout.chat_row_outgoing,null); // depending on the position, show layout outgoing
}
TextView message = (TextView)result.findViewById(R.id.messageText); // creating a message of type TextView connected to messageText
final String messageText = getItem(position) ;
message.setText(messageText);
result.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(MessageDetailFragment.ARG_ITEM_ID,messageText );
MessageDetailFragment fragment = new MessageDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.message_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, MessageDetailActivity.class);
intent.putExtra(MessageDetailFragment.ARG_ITEM_ID,messageText );
context.startActivity(intent);
}
}
});
return result; // return the view which is the Inflater.
}
} // end of chat adapter class
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<DummyContent.DummyItem> mValues;
public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.message_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(MessageDetailFragment.ARG_ITEM_ID, holder.mItem.id);
MessageDetailFragment fragment = new MessageDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.message_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, MessageDetailActivity.class);
intent.putExtra(MessageDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public DummyContent.DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ChatWindow">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/chatListView"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="false"
android:layout_alignWithParentIfMissing="false"
android:layout_above="#+id/sendButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/sendButton"
android:id="#+id/sendButton"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:singleLine="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/messageText"
android:layout_toStartOf="#id/sendButton"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:enabled="true"
/>
</RelativeLayout>
just try
messageAdapter = new ChatAdapter(MessageListActivity .this);
I'm a beginner in android development. I'm trying to send data from an ArrayList of Type Workout Item to the MainActivity using an Adapter, but I don't understand base adapters very well. Here is my code:
WorkoutActivity.java:
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;
public class WorkoutActivity extends Activity {
WorkoutItemAdapter workoutItemAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_workout);
}
public class WorkoutItemAdapter extends BaseAdapter{
int rowCount = 1;
List<WorkoutItem> workoutsList = getDataForListView();
public WorkoutItem getWorkout(int position)
{
return workoutsList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) WorkoutActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.workout_item, parent, false);
}
TextView workoutNum = (TextView) convertView.findViewById(R.id.workout_col);
TextView workoutTime = (TextView) convertView.findViewById(R.id.time_col);
WorkoutItem workout = workoutsList.get(position);
workoutNum.setText(workout.workoutNum);
workoutTime.setText(workout.time);
return convertView;
}
#Override
public int getCount() {
return workoutsList.size();
// TODO Auto-generated method stub
}
#Override
public WorkoutItem getItem(int position) {
// TODO Auto-generated method stub
return workoutsList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public void addRow() {
rowCount++;
notifyDataSetChanged();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.workout, menu);
return true;
}
#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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
public List<WorkoutItem> getDataForListView()
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String workoutTime = prefs.getString("Workout Time", "");
List<WorkoutItem> workoutsList = new ArrayList<WorkoutItem>();
for(int i = 0; i < (workoutsList.size() + 1); i++)
{
WorkoutItem workout = new WorkoutItem();
workout.workoutNum = "Workout " + (i+1);
workout.time = workoutTime;
workoutsList.add(workout);
}
return workoutsList;
}
public void startAndStopTimer(View view)
{
long totalTime = 0;
Button startAndStop = (Button) findViewById(R.id.button1);
Chronometer c = (Chronometer) findViewById(R.id.chronometer1);
if(startAndStop.getText().equals("Start"))
{
c.setBase(SystemClock.elapsedRealtime() + totalTime);
c.start();
startAndStop.setText("Pause");
}
else
{
totalTime = c.getBase() - SystemClock.elapsedRealtime();
c.stop();
startAndStop.setText("Start");
}
}
public void save(View view)
{
// create broadcast receiver saying ...saved.
// Add ArrayList value to arrayList
Chronometer timer = (Chronometer) findViewById(R.id.chronometer1);
SharedPreferences timerSettings = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = timerSettings.edit();
editor.putString("Workout Time", timer.getText().toString());
editor.commit();
// go back to main activity.
Intent intent = new Intent(WorkoutActivity.this, OverviewActivity.class);
startActivity(intent);
finish();
}
public void cancel(View view)
{
// go back to main activity
Intent intent = new Intent(WorkoutActivity.this, OverviewActivity.class);
startActivity(intent);
finish();
}
}
OverviewActivity.java:
import edu.uark.csce.razorrunner.WorkoutActivity.WorkoutItemAdapter;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
public class OverviewActivity extends Activity{
WorkoutItemAdapter workoutAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_overview);
LoadPreferences();
LoadListView();
}
private void LoadListView() {
// TODO Auto-generated method stub
ListView workoutList = (ListView) findViewById(R.id.workout_list);
workoutList.setAdapter(workoutAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.overview, menu);
return true;
}
#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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void LoadPreferences()
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String Name = sharedPreferences.getString("Name", "");
TextView textView = (TextView) findViewById(R.id.textView2);
textView.setText(Name);
}
public void openWorkoutActivity(View view)
{
Intent intent = new Intent(OverviewActivity.this, WorkoutActivity.class);
startActivity(intent);
finish();
}
public void openProfileActivity(View view)
{
Intent intent = new Intent(OverviewActivity.this, ProfileActivity.class);
startActivity(intent);
finish();
}
public void openHistoryActivity(View view)
{
Intent intent = new Intent(OverviewActivity.this, HistoryActivity.class);
startActivity(intent);
finish();
}
}
activity_overview.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="edu.uark.csce.razorrunner.OverviewActivity" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/profileButton"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:onClick="openProfileActivity"
android:text="Profile" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
<ListView
android:id="#+id/workout_list"
android:layout_width="wrap_content"
android:layout_height="195dp"
android:layout_weight="0.19" >
</ListView>
<Button
android:id="#+id/startNewWorkout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:onClick="openWorkoutActivity"
android:text="Start New Workout!"
android:typeface="sans" />
</LinearLayout>
activity_workout.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="edu.uark.csce.razorrunner.WorkoutActivity" >
<Button
android:id="#+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button2"
android:layout_alignBottom="#+id/button2"
android:layout_alignRight="#+id/button1"
android:text="Cancel"
android:onClick="cancel" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/Button01"
android:text="Save"
android:onClick="save" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Button01"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_marginRight="22dp"
android:text="Start"
android:onClick="startAndStopTimer" />
<TextView
android:id="#+id/time_col"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_alignParentTop="true"
android:text="New Workout"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/time_col"
android:layout_marginTop="18dp"
android:text="Calories Burned"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/textView2"
android:layout_marginTop="14dp"
android:text="Duration"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/TextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView2"
android:layout_alignBottom="#+id/textView2"
android:layout_alignRight="#+id/button1"
android:layout_toRightOf="#+id/button2"
android:ems="10"
android:text="0"
android:textAppearance="?android:attr/textAppearanceLarge">
<requestFocus />
</TextView>
<Chronometer
android:id="#+id/chronometer1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/TextView01"
android:layout_alignLeft="#+id/TextView1"
android:layout_alignRight="#+id/TextView1"
android:text="Chronometer" />
</RelativeLayout>
I'd like to show the workout number and duration for each list item every time I click Save, but currently all I get is a blank ListView every time I click Save. Any help and/or additional sources on this topic would be useful.
I hope two mistakes you made.
public List<WorkoutItem> getDataForListView()
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String workoutTime = prefs.getString("Workout Time", "");
List<WorkoutItem> workoutsList = new ArrayList<WorkoutItem>();
for(int i = 0; i < (workoutsList.size() + 1); i++)
{
WorkoutItem workout = new WorkoutItem();
workout.workoutNum = "Workout " + (i+1);
workout.time = workoutTime;
workoutsList.add(workout);
}
return workoutsList;
}
I guess you are trying to add data to list view. Since you are creating new List using
List<WorkoutItem> workoutsList = new ArrayList<WorkoutItem>();
workoutsList.size() will return zero. your loop iterates till list size+1. (only one time )
then you need to pass the List from WorkoutActivity to OverviewActivity.
change WorkoutActivity insert following code
public class WorkoutActivity extends Activity {
WorkoutItemAdapter workoutItemAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_workout);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.workout, menu);
return true;
}
#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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
public List<WorkoutItem> getDataForListView() {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
String workoutTime = prefs.getString("Workout Time", "");
List<WorkoutItem> workoutsList = new ArrayList<WorkoutItem>();
for (int i = 0; i < (10+ 1); i++) {
WorkoutItem workout = new WorkoutItem();
workout.workoutNum = "Workout " + (i + 1);
workout.time = workoutTime;
workoutsList.add(workout);
}
return workoutsList;
}
public void startAndStopTimer(View view) {
long totalTime = 0;
Button startAndStop = (Button) findViewById(R.id.button1);
Chronometer c = (Chronometer) findViewById(R.id.chronometer1);
if (startAndStop.getText().equals("Start")) {
c.setBase(SystemClock.elapsedRealtime() + totalTime);
c.start();
startAndStop.setText("Pause");
} else {
totalTime = c.getBase() - SystemClock.elapsedRealtime();
c.stop();
startAndStop.setText("Start");
}
}
public void save(View view) {
// create broadcast receiver saying ...saved.
// Add ArrayList value to arrayList
Chronometer timer = (Chronometer) findViewById(R.id.chronometer1);
SharedPreferences timerSettings = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = timerSettings.edit();
editor.putString("Workout Time", timer.getText().toString());
editor.commit();
// go back to main activity.
Intent intent = new Intent(WorkoutActivity.this, OverviewActivity.class);
intent.putStringArrayListExtra("stock_list", getDataForListView());
startActivity(intent);
finish();
}
public void cancel(View view) {
// go back to main activity
Intent intent = new Intent(WorkoutActivity.this, OverviewActivity.class);
intent.putStringArrayListExtra("stock_list", getDataForListView());
startActivity(intent);
finish();
}
}
and OverviewActivity to this
public class OverviewActivity extends Activity{
List<WorkoutItem> workList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_overview);
Intent i = getIntent();
workList = i.getStringArrayListExtra("stock_list");
LoadPreferences();
LoadListView();
}
private void LoadListView() {
// TODO Auto-generated method stub
ListView workoutList = (ListView) findViewById(R.id.workout_list);
WorkoutItemAdapter workoutAdapter= new WorkoutItemAdapter(workList);
workoutList.setAdapter(workoutAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.overview, menu);
return true;
}
#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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void LoadPreferences()
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String Name = sharedPreferences.getString("Name", "");
TextView textView = (TextView) findViewById(R.id.textView2);
textView.setText(Name);
}
public void openWorkoutActivity(View view)
{
Intent intent = new Intent(OverviewActivity.this, WorkoutActivity.class);
startActivity(intent);
finish();
}
public void openProfileActivity(View view)
{
Intent intent = new Intent(OverviewActivity.this, ProfileActivity.class);
startActivity(intent);
finish();
}
public void openHistoryActivity(View view)
{
Intent intent = new Intent(OverviewActivity.this, HistoryActivity.class);
startActivity(intent);
finish();
}
public class WorkoutItemAdapter extends BaseAdapter{
int rowCount = 1;
List<WorkoutItem> workoutsList ;
public WorkoutItemAdapter( List<WorkoutItem> list) {
workoutsList=list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) WorkoutActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.workout_item, parent, false);
}
TextView workoutNum = (TextView) convertView.findViewById(R.id.workout_col);
TextView workoutTime = (TextView) convertView.findViewById(R.id.time_col);
WorkoutItem workout = workoutsList.get(position);
workoutNum.setText(workout.workoutNum);
workoutTime.setText(workout.time);
return convertView;
}
#Override
public int getCount() {
return workoutsList.size();
// TODO Auto-generated method stub
}
#Override
public WorkoutItem getItem(int position) {
// TODO Auto-generated method stub
return workoutsList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public void addRow() {
rowCount++;
notifyDataSetChanged();
}
}
}
try these code. I have not yet tried, hope will works fine.
So I assume OverviewActivity.java is your main Activity which in return opens WorkoutActivity ?
you haven't initialise workoutAdapter...only declared....
hence workoutAdapter is null....which means the size of adapter is 0 ...which means no rows for list view...
before setting the adapter to listview ..you must have to initialize workoutAdapter
i.e.
workoutAdapter=new WorkoutItemAdapter(getDataForListView());
create the adaper contructor and pass the list array
public class WorkoutItemAdapter extends BaseAdapter{
int rowCount = 1; //don't know about that
List<WorkoutItem> workoutsList;
public WorkoutItemAdapter(List<WorkoutItem> tmp)
{
this.workoutsList=tmp; //setting the list array to datamember of this adapter
}
In WorkOutItemAdapter List<WorkoutItem> workoutsList = getDataForListView();
// check the size of the list is zero or null
In WorkOutItemActivity you do like this
WorkoutItemAdapter workoutItemAdapter = new WorkoutItemAdapter();
ListView workoutList = (ListView) findViewById(R.id.workout_list);
workoutList.setAdapter(workoutAdapter);*