I keep getting an error in regards to the toolbar I have in my code, If i take the code out it works fine but it was working fine before i added in a separate line for a database so i'm really confused to why this isn't working. I've added in my XML at the bottom also.
private static final String TAG = MainActivity.class.getSimpleName();
private ArrayList<Item>list = new ArrayList<Item>();
private ItemAdapter adapter;
private RecyclerView recyclerView;
private AlertDialog dialog;
#Override
***protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);***
FloatingActionButton fab = (FloatingActionButton)
findViewById(R.id.fab);
fetchRecords();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater inflater = getLayoutInflater();
View mView1 = inflater.inflate(R.layout.activity_add,null);
final EditText input_name = (EditText)
mView1.findViewById(R.id.Name);
final EditText input_age = (EditText)
mView1.findViewById(R.id.Age);
final EditText input_weight = (EditText)
mView1.findViewById(R.id.Weight);
final EditText input_height = (EditText)
mView1.findViewById(R.id.Height);
final EditText input_reach = (EditText)
mView1.findViewById(R.id.Reach);
final Button btnSave = (Button)
mView1.findViewById(R.id.btnSave);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setView(mView1).setTitle("Add new Record")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialog.dismiss();
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = input_name.getText().toString();
String age = input_age.getText().toString();
String weight = input_weight.getText().toString();
String height = input_height.getText().toString();
String reach = input_reach.getText().toString();
if (name.equals("") && age.equals("") && weight.equals("") && height.equals("")&& reach.equals("")){
Snackbar.make(view,"Field incomplete",Snackbar.LENGTH_SHORT).show();
}else {
Save(name,age,name,height,reach);
dialog.dismiss();
Snackbar.make(view,"Saving",Snackbar.LENGTH_SHORT).show();
}
}
});
dialog = builder.create();
dialog.show();
}
});
}
public void fetchRecords() {
recyclerView = (RecyclerView) findViewById(R.id.recycler);
adapter = new ItemAdapter(this,list);
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
list.clear();
Functions functions = new Functions(MainActivity.this);
ArrayList<Item>data = functions.getAllRecords();
if (data.size()>0){
for (int i = 0; i<data.size(); i++){
int id = data.get(i).getId();
String namel = data.get(i).getName();
String agel = data.get(i).getAge();
String weightl = data.get(i).getWeight();
String heightl = data.get(i).getHeight();
String reachl = data.get(i).getHeight();
Item item = new Item();
item.setId(id);
item.setName(namel);
item.setAge(agel);
item.setWeight(weightl);
item.setHeight(heightl);
item.setReach(reachl);
list.add(item);
}adapter.notifyDataSetChanged();
}else {
Toast.makeText(MainActivity.this, "No Records found.", Toast.LENGTH_SHORT).show();
}
}
private void Save(String name, String age, String weight, String height, String reach) {
Functions functions = new Functions(MainActivity.this);
Item item = new Item();
item.setName(name);
item.setAge(age);
item.setWeight(weight);
item.setHeight(height);
item.setHeight(reach);
functions.Insert(item);
Toast.makeText(MainActivity.this, "Saved...", Toast.LENGTH_SHORT).show();
fetchRecords();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
Layout file
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="android.wit.dale.fighterstudio.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_gravity="bottom|end"
android:layout_marginBottom="65dp"
android:src="#android:drawable/ic_input_add" />
</android.support.design.widget.CoordinatorLayout>
RUN TIME ERROR
In your styles.xml use Theme.AppCompat.Light.NoActionBar
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
........
</style>
use
androidx.appcompat.widget.Toolbar
instead of
Toolbar
in your layout. Also, make sure that in your styles you use Theme.AppCompat.Light.NoActionBar
Related
I have a fragment with this view:
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:tag="general"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#343535"
android:orientation="vertical"
tools:context=".fragments.GeneralFragment">
<Button
android:id="#+id/hello"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="#string/hello" />
<Button
android:id="#+id/observed"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="#string/observed" />
<Button
android:id="#+id/thanks"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="#string/thanks" />
</LinearLayout>
There are 3 buttons. Whenever you click on one of them, its text will be displayed.
Now I would like to add another button but dynamically. It should be added before #+id/hello.
I have tried it with
LinearLayout root = (LinearLayout) view.findViewById(R.id.root);
root.addView();
but it looks completely wrong since some parameters are missing.
For instance, the new button should be like:
XML:
<Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="I am a dynamic text" />
This button should be saved permanently in the app. How can I do this?
Update
I am using a dialog, so this is the class:
#SuppressLint("ValidFragment")
public class Dialog extends DialogFragment {
private final int _layout;
private TextInputEditText _customTextField;
#SuppressLint("ValidFragment")
public Dialog(int layout) {
_layout = layout;
}
public interface ICustomTts {
void customTts(String input, Activity activity);
}
public ICustomTts iCustomTts;
public interface ITarget {
void getTarget(String input);
}
public ITarget iTarget;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(_layout, container, false);
// Display fragment_custom
if (_layout == R.layout.fragment_custom) {
_customTextField = view.findViewById(R.id.customTextField);
Button _customBtn = view.findViewById(R.id.customCta);
_customBtn.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: Clicked on CTA of custom");
String input = _customTextField.getText().toString();
if (!input.equals("")) {
iCustomTts.customTts(input, getActivity());
_dismiss();
}
}
});
MaterialCheckBox customeSave = view.findViewById(R.id.customSave);
customeSave.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
Log.d(TAG, "customeSave was clicked!");
LinearLayout root = view.findViewById(R.id.root);
Button button = new Button(getContext());
float heightInPixel = 60 * getResources().getDisplayMetrics().density;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) heightInPixel);
params.gravity = Gravity.CENTER;
button.setText("I am a dynamic text");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do the stuff on the click
}
});
root.addView(button, 0);
}
});
}
// Display fragment_target
if (_layout == R.layout.fragment_target) {
_customTextField = view.findViewById(R.id.targetTextField);
Button _customBtn = view.findViewById(R.id.targetCta);
_customBtn.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: Clicked on CTA of target");
String input = _customTextField.getText().toString();
if (!input.equals("")) {
iTarget.getTarget(input);
_dismiss();
}
}
});
}
return view;
}
/**
* Dismissing the dialog
*/
private void _dismiss() {
this.dismiss();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
if (_layout == R.layout.fragment_custom) {
iCustomTts = (ICustomTts) getActivity();
}
else if (_layout == R.layout.fragment_target) {
iTarget = (ITarget) getActivity();
}
}
catch (ClassCastException e) {
Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage());
}
}
}
You need to use the two-argument version of addView() to determine the order (index) of the button inside the LinearLayout:
LinearLayout root = view.findViewById(R.id.root);
Button button = new Button(requireContext());
float heightInPixel = 60 * getResources().getDisplayMetrics().density;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) heightInPixel);
params.gravity = Gravity.CENTER;
button.setText("I am a dynamic text");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do the stuff on the click
}
});
root.addView(button, 0);
I have added navigation view and drawer layout in my app. When I open and close the drawer it lags in time. opens and close slowly. I got this issue prominently on version 4.4 also on 6.0 but not as prominently as 4.4.
When I am running on 4.4 device as I open the drawer I noticed messages in log that too much work may be doing on main thread.
So I tried to comment all the code except the navigation drawer and options menu code. So after that I found it was working bit well.
Is it the issue? or some memory issue can be there? But on larger memory devices also I found the problem.
Do I need to create another activity for other code? So that drawer will work faster?
I also tried to create a fragment and replaced it in framelayout of main activity to separate the code. But it was still lagging.
If I create new activity still I need all the navigation code in that activity, it will be again a same thing.
I am not getting what can be the issue. Can anyone please help.. Thank you..
Here is code:
public class MainActivity extends AppCompatActivity implements GetContactsAsyncTask.ContactGetCallBack,UpdateUserAsyncTask.UpdateUserCallBack {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactDb = new ContactTableHelper(MainActivity.this);
mDb = new UserTableHelper(MainActivity.this);
boolean result = Utility.checkAndRequestPermissions(MainActivity.this);
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(REGISTRATION_COMPLETE));
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(PUSH_NOTIFICATION));
NotificationUtils.clearNotifications(getApplicationContext());
sharedpreferences = getSharedPreferences("UserProfile", Context.MODE_PRIVATE);
mUserId = sharedpreferences.getString("userId", "");
firstTimeLogin = sharedpreferences.getBoolean("login", false);
refreshedToken = sharedpreferences.getString("deviceId", "");
parentLayout = (LinearLayout) findViewById(R.id.toolbar_container);
setupView();
mUser = new User();
url = sharedpreferences.getString("url", "");
contactList = new ArrayList<Contact>();
txtuserName = (TextView) findViewById(R.id.txtusername);
txtmobile = (TextView) findViewById(R.id.txtmobile);
profileImageView = (CircleImageView) findViewById(R.id.thumbnail);
if (profileImageView != null) {
profileImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout.closeDrawers();
Intent Intent = new Intent(MainActivity.this, ProfileActivity.class);
Intent.putExtra("user", mUser);
Intent.putExtra("url", url);
startActivity(Intent);
}
});
}
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getPath(), bmOptions);
if (bitmap != null) {
profileImageView.setImageBitmap(bitmap);
} else {
profileImageView.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_account_circle_white_48dp));
}
ImageView sync = (ImageView) findViewById(R.id.sync);
sync.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
contactList.clear();
contactDb.deleteAllContacts();
GetContactsAsyncTask getContactsAsyncTask = new GetContactsAsyncTask(MainActivity.this, MainActivity.this, mUserId, MainActivity.this);
getContactsAsyncTask.execute(mUserId);
}
});
}
void setupView() {
File sd = Environment.getExternalStorageDirectory();
image = new File(sd + "/Profile", "Profile_Image.png");
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
drawerLayout.closeDrawers();
menuItem.setChecked(true);
FragmentManager fragmentManager = getSupportFragmentManager();
switch (menuItem.getItemId()) {
case R.id.nav_menu_contacts:
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
break;
case R.id.nav_menu_settings:
Intent i = new Intent(MainActivity.this, PreferencesActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(i);
break;
case R.id.nav_log_out:
SharedPreferences pref = getSharedPreferences("UserProfile", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.remove("UserUsername");
editor.remove("userId");
editor.remove("url");
editor.remove("login");
editor.remove("company");
editor.remove("emailId");
editor.remove("profileImage");
editor.remove("fullName");
editor.remove("homeAddress");
editor.remove("workAddress");
editor.remove("workPhone");
editor.remove("pass");
editor.remove("jobTitle");
editor.remove("mobileNo");
editor.commit();
mDb.deleteAllUsers();
contactDb.deleteAllContacts();
UpdateTokenAsyncTask updateTokenAsyncTask = new UpdateTokenAsyncTask(MainActivity.this, mUserId, "");
updateTokenAsyncTask.execute(mUserId, "");
finish();
i = new Intent(MainActivity.this, LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(i);
break;
case R.id.nav_invite:
i = new Intent(MainActivity.this, InviteContactsActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(i);
break;
}
return true;
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
TextView mTitle = (TextView) findViewById(R.id.toolbar_title);
final ImageView menu = (ImageView) findViewById(R.id.menu);
menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PopupMenu popup = new PopupMenu(MainActivity.this, menu);
popup.getMenuInflater().inflate(R.menu.main_pop_up_menu, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.pendingInvites) {
startActivity(new Intent(MainActivity.this, PendingInvitesActivity.class));
} else if (item.getItemId() == R.id.feedback) {
final MaterialDialog dialog = new MaterialDialog.Builder(MainActivity.this)
.title("Feedback")
.customView(R.layout.feedback_dialog, true).build();
positiveAction = dialog.getActionButton(DialogAction.POSITIVE);
edtName = (EditText) dialog.getCustomView().findViewById(R.id.editName);
edtEmailId = (EditText) dialog.getCustomView().findViewById(R.id.editTextEmailId);
edtComment = (EditText) dialog.getCustomView().findViewById(R.id.editTextComment);
buttonSave = (Button) dialog.getCustomView().findViewById(R.id.buttonSave);
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View view1 = getCurrentFocus();
if (view1 != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view1.getWindowToken(), 0);
}
mName = String.valueOf(edtName.getText().toString());
mEmailId = String.valueOf(edtEmailId.getText().toString());
mComment = String.valueOf(edtComment.getText().toString());
if (mComment.equals("")) {
showAlert("Please enter comments.");
} else if (mEmailId.equals("")) {
showAlert("Please enter an email-id.");
} else {
if (!isValidEmail(mEmailId)) {
showAlert("Please enter valid email id.");
} else {
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", mName);
params.put("email_id", mEmailId);
params.put("comment", mComment);
CreateFeedbackAsyncTask createFeedbackAsyncTask = new CreateFeedbackAsyncTask(MainActivity.this, MainActivity.this);
createFeedbackAsyncTask.execute(params);
dialog.dismiss();
}
}
}
});
edtName.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) {
positiveAction.setEnabled(s.toString().trim().length() > 0);
}
#Override
public void afterTextChanged(Editable s) {
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
});
edtComment.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) {
positiveAction.setEnabled(s.toString().trim().length() > 0);
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
edtEmailId.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) {
positiveAction.setEnabled(s.toString().trim().length() > 0);
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
dialog.show();
positiveAction.setEnabled(false);
return true;
}
return true;
}
});
popup.show();//showing popup menu
}
});
if (toolbar != null) {
toolbar.setTitle("");
setSupportActionBar(toolbar);
}
if (toolbar != null) {
toolbar.setNavigationIcon(R.drawable.ic_menu_white_24dp);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
}
}
#Override
public void doPostExecute(JSONArray response) throws JSONException {
contactListArray = response;
contactDb = new ContactTableHelper(MainActivity.this);
if (null == contactList) {
contactList = new ArrayList<Contact>();
}
for (int i = 0; i < contactListArray.length(); i++) {
JSONObject subObject1 = contactListArray.getJSONObject(i);
Contact contact = new Contact();
JSONObject subObject = subObject1;
String contactName = subObject.getString("user_name");
//name of the attribute in response
String pass = subObject.getString("password");
String contactId = subObject.getString("user_id");
String contactMobile = subObject.getString("mobile_no");
String contactEmailId = subObject.getString("email_id");
String contactProfile = subObject.getString("profile_image");
String fullName = subObject.getString("full_name");
String jobTitle = subObject.getString("job_title");
String homeAddress = subObject.getString("home_address");
String workPhone = subObject.getString("work_phone");
String workAddress = subObject.getString("work_address");
String company = subObject.getString("company");
contact.setmThumbnail(contactProfile);
contact.setmUserName(contactName);
contact.setmMobileNo(contactMobile);
contact.setmEmailId(contactEmailId);
contact.setmProfileImage(contactProfile);
contact.setContactId(contactId);
contact.setmHomeAddress(homeAddress);
contact.setmFullName(fullName);
contact.setmJobTitle(jobTitle);
contact.setmWorkAddress(workAddress);
contact.setmWorkPhone(workPhone);
contact.setmPass(pass);
contact.setmCompany(company);
contactList.add(contact);//adding string to arraylist
contactDb.addContact(new Contact(contactId, contactName, pass, contactMobile, contactEmailId, contactProfile, fullName, jobTitle, workAddress, workPhone, homeAddress, company));
}
adapter = new ContactAdapter(MainActivity.this, contactList);
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setItemViewCacheSize(20);
recyclerView.setDrawingCacheEnabled(true);
recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
}
#Override
public void onResume() {
super.onResume();
contactList.clear();
if (!firstTimeLogin) {
contactList.clear();
contactList = contactDb.getAllContacts();
mUser = mDb.getUser(mUserId);
txtuserName.setText(mUser.getmUserName());
txtmobile.setText(mUser.getmMobileNo());
} else {
new GetUserAsyncTask1(MainActivity.this,mUserId).execute(mUserId);
new GetContactsAsyncTask(this, MainActivity.this, mUserId, MainActivity.this).execute();
firstTimeLogin = false;
SharedPreferences.Editor editor = getSharedPreferences("UserProfile", MODE_PRIVATE).edit();
editor.putBoolean("login", firstTimeLogin);
editor.commit();
}
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new ContactAdapter(MainActivity.this, contactList);
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(MainActivity.this, recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
final Contact contact = contactList.get(position);
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_ID_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_CONTACTS, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.SEND_SMS, PackageManager.PERMISSION_GRANTED);
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
if (perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
} else {
showAlert("Some Permissions are Denied.");
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
#Override
public void doPostExecute(JSONObject response, Boolean update) throws JSONException {
}
}
Main layout :
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container">
</FrameLayout>
<!-- Your normal content view -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id = "#+id/toolbar_container">
<!-- We use a Toolbar so that our drawer can be displayed
in front of the action bar -->
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/Contacts"
android:layout_gravity="center"
android:id="#+id/toolbar_title"
android:textSize="20sp"
android:textColor="#ffffff"
android:textStyle="bold"
android:textAlignment="center"
android:gravity="center_vertical|center|center_horizontal"
android:layout_toLeftOf="#+id/sync"
android:layout_toStartOf="#+id/sync"
android:layout_centerInParent="true"
android:layout_marginLeft="30dp"
android:layout_marginRight="10dp" />
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:background="#drawable/ic_refresh_white_24dp"
android:id="#+id/sync"
android:layout_gravity = "right"
android:layout_toStartOf="#+id/menu"
android:layout_toLeftOf="#+id/menu"
android:layout_centerVertical="true"
android:layout_alignParentRight="false"
android:layout_marginRight="10dp" />
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_gravity= "end"
android:layout_marginRight="10dp"
android:background="#drawable/ic_more_vert_white_36dp"
android:id="#+id/menu"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
<view
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
class="android.support.v7.widget.RecyclerView"
android:id="#+id/recycler_view"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true" />
<!-- The rest of your content view -->
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="?attr/colorPrimary"
app:headerLayout="#layout/drawer_header"
app:itemTextColor="#color/yourColor"
app:itemIconTint="#color/yourColor"
app:menu="#menu/nav_menu" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
layout="#layout/drawer_header"
android:layout_width="match_parent"
android:layout_height="103dp" />
<ExpandableListView
android:id="#+id/elvGuideNavigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:groupIndicator="#null"
/>
</LinearLayout>
</android.support.design.widget.NavigationView>
Do the Json Parsing and adding the Entries into the DB also in Background Thread and Pass only the ArrayList of Entries to the Main Thread, this way you can reduce the Load on the Main Thread.
Another thing you can try is Enabling hardwareAcceleration to true
Definitely try to move any database operations on another threads. Decoding that bitmap in onCreate() also is dangerous.
Maybe organising your code will help a bit.
I am trying to retrieve data from server and display it in listview. But when I compile this it is not working and the list is even not showing in the activity.
Mylist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/fab_margin"
android:orientation="vertical" >
<AbsoluteLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/edItem"
android:layout_width="180dp"
android:layout_marginTop="10dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="180dp"
android:orientation="horizontal">
<TextView
android:id="#+id/edUnit"
android:layout_width="100dp"
android:layout_marginTop="80dp"
android:layout_height="40dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"/>
<TextView
android:id="#+id/edPrice"
android:layout_width="100dp"
android:layout_marginTop="80dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"/>
<TextView
android:id="#+id/edDisc"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginRight="10dp"
android:layout_marginTop="80dp"
android:layout_marginLeft="10dp"/>
</LinearLayout>
</AbsoluteLayout>
</LinearLayout>
Content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.user.merchant.MainActivity"
tools:showIn="#layout/app_bar_main">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:dividerHeight="10dp">
</ListView>
<SearchView
android:id="#+id/search_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</SearchView>
</RelativeLayout>
AppController.java
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
// private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
CustomListAdapter.java
public class CustomListAdapter extends BaseAdapter implements Filterable {
private Activity activity;
CustomFilter filter;
private LayoutInflater inflater;
private List<InventoryModel> InventoryModelItems;
private List<InventoryModel> filterList;
public CustomListAdapter(Activity activity, List<InventoryModel> InventoryModelItems) {
this.activity = activity;
this.InventoryModelItems = InventoryModelItems;
this.filterList=InventoryModelItems;
}
#Override
public int getCount() {
return InventoryModelItems.size();
}
#Override
public Object getItem(int location) {
return InventoryModelItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.mylist, null);
TextView ItemName = (TextView) convertView.findViewById(R.id.edItem);
TextView Unit = (TextView) convertView.findViewById(R.id.edUnit);
TextView Price = (TextView) convertView.findViewById(R.id.edPrice);
TextView Discount = (TextView) convertView.findViewById(R.id.edDisc);
// getting InventoryModel data for the row
InventoryModel m = InventoryModelItems.get(position);
// thumbnail image
// title
ItemName.setText(m.getItemName());
// rating
Unit.setText("Unit: " + (m.getUnit()));
// release year
Price.setText("Rs: " + String.valueOf(m.getPrice()));
Discount.setText("Discount: " + String.valueOf(m.getUnit()));
return convertView;
}
#Override
public Filter getFilter() {
if(filter==null)
{
filter=new CustomFilter();
}
return filter;
}
class CustomFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results=new FilterResults();
if(constraint != null&&constraint.length()>0)
{
constraint=constraint.toString().toUpperCase();
ArrayList<InventoryModel> filters=new ArrayList<InventoryModel>();
for(int i=0;i<filterList.size();i++)
{
if(filterList.get(i).getItemName().toUpperCase().contains(constraint))
{
InventoryModel p= new InventoryModel(filterList.get(i).getItemName(),filterList.get(i).getUnit(),filterList.get(i).getPrice(),filterList.get(i).getDiscount());
filters.add(p);
}
}
results.count=filters.size();
results.values=filters;
}
else
{
results.count=filterList.size();
results.values=filterList;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
InventoryModelItems=(List<InventoryModel>) results.values;
notifyDataSetChanged();
}
}
}
mainactivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String url = "url";
private ProgressDialog pDialog;
private List<InventoryModel> InventoryModelList = new ArrayList<InventoryModel>();
private ListView listView;
private CustomListAdapter adapter;
public TextView test;
SearchView inputSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView)findViewById(R.id.list);
adapter = new CustomListAdapter(this, InventoryModelList);
listView.setAdapter(adapter);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//toolbar.setLogo(R.drawable.ic_menu_slideshow);
//toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_menu_slideshow));
// test=(TextView)findViewById(R.id.listtest);
setSupportActionBar(toolbar);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
assert getSupportActionBar() != null;
getSupportActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
JsonArrayRequest InventoryModelReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// test.setText(response);
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
InventoryModel InventoryModel = new InventoryModel();
InventoryModel.setItemName(obj.getString("Item_Name"));
InventoryModel.setUnit(obj.getString("Unit"));
InventoryModel.setPrice(((Number) obj.get("Price"))
.floatValue());
InventoryModel.setDiscount(((Number) obj.get("Discount")).floatValue());
// adding InventoryModel to InventoryModels array
InventoryModelList.add(InventoryModel);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(InventoryModelReq);
/* toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intenthome = new Intent(MainActivity.this, MainActivity.class);
startActivity(intenthome);
}
});*/
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intentfloat = new Intent(MainActivity.this, ItemAdd.class);
startActivity(intentfloat);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
//toggle.setHomeAsUpIndicator(R.drawable.ic_menu_slideshow);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if(id == R.id.account) {
Intent intentaccount = new Intent(MainActivity.this, account.class);
startActivity(intentaccount);
}
if (id == R.id.action_settings) {
return true;
}
if(id==R.id.action_notify) {
Intent intentNotify = new Intent(MainActivity.this, Notification.class);
startActivity(intentNotify);
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_processing) {
// Handle the camera action
Intent intentProcessing = new Intent(MainActivity.this, ProcessingItem.class);
startActivity(intentProcessing);
} else if (id == R.id.nav_processed) {
Intent intentProcessed = new Intent(MainActivity.this, ProcessedItem.class);
startActivity(intentProcessed);
} else if (id == R.id.nav_Aborted) {
Intent intentAborted = new Intent(MainActivity.this, AbortedIem.class);
startActivity(intentAborted);
} else if (id == R.id.nav_delivery) {
Intent intentDelivered = new Intent(MainActivity.this, DeliveredItem.class);
startActivity(intentDelivered);
}
else if (id == R.id.logout)
{
// private void logout(){
//Creating an alert dialog to confirm logout
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure you want to logout?");
alertDialogBuilder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
//Getting out sharedpreferences
SharedPreferences preferences = getSharedPreferences(config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Getting editor
SharedPreferences.Editor editor = preferences.edit();
//Puting the value false for loggedin
editor.putBoolean(config.LOGGEDIN_SHARED_PREF, false);
//Putting blank value to email
editor.putString(config.EMAIL_SHARED_PREF, "");
//Saving the sharedpreferences
editor.commit();
//Starting login activity
Intent intent = new Intent(MainActivity.this, LoginActivityMerchant.class);
startActivity(intent);
}
});
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
//Showing the alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
I'm trying to make a To Do List app. When the screen rotates, all of the dynamically added textviews get removed. The textviews get added into a LinearLayout within a linearlayout, right above the add button.
MainActivity.Java
public class MainActivity extends Activity {
private LinearLayout mLayout;
private LinearLayout ListItems;
static final String counter_value = "int_value";
static final String toDoList_value = "toDolist";
private EditText mEditText;
private Button mButton;
private int counter;
private ArrayList<String> toDoList;
private ArrayList<String> keys;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//This makes it so that the keyboard appears only after you tap the EditText. Stackoverflow question by fixEdd Android on-screen keyboard auto popping up
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
// end code
if (toDoList != null){
System.out.println("Success!");
for(int i = 0; i< toDoList.size(); i++){
System.out.println(toDoList.get(i));
ListItems.addView(createNewTextView(toDoList.get(i)));
}
}
else{
System.out.println("Nope!");
toDoList = new ArrayList<String>();
}
counter = 1;
mLayout = (LinearLayout) findViewById(R.id.linearLayout);
ListItems = (LinearLayout) findViewById(R.id.listItems);
mEditText = (EditText) findViewById(R.id.editText);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(onClick());
TextView textView = new TextView(this);
textView.setText("New text");
}
private View.OnClickListener onClick() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
ListItems.addView(createNewTextView(mEditText.getText().toString()));
}
};
}
private TextView createNewTextView(String text) {
final RadioGroup.LayoutParams lparams = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setFreezesText(true);
textView.setText(counter + ":" + text);
textView.setId(counter);
System.out.println(textView.getId());
toDoList.add(text);
counter++;
return textView;
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
counter = savedInstanceState.getInt(counter_value);
toDoList = savedInstanceState.getStringArrayList("key");
//REad values from the savedInstanceState" -object and put them in your textview
}
#Override
protected void onSaveInstanceState(Bundle outState){
// Save the values you need from your textview into "outSTate" -object
// outState.putParcelableArrayList("key", toDoList);
outState.putInt(counter_value, counter);
outState.putStringArrayList("key", toDoList);
super.onSaveInstanceState(outState);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/linearLayout"
android:weightSum="1">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:id="#+id/listItems"></LinearLayout>
<EditText
android:id="#+id/editText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add+"
/>
</LinearLayout>
Also I am not sure if readding the views is the best way to do this. It seems like it's a waste of operations. Is there a way to just keep the textviews in place?
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
counter = savedInstanceState.getInt(counter_value);
toDoList = savedInstanceState.getStringArrayList("key");
// Add this for-loop to restoring your list
for(String str : toDoList){
ListItems.addView(createNewTextView(str));
}
}
However, in my opinion, this is not a good approach. It's better to use a ListView
It's better if you implement your To Do list using a ListView with its Adapter. There are plenty of tutorials on the web, start for example from this one.
I have a ListView in one my activity_main.xml file, the problem is, when I click on a Item in that ListView (activity_main.xml), it calls setContentView() and loads another XML file called activity_settings.xml.
The problem is, when I click the back button in activity_settings.xml (Button to call setContentView() again and go back to activity_main.xml) The ListView from activity_main.xml disappears.
I have tried about dozen ways of fixing it, but nothing seems to work.
Here is my MainActivity.java (It is pretty big):
package com.NautGames.xectav2.app;
import {...}
public class MainActivity extends ASR {
private ToggleButton homeOnOff;
HomeHoldDown hhd = new HomeHoldDown();
int keyCode;
KeyEvent event;
Context context;
private static final String LOGTAG = "Xecta";
private static final String BOTID = "e38006d97e34053e";
private TTS myTts;
private ImageButton speakButton;
private Bot bot;
Button backB1;
Button backB2;
Button backB3;
boolean mBound = false;
SimpleAdapter simpleAdpt;
BoundService myService = new BoundService();
boolean isBound = false;
EditText name, email, mMessage, subject;
String key;
String Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, BoundService.class);
bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
//homeOnOff = (ToggleButton) findViewById(R.id.toggleButton);
name = (EditText) findViewById(R.id.etName);
email = (EditText) findViewById(R.id.etEmail);
mMessage = (EditText) findViewById(R.id.etAdd);
subject = (EditText) findViewById(R.id.txtSubject);
Button startBtn = (Button) findViewById(R.id.send);
backB1 = (Button)findViewById(R.id.button1);
backB2 = (Button)findViewById(R.id.button2);
backB3 = (Button)findViewById(R.id.button3);
//Initialize GUI elements
setSpeakButton();
//Initialize the speech recognizer
createRecognizer(getApplicationContext());
//Initialize text to speech
myTts = TTS.getInstance(this);
//Create bot
bot = new Bot(this, BOTID, myTts, "assistant");
initList();
// We get the ListView component from the layout
ListView lv = (ListView) findViewById(R.id.listView);
// This is a simple adapter that accepts as parameter
// Context
// Data list
// The row layout that is used during the row creation
// The keys used to retrieve the data
// The View id used to show the data. The key number and the view id must match
simpleAdpt = new SimpleAdapter(this, planetsList, android.R.layout.simple_list_item_1, new String[] {"page"}, new int[] {android.R.id.text1});
lv.setAdapter(simpleAdpt);
// React to user clicks on item
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id)
{
// We know the View is a TextView so we can cast it
TextView clickedView = (TextView) view;
//Toast.makeText(MainActivity.this, "Item with id ["+id+"] - Position ["+position+"] - Planet ["+clickedView.getText()+"]", Toast.LENGTH_SHORT).show();
if(id == 0)
{
setContentView(R.layout.activity_settings);
}
if(id == 1)
{
setContentView(R.layout.activity_about);
}
if(id == 2)
{
setContentView(R.layout.activity_feedback);
}
}
});
}
public void onClickSend(View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"name#email.com"});
i.putExtra(Intent.EXTRA_SUBJECT, subject.getText().toString());
i.putExtra(Intent.EXTRA_TEXT , mMessage.getText().toString());
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
//from here
private ServiceConnection myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
BoundService.MyLocalBinder binder = (BoundService.MyLocalBinder) service;
myService = binder.getService();
isBound = true;
}
public void onServiceDisconnected(ComponentName arg0) {
isBound = false;
}
};
//to HERE
public void showTime(View view)
{
myService.getCurrentTime();
}
/************************************************************************
* WHEN THE USER TURNS THE HOME LISTENING ON AND OFF
* IT WILL START SERVICE AND STOP SERVICE
*************************************************************************/
/*public void onToggleClicked(View view) {
boolean on = ((ToggleButton) view).isChecked();
if (on) {
//Toast.makeText(MainActivity.this, "Activate Xecta with Home ON", Toast.LENGTH_LONG).show();
//startService(new Intent(getBaseContext(), Service1.class));
} else {
//Toast.makeText(MainActivity.this, "Activate Xecta with Home OFF", Toast.LENGTH_LONG).show();
//stopService(new Intent(getBaseContext(), LocalService.class));
}
}*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*public void onClickService(View view)
{
if(isApplicationSentToBackground(context))
{
hhd.onKeyLongPress(keyCode, event);
}
}*/
/**************************************************************************
* WHEN THE USER HOLDS DOWN THE HOME BUTTON
*************************************************************************/
#Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Toast.makeText(MainActivity.this, "Key pressed long!", Toast.LENGTH_LONG).show();
return true;
}
return super.onKeyLongPress(keyCode, event);
}
public void onClickBack(View view)
{
setContentView(R.layout.activity_main);
}
// The data to show
List<Map<String, String>> planetsList = new ArrayList<Map<String,String>>();
private void initList() {
// We populate the planets
planetsList.add(newList("page", "Settings"));
planetsList.add(newList("page", "About"));
planetsList.add(newList("page", "FeedBack"));
}
private HashMap<String, String> newList(String key, String name) {
HashMap<String, String> planet = new HashMap<String, String>();
planet.put(key, name);
return planet;
}
public void onClick(View view)
{
speakButton = (ImageButton) findViewById(R.id.speech_btn);
try {
listen(RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH, 10);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"ASR could not be started: invalid params", Toast.LENGTH_SHORT).show();
Log.e(LOGTAG, e.getMessage());
}
}
private void setSpeakButton() {
speakButton = (ImageButton) findViewById(R.id.speech_btn);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
listen(RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH, 10);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "ASR could not be started: invalid params", Toast.LENGTH_SHORT).show();
Log.e(LOGTAG, e.getMessage());
}
}
});
}
/**
* Provides feedback to the user when the ASR encounters an error
*/
public void processAsrError(int errorCode) {
String errorMessage;
switch (errorCode)
{
case SpeechRecognizer.ERROR_AUDIO:
errorMessage = "Audio recording error";
break;
case SpeechRecognizer.ERROR_CLIENT:
errorMessage = "Client side error";
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
errorMessage = "Insufficient permissions" ;
break;
case SpeechRecognizer.ERROR_NETWORK:
errorMessage = "Network related error" ;
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
errorMessage = "Network operation timeout";
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
errorMessage = "RecognitionServiceBusy" ;
break;
case SpeechRecognizer.ERROR_SERVER:
errorMessage = "Server sends error status";
break;
case SpeechRecognizer.ERROR_NO_MATCH:
errorMessage = "No matching message" ;
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
errorMessage = "Input not audible";
break;
default:
errorMessage = "ASR error";
break;
}
try {
myTts.speak(errorMessage,"EN");
} catch (Exception e) {
Log.e(LOGTAG, "English not available for TTS, default language used instead");
}
//If there is an error, shows feedback to the user and writes it in the log
Log.e(LOGTAG, "Error: "+ errorMessage);
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
public void processAsrReadyForSpeech() {
Toast.makeText(this, "I'm listening", Toast.LENGTH_LONG).show();
}
public void processAsrResults(ArrayList<String> nBestList, float[] confidences) {
String bestResult = nBestList.get(0);
Log.d(LOGTAG, "Speech input: " + bestResult);
// insert %20 for spaces in query
bestResult = bestResult.replaceAll(" ", "%20");
bot.initiateQuery(bestResult);
//Toast.makeText(MainActivity.this, "", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
myTts.shutdown();
super.onDestroy();
}
#Override
public void onBackPressed() {
super.onBackPressed();
setContentView(R.layout.activity_main);
newList(key, Name);
initList();
}
#Override
public void onStop()
{
super.onStop();
Toast.makeText(MainActivity.this, "Bye bye!", Toast.LENGTH_SHORT).show();
onKeyLongPress(keyCode, event);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
onClickBack is the button to go back to activity_main.xml, I am also initialising the ListView in onCreate().
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/onericblur"
android:orientation="vertical"
android:paddingBottom="5dp"
android:onClick="onClick"
android:weightSum="1">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#000000"
android:orientation="vertical" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#000000"
android:paddingBottom="10dip"
android:paddingTop="10dip"
android:text="#string/title"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</LinearLayout>
<ViewAnimator
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/viewAnimator"
android:layout_gravity="right" />
<ImageButton
android:id="#+id/speech_btn"
android:background="#null"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/xectaicon"
android:onClick="onClick"
android:layout_marginTop="32dp"
android:layout_gravity="center_horizontal|top" />
<ListView
android:layout_width="match_parent"
android:layout_height="127dp"
android:id="#+id/listView"
android:layout_weight="1.22"
android:background="#android:drawable/screen_background_light_transparent" />
</LinearLayout>
And activity_settings...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:background="#drawable/onericblur">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="?android:attr/listSeparatorTextViewStyle"
android:text="Settings"
android:id="#+id/textView"
android:layout_gravity="center_horizontal"
android:textSize="30dp"
android:textColor="#android:color/black" />
<TextView
android:layout_width="291dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Xecta is currently in Beta being tested, you can request settings by going to the feedback section. Sorry!"
android:id="#+id/textView2"
android:layout_weight="0.04"
android:layout_gravity="center_horizontal"
android:textSize="20dp"
android:gravity="center|top" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back to home"
android:id="#+id/button3"
android:onClick="onClickBack"
android:layout_gravity="center_horizontal" />
</LinearLayout>
What could be causing the problem?!?!?
Thanks.
As suggested by Ram Kiran, it's better to have different activities for Settings / Home.
The problem with the code you have posted is that you are not populating the list with the contents when you press back. I believe it should be fixed with the following code,
public void onClickBack(View view)
{
setContentView(R.layout.activity_main);
ListView lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(simpleAdpt);
}
Basically when you call setContentView(layoutId) new view will be inflated from the layout and you need to do all the UI lookup, initialization again.
I dont think loading xml files repeatedly in same activity is a good one. Try to use two activities instead of loading different xml files in same activity.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView) findviewById(R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id)
{
Intent n = new Intent(getApplicationContext(),SettingsActivity.class);
startActivity(n);
}
}
SettingsActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Buttoon btn = (Button) findviewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent n = new Intent(getApplicationContext(),MainActivity.class);
startActivity(n);
}
});
Try out as below:
#Override
public void onResume()
{
super.onResume();
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, BoundService.class);
bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
//homeOnOff = (ToggleButton) findViewById(R.id.toggleButton);
name = (EditText) findViewById(R.id.etName);
email = (EditText) findViewById(R.id.etEmail);
mMessage = (EditText) findViewById(R.id.etAdd);
subject = (EditText) findViewById(R.id.txtSubject);
Button startBtn = (Button) findViewById(R.id.send);
backB1 = (Button)findViewById(R.id.button1);
backB2 = (Button)findViewById(R.id.button2);
backB3 = (Button)findViewById(R.id.button3);
//Initialize GUI elements
setSpeakButton();
//Initialize the speech recognizer
createRecognizer(getApplicationContext());
//Initialize text to speech
myTts = TTS.getInstance(this);
//Create bot
bot = new Bot(this, BOTID, myTts, "assistant");
initList();
// We get the ListView component from the layout
ListView lv = (ListView) findViewById(R.id.listView);
// This is a simple adapter that accepts as parameter
// Context
// Data list
// The row layout that is used during the row creation
// The keys used to retrieve the data
// The View id used to show the data. The key number and the view id must match
simpleAdpt = new SimpleAdapter(this, planetsList, android.R.layout.simple_list_item_1, new String[] {"page"}, new int[] {android.R.id.text1});
lv.setAdapter(simpleAdpt);
}