I am confused what might be the reason behind this error.While making my edittext field null after entering a digit into it my application is getting crashed.can you find a solution for this situation ??
here is my code
java file
public class CSLActivity extends AppCompatActivity {
private Common mApp;
private AutoCompleteTextView clgName, conCent, loc;
private MultiAutoCompleteTextView skill;
private String[] qulify = new String[]{"Select Highest Qualification", "PG", "UG", "DIPLOMA"};
public String abc, abcd;
public ScrollView scrollView;
public ProgressBar progressBar;
private String q;
private Spinner level;
private int ab = 1990;
public EditText fullName, frm_yr, to_yr;
private boolean ins = false;
private boolean cIns = false;
private Button next;
private TextfieldValidator textfieldValidator;
private AlphabetValidator alphabetValidator;
private int i = 0, j = 0;
private boolean exit = false;
private String get;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_csl);
scrollView = (ScrollView) findViewById(R.id.scroll_view);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
fullName = (EditText) findViewById(R.id.fullName);
level = (Spinner) findViewById(R.id.level);
clgName = (AutoCompleteTextView) findViewById(R.id.clg_name);
conCent = (AutoCompleteTextView) findViewById(R.id.concent);
frm_yr = (EditText) findViewById(R.id.frm_yr);
to_yr = (EditText) findViewById(R.id.to_yr);
skill = (MultiAutoCompleteTextView) findViewById(R.id.skill);
loc = (AutoCompleteTextView) findViewById(R.id.location);
textfieldValidator = new TextfieldValidator();
alphabetValidator = new AlphabetValidator();
next = (Button) findViewById(R.id.next);
frm_yr.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//abc = frm_yr.getText().toString();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
//i = Integer.parseInt(frm_yr.getText().toString());
//i = Integer.parseInt(abc.toString());
i = Integer.parseInt(frm_yr.getText().toString());
}
});
to_yr.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
//j = Integer.parseInt(to_yr.getText().toString());
//j = Integer.parseInt(abcd.toString());
j = Integer.parseInt(to_yr.getText().toString());
}
});
new GetCollege(CSLActivity.this, progressBar, scrollView, clgName).execute();
new GetCourse(CSLActivity.this, conCent).execute();
new GetSkillSet(CSLActivity.this, scrollView, progressBar, skill).execute();
new GetLocation(CSLActivity.this, scrollView, loc, progressBar).execute();
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_item, qulify);
level.setAdapter(adapter1);
level.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
get = level.getSelectedItem().toString();
if (get.equalsIgnoreCase("PG")) {
q = "1";
} else if (get.equalsIgnoreCase("UG")) {
q = "2";
} else {
q = "3";
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
clgName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view.findViewById(R.id.ins_name);
clgName.setText(txt.getText().toString());
conCent.requestFocus();
ins = true;
}
});
conCent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view.findViewById(R.id.display);
conCent.setText(txt.getText().toString());
cIns = true;
frm_yr.requestFocus();
}
});
loc.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt1 = (TextView) view.findViewById(R.id.ins_name);
loc.setText(txt1.getText().toString());
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromInputMethod(view.getWindowToken(), 0);
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.next:
if (fullName.getText().toString().length() == 0) {
fullName.setError("Field Mandatory");
fullName.requestFocus();
} else if (!alphabetValidator.validate(fullName.getText().toString())) {
fullName.setError("Enter a Valid Name");
fullName.requestFocus();
} else if (get.equalsIgnoreCase("Select Highest Qualification")) {
level.requestFocus();
Toast.makeText(getApplicationContext(), "select Qualification", Toast.LENGTH_SHORT).show();
} else if (clgName.getText().toString().length() == 0) {
clgName.setError("Field Mandatory");
clgName.requestFocus();
} else if (conCent.getText().toString().length() == 0) {
conCent.setError("Field Mandatory");
conCent.requestFocus();
} else if (frm_yr.getText().toString().length() == 0) {
frm_yr.setError("Field Mandatory");
frm_yr.requestFocus();
} else if (to_yr.getText().toString().length() == 0) {
to_yr.setError("Field Mandatory");
to_yr.requestFocus();
} else if (i > j) {
to_yr.setError("Passed out year less than join year");
to_yr.requestFocus();
} else if (i == j) {
to_yr.setError("Check the year entered");
to_yr.requestFocus();
} else if (i <= ab) {
frm_yr.setError("Enter a valid Year");
frm_yr.requestFocus();
} else if (j <= ab) {
to_yr.setError("Enter a valid Year");
to_yr.requestFocus();
} else if (skill.getText().toString().length() == 0) {
skill.setError("Field Mandatory");
skill.requestFocus();
} else if (!textfieldValidator.validate(skill.getText().toString())) {
skill.setError("Enter a Valid Skill");
skill.requestFocus();
} else if (loc.getText().toString().length() == 0) {
loc.setError("Field Mandatory");
loc.requestFocus();
} else if (!textfieldValidator.validate(loc.getText().toString())) {
loc.setError("Enter a Valid Location");
} else {
next.setEnabled(false);
new CslIns(CSLActivity.this, mApp.getPreference().getString(Common.u_id, ""), fullName.getText().toString(), q,
clgName.getText().toString(), conCent.getText().toString(), frm_yr.getText().toString(), to_yr.getText().toString(),
skill.getText().toString(), loc.getText().toString(), ins, cIns).execute();
/*startActivity(new Intent(getApplicationContext(), MailVerify.class));
finish();*/
}
break;
}
}
});
}
#Override
public void onBackPressed() {
if (exit) {
mApp.getPreference().edit().putBoolean(Common.PAGE1, false).commit();
super.onBackPressed();
return;
} else {
Toast.makeText(this, "Press Back again to Cancel Signup Process.", Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 2000);
}
}
}
my xml file
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.shuan.Project.signup.employee.CSLActivity">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<ScrollView
android:id="#+id/scroll_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/activity_horizontal_margin"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/fullName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin"
android:hint="Full Name"
android:imeOptions="actionNext"
android:inputType="textPersonName" />
</android.support.design.widget.TextInputLayout>
<Spinner
android:id="#+id/level"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin" />
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin">
<AutoCompleteTextView
android:id="#+id/clg_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/clg_name"
android:imeOptions="actionNext" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin">
<AutoCompleteTextView
android:id="#+id/concent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/concent"
android:imeOptions="actionNext"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<LinearLayout
android:id="#+id/yr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Joined"
android:textColor="#000"
android:textStyle="bold" />
<EditText
android:id="#+id/frm_yr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/small_margin"
android:hint="Year"
android:imeOptions="actionNext"
android:inputType="numberDecimal"
android:maxLength="4"
android:singleLine="true" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Passed :"
android:textColor="#000"
android:textStyle="bold" />
<EditText
android:id="#+id/to_yr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/small_margin"
android:hint="Year"
android:imeOptions="actionNext"
android:inputType="numberDecimal"
android:maxLength="4"
android:singleLine="true" />
</LinearLayout>
</LinearLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/layout_skill"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin">
<MultiAutoCompleteTextView
android:id="#+id/skill"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Your Skills"
android:imeOptions="actionNext"
android:inputType="text" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/layout_location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_margin">
<AutoCompleteTextView
android:id="#+id/location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/location"
android:imeOptions="actionDone"
android:inputType="textAutoComplete" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/next"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="#dimen/activity_horizontal_margin"
android:background="#drawable/signin_border"
android:text="START"
android:textAppearance="?android:textAppearanceMedium"
android:textColor="#fff"
android:textStyle="bold" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
log cat
FATAL EXCEPTION: main
Process: com.shuan.Project, PID: 1432
java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at com.shuan.Project.signup.employee.CSLActivity$1.afterTextChanged(CSLActivity.java:95)
at android.widget.TextView.sendAfterTextChanged(TextView.java:7998)
at android.widget.TextView$ChangeWatcher.afterTextChanged(TextView.java:9814)
at android.text.SpannableStringBuilder.sendAfterTextChanged(SpannableStringBuilder.java:990)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:529)
at android.text.SpannableStringBuilder.delete(SpannableStringBuilder.java:224)
at android.text.SpannableStringBuilder.delete(SpannableStringBuilder.java:38)
at android.view.inputmethod.BaseInputConnection.deleteSurroundingText(BaseInputConnection.java:252)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:389)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:78)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5649)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
Try this code
public void afterTextChanged(Editable s) {
if(to_yr.getText().toString().length != 0){
j =Integer.parseInt(to_yr.getText().toString());
}
}
it works fine for me
At a first look, to me it seems to block on onAfterTextChanged, because is trying to parse an int from a String which is empty, so it just throws the error.
Try to verify if the EditText is "" before of parsing the integer, if it is not "" or null do as your code, if it's "" or null give it a default value, like 0 or what you want.
This crash is because of your code in afterTextChanged callback.
You should check if to_yr.getText is having some valid value before parsing it to the integer. Do not parse empty string.
Use below code:
public void afterTextChanged(Editable s) {
if(!TextUtils.isEmpty(to_yr.getText()){
j = Integer.parseInt(to_yr.getText().toString());
}
}
This is happening because you parse the empty string and the Integer class throws exception named:
Invalid int
java.lang.NumberFormatException
Do the check before parsing integer. For example
String s;
if(s != null && (!s.isEmpty())){
Integer i = s.ParseInt();
}
Related
Actually I created a pdf viewer and i jus want to create a longclicklistener to open my new activity and as u can see here
Screenshot
And there is already a click listener assigned with this button and i also want to combine longclicklistener so when i long click that button then automatically launch my second activity
public void actionButtonClick(View view) {
if (pageCount == 0) {
Toast.makeText(getApplicationContext(), getString(R.string.no_selected_pdf), Toast.LENGTH_LONG).show();
return;
}
final BottomSheetDialog dialog = new BottomSheetDialog(MainActivity.this);
dialog.setContentView(R.layout.bottom_sheet);
dialog.setCanceledOnTouchOutside(true);
NumberPicker numberPicker = (NumberPicker) dialog.findViewById(R.id.number_picker);
if (numberPicker != null) {
numberPicker.setMaxValue(pageCount);
numberPicker.setValue(pdfView.getCurrentPage() + 1);
numberPicker.setOnValueChangedListener((picker, oldVal, newVal) -> {
pdfView.jumpTo(newVal - 1, true);
});
}
dialog.show();
}
public void openButtonClick(View view) {
launchPicker();
}
private void startAnimation(int state) {
actionLayout.animate()
.translationY(state == 0 ? actionLayout.getHeight() : 0)
.alpha(state == 0 ? 0 : 1.0f)
.setDuration(300).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
menu.findItem(R.id.hide_or_show_button).setChecked(state != 1);
super.onAnimationEnd(animation);
}
});
}
private void hideOrShowActionButton() {
if (actionLayout.getAlpha() == 1.0)
startAnimation(0);
else
startAnimation(1);
}
private void showSnackBar(#NonNull String msg, boolean isError) {
Snackbar snackbar = Snackbar
.make(findViewById(R.id.main_layout), msg, Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(ContextCompat
.getColor(Objects.requireNonNull(getApplicationContext()),
isError ? R.color.err_color : R.color.main_color));
snackbar.setTextColor(ContextCompat
.getColor(Objects.requireNonNull(getApplicationContext()), R.color.white));
snackbar.show();
}
#Override
public void loadComplete(int nbPages) {
pageCount = nbPages;
warningLayout.setVisibility(View.GONE);
PdfDocument.Meta meta = pdfView.getDocumentMeta();
detailsMap.clear();
detailsMap.add(meta.getTitle());
detailsMap.add(meta.getAuthor());
detailsMap.add(meta.getSubject());
detailsMap.add(meta.getKeywords());
detailsMap.add(meta.getCreator());
detailsMap.add(meta.getProducer());
detailsMap.add(dateFormatter(meta.getCreationDate()));
detailsMap.add(dateFormatter(meta.getModDate()));
}
private String dateFormatter(String data) {
if (!data.isEmpty()) {
String date = data.substring(2);
String y = date.substring(0, 4);
String m = date.substring(4, 6);
String d = date.substring(6, 8);
return y + "/" + m + "/" + d;
} else {
return data;
}
}
#Override
public void onPageChanged(int page, int pageCount) {
pageNumber.setText(String.valueOf(page + 1));
}
#Override
public void onPageError(int page, Throwable t) {
showSnackBar(getString(R.string.page_not_loaded) + page, true);
}
}
Xml File
This Is Xml File if needed
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.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:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_color"
tools:context=".MainActivity">
<com.github.barteksc.pdfviewer.PDFView
android:id="#+id/pdf_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_color"
app:layout_anchor="#+id/warning"
app:layout_anchorGravity="center">
<Button
android:id="#+id/button"
android:layout_width="42dp"
android:layout_height="11dp"
android:layout_below="#id/textView"
android:layout_alignParentBottom="true"
android:layout_marginBottom="518dp"
android:text="open activity 2" />
</com.github.barteksc.pdfviewer.PDFView>
<LinearLayout
android:id="#+id/warning"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/no_selected_pdf"
android:textColor="#color/secondary_text_color"
android:textSize="16sp" />
<TextView
android:id="#+id/tv_open_pdf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:clickable="true"
android:focusable="true"
android:onClick="openButtonClick"
android:padding="10dp"
android:text="#string/click_to_select_pdf"
android:textColor="#color/main_color"
android:textSize="18sp" />
</LinearLayout>
<FrameLayout
android:id="#+id/action_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/action_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="20dp"
android:contentDescription="#string/action_btn_description"
android:onClick="actionButtonClick"
app:backgroundTint="#color/main_color"
app:borderWidth="0dp"
app:tint="#color/white" />
<TextView
android:id="#+id/tv_page_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:elevation="16dp"
android:text="x"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/white"
android:textSize="16sp" />
</FrameLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
There is an onClick and onLongClick listener for each view :
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
FloatingActionButton actionButton = findViewById(R.id.actionButton);
actionButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// start your activity from here
return true;
}
});
}
I have issue when I change some value, example delete comment in my recyclerview it's doesn't update automatically, Google says use LiveData DataBinding RecyclerView, is anyone ever to make RecyclerView LiveData databinding please help me out
This is my MainActivity.java
public class TabDetailHotActivity extends AppCompatActivity {
//GLOBAL
public static MainActivity mainActivity_;
TextView TVGameDate;
TextView TVGameTitle;
ImageView IMGGameImage;
TextView TVSeenCounter;
TextView TVCommentCounter;
TextView TVLikeCounter;
ImageView IMGSeenView;
ImageView IMGCommentView;
ImageView IMGLikeView;
ImageView ICONHotTrendingNewsSaving;
//EVENT BUS
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MainActivity.EventStoredMessageTrending event) {
getMessageTrendingMainActivity(event.SendMessageUrutan, event.SendTotalThread, event.SendMessageIDComment, event.SendMessageComment, event.SendMessageEntryTime, event.SendMessageisEdited, event.SendMessageEditTime);
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MainActivity.EventStoredMessageTrendingLogin event) {
getMessageTrendingLoginMainActivity(event.SendMessageUrutan, event.SendTotalThread, event.SendMessageIDComment, event.SendMessageComment, event.SendMessageEntryTime, event.SendMessageisEdited, event.SendMessageEditTime, event.SendMessageEditable);
}
public void getMessageTrendingMainActivity(int ReceivedMessageUrutan, int ReceivedTotalThread, String ReceivedMessageIDComment, String ReceivedMessageComment, String ReceivedMessageEntryTime, int ReceivedMessageEdited, String ReceivedMessageEditTime){
Toast.makeText(this, "Load Comment Not Login :( >> ReceivedMessageComment:"+ReceivedMessageComment+", Toast.LENGTH_LONG).show();
}
public void getMessageTrendingLoginMainActivity(int ReceivedMessageUrutan, int ReceivedTotalThread, String ReceivedMessageIDComment, String ReceivedMessageComment, String ReceivedMessageEntryTime, int ReceivedMessageEdited, String ReceivedMessageEditTime, int ReceivedMessageEditable){
Toast.makeText(this, "Load Comment Login :) >> ReceivedMessageComment:" + ReceivedMessageComment, Toast.LENGTH_LONG).show();
createDummyDataComment(ReceivedMessageUrutan, ReceivedTotalThread, ReceivedMessageIDComment, ReceivedMessageComment, ReceivedMessageEntryTime, ReceivedMessageEdited, ReceivedMessageEditTime, ReceivedMessageEditable);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activitydetail_tabhot);
ToolbarX = findViewById(R.id.toolbar);
setSupportActionBar(ToolbarX);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final CollapsingToolbarLayout collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar);
collapsingToolbarLayout.setTitle("");
Intent intent = getIntent();
mDummyIDContent = intent.getStringExtra("DummyIDContentPKG");
mDummyTitle = intent.getStringExtra("DummyTitlePKG");
mDummyPublishTime = intent.getStringExtra("DummyPublishTimePKG");
mDummyImageOriPKG = intent.getStringExtra("DummyImageOriPKG");
mDummyShortDescription = intent.getStringExtra("DummyShortDescriptionPKG");
mDummySeen = intent.getIntExtra("DummySeenPKG", 0);
mDummyComment = intent.getIntExtra("DummyCommentPKG", 0);
mDummyLike = intent.getIntExtra("DummyLikePKG", 0);
mDummyisComment = intent.getIntExtra("DummyisCommentPKG", 0);
mDummyisLike = intent.getIntExtra("DummyisLikePKG", 0);
mDummyisBookmark = intent.getIntExtra("DummyisBookmarkPKG", 0);
date_Behaviour = findViewById(R.id.date_behavior);
IMGGameImage = findViewById(R.id.backdrop);
TVGameDate = findViewById(R.id.date);
TVGameTitle = findViewById(R.id.title);
TVSeenCounter = findViewById(R.id.TV_SeenCounter);
TVCommentCounter = findViewById(R.id.TV_CommentCounter);
TVLikeCounter = findViewById(R.id.TV_LikeCounter);
RequestOptions requestOptions = new RequestOptions();
requestOptions.error(UtilsNews.getRandomDrawbleColor());
TVGameDate.setText(mDummyPublishTime);
TVGameTitle.setText(mDummyTitle);
TVSeenCounter.setText(String.valueOf(mDummySeen));
TVCommentCounter.setText(String.valueOf(mDummyComment));
TVLikeCounter.setText(String.valueOf(mDummyLike));
Glide.with(this)
.load(mDummyImageOriPKG)
.apply(requestOptions)
.transition(DrawableTransitionOptions.withCrossFade())
.into(IMGGameImage);
/* initWebView(mUrl);*/
ImageButton BTNSendMessageDetailHotTrendingNews = findViewById(R.id.BTN_SendMessageDetailHotTrendingNews);
final TextView ETSendMessageDetailHotTrendingNews = findViewById(R.id.ET_SendMessageDetailHotTrendingNews);
BTNSendMessageDetailHotTrendingNews.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String TheMessage = ETSendMessageDetailHotTrendingNews.getText().toString();
if(!TheMessage.equals("")){
if(mainActivity_!=null) {
mainActivity_.rncryptorLoadSendEditDelete("SendComment", mDummyIDContent, TheMessage);
}
}else{
Toast.makeText(TabDetailHotActivity.this, "You don't send anything", Toast.LENGTH_SHORT).show();
}
ETSendMessageDetailHotTrendingNews.setText("");
}
});
//
if(mainActivity_!=null) {
mainActivity_.rncryptorLoadSendEditDelete("LoadComment", mDummyIDContent, "");
}
}
private void initWebView(String url) {
WebView webView = findViewById(R.id.webView);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(url);
}
ArrayList<ModelDetailHotTrendingNewsComment> modelDetailHotTrendingNewsComments = new ArrayList<ModelDetailHotTrendingNewsComment>();
AdapterDetailHotTrendingNewsComment.RecyclerViewClickListener listenerDetailHotTrendingNewsComment;
public void createDummyDataComment(int ReceivedMessageUrutan, int ReceivedTotalThread, final String ReceivedMessageIDComment, String ReceivedMessageComment, String ReceivedMessageEntryTime, int ReceivedMessageEdited, String ReceivedMessageEditTime, int ReceivedMessageEditable) {
modelDetailHotTrendingNewsComments.add(new ModelDetailHotTrendingNewsComment(ReceivedMessageIDComment,ReceivedMessageComment,ReceivedMessageEntryTime,ReceivedMessageEditable,ReceivedMessageEditTime));
if(ReceivedMessageUrutan == ReceivedTotalThread-1){
listenerDetailHotTrendingNewsComment = new AdapterDetailHotTrendingNewsComment.RecyclerViewClickListener(){
#Override
public void onRowDetailHotTrendingNewsContainerClick(View view, int position) {
}
#Override
public void onRowMessageEditClick(View view, int position) {
}
#Override
public void onRowMessageDeleteClick(View view, final int position) {
String[] YOURCHOICE = {"Yes", "No"};
AlertDialog.Builder builder = new AlertDialog.Builder(TabDetailHotActivity.this);
builder.setTitle("Do you want to delete this comment?");
builder.setItems(YOURCHOICE, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(which == 0){
Toast.makeText(TabDetailHotActivity.this, "Deleted Successfully!", Toast.LENGTH_SHORT).show();
if(mainActivity_!=null) {
mainActivity_.rncryptorLoadSendEditDelete("DeleteComment", modelDetailHotTrendingNewsComments.get(position).getIdcontent(), "");
}
}else if(which == 1){
Toast.makeText(TabDetailHotActivity.this, "You don't delete the Comment", Toast.LENGTH_SHORT).show();
}
}
});
builder.show();
}
};
RecyclerView RVDetailHotTrendingNewsComment = findViewById(R.id.RVDetail_HotTrendingNewsComment);
RVDetailHotTrendingNewsComment.setHasFixedSize(true);
AdapterDetailHotTrendingNewsComment adapterDetailHotTrendingNewsComment = new AdapterDetailHotTrendingNewsComment(this, modelDetailHotTrendingNewsComments, listenerDetailHotTrendingNewsComment);
RVDetailHotTrendingNewsComment.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
RVDetailHotTrendingNewsComment.setAdapter(adapterDetailHotTrendingNewsComment);
//Optimized
RVDetailHotTrendingNewsComment.setHasFixedSize(true);
RVDetailHotTrendingNewsComment.setItemViewCacheSize(20);
}
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#Override
public void onBackPressed() {
super.onBackPressed();
supportFinishAfterTransition();
}
//EVENTBUS
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
}
This is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.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"
android:background="#color/darkgrey"
tools:context=".TabDetailHotActivity">
<androidx.core.widget.NestedScrollView
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:background="#color/darkgrey"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:background="#color/darkgrey"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/title"
android:textColor="#color/colorWhite"
android:textStyle="bold"
android:fontFamily="sans-serif-light"
android:textSize="19sp"
android:text="Title of News"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_below="#id/title"
android:textColor="#color/colorWhite"
android:layout_marginTop="10dp"
android:maxLines="1"
android:drawablePadding="10dp"
android:singleLine="true"
android:ellipsize="end"
android:text="a time ago" />
<ImageView
android:id="#+id/IMG_SeenView"
android:src="#drawable/watch"
android:layout_marginLeft="8dp"
android:layout_width="22dp"
android:layout_height="22dp"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#id/TV_SeenCounter"
android:paddingTop="2dp"
android:layout_marginTop="1dp"
android:scaleType="centerInside"
android:adjustViewBounds="true"/>
<TextView
android:id="#+id/TV_SeenCounter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#id/IMG_CommentView"
android:text="999"
android:layout_marginTop="2dp"
android:textSize="14dp"
android:textColor="#color/white"
android:paddingLeft="#dimen/small_intrinsic_padding"
android:textAppearance="#style/TextAppearance.Second.Light" />
<ImageView
android:id="#+id/IMG_CommentView"
android:src="#drawable/comment_off"
android:layout_toLeftOf="#id/TV_CommentCounter"
android:layout_alignParentBottom="true"
android:layout_width="18dp"
android:layout_height="18dp"
android:layout_marginTop="4dp"
android:layout_marginLeft="5dp"
android:layout_marginBottom="2dp"
android:scaleType="centerInside"
android:adjustViewBounds="true"/>
<TextView
android:id="#+id/TV_CommentCounter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#id/IMG_LikeView"
android:layout_marginTop="2dp"
android:text="999"
android:textSize="14dp"
android:textColor="#color/white"
android:paddingLeft="#dimen/small_intrinsic_padding"
android:textAppearance="#style/TextAppearance.Second.Light" />
<ImageView
android:id="#+id/IMG_LikeView"
android:src="#drawable/heart_off"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#id/TV_LikeCounter"
android:layout_width="18dp"
android:layout_height="18dp"
android:layout_marginTop="4dp"
android:layout_marginLeft="5dp"
android:layout_marginBottom="2dp"
android:scaleType="centerInside"
android:adjustViewBounds="true"/>
<TextView
android:id="#+id/TV_LikeCounter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:layout_alignParentEnd="true"
android:text="999"
android:textSize="14dp"
android:layout_alignParentBottom="true"
android:textColor="#color/white"
android:paddingLeft="#dimen/small_intrinsic_padding"
android:textAppearance="#style/TextAppearance.Second.Light" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/darkgrey">
<ProgressBar
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:id="#+id/progress_bar"
android:layout_marginTop="50dp"
android:layout_marginBottom="70dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<WebView
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/RL_Bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:background="#FFFFFF"
android:layout_alignParentBottom="true">
<EditText
android:id="#+id/ET_SendMessageDetailHotTrendingNews"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:hint="Type a comment..."
android:layout_toLeftOf="#id/BTN_SendMessageDetailHotTrendingNews"
android:layout_centerVertical="true"/>
<ImageButton
android:id="#+id/BTN_SendMessageDetailHotTrendingNews"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="#drawable/ic_send_black_24dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/darkgrey">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/RVDetail_HotTrendingNewsComment"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
<FrameLayout
android:id="#+id/date_behavior"
app:layout_anchor="#+id/appbar"
app:behavior_autoHide="true"
android:adjustViewBounds="true"
app:layout_anchorGravity="right|end|bottom"
android:clickable="false"
android:background="#drawable/round_white"
android:layout_width="wrap_content"
android:padding="5dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
android:layout_marginBottom="410dp"
android:layout_height="wrap_content"
tools:ignore="UnusedAttribute">
<ImageView
android:src="#drawable/ic_date"
android:layout_width="18dp"
android:layout_height="18dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"/>
<TextView
android:textColor="#606060"
android:id="#+id/date"
android:layout_marginLeft="27dp"
android:layout_marginRight="10dp"
android:text="01 January 1990"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
This is AdapterComment.java
public class AdapterDetailHotTrendingNewsComment extends RecyclerView.Adapter {
private Context mContext;
private ArrayList<ModelDetailHotTrendingNewsComment> modelDetailHotTrendingNewsComments;
private AdapterDetailHotTrendingNewsComment.RecyclerViewClickListener mListener;
public AdapterDetailHotTrendingNewsComment(Context mContext, ArrayList<ModelDetailHotTrendingNewsComment> modelDetailHotTrendingNewsComments, AdapterDetailHotTrendingNewsComment.RecyclerViewClickListener mListener) {
this.mContext = mContext;
this.modelDetailHotTrendingNewsComments = modelDetailHotTrendingNewsComments;
this.mListener = mListener;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemdetail_hottrendingnewscomment, null);
return new DetailHotTrendingNewsViewHolder(v, mListener);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
final DetailHotTrendingNewsViewHolder detailHotTrendingNewsViewHolder = (DetailHotTrendingNewsViewHolder) holder;
final ModelDetailHotTrendingNewsComment modelDetailHotTrendingNewsCommentX = modelDetailHotTrendingNewsComments.get(position);
Glide.with(mContext).load(modelDetailHotTrendingNewsCommentX.getMessageimage()).into(detailHotTrendingNewsViewHolder.IMGMessageImage);
detailHotTrendingNewsViewHolder.TVMessageUsername.setText(modelDetailHotTrendingNewsCommentX.getMessageusername());
detailHotTrendingNewsViewHolder.TVMessageDescription.setText(modelDetailHotTrendingNewsCommentX.getMessagedescription());
detailHotTrendingNewsViewHolder.TVMessageDate.setText(modelDetailHotTrendingNewsCommentX.getMessagedate());
}
#Override
public int getItemCount() {
int itemCount = modelDetailHotTrendingNewsComments.size();
return itemCount;
}
public class DetailHotTrendingNewsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView IMGMessageImage;
TextView TVMessageUsername;
TextView TVMessageDescription;
TextView TVMessageDate;
private RelativeLayout ROWDetailHotTrendingNewsContainer;
TextView TVMessageEdit;
ImageView IMGMessageDelete;
private AdapterDetailHotTrendingNewsComment.RecyclerViewClickListener mListener;
public DetailHotTrendingNewsViewHolder(View itemView, AdapterDetailHotTrendingNewsComment.RecyclerViewClickListener listener) {
super(itemView);
IMGMessageImage = itemView.findViewById(R.id.IMG_MessageImage);
TVMessageUsername = itemView.findViewById(R.id.TV_MessageUsername);
TVMessageDescription = itemView.findViewById(R.id.TV_MessageDescription);
TVMessageDate = itemView.findViewById(R.id.TV_MessageDate);
ROWDetailHotTrendingNewsContainer = itemView.findViewById(R.id.ROW_DetailHotTrendingNewsContainer);
TVMessageEdit = itemView.findViewById(R.id.TV_MessageEdit);
IMGMessageDelete = itemView.findViewById(R.id.IMG_MessageDelete);
mListener = listener;
ROWDetailHotTrendingNewsContainer.setOnClickListener(this);
TVMessageEdit.setOnClickListener(this);
IMGMessageDelete.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ROW_DetailHotTrendingNewsContainer:
mListener.onRowDetailHotTrendingNewsContainerClick(ROWDetailHotTrendingNewsContainer, getAdapterPosition());
break;
case R.id.TV_MessageEdit:
mListener.onRowMessageEditClick(TVMessageEdit, getAdapterPosition());
break;
case R.id.IMG_MessageDelete:
mListener.onRowMessageDeleteClick(IMGMessageDelete, getAdapterPosition());
break;
default:
break;
}
}
}
public interface RecyclerViewClickListener {
void onRowDetailHotTrendingNewsContainerClick(View view, int position);
void onRowMessageEditClick(View view, int position);
void onRowMessageDeleteClick(View view, int position);
}
}
This is ModelComment.java
public class ModelDetailHotTrendingNewsComment {
private String idcontent;
private String messageimage;
private String messageusername;
private String messagedescription;
private String messagedate;
private int messageisedit;
private String messageedittime;
private String messageedit;
private String messagedelete;
public ModelDetailHotTrendingNewsComment(String idcontent, String messagedescription, String messagedate, int messageisedit, String messageedittime) {
this.idcontent = idcontent;
this.messagedescription = messagedescription;
this.messagedate = messagedate;
this.messageisedit = messageisedit;
this.messageedittime = messageedittime;
}
public String getIdcontent() {
return idcontent;
}
public void setIdcontent(String idcontent) {
this.idcontent = idcontent;
}
public String getMessageimage() {
return messageimage;
}
public void setMessageimage(String messageimage) {
this.messageimage = messageimage;
}
public String getMessageusername() {
return messageusername;
}
public void setMessageusername(String messageusername) {
this.messageusername = messageusername;
}
public String getMessagedescription() {
return messagedescription;
}
public void setMessagedescription(String messagedescription) {
this.messagedescription = messagedescription;
}
public String getMessagedate() {
return messagedate;
}
public void setMessagedate(String messagedate) {
this.messagedate = messagedate;
}
public String getMessageedittime() {
return messageedittime;
}
public void setMessageedittime(String messageedittime) {
this.messageedittime = messageedittime;
}
public String getMessageedit() {
return messageedit;
}
public void setMessageedit(String messageedit) {
this.messageedit = messageedit;
}
public String getMessagedelete() {
return messagedelete;
}
public void setMessagedelete(String messagedelete) {
this.messagedelete = messagedelete;
}
}
To avoid unnecessary stuff, the validate function is called when the update, delete, insert button are clicked. The problem is with the EditText with inputType="number" i.e with etPrice and etSNumber.I think,there is something wrong with the validate_price() and validate_supplier_no().Please Correct Me.
public class QueryActivity extends AppCompatActivity {
private EditText etName, etPrice, etSupplier, etSNumber;
private Button insert_btn, increment, decrement, update_btn, delete_btn, call_btn;
private TextView quantity_tv;
private int quantity_value = 0;
private TextInputLayout inputLayout_name, inputLayout_price, inputLayout_supplier, inputLayout_supplier_no;
int _id, price, quantity, supplier_no = 0;
String name, supplier;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_query);
increment = findViewById(R.id.increment);
decrement = findViewById(R.id.decrement);
insert_btn = findViewById(R.id.insert_btn);
update_btn = findViewById(R.id.update_product);
delete_btn = findViewById(R.id.delete_product);
call_btn = findViewById(R.id.call_btn);
etName = findViewById(R.id.et_name);
etPrice = findViewById(R.id.et_price);
quantity_tv = findViewById(R.id.quantity);
etSupplier = findViewById(R.id.et_supplier);
etSNumber = findViewById(R.id.et_sNumber);
inputLayout_name = findViewById(R.id.textInput_name);
inputLayout_price = findViewById(R.id.textInput_price);
inputLayout_supplier = findViewById(R.id.textInput_supplier);
inputLayout_supplier_no = findViewById(R.id.textInput_supplier_no);
Intent intent = getIntent();
_id = intent.getIntExtra("_id", 0);
name = intent.getStringExtra("name");
price = intent.getIntExtra("price", 0);
quantity = intent.getIntExtra("quantity", 0);
quantity_value = quantity;
supplier = intent.getStringExtra("supplier");
supplier_no = intent.getIntExtra("supplier_no", 0);
String price_str = String.valueOf(price);
if (_id != 0) {
etName.setText(name.toString());
etPrice.setText(String.valueOf(price));
quantity_tv.setText(String.valueOf(quantity).toString());
etSupplier.setText(supplier.toString());
etSNumber.setText(String.valueOf(supplier_no));
insert_btn.setVisibility(View.GONE);
} else {
update_btn.setVisibility(View.GONE);
delete_btn.setVisibility(View.GONE);
}
//OnClickListeners
insert_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(v);
insertProduct();
}
});
update_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(v);
updateProduct();
}
});
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(v);
deleteProduct();
}
});
//add quantity btn
increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
quantity_value += 1;
display(quantity_value);
}
});
//subtract quantity btn
decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
quantity_value -= 1;
if (quantity_value <= -1) {
quantity_value = 0;
}
display(quantity_value);
}
});
call_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(supplier_no==0){
Toast.makeText(getApplicationContext(),"Please Enter Supplier Number",Toast.LENGTH_SHORT).show();
}
else {
Intent intent_call = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", String.valueOf(supplier_no), null));
startActivity(intent_call);
}
}
});
}//onCreate Ends
public void validate(View view) {
try {
if (validate_name() && validate_price() && validate_supplier() && validate_supplier_no()) {
Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_SHORT).show();
}
}
catch (NumberFormatException e){
Toast.makeText(getApplicationContext(), "Not Success!", Toast.LENGTH_SHORT).show();
}
}
private boolean validate_supplier_no() {
if (TextUtils.isEmpty(etSNumber.getText().toString())) {
inputLayout_supplier_no.setError("Invalid input");
return false;
} else {
inputLayout_supplier_no.setErrorEnabled(false);
return true;
}
}
private boolean validate_supplier() {
if (etSupplier.getText().toString().isEmpty()) {
inputLayout_supplier.setError("Supplier cannot be blanked");
return false;
} else {
inputLayout_supplier.setErrorEnabled(false);
return true;
}
}
private boolean validate_price() {
if (TextUtils.isEmpty(etPrice.getText().toString())) {
inputLayout_price.setError("Invalid input");
return false;
} else {
inputLayout_price.setErrorEnabled(false);
return true;
}
}
private boolean validate_name() {
if (etName.getText().toString().isEmpty()) {
inputLayout_name.setError("Name cannot be blanked");
return false;
} else {
inputLayout_name.setErrorEnabled(false);
return true;
}
}
private void deleteProduct() {
String selection = _ID + " = ? ";
String[] selectionArgs = {String.valueOf(_id)};
Uri uri = ContentUris.withAppendedId(CONTENT_URI, _id);
int rowsDeleted = getContentResolver().delete(uri, selection, selectionArgs);
}
private void updateProduct() {
String selection = _ID + " = ? ";
String[] selectionArgs = {String.valueOf(_id)};
String et_productName = etName.getText().toString();
int et_productPrice = Integer.parseInt(etPrice.getText().toString());
int tv_productQuantity = Integer.parseInt(quantity_tv.getText().toString());
String et_productSupplier = etSupplier.getText().toString();
int et_productSNumber = Integer.parseInt(etSNumber.getText().toString());
ContentValues values = new ContentValues();
values.put(PRODUCT_NAME, et_productName);
values.put(PRICE, et_productPrice);
values.put(QUANTITY, tv_productQuantity);
values.put(SUPPLIER, et_productSupplier);
values.put(SUPPLIER_NO, et_productSNumber);
Uri uri = CONTENT_URI;
int rowsUpdated = getContentResolver().update(uri, values, selection, selectionArgs);
Toast.makeText(this, "Item inserted at: " + rowsUpdated, Toast.LENGTH_SHORT).show();
}
private void insertProduct() {
String et_productName = etName.getText().toString();
int et_productPrice = Integer.parseInt(etPrice.getText().toString());
int tv_productQuantity = Integer.parseInt(quantity_tv.getText().toString());
String et_productSupplier = etSupplier.getText().toString();
int et_productSNumber = Integer.parseInt(etSNumber.getText().toString());
ContentValues values = new ContentValues();
values.put(PRODUCT_NAME, et_productName);
values.put(PRICE, et_productPrice);
values.put(QUANTITY, tv_productQuantity);
values.put(SUPPLIER, et_productSupplier);
values.put(SUPPLIER_NO, et_productSNumber);
Uri uri = CONTENT_URI;
Uri uriRowsInserted = getContentResolver().insert(uri, values);
Toast.makeText(this, "Item inserted at: " + uriRowsInserted, Toast.LENGTH_SHORT).show();
}
//for updating the quantity_tv
public void display(int number) {
quantity_tv.setText(String.valueOf(number));
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<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:background="#e0e0e0"
android:orientation="vertical"
tools:context=".QueryActivity"
>
<android.support.design.widget.TextInputLayout
android:id="#+id/textInput_name"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Product Name..."
android:inputType="text" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/textInput_price"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/et_price"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Product Price..."
android:inputType="number" />
</android.support.design.widget.TextInputLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal">
<Button
android:id="#+id/increment"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="+" />
<TextView
android:id="#+id/quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="0"
android:textSize="24sp" />
<Button
android:id="#+id/decrement"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="-" />
</LinearLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/textInput_supplier"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/et_supplier"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Supplier Name..."
android:inputType="text" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/textInput_supplier_no"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/et_sNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter SupplierNumber..."
android:inputType="number" />
</android.support.design.widget.TextInputLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:gravity="center_horizontal"
android:orientation="vertical">
<Button
android:id="#+id/insert_btn"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#drawable/button_layout"
android:text="ADD IT" />
<Button
android:id="#+id/delete_product"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#drawable/button_layout"
android:text="DELETE IT" />
<Button
android:id="#+id/update_product"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#drawable/button_layout"
android:text="Save Changes" />
<Button
android:id="#+id/call_btn"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:background="#drawable/button_layout"
android:drawableLeft="#drawable/call"
android:drawablePadding="-40dp"
android:text="CALL" />
</LinearLayout>
</LinearLayout>
Note: With Empty etPrice or etSNumber,this code throws java.lang.NumberFormatException: Invalid int: ""
You should call insertProduct, deleteProduct and updateProduct only if inputs are valid. Change your method validate like below
public boolean validate(View view) {
try {
if (validate_name() && validate_price() && validate_supplier() && validate_supplier_no()) {
Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_SHORT).show();
return true;
}
}
catch (NumberFormatException e){
Toast.makeText(getApplicationContext(), "Not Success!", Toast.LENGTH_SHORT).show();
}
return false;
}
and start using as
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(validate(v)) {
deleteProduct();
}
}
});
you can Set Error for your EditText not for your Layout.So you car rewrite your code by this way:
etPrice.setError ("Price cannot be blanked");
return false;
} else {
etPrice.setErrorEnabled(false);
return true;
As a beginner I have some questions about optimizing my application speed. I'm building a simple quiz app there I have an sqlite database inside with some information. With that information I'm generating my questions in quiz page.
It was working pretty fine and fast until I fixed some buttons/background in sketch and use them. Now it's working much more slower and I'm getting error messages at logcat like "Skipped xxx frames! The application may be doing too much work on its main thread." I have searched on google for a while and found out that the bitmaps are slowing down my application. Have read about async and using a new thread to make it run faster.
As a solution I have resized some of my bitmaps, but then I'm getting less quality in my design, so I decided to fix it. I have googled some more about loading my layout with async or a new thread but didn't really find out how/where to do it. What makes me confused is that I don't know if it's to load layout with a new thread is the best solution or to load other processes with new thread. Need some recommendation about how to optimize my app. Here is my code, at least the quiz page that is slowest. I'm not really sure what to optimize there with a new thread. Under a question it's just countdowntimer that is running, and when next clicked countdowntimer starts over and the gui updates with the new question.
My quizpage code:
public class QuizPage extends ActionBarActivity
{
DatabaseHelper dbHelper = new DatabaseHelper(this);
Cursor kommunCrs, lanCrs, riktCrs;
ArrayList<Kommuner> kommunLista = new ArrayList<Kommuner>();
ArrayList<Lan> lanLista = new ArrayList<Lan>();
ArrayList<Riktnummer> riktLista = new ArrayList<Riktnummer>();
ArrayList<Fragar> fragaLista = new ArrayList<Fragar>();
Fragar svList = new Fragar();
Fragar frageObj = new Fragar();
int buttonRaknare = 0;
CountDownTimer cd;
long millisLeft;
long totalMillis = 10100;
int pBarProgress;
TextView pageNr, fraga, cdText;
RadioButton valA, valB, valC, valD;
RadioGroup rg;
Button avsluta, nasta;
ProgressBar pBar;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_page);
checkDB(); // Checking the DB
getCursorData(); // Getting data to cursors
setCrsdataList(); // Setting cursor data to lists
setViewElements(); // Set textview, buttons etc.
setButtonListeners();
getNastaFragaData(); // Refresing the gui with the next question
startCountdownTimer(totalMillis, false); // Countdowntimer starts
}
private void getCursorData()
{
kommunCrs = dbHelper.getDatabase().query("Kommuner ORDER BY RANDOM() LIMIT 50", new String[]{"kommun_id", "kommun_namn", "kommun_lan", "kommun_befolkning"}, null, null, null, null, null);
lanCrs = dbHelper.getDatabase().query("Lan ORDER BY RANDOM()", new String[]{"lan_namn", "lan_befolkning", "lan_antal_kommun", "lan_yta", "lan_id"}, null, null, null, null, null);
riktCrs = dbHelper.getDatabase().query("Riktnummer ORDER BY RANDOM() LIMIT 50", new String[]{"riktnr", "riktnr_omrade", "riktnr_id"}, null, null, null, null, null);
}
private void setCrsdataList()
{
if (kommunCrs.getCount() != 0 && lanCrs.getCount() != 0 && riktCrs.getCount() != 0) {
kommunCrs.moveToFirst();
lanCrs.moveToFirst();
riktCrs.moveToFirst();
for (int i = 0; i < kommunCrs.getCount(); i++) {
Kommuner tempKommun = new Kommuner();
tempKommun.setKommun_namn(kommunCrs.getString(kommunCrs.getColumnIndex("kommun_namn")));
tempKommun.setKommun_lan(kommunCrs.getString(kommunCrs.getColumnIndex("kommun_lan")));
tempKommun.setKommun_befolkning(kommunCrs.getString(kommunCrs.getColumnIndex("kommun_befolkning")));
tempKommun.setKommun_id(kommunCrs.getInt(kommunCrs.getColumnIndex("kommun_id")));
kommunLista.add(tempKommun);
kommunCrs.moveToNext();
}
for (int i = 0; i < lanCrs.getCount(); i++) {
Lan tempLan = new Lan();
tempLan.setLan_namn(lanCrs.getString(lanCrs.getColumnIndex("lan_namn")));
tempLan.setLan_befolkning(lanCrs.getString(lanCrs.getColumnIndex("lan_befolkning")));
tempLan.setLan_antal_kommun(lanCrs.getString(lanCrs.getColumnIndex("lan_antal_kommun")));
tempLan.setLan_yta(lanCrs.getString(lanCrs.getColumnIndex("lan_yta")));
tempLan.setLan_id(lanCrs.getInt(lanCrs.getColumnIndex("lan_id")));
lanLista.add(tempLan);
lanCrs.moveToNext();
}
for (int i = 0; i < riktCrs.getCount(); i++) {
Riktnummer tempRiktnr = new Riktnummer();
tempRiktnr.setRiktnr(riktCrs.getString(riktCrs.getColumnIndex("riktnr")));
tempRiktnr.setRiktnr_omrade(riktCrs.getString(riktCrs.getColumnIndex("riktnr_omrade")));
tempRiktnr.setRiktnr_id(riktCrs.getInt(riktCrs.getColumnIndex("riktnr_id")));
riktLista.add(tempRiktnr);
riktCrs.moveToNext();
}
//Generating my questions here and taking in to a list
fragaLista = frageObj.slumpaFragor(kommunLista, lanLista, riktLista);
Collections.shuffle(fragaLista);
}
else
{
Toast.makeText(getApplicationContext(), "Finns ingen data i databasen!", Toast.LENGTH_SHORT).show();
}
}
private void getNastaFragaData()
{
fraga.setText(fragaLista.get(buttonRaknare).getFraga());
valA.setText(fragaLista.get(buttonRaknare).getSvarArr().get(0).toString());
valB.setText(fragaLista.get(buttonRaknare).getSvarArr().get(1).toString());
valC.setText(fragaLista.get(buttonRaknare).getSvarArr().get(2).toString());
valD.setText(fragaLista.get(buttonRaknare).getSvarArr().get(3).toString());
pageNr.setText(Integer.toString(buttonRaknare+1) + "/20");
}
private void rattSvarCheck()
{
if (valA.isChecked())
{
fragaLista.get(buttonRaknare).userInput = valA.getText().toString();
if (valA.getText().hashCode() == fragaLista.get(buttonRaknare).getRattSvar().hashCode())
{
svList.antalRattSvar++;
}
else
{
svList.antalFelSvar++;
}
}
else if (valB.isChecked())
{
fragaLista.get(buttonRaknare).userInput = valB.getText().toString();
if (valB.getText().hashCode() == fragaLista.get(buttonRaknare).getRattSvar().hashCode())
{
svList.antalRattSvar++;
}
else
{
svList.antalFelSvar++;
}
}
else if (valC.isChecked())
{
fragaLista.get(buttonRaknare).userInput = valC.getText().toString();
if (valC.getText().hashCode() == fragaLista.get(buttonRaknare).getRattSvar().hashCode())
{
svList.antalRattSvar++;
}
else
{
svList.antalFelSvar++;
}
}
else if (valD.isChecked())
{
fragaLista.get(buttonRaknare).userInput = valD.getText().toString();
if (valD.getText().hashCode() == fragaLista.get(buttonRaknare).getRattSvar().hashCode())
{
svList.antalRattSvar++;
}
else
{
svList.antalFelSvar++;
}
}
else
{
fragaLista.get(buttonRaknare).userInput = "";
svList.antalTomtSvar++;
}
}
private void resultatToDatabas()
{
dbHelper.resultatToDatabas(svList.antalRattSvar, svList.antalFelSvar, svList.antalTomtSvar);
Intent i = new Intent(getBaseContext(),QuizResultat.class);
i.putExtra("rslist", fragaLista);
i.putExtra("sl", svList);
finish();
startActivity(i);
}
private void startCountdownTimer(long millis, final boolean isResume)
{
if (!isResume)
{
pBar.setProgress(100);
pBar.setProgressDrawable(pBar.getResources().getDrawable(R.drawable.nypbar));
}
else
{
pBar.setProgress(pBarProgress);
pBar.setProgressDrawable(pBar.getResources().getDrawable(R.drawable.nypbar));
if (pBar.getProgress() < 55 && pBar.getProgress() > 23 )
{
pBar.getProgressDrawable().setColorFilter(Color.parseColor("#FFFFB800"), PorterDuff.Mode.SRC_IN);
}
else if (pBar.getProgress() < 23)
{
pBar.getProgressDrawable().setColorFilter(Color.parseColor("#FFE71000"), PorterDuff.Mode.SRC_IN);
}
}
int callInterval = 100;
cd = new CountDownTimer(millis, callInterval)
{
public void onTick(long millisUntilFinished)
{
millisLeft = millisUntilFinished;
pBarProgress = pBar.getProgress();
int secondsRemaining = (int) millisUntilFinished / 100;
float fraction = millisUntilFinished / (float) totalMillis;
// progress bar is based on scale of 1 to 100;
pBar.setProgress((int) (fraction * 100));
cdText.setText(String.format("%2.1f", secondsRemaining / 10.0, Integer.toString(secondsRemaining)));
if (pBar.getProgress() < 55 && pBar.getProgress() > 23 )
{
pBar.getProgressDrawable().setColorFilter(Color.parseColor("#FFFFB800"), PorterDuff.Mode.SRC_IN);
}
else if (pBar.getProgress() < 23)
{
pBar.getProgressDrawable().setColorFilter(Color.parseColor("#FFE71000"), PorterDuff.Mode.SRC_IN);
}
}
public void onFinish() {
nasta.performClick();
}
}.start();
}
// Deklarera knappar, textview osv.
private void setViewElements()
{
pageNr = (TextView) findViewById(R.id.pageNumberTxt);
fraga = (TextView) findViewById(R.id.fragaTxt);
valA = (RadioButton) findViewById(R.id.valAbtn);
valB = (RadioButton) findViewById(R.id.valBbtn);
valC = (RadioButton) findViewById(R.id.valCbtn);
valD = (RadioButton) findViewById(R.id.valDbtn);
rg = (RadioGroup) findViewById(R.id.valRadioGrupp);
avsluta = (Button) findViewById(R.id.avslutaBtn);
nasta = (Button) findViewById(R.id.nastaBtn);
pBar = (ProgressBar) findViewById(R.id.progressBar);
cdText = (TextView) findViewById(R.id.counterTxt);
}
private void setButtonListeners()
{
// Nästaknapp onClick
nasta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
cd.cancel(); // Avslutar countdowntimer
rattSvarCheck(); // Kontrollerar om svaret är rätt
if (buttonRaknare > 17)
{
nasta.setBackground(getResources().getDrawable(R.drawable.avsluta_selector));
}
if (buttonRaknare != 19) // Så länge det inte är sista frågan
{
buttonRaknare++;
rg.clearCheck(); // Tar bort check från valknapparna
startCountdownTimer(totalMillis, false); // Startar om den avslutade countdowntimer
getNastaFragaData(); // Tar nästa frågans innehåll till view
}
else if (buttonRaknare == 19)
{
resultatToDatabas(); // Sparar resultaten till databasen
}
}
});
// Avslutaknapp onClick
avsluta.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
cd.cancel(); // Pausar cooldowntimer först
visaAlertDialog(); // Visar alert dialog
}
});
}
// Visa alertDialog
private void visaAlertDialog()
{
AlertDialog.Builder adBuild = new AlertDialog.Builder(this)
.setTitle("Avsluta")
.setMessage("Vill du avsluta quizet?")
.setIcon(android.R.drawable.ic_delete)
.setPositiveButton(new String(Character.toChars(0x1F616)) + " Japp! ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton(new String(Character.toChars(0x1F60A)) + " Nej", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
cd.cancel();
//RESUME COUNTDOWNTIMER
startCountdownTimer(millisLeft, true);
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
dialog.cancel();
cd.cancel();
//RESUME COUNTDOWNTIMER
startCountdownTimer(millisLeft, true);
}
});
AlertDialog alertDialog = adBuild.create();
alertDialog.show();
}
private void checkDB()
{
try
{
dbHelper.createDataBase();
dbHelper.openDataBase();
} catch (IOException a) {
a.printStackTrace();
} catch (SQLException b) {
b.printStackTrace();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
setContentView(R.layout.activity_quiz_page);
setViewElements();
setButtonListeners();
getNastaFragaData();
}
else
{
setContentView(R.layout.activity_quiz_page);
setViewElements();
setButtonListeners();
getNastaFragaData();
}
}
// onBackPressed metod som visar alertDialog
#Override
public void onBackPressed()
{
cd.cancel();
visaAlertDialog();
}
// onStop METHOD
#Override
protected void onStop()
{
super.onStop();
dbHelper.close();
}
}
My quizpage layout:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:background="#drawable/quizpage_bg"
tools:context="com.example.onur.quiz.QuizPage">
<TextView
android:layout_width="60dp"
android:layout_height="wrap_content"
android:text="1/20"
android:id="#+id/pageNumberTxt"
android:textSize="18dp"
android:textColor="#ffab6200"
android:background="#drawable/pagenumberbg"
android:textStyle="italic|bold"
android:gravity="center"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:paddingTop="2dp"
android:paddingBottom="5dp"
android:paddingRight="3dp"
android:paddingLeft="3dp" />
<Button
android:layout_width="135dp"
android:layout_height="50dp"
android:id="#+id/nastaBtn"
android:focusable="false"
android:nestedScrollingEnabled="false"
android:background="#drawable/nasta_selector"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="15dp" />
<Button
android:layout_width="30dp"
android:layout_height="30dp"
android:id="#+id/avslutaBtn"
android:background="#drawable/exit_selector"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true" />
<RadioGroup
android:id="#+id/valRadioGrupp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="false"
android:gravity="center_vertical"
android:layout_marginTop="20dp"
android:layout_alignParentStart="false"
android:layout_below="#+id/progressBar"
android:divider="#00FFFFFF"
android:layout_above="#+id/nastaBtn"
android:layout_marginBottom="10dp"
android:background="#drawable/svarbg" >
<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="valAtxt"
android:id="#+id/valAbtn"
android:checked="false"
android:textSize="22dp"
android:layout_alignParentLeft="true"
android:paddingBottom="12dp"
android:paddingTop="12dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/custom_rg_drawer"
android:paddingLeft="15dp" />
<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="valBbtn"
android:id="#+id/valBbtn"
android:checked="false"
android:textSize="22dp"
android:layout_alignLeft="#+id/nastaBtn"
android:paddingBottom="12dp"
android:paddingTop="12dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/custom_rg_drawer"
android:paddingLeft="15dp" />
<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="valCbtn"
android:id="#+id/valCbtn"
android:checked="false"
android:textSize="22dp"
android:paddingBottom="12dp"
android:paddingTop="12dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/custom_rg_drawer"
android:paddingLeft="15dp" />
<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="valDbtn"
android:id="#+id/valDbtn"
android:checked="false"
android:textSize="22dp"
android:layout_alignParentLeft="true"
android:paddingBottom="12dp"
android:paddingTop="12dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:background="#drawable/custom_rg_drawer"
android:paddingLeft="15dp" />
</RadioGroup>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Hur många personer bor i Trollhättan?"
android:id="#+id/fragaTxt"
android:textColor="#ffc37800"
android:textSize="24dp"
android:layout_marginTop="20dp"
android:layout_below="#+id/avslutaBtn"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="false"
android:gravity="center"
android:background="#drawable/fragabg"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<ProgressBar
style="#android:style/Widget.ProgressBar.Horizontal"
android:progressDrawable = "#drawable/nypbar"
android:layout_width="290dp"
android:layout_height="10dp"
android:id="#+id/progressBar"
android:layout_marginTop="15dp"
android:layout_below="#+id/fragaTxt" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="10.00"
android:id="#+id/counterTxt"
android:layout_alignParentRight="true"
android:layout_below="#+id/fragaTxt"
android:layout_marginTop="11dp" />
</RelativeLayout>
I don't think it has much to do with bitmaps, especially if you are pulling them from Drawable resources. The source of your lag is likely your database queries, which are happening in onCreate, which are blocking the main thread to do disk access. Instead, use a CursorLoader as described in https://developer.android.com/training/load-data-background/setup-loader.html
I'm here to ask you a question as a newbie in android developing. Right now I'm trying to follow a tutorial which teaches the basics of android developing in Android Studio, but I encountered an issue with my Samsung Galaxy S5.
What I'm trying to do is to import an image from the gallery and put it into an ImageView but when I try to start the application I get a crash error. I know that many people had this issue and I downloaded the samsung SDK, but I don't know what and how to use for this problem. (Sorry, but I started all this yesterday and I can't find anything that can help me...)
The code is here:
activity_main.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"
tools:context="${packageName}.${activityClass}">
<TabHost
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/tabHost"
android:layout_alignParentTop="false">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/tabCreator"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Contatto"
android:id="#+id/textView"
android:layout_gravity="center_horizontal" />
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imgContact"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:src="#drawable/no_user_logo"
android:clickable="false" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/txtName"
android:textAllCaps="false"
android:hint="Nome"
android:layout_marginTop="10dp" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:id="#+id/txtNumber"
android:hint="Numero di Telefono"
android:layout_marginTop="10dp"
android:layout_below="#id/txtName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="false" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/txtMail"
android:layout_marginTop="10dp"
android:hint="Email" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Aggiungi Contatto"
android:id="#+id/btnAdd"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:enabled="false"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:id="#+id/tabList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Contatti"
android:id="#+id/textView2"
android:layout_gravity="center_horizontal" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/banana"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</RelativeLayout>
MainActivity.java
public class MainActivity extends Activity {
EditText txtName, txtPhone, txtEmail;
List<Contact> lstContacts = new ArrayList<Contact>();
ListView lstViewContact;
ImageView img = (ImageView)findViewById(R.id.imgContact);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtName = (EditText) findViewById(R.id.txtName);
txtPhone = (EditText) findViewById(R.id.txtNumber);
txtEmail = (EditText) findViewById(R.id.txtMail);
lstViewContact = (ListView)findViewById(R.id.banana);
final Button btn = (Button) findViewById(R.id.btnAdd);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addContact(txtName.getText().toString().trim(), txtPhone.getText().toString(), txtEmail.getText().toString());
Toast.makeText(getApplicationContext(), "Banana", Toast.LENGTH_SHORT).show();
}
});
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
}
});
txtName.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
boolean goName = false, goPhone = false;
if(txtName.length() > 0) goName = txtName.getText().toString().trim().length() > 0;
if(txtPhone.length() > 0) goPhone = txtPhone.getText().toString().trim().length() > 0;
btn.setEnabled(goName && goPhone);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
txtPhone.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
boolean goName = false, goPhone = false;
if(txtName.length() > 0) goName = txtName.getText().toString().trim().length() > 0;
if(txtPhone.length() > 0) goPhone = txtPhone.getText().toString().trim().length() > 0;
btn.setEnabled(goName && goPhone);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
TabHost tabHost = (TabHost)findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("creator");
tabSpec.setContent(R.id.tabCreator);
tabSpec.setIndicator("Creator");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("list");
tabSpec.setContent(R.id.tabList);
tabSpec.setIndicator("List");
tabHost.addTab(tabSpec);
}
public void onActivityResult(int reqCode, int resCode, Intent data) {
if(resCode == RESULT_OK) {
if(reqCode == 1) img.setImageURI(data.getData());
}
}
private class lstContactsAdapter extends ArrayAdapter<Contact> {
public lstContactsAdapter() {
super(MainActivity.this, R.layout.listview_item, lstContacts);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
//Se la view non esiste io la metto come listview_item all'interno della lista alla fine (non al root)
if(view == null) view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);
Contact currentContact = lstContacts.get(position);
TextView name = (TextView)view.findViewById(R.id.contactName);
TextView phone = (TextView)view.findViewById(R.id.contactPhone);
TextView mail = (TextView)view.findViewById(R.id.contactMail);
name.setText(currentContact.getName());
phone.setText(currentContact.getPhone());
mail.setText(currentContact.getEmail());
return view;
}
}
private void addContact(String name, String phone, String email) {
lstContacts.add(new Contact(name, phone, email));
ArrayAdapter<Contact> adapter = new lstContactsAdapter();
lstViewContact.setAdapter(adapter);
}
}
I'm so sorry for asking this without a proper knowledge, but I hope you'll understand and help me. Thank you for reading and sorry for any grammatical error I did.
In your class, in place of this
public void onActivityResult(int reqCode, int resCode, Intent data) {
if(resCode == RESULT_OK) {
if(reqCode == 1) img.setImageURI(data.getData());
}
}
put this,
#Override
public void onActivityResult(int reqCode, int resCode, Intent data) {
if(resCode == RESULT_OK) {
if(reqCode == 1 && data.getData() != null)
img.setImageURI(data.getData());
}
super.onActivityResult(reqCode, resCode, data);
}
You should always call super class method to ensure default behaviour with your own. Also, #Override annotation makes sure that onActivityResult is called as a callback. Lastly, data.getData() != null ensures that you don't get a NPE.