I am setting text to a custom dialog box. I am getting a NullPointerException. The dialog is called when a listItem is clicked. EDIT, Scroll to the bottom to see updated code. Or See here:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HomeItem homeItem = (HomeItem) adapter.getItem(position);
DialogClass dialogClass = new DialogClass(databaseFightCard.this);
dialogClass.setDialog(homeItem.getHomeItemRedName(), homeItem.getHomeItemRedAge(), homeItem.getHomeItemRedRecord(),
homeItem.getHomeItemRedHeight(), homeItem.getHomeItemRedWeight(), homeItem.getHomeItemRedCity(), homeItem.getHomeItemRedExp(),
homeItem.getHomeItemBlueName(), homeItem.getHomeItemBlueAge(), homeItem.getHomeItemBlueRecord(), homeItem.getHomeItemBlueHeight(),
homeItem.getHomeItemBlueWeight(), homeItem.getHomeItemBlueCity(), homeItem.getHomeItemBlueExp());
dialogClass.show();
}
});
DialogClass
public class DialogClass extends Dialog implements View.OnClickListener {
public Activity c;
public Dialog d;
public Button yes, no;
public TextView rn, ra, rr, rh, rw, rc, re, bn, ba, br, bh, bw, bc, be;
public void setDialog(String redName, String redAge, String redRecord, String redHeight,
String redWeight, String redCity, String redExp,String blueName, String blueAge,
String blueRecord, String blueHeight,
String blueWeight, String blueCity, String blueExp){
rn = (TextView) findViewById(R.id.tvRName);
ra = (TextView) findViewById(R.id.tvRAge);
rr = (TextView) findViewById(R.id.tvRRecord);
rh = (TextView) findViewById(R.id.tvRHeight);
rw = (TextView) findViewById(R.id.tvRWeight);
rc = (TextView) findViewById(R.id.tvRCity);
re = (TextView) findViewById(R.id.tvRExp);
bn = (TextView) findViewById(R.id.tvBName);
ba = (TextView) findViewById(R.id.tvBAge);
br = (TextView) findViewById(R.id.tvBRecord);
bh = (TextView) findViewById(R.id.tvBHeight);
bw = (TextView) findViewById(R.id.tvBWeight);
bc = (TextView) findViewById(R.id.tvBCity);
be = (TextView) findViewById(R.id.tvBExp);
<----------Where the NullPointer is being thrown----------->
rn.setText(redName);
ra.setText(redAge);
rr.setText(redRecord);
rh.setText(redHeight);
rw.setText(redWeight);
rc.setText(redCity);
re.setText(redExp);
bn.setText(blueName);
ba.setText(blueAge);
br.setText(blueRecord);
bh.setText(blueHeight);
bw.setText(blueWeight);
bc.setText(blueCity);
be.setText(blueExp);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog);
yes = (Button) findViewById(R.id.bPlay);
no = (Button) findViewById(R.id.bDone);
yes.setOnClickListener(this);
no.setOnClickListener(this);
}
public DialogClass(Activity a) {
super(a);
this.c = a;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bPlay:
dismiss();
break;
case R.id.bDone:
dismiss();
break;
default:
break;
}
dismiss();
}
}
LogCat
10-05 18:48:01.843 994-994/com.codealchemist.clashmma E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.codealchemist.clashmma.DialogClass.setDialog(DialogClass.java:43)
at com.codealchemist.clashmma.databaseFightCard$1.onItemClick(databaseFightCard.java:71)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
at android.widget.AbsListView$1.run(AbsListView.java:3423)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
The LogCat is point to my DialogClass on the line
rn.setText(redName);
I have never set the text to a custom built dialog, so please explain what I am doing wrong.
EDIT DUE TO blackbelt This is how I tried to do a class member. If it is not obvious by my reputation, I am a beginner so please explain a better way to do this:
Changed this in my activity that calls for the dialog
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HomeItem homeItem = (HomeItem) adapter.getItem(position);
DialogClass dialogClass = new DialogClass(homeItem);
dialogClass.show();
}
});
Changed this in my DialogClass
public DialogClass(HomeItem context) {
super(context);
this.hi = context;
}
Then in my onCreate of my DialogClass:
rn.setText(hi.getHomeItemRedName());
bn.setText(hi.getHomeItemBlueName());
Because I had to use Context of HomeItem, or whatever I did I have to make my HomeItem class extend Context. I had to #Override about 80 methods:
public class HomeItem extends Context {
private int HomeItemID;
private String HomeItemRedName, HomeItemRedAge, HomeItemRedRecord, HomeItemRedHeight, HomeItemRedWeight,
HomeItemRedCity, HomeItemRedExp;
private String HomeItemBlueName, HomeItemBlueAge, HomeItemBlueRecord, HomeItemBlueHeight, HomeItemBlueWeight,
HomeItemBlueCity, HomeItemBlueExp;
public int getHomeItemID() {
return HomeItemID;
}
public void setHomeItemID(int ID) {
this.HomeItemID = ID;
}
public String getHomeItemRedName() {
return HomeItemRedName;
}
public void setHomeItemRedName(String Name) {
this.HomeItemRedName = Name;
}
public String getHomeItemRedAge(){
return HomeItemRedAge;
}
public void setHomeItemRedAge(String Age){
if (Age == null)
this.HomeItemRedAge = "Unknown";
this.HomeItemRedAge = Age;
}
public String getHomeItemRedRecord(){
return HomeItemRedRecord;
}
public void setHomeItemRedRecord(String Record){
if (Record == null)
this.HomeItemRedRecord = "Unknown";
this.HomeItemRedRecord = Record;
}
public String getHomeItemRedHeight(){
return HomeItemRedHeight;
}
public void setHomeItemRedHeight(String Height){
if (Height == null)
this.HomeItemRedHeight = "Unknown";
this.HomeItemRedHeight = Height;
}
public String getHomeItemRedWeight(){
return HomeItemRedWeight;
}
public void setHomeItemRedWeight(String Weight){
if (Weight == null)
this.HomeItemRedWeight = "Unknown";
this.HomeItemRedWeight = Weight;
}
public String getHomeItemRedCity(){
return HomeItemRedCity;
}
public void setHomeItemRedCity(String City){
if (City == null)
this.HomeItemRedCity = "Unknown";
this.HomeItemRedCity = City;
}
public String getHomeItemRedExp(){
return HomeItemRedExp;
}
public void setHomeItemRedExp(String Exp){
if (Exp == null)
this.HomeItemRedExp = "Unknown";
this.HomeItemRedExp = Exp;
}
//Blue side
public String getHomeItemBlueName(){
return HomeItemBlueName;
}
public void setHomeItemBlueName(String Name){
this.HomeItemBlueName = Name;
}
public String getHomeItemBlueAge(){
return HomeItemBlueAge;
}
public void setHomeItemBlueAge(String Age){
if (Age == null)
this.HomeItemBlueAge = "Unknown";
this.HomeItemBlueAge = Age;
}
public String getHomeItemBlueRecord(){
return HomeItemBlueRecord;
}
public void setHomeItemBlueRecord(String Record){
if (Record == null)
this.HomeItemBlueRecord = "Unknown";
this.HomeItemBlueRecord = Record;
}
public String getHomeItemBlueHeight(){
return HomeItemBlueHeight;
}
public void setHomeItemBlueHeight(String Height){
if (Height == null)
this.HomeItemBlueHeight = "Unknown";
this.HomeItemBlueHeight = Height;
}
public String getHomeItemBlueWeight(){
return HomeItemBlueWeight;
}
public void setHomeItemBlueWeight(String Weight){
if (Weight == null)
this.HomeItemBlueWeight = "Unknown";
this.HomeItemBlueWeight = Weight;
}
public String getHomeItemBlueCity(){
return HomeItemBlueCity;
}
public void setHomeItemBlueCity(String City){
if (City == null)
this.HomeItemBlueCity = "Unknown";
this.HomeItemBlueCity= City;
}
public String getHomeItemBlueExp(){
return HomeItemBlueExp;
}
public void setHomeItemBlueExp(String Exp){
if (Exp == null)
this.HomeItemBlueExp = "Unknown";
this.HomeItemBlueExp = Exp;
}
#Override
public AssetManager getAssets() {
return null;
}
#Override
public Resources getResources() {
return null;
}
#Override
public PackageManager getPackageManager() {
return null;
}
#Override
public ContentResolver getContentResolver() {
return null;
}
#Override
public Looper getMainLooper() {
return null;
}
#Override
public Context getApplicationContext() {
return null;
}
#Override
public void setTheme(int i) {
}
#Override
public Resources.Theme getTheme() {
return null;
}
#Override
public ClassLoader getClassLoader() {
return null;
}
#Override
public String getPackageName() {
return null;
}
#Override
public ApplicationInfo getApplicationInfo() {
return null;
}
#Override
public String getPackageResourcePath() {
return null;
}
#Override
public String getPackageCodePath() {
return null;
}
#Override
public SharedPreferences getSharedPreferences(String s, int i) {
return null;
}
#Override
public FileInputStream openFileInput(String s) throws FileNotFoundException {
return null;
}
#Override
public FileOutputStream openFileOutput(String s, int i) throws FileNotFoundException {
return null;
}
#Override
public boolean deleteFile(String s) {
return false;
}
#Override
public File getFileStreamPath(String s) {
return null;
}
#Override
public File getFilesDir() {
return null;
}
#Override
public File getExternalFilesDir(String s) {
return null;
}
#Override
public File getObbDir() {
return null;
}
#Override
public File getCacheDir() {
return null;
}
#Override
public File getExternalCacheDir() {
return null;
}
#Override
public String[] fileList() {
return new String[0];
}
#Override
public File getDir(String s, int i) {
return null;
}
#Override
public SQLiteDatabase openOrCreateDatabase(String s, int i, SQLiteDatabase.CursorFactory cursorFactory) {
return null;
}
#Override
public SQLiteDatabase openOrCreateDatabase(String s, int i, SQLiteDatabase.CursorFactory cursorFactory, DatabaseErrorHandler databaseErrorHandler) {
return null;
}
#Override
public boolean deleteDatabase(String s) {
return false;
}
#Override
public File getDatabasePath(String s) {
return null;
}
#Override
public String[] databaseList() {
return new String[0];
}
#Override
public Drawable getWallpaper() {
return null;
}
#Override
public Drawable peekWallpaper() {
return null;
}
#Override
public int getWallpaperDesiredMinimumWidth() {
return 0;
}
#Override
public int getWallpaperDesiredMinimumHeight() {
return 0;
}
#Override
public void setWallpaper(Bitmap bitmap) throws IOException {
}
#Override
public void setWallpaper(InputStream inputStream) throws IOException {
}
#Override
public void clearWallpaper() throws IOException {
}
#Override
public void startActivity(Intent intent) {
}
#Override
public void startActivity(Intent intent, Bundle bundle) {
}
#Override
public void startActivities(Intent[] intents) {
}
#Override
public void startActivities(Intent[] intents, Bundle bundle) {
}
#Override
public void startIntentSender(IntentSender intentSender, Intent intent, int i, int i2, int i3) throws IntentSender.SendIntentException {
}
#Override
public void startIntentSender(IntentSender intentSender, Intent intent, int i, int i2, int i3, Bundle bundle) throws IntentSender.SendIntentException {
}
#Override
public void sendBroadcast(Intent intent) {
}
#Override
public void sendBroadcast(Intent intent, String s) {
}
#Override
public void sendOrderedBroadcast(Intent intent, String s) {
}
#Override
public void sendOrderedBroadcast(Intent intent, String s, BroadcastReceiver broadcastReceiver, Handler handler, int i, String s2, Bundle bundle) {
}
#Override
public void sendBroadcastAsUser(Intent intent, UserHandle userHandle) {
}
#Override
public void sendBroadcastAsUser(Intent intent, UserHandle userHandle, String s) {
}
#Override
public void sendOrderedBroadcastAsUser(Intent intent, UserHandle userHandle, String s, BroadcastReceiver broadcastReceiver, Handler handler, int i, String s2, Bundle bundle) {
}
#Override
public void sendStickyBroadcast(Intent intent) {
}
#Override
public void sendStickyOrderedBroadcast(Intent intent, BroadcastReceiver broadcastReceiver, Handler handler, int i, String s, Bundle bundle) {
}
#Override
public void removeStickyBroadcast(Intent intent) {
}
#Override
public void sendStickyBroadcastAsUser(Intent intent, UserHandle userHandle) {
}
#Override
public void sendStickyOrderedBroadcastAsUser(Intent intent, UserHandle userHandle, BroadcastReceiver broadcastReceiver, Handler handler, int i, String s, Bundle bundle) {
}
#Override
public void removeStickyBroadcastAsUser(Intent intent, UserHandle userHandle) {
}
#Override
public Intent registerReceiver(BroadcastReceiver broadcastReceiver, IntentFilter intentFilter) {
return null;
}
#Override
public Intent registerReceiver(BroadcastReceiver broadcastReceiver, IntentFilter intentFilter, String s, Handler handler) {
return null;
}
#Override
public void unregisterReceiver(BroadcastReceiver broadcastReceiver) {
}
#Override
public ComponentName startService(Intent intent) {
return null;
}
#Override
public boolean stopService(Intent intent) {
return false;
}
#Override
public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
return false;
}
#Override
public void unbindService(ServiceConnection serviceConnection) {
}
#Override
public boolean startInstrumentation(ComponentName componentName, String s, Bundle bundle) {
return false;
}
#Override
public Object getSystemService(String s) {
return null;
}
#Override
public int checkPermission(String s, int i, int i2) {
return 0;
}
#Override
public int checkCallingPermission(String s) {
return 0;
}
#Override
public int checkCallingOrSelfPermission(String s) {
return 0;
}
#Override
public void enforcePermission(String s, int i, int i2, String s2) {
}
#Override
public void enforceCallingPermission(String s, String s2) {
}
#Override
public void enforceCallingOrSelfPermission(String s, String s2) {
}
#Override
public void grantUriPermission(String s, Uri uri, int i) {
}
#Override
public void revokeUriPermission(Uri uri, int i) {
}
#Override
public int checkUriPermission(Uri uri, int i, int i2, int i3) {
return 0;
}
#Override
public int checkCallingUriPermission(Uri uri, int i) {
return 0;
}
#Override
public int checkCallingOrSelfUriPermission(Uri uri, int i) {
return 0;
}
#Override
public int checkUriPermission(Uri uri, String s, String s2, int i, int i2, int i3) {
return 0;
}
#Override
public void enforceUriPermission(Uri uri, int i, int i2, int i3, String s) {
}
#Override
public void enforceCallingUriPermission(Uri uri, int i, String s) {
}
#Override
public void enforceCallingOrSelfUriPermission(Uri uri, int i, String s) {
}
#Override
public void enforceUriPermission(Uri uri, String s, String s2, int i, int i2, int i3, String s3) {
}
#Override
public Context createPackageContext(String s, int i) throws PackageManager.NameNotFoundException {
return null;
}
#Override
public Context createConfigurationContext(Configuration configuration) {
return null;
}
#Override
public Context createDisplayContext(Display display) {
return null;
}
Compiling this, in my LogCat, I receive this error:
10-06 18:42:59.465 785-785/com.codealchemist.clashmma E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.Dialog.<init>(Dialog.java:154)
at android.app.Dialog.<init>(Dialog.java:131)
at com.codealchemist.clashmma.DialogClass.<init>(DialogClass.java:83)
at com.codealchemist.clashmma.databaseFightCard$1.onItemClick(databaseFightCard.java:70)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
at android.widget.AbsListView$1.run(AbsListView.java:3423)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
I ALSO TRIED THIS
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HomeItem homeItem = (HomeItem) adapter.getItem(position);
final Dialog dialog = new Dialog(databaseFightCard.this, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
WindowManager.LayoutParams lp = (dialog.getWindow().getAttributes());
lp.dimAmount = 0.5f;
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
Window window = dialog.getWindow();
window.setGravity(Gravity.CENTER);
dialog.setContentView(R.layout.custom_dialog);
Button play = (Button) findViewById(R.id.bPlay);
Button done = (Button) findViewById(R.id.bDone);
TextView rn = (TextView) findViewById(R.id.tvRName);
TextView ra = (TextView) findViewById(R.id.tvRAge);
TextView rr = (TextView) findViewById(R.id.tvRRecord);
TextView rh = (TextView) findViewById(R.id.tvRHeight);
TextView rw = (TextView) findViewById(R.id.tvRWeight);
TextView rc = (TextView) findViewById(R.id.tvRCity);
TextView re = (TextView) findViewById(R.id.tvRExp);
TextView bn = (TextView) findViewById(R.id.tvBName);
TextView ba = (TextView) findViewById(R.id.tvBAge);
TextView br = (TextView) findViewById(R.id.tvBRecord);
TextView bh = (TextView) findViewById(R.id.tvBHeight);
TextView bw = (TextView) findViewById(R.id.tvBWeight);
TextView bc = (TextView) findViewById(R.id.tvBCity);
TextView be = (TextView) findViewById(R.id.tvBExp);
rn.setText(homeItem.getHomeItemRedName()+"");
ra.setText(homeItem.getHomeItemRedAge()+"");
rr.setText(homeItem.getHomeItemRedRecord()+"");
rh.setText(homeItem.getHomeItemRedHeight()+"");
rw.setText(homeItem.getHomeItemRedWeight()+"");
rc.setText(homeItem.getHomeItemRedCity()+"");
re.setText(homeItem.getHomeItemRedExp()+"");
bn.setText(homeItem.getHomeItemBlueName()+"");
ba.setText(homeItem.getHomeItemBlueAge()+"");
br.setText(homeItem.getHomeItemBlueRecord()+"");
bh.setText(homeItem.getHomeItemBlueHeight()+"");
bw.setText(homeItem.getHomeItemBlueWeight()+"");
bc.setText(homeItem.getHomeItemBlueCity()+"");
be.setText(homeItem.getHomeItemBlueExp()+"");
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
}
});
Still getting NullPointerException on
rn.setText(homeItem.getHomeItemRedName()+"");
setDialog is called before the Dialog's onCreate . Instead of passing all the Strings to setDialog you can pass a HomeItem reference and you can keep it as class member. Inside the onCreate, after setContentView you can perform all the findViewById and set the text accordingly
Edit
public class DialogClass extends Dialog implements View.OnClickListener {
public Activity c;
public Dialog d;
public Button yes, no;
public TextView rn, ra, rr, rh, rw, rc, re, bn, ba, br, bh, bw, bc, be;
private HomeItem homeItem;
public void setDialog(HomeItem homeItem){
this.homeItem = homeItem;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog);
yes = (Button) findViewById(R.id.bPlay);
no = (Button) findViewById(R.id.bDone);
yes.setOnClickListener(this);
no.setOnClickListener(this);
rn = (TextView) findViewById(R.id.tvRName);
ra = (TextView) findViewById(R.id.tvRAge);
rr = (TextView) findViewById(R.id.tvRRecord);
rh = (TextView) findViewById(R.id.tvRHeight);
rw = (TextView) findViewById(R.id.tvRWeight);
rc = (TextView) findViewById(R.id.tvRCity);
re = (TextView) findViewById(R.id.tvRExp);
bn = (TextView) findViewById(R.id.tvBName);
ba = (TextView) findViewById(R.id.tvBAge);
br = (TextView) findViewById(R.id.tvBRecord);
bh = (TextView) findViewById(R.id.tvBHeight);
bw = (TextView) findViewById(R.id.tvBWeight);
bc = (TextView) findViewById(R.id.tvBCity);
be = (TextView) findViewById(R.id.tvBExp);
rn.setText(homeItem.getHomeItemRedName());
// the rest of your code
}
// other code
}
This was actually really simple. I just ditched the Dialog class, and did it all here in my onClick.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HomeItem homeItem = (HomeItem) adapter.getItem(position);
final Dialog dialog = new Dialog(databaseFightCard.this);
Window window = dialog.getWindow();
window.setGravity(Gravity.CENTER);
window.requestFeature(window.FEATURE_NO_TITLE);
LayoutInflater inflater = (LayoutInflater) databaseFightCard.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout relative = (RelativeLayout) inflater.inflate(R.layout.custom_dialog, null, false);
dialog.setContentView(relative);
Button play = (Button) relative.findViewById(R.id.bPlay);
Button done = (Button) relative.findViewById(R.id.bDone);
TextView rn = (TextView) relative.findViewById(R.id.tvRName);
TextView ra = (TextView) relative.findViewById(R.id.tvRAge);
TextView rr = (TextView) relative.findViewById(R.id.tvRRecord);
TextView rh = (TextView) relative.findViewById(R.id.tvRHeight);
TextView rw = (TextView) relative.findViewById(R.id.tvRWeight);
TextView rc = (TextView) relative.findViewById(R.id.tvRCity);
TextView re = (TextView) relative.findViewById(R.id.tvRExp);
TextView bn = (TextView) relative.findViewById(R.id.tvBName);
TextView ba = (TextView) relative.findViewById(R.id.tvBAge);
TextView br = (TextView) relative.findViewById(R.id.tvBRecord);
TextView bh = (TextView) relative.findViewById(R.id.tvBHeight);
TextView bw = (TextView) relative.findViewById(R.id.tvBWeight);
TextView bc = (TextView) relative.findViewById(R.id.tvBCity);
TextView be = (TextView) relative.findViewById(R.id.tvBExp);
rn.setText(homeItem.getHomeItemRedName()+"");
ra.setText(homeItem.getHomeItemRedAge()+"");
rr.setText(homeItem.getHomeItemRedRecord()+"");
rh.setText(homeItem.getHomeItemRedHeight()+"");
rw.setText(homeItem.getHomeItemRedWeight()+"");
rc.setText(homeItem.getHomeItemRedCity()+"");
re.setText(homeItem.getHomeItemRedExp()+"");
bn.setText(homeItem.getHomeItemBlueName()+"");
ba.setText(homeItem.getHomeItemBlueAge()+"");
br.setText(homeItem.getHomeItemBlueRecord()+"");
bh.setText(homeItem.getHomeItemBlueHeight()+"");
bw.setText(homeItem.getHomeItemBlueWeight()+"");
bc.setText(homeItem.getHomeItemBlueCity()+"");
be.setText(homeItem.getHomeItemBlueExp()+"");
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
}
});
Related
I'm not able to see the recycle view, not sure where It has gone wrong. It would be great if you can help me.
Fragment
public class CallDurationFragment extends Fragment {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
ArrayList<CallHistroy> callList = new ArrayList<>();
ArrayList<CallHistroy> callListTemp = new ArrayList<>();
ArrayList<CallHistroy> callObject = new ArrayList<>();
ArrayList<CallHistroy> callListText = new ArrayList<>();
private CallDurationFragment.OnFragmentInteractionListener mListener;
private RecyclerView rvCall;
private RecyclerView.Adapter callAdaptor;
private RecyclerView.LayoutManager eLayoutManager;
private EditText phoneNumber;
private static final int DIALOG_DATE_PICKER = 100;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_callduration_list, container, false);
phoneNumber = (EditText) getActivity().findViewById(editTextSearchKeyPhoneNo);
Context context = getActivity();
rvCall = (RecyclerView) rootView.findViewById(R.id.rvCallDuration);
rvCall.setHasFixedSize(true);
rvCall.setLayoutManager(eLayoutManager);
eLayoutManager = new LinearLayoutManager(getActivity());
phoneNumber.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
callListTemp = getAllCallRecords();
for(int i = 0 ; i < callListTemp.size() ; i++)
if(callListTemp.get(i).getPhoneNumber().contains(s.toString()) )
callListText.add(callListTemp.get(i));
callList = calculateIncomingOutgoing();
callAdaptor = new CallDurationAdapter(getActivity(), callList);
rvCall.setAdapter(callAdaptor);
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
}
});
callList = calculateIncomingOutgoing();
callAdaptor = new CallDurationAdapter(getActivity(), callList);
rvCall.setAdapter(callAdaptor);
return rootView;
}
public ArrayList<CallHistroy> getAllCallRecords(){
DatabaseReference ref = database.getReference();
ref.child("Call").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
callObject.clear();
HashMap<String,Object> call = null;
Iterator<DataSnapshot> items = dataSnapshot.getChildren().iterator();
while(items.hasNext()){
DataSnapshot item = items.next();
Log.e("Listener",item.toString() );
call =(HashMap<String, Object>) item.getValue();
callObject.add(new CallHistroy(call.get("phoneNumber").toString(),call.get("mode").toString(),call.get("duration").toString(), call.get("date").toString(),item.getKey()));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return callObject;
}
public ArrayList<CallHistroy> calculateIncomingOutgoing(){
if(callListText.size() > 0){
callList = callListText;
}else {
callList = getAllCallRecords();
}
ArrayList<CallHistroy> callHistroyIncomingOutgoing = new ArrayList<>();
if(callList.size() > 0){
if(callList.get(0).getMode().equals("Outgoing")) {
callHistroyIncomingOutgoing.add(new CallHistroy(callList.get(0).getPhoneNumber(), "0", callList.get(0).getDuration()));
}else{
callHistroyIncomingOutgoing.add(new CallHistroy(callList.get(0).getPhoneNumber(), callList.get(0).getDuration(), "0"));
}
}
for( int i = 1 ; i < callList.size() ; i++){
boolean setValue = false;
for (int j = 0; j < callHistroyIncomingOutgoing.size() ;j++){
if( callHistroyIncomingOutgoing.get(j).getPhoneNumber().equals(callList.get(i).getPhoneNumber())){
setValue = true;
int incoming = Integer.parseInt(callHistroyIncomingOutgoing.get(j).getIncomingDuration());
int outgoing = Integer.parseInt( callHistroyIncomingOutgoing.get(j).getOutgoingDuration());
int duration = Integer.parseInt( callList.get(i).getDuration());
if(callList.get(i).getMode().equals("Outgoing")) {
callHistroyIncomingOutgoing.get(j).updateDuration(String.valueOf(incoming), String.valueOf(outgoing + duration));
}else{
callHistroyIncomingOutgoing.get(j).updateDuration(String.valueOf(incoming + duration), String.valueOf(outgoing));
}
}
}
if(!setValue) {
if(callList.get(i).getMode() == "Outgoing") {
callHistroyIncomingOutgoing.add(new CallHistroy(callList.get(i).getPhoneNumber(), "0", callList.get(i).getDuration()));
}else{
callHistroyIncomingOutgoing.add(new CallHistroy(callList.get(i).getPhoneNumber(), callList.get(i).getDuration(), "0"));
}
}
}
return callHistroyIncomingOutgoing;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof CallListFragment.OnFragmentInteractionListener) {
mListener = (CallDurationFragment.OnFragmentInteractionListener) context;
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onPause(){
super.onPause();
}
#Override
public void onDestroyView(){
super.onDestroyView();
}
#Override
public void onDestroy(){
super.onDestroy();
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Adaptor
RecyclerView.Adapter<CallDurationAdapter.ViewHolder> {
private List<CallHistroy> mCalls;
private Context mContext;
public CallDurationAdapter(Context context, List<CallHistroy> calls) {
mCalls = calls;
mContext = context;
}
private Context getContext() {
return mContext;
}
#Override
public CallDurationAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View callDurationView = inflater.inflate(R.layout.item_call_duration_details, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(callDurationView);
return viewHolder;
}
#Override
public void onBindViewHolder(CallDurationAdapter.ViewHolder viewHolder, final int position) {
// Get the data model based on position
final CallHistroy ch = mCalls.get(position);
// Set item views based on your views and data model
viewHolder._phoneNoTextView.setText(ch.getPhoneNumber());
viewHolder._incomingTextView.setText(ch.getIncomingDuration());
viewHolder._outgoingTextView.setText(ch.getOutgoingDuration());
final String key = ch.getKey();
}
#Override
public int getItemCount() {
return mCalls.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView _phoneNoTextView;
public TextView _incomingTextView;
public TextView _outgoingTextView;
public ViewHolder(View itemView) {
super(itemView);
_phoneNoTextView = (TextView) itemView.findViewById(R.id.rvs_duration_phone_no);
_incomingTextView = (TextView) itemView.findViewById(R.id.rvs_duration_outing_total_call);
_outgoingTextView = (TextView) itemView.findViewById(R.id.rvs_duration_incoming_total_call);
}
}
}
Activity
public class CallDurationActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call_duration);
CallDurationFragment newFragment = new CallDurationFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.recordFragmentContainer, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
public void refreshCallDuration(View v) {
Intent intent = new Intent(this, CallDurationActivity.class);
startActivity(intent);
}
protected void onPause() {
super.onPause();
}
protected void onStop() {
super.onStop();
}
protected void onDestroy() {
super.onDestroy();
}
public void onBackCallDuration(View v) {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
Object
public class CallHistroy implements Comparable<CallHistroy> {
String phoneNumber;
String mode;
String duration;
String date;
String key;
String incomingDuration;
String outgoingDuration;
int totalIncoming;
int totalOutgoing;
public CallHistroy(String _phontNumber, String _incomingDuration, String _outgoingDuration ){
setPhoneNumber( _phontNumber );
setIncomingDuration( _incomingDuration );
setOutgoingDuration( _outgoingDuration );
}
public CallHistroy(String _date, int _totalIncoming, int _totalOutgoing ){
setDate(_date);
setTotalIncoming( _totalIncoming );
setTotalOutgoing( _totalOutgoing );
}
public void updateCall(int _totalIncoming, int _totalOutgoing){
setTotalIncoming( _totalIncoming );
setTotalOutgoing( _totalOutgoing );
}
public void updateDuration(String _incomingDuration, String _outgoingDuration){
setOutgoingDuration( _incomingDuration );
setIncomingDuration( _outgoingDuration );
}
public CallHistroy(String _phoneNumber, String _mode, String _duration, String _date ){
setPhoneNumber( _phoneNumber );
setDuration( _duration );
setDate( _date );
setMode( _mode );
}
public CallHistroy(String _phoneNumber, String _mode, String _duration, String _date, String _key ){
setPhoneNumber( _phoneNumber );
setDuration( _duration );
setDate( _date );
setMode( _mode );
setKey( _key );
}
public String getIncomingDuration() {
return incomingDuration;
}
public String getOutgoingDuration() {
return outgoingDuration;
}
public int getTotalIncoming() {
return totalIncoming;
}
public int getTotalOutgoing() {
return totalOutgoing;
}
public void setIncomingDuration(String incomingDuration) {
this.incomingDuration = incomingDuration;
}
public void setOutgoingDuration(String outgoingDuration) {
this.outgoingDuration = outgoingDuration;
}
public void setTotalIncoming(int totalIncoming) {
this.totalIncoming = totalIncoming;
}
public void setTotalOutgoing(int totalOutgoing) {
this.totalOutgoing = totalOutgoing;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getDate() {
return date;
}
public String getMode() {
return mode;
}
public String getDuration() {
return duration;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setDate(String date) {
this.date = date;
}
public void setDuration(String duration) {
this.duration = duration;
}
public void setMode(String mode) {
this.mode = mode;
}
#Override
public int compareTo(#NonNull CallHistroy callHistroyObject) {
String[] part = callHistroyObject.date.split("/");
String[] part1 = date.split("/");
int date = Integer.parseInt(part[0]);
int month = Integer.parseInt(part[1]);
String _year = part[2];
int year = Integer.parseInt(_year.substring(0,4));
int date1 = Integer.parseInt(part1[0]);
int month1 = Integer.parseInt(part1[1]);
String _year1 = part1[2];
int year1 = Integer.parseInt(_year1.substring(0,4));
if(year > year1)
return -1;
else if(month > month1)
return -1;
else if(date >date1)
return -1;
else
return 0;
}
}
You're setting your layout manager before it's created
rvCall.setLayoutManager(eLayoutManager);
eLayoutManager = new LinearLayoutManager(getActivity());
should be
eLayoutManager = new LinearLayoutManager(getActivity());
rvCall.setLayoutManager(eLayoutManager);
I have 2 Activities in my application.
activityMain contain 3 Fragments
The third fragment is a conversations list. This is a recylerView where each Item leads to a specific chat.
activityConversation contains a Chat.
First, i would like to sort the conversations in the the recyclerView in order of "Last actives". The most recent active should be displayed on top of the list, the second last active on second postition etc...
Secondly, each Item of the recyclerView contains a Textview. For each item, I would like to display the last message posted in the related chat in this Texview.
Finally, i would like to display these Item textViews in Bold since the conversation has not been opened until the last chat update.
Has anyone an Idea to help me achieve that?
Here my Chat Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversation);
getWindow().setBackgroundDrawableResource(R.drawable._background_black_lchatxxxhdpi) ;
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
LinearLayout leftNav = (LinearLayout)findViewById(R.id.conv_left_nav);
LinearLayout helperAdmin = (LinearLayout) getLayoutInflater().inflate(R.layout.list_participant_admin, leftNav, false);
leftNav.addView(helperAdmin);
final EditText input_post = (EditText)findViewById(R.id.input_post);
context = this;
input_post.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
ImageButton btn_submit = (ImageButton)findViewById(R.id.btn_submit);
btn_submit.setEnabled(!TextUtils.isEmpty(s.toString().trim()));
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Intent intent = getIntent();
if (intent.hasExtra("conversationId"))
conversationId = intent.getStringExtra("conversationId");
rpcHelper = new RPCHelper(context, this);
String unique_device_id = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
Log.i("US", unique_device_id);
rpcHelper.loginOrRegister(unique_device_id, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
refreshConversation();
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
dbHelper = new DataBaseHelper(context, "us", null, Statics.DB_VERSION);
userInConv = dbHelper.dbReader.getUserInConversation(Integer.parseInt(conversationId));
storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
leftRecycler = (RecyclerView) helperAdmin.findViewById(R.id.conv_left_recycler);
//mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
leftLayoutManager = new LinearLayoutManager(this);
leftRecycler.setLayoutManager(leftLayoutManager);
leftAdapter = new ConvLeftAdapter(userInConv, storageDir, Integer.parseInt(conversationId));
leftRecycler.setAdapter(leftAdapter);
helpersImg = new View[3];
helpers = new DataBaseReader.User[3];
photos = dbHelper.dbReader.getPhotosInConversation(Integer.parseInt(conversationId));
photoRecycler = (RecyclerView) findViewById(R.id.photo_recycler);
photoLayoutManager = new GridLayoutManager(this, Math.max(photos.length, 1));
photoRecycler.setLayoutManager(photoLayoutManager);
rightAdapter = new ConvRightAdapter(photos, storageDir, context);
photoRecycler.setAdapter(rightAdapter);
IntentFilter filter = new IntentFilter(Statics.ACTION_NEW_POST);
this.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context ctx, Intent intent) {
Log.d("new", " message");
refreshConversation();
}
}, filter);
}
#Override
public void onNewIntent(Intent intent){
if (intent.hasExtra("conversationId"))
conversationId = intent.getStringExtra("conversationId");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_conversation, menu);
DataBaseReader.Conversation conversation = dbHelper.dbReader.getConversation(conversationId);
DataBaseReader.User owner = dbHelper.dbReader.getConversationOwner(conversationId);
final ImageView owner_img = (ImageView)findViewById(R.id.img_userprofilpic);
TextView owner_name = (TextView)findViewById(R.id.lbl_username_owner);
TextView owner_city = (TextView)findViewById(R.id.lbl_usercity_owner);
TextView conversation_question = (TextView)findViewById(R.id.question_text);
owner_name.setText(owner.name);
owner_city.setText(owner.city);
conversation_question.setText(conversation.question.text);
conversation_question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView text = (TextView)findViewById(R.id.question_text);
int maxLines = TextViewCompat.getMaxLines(text);
if (maxLines==2){
text.setMaxLines(Integer.MAX_VALUE);
}
else{
text.setMaxLines(2);
}
}
});
rpcHelper.getPhoto(storageDir + "/", owner.photo, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
owner_img.setImageBitmap(bm);
}
#Override
public void onPreExecute() {
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
public void refreshConversation(){
dbHelper.dbSyncer.syncPosts(rpcHelper.user_id, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
DataBaseReader.Post[] posts = dbHelper.dbReader.getPosts(conversationId);
postsRecycler = (RecyclerView) findViewById(R.id.posts_recycler);
postsLayoutManager = new LinearLayoutManager(context);
postsRecycler.setLayoutManager(postsLayoutManager);
postsAdapter = new PostsAdapter(posts, storageDir, rpcHelper);
postsRecycler.setAdapter(postsAdapter);
postsRecycler.scrollToPosition(postsAdapter.getItemCount() - 1);
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
/*
rpcHelper.getPosts(conversationId, new AsyncResponseListener(){
#Override
public void onResponse(JSONArray response) throws JSONException {
LinearLayout posts_root = (LinearLayout) findViewById(R.id.posts_root);
posts_root.removeAllViews();
for (int i = 0; i < response.length(); i++){
Log.d("Conv refresh", response.get(i) + "");
final JSONObject jConversation = (JSONObject) response.get(i);
LinearLayout post;
if (jConversation.getString("userId") == rpcHelper.user_id) {
post = (LinearLayout) getLayoutInflater().inflate(R.layout.item_chatpost_sent, posts_root, false);
}
else{
post = (LinearLayout) getLayoutInflater().inflate(R.layout.item_chatpost_received, posts_root, false);
((TextView)post.findViewById(R.id.post_name_)).setText(jConversation.getString("name"));
}
((TextView)post.findViewById(R.id.lbl_message_chat)).setText(jConversation.getString("text"));
posts_root.addView(post);
}
hideProcessDialog();
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});*/
}
public void onSubmit(View v){
final EditText input_post = (EditText)findViewById(R.id.input_post);
String post_text = input_post.getText().toString();
rpcHelper.post(conversationId, post_text, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
refreshConversation();
input_post.setText("");
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
}
Button no = (Button)alertDialog.findViewById(R.id.btn_cancel);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
helpersImg[0] = null;
helpersImg[1] = null;
helpersImg[2] = null;
helpers[0] = null;
helpers[1] = null;
helpers[2] = null;
alertDialog.dismiss();
}
});
}
public void onSelectUser(View v){
View vi = snapHelper.findSnapView(participantsLayoutManager);
if (helpersImg[0] == vi || helpersImg[1] == vi || helpersImg[2] == vi)
return;
Log.i("get helper Id", ""+ participantsAdapter.selectedUserId);
ImageView photo = (ImageView) vi.findViewById(R.id.img_userprofilpic);
photo.setDrawingCacheEnabled(true);
Bitmap bmap = photo.getDrawingCache();
ImageView helperImage = null;
if (helpersImg[0] == null) {
helperImage = (ImageView) alertDialog.findViewById(R.id.reward_dialog_helper0);
helpersImg[0] = vi;
helperImage.setImageBitmap(bmap);
photo.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);
helpers[0] = userInConv[participantsAdapter.selectedUserId];
}
else if (helpersImg[1] == null){
helperImage = (ImageView) alertDialog.findViewById(R.id.reward_dialog_helper1);
helpersImg[1] = vi;
helperImage.setImageBitmap(bmap);
photo.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);
helpers[1] = userInConv[participantsAdapter.selectedUserId];
}
else if (helpersImg[2] == null){
helperImage = (ImageView) alertDialog.findViewById(R.id.reward_dialog_helper2);
helpersImg[2] = vi;
helperImage.setImageBitmap(bmap);
photo.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);
helpers[1] = userInConv[participantsAdapter.selectedUserId];
}
else{
return;
}
}
/**private void showTipDialog(){
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
LayoutInflater inflater = LayoutInflater.from(context);
final View dialogView = inflater.inflate(R.layout.dialog_add_tip, null);
final EditText value = (EditText) dialogView.findViewById(R.id.tip_value);
final SeekBar sb = (SeekBar) dialogView.findViewById(R.id.seekBar);
sb.setMax(50);
sb.setProgress(5);
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
progress = (Math.round(progress/5 ))*5;
seekBar.setProgress(progress);
value.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
value.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Convert text to integer. Do you already use editText.setInputType(InputType.TYPE_CLASS_NUMBER), don't you?
Integer enteredProgress = Integer.valueOf(s.toString());
sb.setProgress(enteredProgress);
}
#Override
public void afterTextChanged(Editable s) {}});
dialogBuilder.setView(dialogView);
alertDialog = dialogBuilder.create();
alertDialog.show();
Button ok = (Button)alertDialog.findViewById(R.id.btn_ok);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
Button no = (Button)alertDialog.findViewById(R.id.btn_no);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
}*/
public void removeHelper(View v){
int index = 0;
if (v == alertDialog.findViewById(R.id.reward_dialog_helper0)){
index = 0;
}
else if (v == alertDialog.findViewById(R.id.reward_dialog_helper1)){
index = 1;
}
else if (v == alertDialog.findViewById(R.id.reward_dialog_helper2)){
index = 2;
}
if (helpersImg[index] == null){
return;
}
ImageView photo = (ImageView) helpersImg[index].findViewById(R.id.img_userprofilpic);
photo.setDrawingCacheEnabled(true);
photo.clearColorFilter();
helpersImg[index] = null;
helpers[index] = null;
ImageView imv = (ImageView)v;
imv.setImageResource(R.drawable.stroke_rounded_corners_white);
}
private void showProcessDialog(){
pd = new ProgressDialog(this);
pd.setTitle("Processing");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
private void hideProcessDialog(){
pd.hide();
}
#Override
public void onInternetConnectionLost() {
}
#Override
public void onInternetConnectionFound() {
}
public void onTakePicture(View v){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, Statics.REQUEST_IMAGE_CAPTURE);
}
}
public void onTakePictureFromGallery(View v){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), Statics.REQUEST_PROFILE_IMAGE_GALLERY);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap imageBitmap;
if ((requestCode == Statics.REQUEST_IMAGE_CAPTURE || requestCode == Statics.REQUEST_IMAGE_CAPTURE_0
|| requestCode == Statics.REQUEST_IMAGE_CAPTURE_1 || requestCode == Statics.REQUEST_IMAGE_CAPTURE_2) && resultCode == RESULT_OK && data != null) {
Bundle extras = data.getExtras();
if (extras == null){
return;
}
imageBitmap = (Bitmap) extras.get("data");
addPhoto(imageBitmap);
}
else if (requestCode == Statics.REQUEST_PROFILE_IMAGE_GALLERY && resultCode == RESULT_OK){
try {
imageBitmap = getBitmapFromUri(data.getData());
addPhoto(imageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void addPhoto(Bitmap image) {
DataBaseReader.Conversation c = dbHelper.dbReader.getConversation(conversationId);
String encodedImage = encodeBitmap(image);
rpcHelper.addPhotosToQuestion("" + c.question.id, encodedImage, null, null, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
dbHelper.dbSyncer.sync(rpcHelper.user_id, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
photos = dbHelper.dbReader.getPhotosInConversation(Integer.parseInt(conversationId));
photoRecycler = (RecyclerView) findViewById(R.id.photo_recycler);
photoLayoutManager = new GridLayoutManager(context, Math.max(photos.length, 1));
photoRecycler.setLayoutManager(photoLayoutManager);
rightAdapter = new ConvRightAdapter(photos, storageDir, context);
photoRecycler.setAdapter(rightAdapter);
}
#Override
public void onResponse() {
photos = dbHelper.dbReader.getPhotosInConversation(Integer.parseInt(conversationId));
photoRecycler = (RecyclerView) findViewById(R.id.photo_recycler);
photoLayoutManager = new GridLayoutManager(context, Math.max(photos.length, 1));
photoRecycler.setLayoutManager(photoLayoutManager);
rightAdapter = new ConvRightAdapter(photos, storageDir, context);
photoRecycler.setAdapter(rightAdapter);
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
}
private String encodeBitmap(Bitmap bitmap){
try{
bitmap = Bitmap.createScaledBitmap(bitmap, Statics.BITMAP_WIDTH, Statics.BITMAP_HEIGHT, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
final byte[] imageInByte = stream.toByteArray();
return Base64.encodeToString(imageInByte, Base64.DEFAULT);
}
catch(Exception e){
return "";
}
}
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
}
This is my Fragment with conversations List:
public class ConversationFragment extends Fragment {
private View v;
private OnFragmentInteractionListener mListener;
public ConversationFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment ConversationFragment.
*/
// TODO: Rename and change types and number of parameters
public static ConversationFragment newInstance() {
ConversationFragment fragment = new ConversationFragment();
Bundle args = new Bundle();
//args.putString(ARG_PARAM1, param1);
//args.putString(ARG_PARAM2, param2);
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
if (v == null) {
v = inflater.inflate(R.layout.fragment_conversation, container, false);
}
final SwipeRefreshLayout swipeRefresh = (SwipeRefreshLayout)v.findViewById(R.id.swiperefreshconv);
swipeRefresh.post(new Runnable() {
#Override
public void run() {
swipeRefresh.setRefreshing(true);
}
});
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mListener.syncDb();
}
});
return v;
}
#Override
public void onStart(){
super.onStart();
mListener.refreshConversations();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
This is my Conversation Adapter:
public class ConversationsAdapter extends RecyclerView.Adapter {
private final File mStorageDir;
private final RPCHelper mRPCHelper;
private DataBaseReader.Conversation[] mDataset;
Context context;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public View mView;
public ViewHolder(View v) {
super(v);
mView = v;
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public ConversationsAdapter(DataBaseReader.Conversation[] myDataset, File storageDir) {
mDataset = myDataset;
mStorageDir = storageDir;
mRPCHelper = new RPCHelper();
}
// Create new views (invoked by the layout manager)
#Override
public ConversationsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_conversations, parent, false);
ViewHolder vh = new ViewHolder(v);
context = parent.getContext();
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
Log.d("recy", "bind called");
TextView username = (TextView)holder.mView.findViewById(R.id.lbl_username);
final TextView message = (TextView)holder.mView.findViewById(R.id.question_text);
TextView date_and_time = (TextView)holder.mView.findViewById(R.id.lbl_date_and_time);
ImageView status_pending = (ImageView)holder.mView.findViewById(R.id.lbl_status_conversation_pending);
ImageView status_in = (ImageView)holder.mView.findViewById(R.id.lbl_status_conversation_in);
TextView keyword0 = (TextView)holder.mView.findViewById(R.id.post_keywords0);
TextView keyword1 = (TextView)holder.mView.findViewById(R.id.post_keywords1);
TextView keyword2 = (TextView)holder.mView.findViewById(R.id.post_keywords2);
ImageView userprofilpic = (ImageView)holder.mView.findViewById(R.id.img_userprofilpic);
LinearLayout answer_info = (LinearLayout) holder.mView.findViewById(R.id.answer_info);
Button delete_coversation = (Button) holder.mView.findViewById(R.id.btn_confirm_delete);
userprofilpic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, UserProfileActivity.class);
i.putExtra("userId", mDataset[position].question.userId);
context.startActivity(i);
}
});
username.setText(mDataset[position].question.userName);
message.setText(mDataset[position].question.text);
keyword0.setText(mDataset[position].question.keywords[0]);
keyword1.setText(mDataset[position].question.keywords[1]);
keyword2.setText(mDataset[position].question.keywords[2]);
addImgToView(mDataset[position].question.photo, userprofilpic);
if (Integer.parseInt(mDataset[position].confirmed) == 1) {
status_pending.setEnabled(false);
status_pending.setVisibility(View.GONE);
status_in.setVisibility(View.VISIBLE);
answer_info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
message.setTypeface(Typeface.DEFAULT);
message.onSaveInstanceState();
int convId = mDataset[position].id;
Intent i = new Intent(context, ConversationActivity.class);
i.putExtra("conversationId", "" + convId);
context.startActivity(i);
}
});
}
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.length;
}
private void addImgToView(final String uri, final ImageView v){
mRPCHelper.getPhoto(mStorageDir + "/", uri, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
v.setImageBitmap(bm);
}
#Override
public void onPreExecute() {
}
});
}
}
Thank you in advance for your time.
maintain a flag in data level to know is it read or unread,based on that you can apply the styles.
There is two way to do this.
First you can ask to backend to write server side to query to handle last activity bases of timestamp .In this case you have to send your particular timestamp to server when you open particular conversation .
Other you can make local database ex-(sql database) and handle it in your own code by updating query when you reading or undreading conversation.
I'm updating the database to other classes and I want the custom listview to be updated when I get to the main activity. My customListview is still standing
I have searched for this problem, but I could not solve it myself. Where should I add the code to solve this problem? Please help me 3 days did not solve my problem.
public class MainActivity extends AppCompatActivity {
veritabani vtabani; //database
List<Yukleclas> yuklele =new ArrayList<Yukleclas>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vtabani=new veritabani(this);
OzelAdaptor adaptor=new OzelAdaptor(this,yuklele);
ListView listView=(ListView) findViewById(R.id.listview);
String[] sutunlar =
{"id","bilgi","simdikiyil","simdikiay","simdikigun","alarmsaat",
"alarmdakika","gsonrayil","gsonraay","gsonragun","hsonrayil","hsonraay",
"hsonragun","asonrayil","asonraay","asonragun","seviye","durum"};
SQLiteDatabase dboku =vtabani.getReadableDatabase();
Cursorcursor=dboku.query("tablo_adi",sutunlar,null,null,null,null,null);
while (cursor.moveToNext()) {
if (cursor.getInt(17)==1) {
yuklele.add(new Yukleclas(cursor.getString(1), cursor.getInt(2),
cursor.getInt(3), cursor.getInt(4),
cursor.getInt(7),cursor.getInt(8),cursor.getInt(9),cursor.getInt(10),
cursor.getInt(11),cursor.getInt(12),cursor.getInt(13),cursor.getInt(14),
cursor.getInt(15),cursor.getInt(16)));
}
}
cursor.close();
dboku.close();
listView.setAdapter(adaptor);
adaptor.notifyDataSetChanged();
}
public void ekleyegit(View view) {
Intent intent =new Intent(this,ekleactivity.class);
startActivity(intent);
finish();
}}
and this is myAdapter:
public class OzelAdaptor extends BaseAdapter {
LayoutInflater layoutInflater;
List<Yukleclas> list;
public OzelAdaptor(Activity activity,List<Yukleclas> mList){
layoutInflater= (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
list=mList;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View satirView;
satirView=layoutInflater.inflate(R.layout.satir,null);
TextView tv_tarih = (TextView) satirView.findViewById(R.id.text_tarih);
TextView tv_bilgi= (TextView) satirView.findViewById(R.id.text_bilgi);
ImageView imageView= (ImageView) satirView.findViewById(R.id.imageView);
Yukleclas yukleclas =list.get(position);
tv_bilgi.setText(yukleclas.getBilgi());
if(yukleclas.getSeviye()==1){
tv_tarih.setText("Sonraki tekrar:" +yukleclas.getGun() +"/" +yukleclas.getAy() + "/" +yukleclas.getYil() );
}else if(yukleclas.getSeviye()==2){
tv_tarih.setText("Sonraki tekrar:" +yukleclas.getGsgun() +"/" +yukleclas.getGsay() + "/" +yukleclas.getGsyil() );
}else if (yukleclas.getSeviye()==3){
tv_tarih.setText("Sonraki tekrar:" +yukleclas.getHsgun() +"/" +yukleclas.getHsay() + "/" +yukleclas.getHsyil() );
}else if (yukleclas.getSeviye()==4){
tv_tarih.setText("Sonraki tekrar:" +yukleclas.getAsgun() +"/" +yukleclas.getAsay() + "/" +yukleclas.getAsyil() );
}
if(yukleclas.getSeviye()==1){
imageView.setImageResource(bir); // eğer 1. seviyede ise bir isimli ikonu göster
}else if(yukleclas.getSeviye()==2){
imageView.setImageResource(iki);
}else if(yukleclas.getSeviye()==3){
imageView.setImageResource(uc);
}else if(yukleclas.getSeviye()==4){
imageView.setImageResource(ic_launcher);
}
return satirView;
}
}
and this is my class to get-set:
public class Yukleclas {
private String bilgi;
private int yil;
private int ay;
private int gun;
private int seviye;
private int gsyil;
private int gsay;
private int gsgun;
private int hsyil;
private int hsay;
private int hsgun;
private int asyil;
private int asay;
private int asgun;
public Yukleclas(String mBilgi,int mYil,int mAy,int mGun,int mGsyil,int
mGsay,int mGsgun,int mHsyil,int mHsay,int mHsgun,int mAsyil,int mAsay,int
mAsgun,int mSeviye){
yil=mYil;
bilgi=mBilgi;
ay=mAy;
gun=mGun;
gsyil=mGsyil;
gsay=mGsay;
gsgun=mGsgun;
hsyil=mHsyil;
hsay=mHsay;
hsgun=mHsgun;
asyil=mAsyil;
asay=mAsay;
asgun=mAsgun;
seviye=mSeviye;
}
public int getYil() {
return yil;
}
public void setYil(int yil) {
this.yil = yil;
}
public int getSeviye() {
return seviye;
}
public void setSeviye(int yil) {
this.seviye = seviye;
}
public String getBilgi() {
return bilgi;
}
public void setBilgi(String bilgi) {
this.bilgi = bilgi;
}
public int getAy() {
return ay;
}
public void setAy(int ay) {
this.ay = ay;
}
public int getGun() {
return gun;
}
public void setGun(int gun) {
this.gun = gun;
}
public int getGsyil() {return gsyil;
}
public void setGsyil(int gsyil) {this.gsyil = gsyil;
}
public int getGsay() {return gsay;
}
public void setGsay(int gsay) {this.gsay = gsay;
}
public int getGsgun() {return gsgun;
}
public void setGsgun(int gsgun) {this.gsgun = gsgun;
}
public int getHsyil() {return hsyil;
}
public void setHsyil(int hsyil) {this.hsyil = hsyil;
}
public int getHsay() {return hsay;
}
public void setHsay(int hsay) {this.hsay = hsay;
}
public int getHsgun() {return hsgun;
}
public void setHsgun(int hsgun) {this.hsgun = hsgun;
}
public int getAsyil() {return asyil;
}
public void setAsyil(int asyil) {this.asyil = asyil;
}
public int getAsay() {return asay;
}
public void setAsay(int asay) {this.asay = asay;
}
public int getAsgun() {return asgun;
}
public void setAsgun(int asgun) {this.asgun = asgun;
}
}
I know it is very complex but How to replace my customlistview ?
Easy way is to call adapter.notifyDataSetChanged() in your onResume function.
But I would suggest you check if your list has been updated then only you call adapter.notifyDataSetChanged(). You can do this in multiple ways, but for a cleaner approach use EventBus which allows you to fire events and listen to them, So you can fire an event every time you update your dataBaseand on listening to this event, simply call adapter.notifyDataSetChanged
Hai I have editext in my app where we can set the date of birth. in that editext I have a calendar icon. If we click on calendar icon it should open the datepicker dialog. But in my case if I click on calendar icon it is showing paste, clicpboard, selectall options in my editext instead of showing the date picker dialog and if we click on the calendar icon again for the second time it is opening the date picker dialog. How to make the datepicker dialog open for the first click on my calendar icon. I alreadt set setFocusable and setFocusableInTouchMode to false but no use. please help to fix the same.
This is the fragment where I am having edittext for date of birth:
public class RegistrationBasicInformationFragment extends Fragment implements
IRegistrationBasicInformationView, IRegistrationItemEventListener, View.OnFocusChangeListener {
private TextView mRegistrationEnterYourBasicInformationLabel;
private RelativeLayout mRegistrationBasicInformationMainLayout;
private DsmApplication mDsmApplication;
private RegistrationItemView mRegistrationBasicInformationItemForFirstName;
private RegistrationItemView mRegistrationBasicInformationItemForLastName;
private RegistrationItemView mRegistrationBasicInformationItemForDob;
private RegistrationItemView mRegistrationBasicInformationItemForEmail;
private RegistrationItemView mRegistrationBasicInformationItemForGender;
private RegistrationItemView mRegistrationBasicInformationItemForNickName;
private RegistrationItemView mRegistrationBasicInformationItemForPhoneNumber;
private RegistrationItemView mRegistrationBasicInformationItemForPractice;
private RegistrationItemView mRegistrationBasicInformationItemForProvider;
private RegistrationBasicInformationController mRegistrationBasicInformationController;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.registration_basicinformation_view_v222, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mDsmApplication = (DsmApplication) getActivity().getApplication();
loadController();
loadView(view);
}
private void loadController() {
mRegistrationBasicInformationController = new RegistrationBasicInformationController(this);
mDsmApplication.registerController(RegistrationBasicInformationController.TAG, mRegistrationBasicInformationController);
}
private void loadView(View view) {
mRegistrationBasicInformationMainLayout = (RelativeLayout) view
.findViewById(R.id.registration_basicinformation_relativelayout_for_itself);
mRegistrationEnterYourBasicInformationLabel = (TextView) view
.findViewById(R.id.registration_basicinformation_textview_for_headerlabel);
mRegistrationBasicInformationItemForFirstName = (RegistrationItemView) view
.findViewById(R.id.registration_basicinformation_registrationitemview_for_firstname);
mRegistrationBasicInformationItemForFirstName.mRegistrationItemTextTypeEditText.setOnFocusChangeListener(this);
mRegistrationBasicInformationItemForLastName = (RegistrationItemView) view
.findViewById(R.id.registration_basicinformation_registrationitemview_for_lastname);
mRegistrationBasicInformationItemForLastName.mRegistrationItemTextTypeEditText.setOnFocusChangeListener(this);
mRegistrationBasicInformationItemForDob = (RegistrationItemView) view
.findViewById(R.id.registration_basicinformation_registrationitemview_for_dob);
mRegistrationBasicInformationItemForGender = (RegistrationItemView) view
.findViewById(R.id.registration_basicinformation_registrationitemview_for_gender);
mRegistrationBasicInformationItemForPhoneNumber = (RegistrationItemView) view
.findViewById(R.id.registration_basicinformation_registrationitemview_for_phonenumber);
mRegistrationBasicInformationItemForPhoneNumber.mRegistrationItemTextTypeEditText.setOnFocusChangeListener(this);
mRegistrationBasicInformationItemForNickName = (RegistrationItemView) view
.findViewById(R.id.registration_basicinformation_registrationitemview_for_nickname);
mRegistrationBasicInformationItemForNickName.mRegistrationItemTextTypeEditText
.setOnFocusChangeListener(this);
mRegistrationBasicInformationItemForNickName.mRegistrationItemTextTypeEditText
.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_NEXT) {
if (mRegistrationBasicInformationItemForDob.isEnabled() ) {
mRegistrationBasicInformationController.OnCalendarDateTimeIconClicked();
ViewUtils.hideVirturalKeyboard((EditText) textView);
} else {
mRegistrationBasicInformationItemForPhoneNumber.mRegistrationItemTextTypeEditText.requestFocus();
ViewUtils.showVirturalKeyboard(getActivity().getApplicationContext());
}
return true;
}
return false;
}
});
mRegistrationBasicInformationItemForEmail = (RegistrationItemView) view
.findViewById(R.id.registration_basicinformation_registrationitemview_for_email);
mRegistrationBasicInformationItemForEmail.mRegistrationItemTextTypeEditText.setOnFocusChangeListener(this);
mRegistrationBasicInformationItemForPractice = (RegistrationItemView) view
.findViewById(R.id.registration_basicinformation_registrationitemview_for_practice);
mRegistrationBasicInformationItemForProvider = (RegistrationItemView) view
.findViewById(R.id.registration_basicinformation_registrationitemview_for_provider);
}
#Override
public void SetEnterYourBasicInformationLabel(String label) {
mRegistrationEnterYourBasicInformationLabel.setText(label);
}
#Override
public IRegistrationItemView CreateFirstNameItemView(String label, int type, String value,
int validationId) {
mRegistrationBasicInformationItemForFirstName.SetEventListener(this);
mRegistrationBasicInformationItemForFirstName.SetLabel(label);
mRegistrationBasicInformationItemForFirstName.SetValue(value);
mRegistrationBasicInformationItemForFirstName.SetValidationId(validationId,
IRegistrationItemView.VALUETYPE_TEXTFIELD);
return mRegistrationBasicInformationItemForFirstName;
}
#Override
public IRegistrationItemView CreateLastNameItemView(String label, int type, String value,
int validationId) {
mRegistrationBasicInformationItemForLastName.SetEventListener(this);
mRegistrationBasicInformationItemForLastName.SetLabel(label);
mRegistrationBasicInformationItemForLastName.SetValue(value);
mRegistrationBasicInformationItemForLastName.SetValidationId(validationId, IRegistrationItemView.VALUETYPE_TEXTFIELD);
return mRegistrationBasicInformationItemForLastName;
}
#Override
public IRegistrationItemView CreateNickNameItemView(String label, int type, String value, int validationId) {
mRegistrationBasicInformationItemForNickName.SetEventListener(this);
mRegistrationBasicInformationItemForNickName.SetLabel(label);
mRegistrationBasicInformationItemForNickName.SetValue(value);
mRegistrationBasicInformationItemForNickName.SetValidationId(validationId, IRegistrationItemView.VALUETYPE_TEXTFIELD);
return mRegistrationBasicInformationItemForNickName;
}
#Override
public IRegistrationItemView CreatePracticeItemView(String label, int type, IStringList
valuesList, String defaultValue, int validationId) {
mRegistrationBasicInformationItemForPractice.SetEventListener(this);
mRegistrationBasicInformationItemForPractice.SetLabel(label);
mRegistrationBasicInformationItemForPractice.SetValueList(type, valuesList);
mRegistrationBasicInformationItemForPractice.SetValidationId(validationId,
IRegistrationItemView.VALUETYPE_LIST);
return mRegistrationBasicInformationItemForPractice;
}
#Override
public IRegistrationItemView CreateProviderItemView(String label, int type, IStringList
valuesList, String defaultValue, int validationId) {
mRegistrationBasicInformationItemForProvider.SetEventListener(this);
mRegistrationBasicInformationItemForProvider.SetLabel(label);
mRegistrationBasicInformationItemForProvider.SetValueList(type, valuesList);
mRegistrationBasicInformationItemForProvider.SetValidationId(validationId,
IRegistrationItemView.VALUETYPE_LIST);
return mRegistrationBasicInformationItemForProvider;
}
#Override
public void ShowPracticeItemView() {
mRegistrationBasicInformationItemForPractice.setVisibility(View.VISIBLE);
}
#Override
public void ShowProviderItemView() {
mRegistrationBasicInformationItemForProvider.setVisibility(View.VISIBLE);
}
#Override
public void RefreshScreen() {
// NA
}
#Override
public void SetGender(int isMale) {
mRegistrationBasicInformationItemForGender.SetValueForSwitch(isMale);
}
#Override
public IRegistrationItemView CreateDobItemView(String label, int type, String value,
int validationId) {
mRegistrationBasicInformationItemForDob.SetEventListener(this);
mRegistrationBasicInformationItemForDob.SetLabel(label);
mRegistrationBasicInformationItemForDob.SetValidationId(validationId, IRegistrationItemView.VALUETYPE_TEXTFIELD);
mRegistrationBasicInformationItemForDob.SetValue(value);
return mRegistrationBasicInformationItemForDob;
}
#Override
public IRegistrationItemView CreatePhoneNumberItemView(String label, int type, String value, int validationId) {
mRegistrationBasicInformationItemForPhoneNumber.SetEventListener(this);
mRegistrationBasicInformationItemForPhoneNumber.SetLabel(label);
mRegistrationBasicInformationItemForPhoneNumber.SetValue(value);
mRegistrationBasicInformationItemForPhoneNumber.SetValidationId(validationId, IRegistrationItemView.VALUETYPE_TEXTFIELD);
return mRegistrationBasicInformationItemForPhoneNumber;
}
#Override
public IRegistrationItemView CreateEmailItemView(String label, int type, String value,
int validationId) {
mRegistrationBasicInformationItemForEmail.SetEventListener(this);
mRegistrationBasicInformationItemForEmail.SetLabel(label);
mRegistrationBasicInformationItemForEmail.SetValue(value);
mRegistrationBasicInformationItemForEmail.SetValidationId(validationId,
IRegistrationItemView.VALUETYPE_TEXTFIELD);
mRegistrationBasicInformationItemForEmail.mRegistrationItemTextTypeEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
return mRegistrationBasicInformationItemForEmail;
}
#Override
public IRegistrationItemView CreateGenderItemView(String label, int type,
IStringList valueList, int validationId, int GenderType) {
mRegistrationBasicInformationItemForGender.SetEventListener(this);
mRegistrationBasicInformationItemForGender.SetLabel(label);
mRegistrationBasicInformationItemForGender.SetValidationId(validationId,
IRegistrationItemView.VALUETYPE_RADIO_BUTTON);
mRegistrationBasicInformationItemForGender.SetValueList(type, valueList);
mRegistrationBasicInformationItemForGender.clearRadioButtons();
mRegistrationBasicInformationItemForGender.SetValueForSwitch(GenderType);
return mRegistrationBasicInformationItemForGender;
}
#Override
public void OnErrorIconClick(int validationId) {
//NA
}
#Override
public void OnCalendarIconClick() {
mRegistrationBasicInformationController.OnCalendarDateTimeIconClicked();
}
#Override
public void OnSwitchButtonClick(int validationId, boolean isChecked) {
//NA
}
#Override
public void OnRegistrationItemEditCompleted(String content, int validationId) {
mRegistrationBasicInformationController.OnRegistrationItemEditCompleted(validationId, content);
}
#Override
public void OnSpinnerItemSelected(int validationId, int position) {
switch (validationId) {
case RegistrationValidator.VALIDATE_PRACTICE:
mRegistrationBasicInformationController.OnPracticeItemSelected(position);
break;
case RegistrationValidator.VALIDATE_PROVIDER:
mRegistrationBasicInformationController.OnProviderItemSelected(position);
break;
}
}
#Override
public Presenter GetPresenter() {
return mRegistrationBasicInformationController;
}
#Override
public String GetClassName() {
return getClass().getSimpleName();
}
#Override
public void onDestroy() {
super.onDestroy();
OnDestroy();
}
#Override
public void OnDestroy() {
mRegistrationEnterYourBasicInformationLabel = null;
if (mRegistrationBasicInformationItemForFirstName != null) {
mRegistrationBasicInformationItemForFirstName.OnDestroy();
mRegistrationBasicInformationItemForFirstName = null;
}
if (mRegistrationBasicInformationItemForLastName != null) {
mRegistrationBasicInformationItemForLastName.OnDestroy();
mRegistrationBasicInformationItemForLastName = null;
}
if (mRegistrationBasicInformationItemForNickName != null) {
mRegistrationBasicInformationItemForNickName.OnDestroy();
mRegistrationBasicInformationItemForNickName = null;
}
if (mRegistrationBasicInformationItemForPhoneNumber != null) {
mRegistrationBasicInformationItemForPhoneNumber.OnDestroy();
mRegistrationBasicInformationItemForPhoneNumber = null;
}
if (mRegistrationBasicInformationItemForDob != null) {
mRegistrationBasicInformationItemForDob.OnDestroy();
mRegistrationBasicInformationItemForDob = null;
}
if (mRegistrationBasicInformationItemForEmail != null) {
mRegistrationBasicInformationItemForEmail.OnDestroy();
mRegistrationBasicInformationItemForEmail = null;
}
if (mRegistrationBasicInformationItemForGender != null) {
mRegistrationBasicInformationItemForGender.OnDestroy();
mRegistrationBasicInformationItemForGender = null;
}
if (mRegistrationBasicInformationItemForPractice != null) {
mRegistrationBasicInformationItemForPractice.OnDestroy();
mRegistrationBasicInformationItemForPractice = null;
}
if (mRegistrationBasicInformationItemForProvider != null) {
mRegistrationBasicInformationItemForProvider.OnDestroy();
mRegistrationBasicInformationItemForProvider = null;
}
ViewUtils.UnbindReferences(mRegistrationBasicInformationMainLayout);
ViewUtils.UnbindReferences(getView());
}
#Override
public void onFocusChange(View view, boolean hasFocus) {
if (!hasFocus) {
CustomTextInputEditText editText = (CustomTextInputEditText) view;
mRegistrationBasicInformationController.OnRegistrationItemEditCompleted((int) view.getTag()
, editText.getText().toString());
}
}
}
I've created an Activity where I've got an "Add subject" button. When I press it, it creates an item in a ListView, which is formed by an EditText where the user enters a number.
What I want to do is to add the numbers inside the EditTexts of each item created, depending if the user has created 3, 4, 5, etc. items in the ListView, via button.
Here is the code of the Activity:
public class PersActivity extends Activity {
Button start, calcaverage1;
private SubjectAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.subject_list_view);
setupListViewAdapter();
setupAddMarkButton();
// Accept button
Button acceptbn= (Button)findViewById(R.id.start1);
acceptbn.setOnClickListener(new OnClickListener()
{ public void onClick(View v)
{
Intent intent = new Intent(PersActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
}
public void removeClick(View v) {
Mark itemToRemove = (Mark)v.getTag();
adapter.remove(itemToRemove);
}
private void setupListViewAdapter() {
adapter = new SubjectAdapter(PersActivity.this, R.layout.subject_list_item, new ArrayList<Mark>());
ListView atomPaysListView = (ListView)findViewById(R.id.subject_list_item);
atomPaysListView.setAdapter(adapter);
}
private void setupAddMarkButton() {
findViewById(R.id.addsubject).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
adapter.insert(new Mark("", 0), 0);
}
});
}
}
Here is the code of the adapter:
public class SubjectAdapter extends ArrayAdapter<Mark> {
protected static final String LOG_TAG = SubjectAdapter.class.getSimpleName();
private List<Mark> items;
private int layoutResourceId;
private Context context;
public SubjectAdapter(Context context, int layoutResourceId, List<Mark> items) {
super(context, layoutResourceId, items);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MarkHolder holder = null;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new MarkHolder();
holder.Mark = items.get(position);
holder.removePaymentButton = (ImageButton)row.findViewById(R.id.remove);
holder.removePaymentButton.setTag(holder.Mark);
holder.name = (TextView)row.findViewById(R.id.subjectname);
setNameTextChangeListener(holder);
holder.value = (TextView)row.findViewById(R.id.subjectmark);
setValueTextListeners(holder);
row.setTag(holder);
setupItem(holder);
return row;
}
private void setupItem(MarkHolder holder) {
holder.name.setText(holder.Mark.getName());
holder.value.setText(String.valueOf(holder.Mark.getValue()));
}
public static class MarkHolder {
Mark Mark;
TextView name;
TextView value;
ImageButton removePaymentButton;
}
private void setNameTextChangeListener(final MarkHolder holder) {
holder.name.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
holder.Mark.setName(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void afterTextChanged(Editable s) { }
});
}
private void setValueTextListeners(final MarkHolder holder) {
holder.value.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try{
holder.Mark.setValue(Double.parseDouble(s.toString()));
}catch (NumberFormatException e) {
Log.e(LOG_TAG, "error reading double value: " + s.toString());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void afterTextChanged(Editable s) { }
});
}
}
I've implemented serializable to pass data through the adapter:
public class Mark implements Serializable {
private static final long serialVersionUID = -5435670920302756945L;
private String name = "";
private double value = 0;
public Mark(String name, double value) {
this.setName(name);
this.setValue(value);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
}
Hope there's a solution. Thanks!
Here is how you would do it
addNumberFromText()
{
int total=0;
for(int i=0;i<listView.getChildCount();i++)
{
View wantedView = listView.getChildAt(i);
EditText edtText=view.findViewById(R.id.specificEditTextId);
//not checking wheter integer valid or not, Please do so
int value=Integer.parseInt(edtText.toString());
total+=value;
}
Log.d(TAG,"total sum is "+total);
}
update your activity from following code
public class PersActivity extends Activity
{
Button start, calcaverage1;
private SubjectAdapter adapter;
ListView atomPaysListView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.subject_list_view);
atomPaysListView = (ListView)findViewById(R.id.subject_list_item);
setupListViewAdapter();
setupAddMarkButton();
// Accept button
Button acceptbn= (Button)findViewById(R.id.start1);
acceptbn.setOnClickListener(new OnClickListener()
{ public void onClick(View v)
{
Intent intent = new Intent(PersActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
}
public void removeClick(View v) {
Mark itemToRemove = (Mark)v.getTag();
adapter.remove(itemToRemove);
}
private void setupListViewAdapter() {
adapter = new SubjectAdapter(PersActivity.this, R.layout.subject_list_item, new ArrayList<Mark>());
atomPaysListView.setAdapter(adapter);
}
private void setupAddMarkButton() {
findViewById(R.id.addsubject).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
adapter.insert(new Mark("", 0), 0);
}
});
}
addNumberFromText()
{
double total=0;
for(int i=0;i<atomPaysListView.getChildCount();i++)
{
View wantedView = atomPaysListView.getChildAt(i);
/*
// if edit text
EditText edt=(EditText)view.findViewById(R.id.editText);
//not checking wheter valid or not, Please do so
double value=Double.parseDouble(edt.toString());
*/
//you say edittext, but its a textview or so it seems
TextView txv=(TextView)view.findViewById(R.id.subjectmark);
//not checking wheter valid or not, Please do so
double value=Double.parseDouble(txv.toString());
total+=value;
}
Log.d(TAG,"total sum is "+total);
}
}