This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have two layouts, one has editText and the other has a listview to change the editText's Fonts.
The app is getting crushed at clicking the button for opening the layout with listView probably because of the array Adapters.
Please help me.
Every Button is working fine. Just the btnChangeFont button is problematic.
My Code:
MainActivity.java[enter image description here][1]
package com.example.xarn.test;
public class MainActivity extends ActionBarActivity {
String[] values = new String[]{
"art_science",
"big_bold",
"bold_itallic",
"crazy_days",
"gabriola",
"handwritting",
"new_bold",
"new_itallic",
"oldschool",
"rough&tough",
"sketch",
};
ListView listView;
EditText text;
LinearLayout choosefonts;
ImageButton btnOpen, btnClose, btnNew, btnSave, btnDelete,btnChangeFont;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (EditText)findViewById(R.id.text);
listView =(ListView)findViewById(R.id.listView);
btnChangeFont = (ImageButton)findViewById(R.id.btnChangeFont);
btnChangeFont.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.choosefonts);
choosefonts = (LinearLayout)findViewById(R.id.choosefonts);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,android.R.id.text1,values);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:text.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/art_science.ttf"));
break;
case 1: text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/big_bold.ttf"));
break;
case 3:text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/bold_itallic.ttf"));
break;
case 4:text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/crazy_days.ttf"));
break;
case 5:text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/gabriola.ttf"));
break;
case 6:text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/handwritting.ttf"));
break;
case 7:text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/new_bold.ttf"));
break;
case 8:text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/new_itallic.ttf"));
break;
case 9:text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/oldschool.ttf"));
break;
case 10:text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/rough&tough.ttf"));
break;
case 11:text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/sketch.ttf"));
break;}
}
});
}
});
text.setHint("Write Your Note Here............");
text.setTextIsSelectable(true);
btnSave = (ImageButton)findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog d = new Dialog(MainActivity.this);
d.setTitle("Save As");
d.setContentView(R.layout.dialogsave);
d.show();
Button btnDialogSave = (Button)d.findViewById(R.id.btnDialogSave);
btnDialogSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText saveText = (EditText)d.findViewById(R.id.SaveText);
try {
File myFile = new File("/sdcard/"+saveText.getText()+".txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(text.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
""+saveText.getText()+" Saved",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
d.dismiss();
}
});
}
});
btnNew = (ImageButton)findViewById(R.id.btnNew);
btnNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text.setText("");
}
});
btnClose = (ImageButton)findViewById(R.id.btnClose);
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
btnOpen = (ImageButton)findViewById(R.id.btnOpen);
btnOpen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog d2 = new Dialog(MainActivity.this);
d2.setTitle("Open");
d2.setContentView(R.layout.dialogopen);
d2.show();
Button btnDialogOpen = (Button)d2.findViewById(R.id.btnDialogOpen);
btnDialogOpen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText openText = (EditText)d2.findViewById(R.id.OpenText);
try {
File myFile = new File("/sdcard/"+openText.getText()+".txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
text.setText(aBuffer);
myReader.close();
Toast.makeText(getBaseContext(),
""+openText.getText()+" Opened",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
d2.dismiss();
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
} else if(id == R.id.changeFont){
final Dialog d3 = new Dialog(MainActivity.this);
d3.setContentView(R.layout.choosefonts);
d3.setTitle("Choose Fonts");
d3.show();
/* String[] values = new String[]{
"art_science",
"big_bold",
"bold_itallic",
"crazy_days",
"gabriola",
"handwritting",
"new_bold",
"new_itallic",
"oldschool",
"rough&tough",
"sketch",
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,android.R.id.text1,values);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position){case 0:text.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/art_science.ttf"));
// text.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/art_science.ttf"));
break;
case 1: text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/big_bold.ttf"));
break;
case 3:text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/bold_itallic.ttf"));
break;
case 4:text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/crazy_days.ttf"));
break;
case 5:text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/gabriola.ttf"));
break;
case 6:text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/handwritting.ttf"));
break;
case 7:text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/new_bold.ttf"));
break;
case 8:text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/new_itallic.ttf"));
break;
case 9:text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/oldschool.ttf"));
break;
case 10:text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/rough&tough.ttf"));
break;
case 11:text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/sketch.ttf"));
break;}
}
});*/
}
return super.onOptionsItemSelected(item);
}
}
xml code for layout 1:
<RelativeLayout
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:height="200pt"
android:gravity="top"
android:scrollbars="horizontal"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnNew"
android:layout_below="#+id/text"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#drawable/new1" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnSave"
android:layout_alignBottom="#+id/btnNew"
android:layout_toRightOf="#+id/btnNew"
android:layout_toEndOf="#+id/btnNew"
android:background="#drawable/save"
android:clickable="true" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnOpen"
android:layout_below="#+id/text"
android:layout_toRightOf="#+id/btnSave"
android:layout_toEndOf="#+id/btnSave"
android:background="#drawable/open4"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnClose"
android:background="#drawable/close"
android:layout_below="#+id/text"
android:layout_toRightOf="#+id/btnOpen"
android:layout_toEndOf="#+id/btnOpen" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnDelete"
android:background="#drawable/delete"
android:layout_below="#+id/text"
android:layout_toRightOf="#+id/btnClose"
android:layout_toEndOf="#+id/btnClose" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnChangeFont"
android:layout_alignBottom="#+id/btnDelete"
android:layout_below="#+id/text"
android:layout_toRightOf="#+id/btnDelete"
android:background="#drawable/star"/>
<RelativeLayout/>
logcat error
06-22 11:48:18.188 8058-8058/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.xarn.test, PID: 8058
java.lang.NullPointerException
at com.example.xarn.test.MainActivity$1.onClick(MainActivity.java:65)
at android.view.View.performClick(View.java:4443)
at android.view.View$PerformClick.run(View.java:18442)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5021)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
at dalvik.system.NativeStart.main(Native Method)
I believe you forgot to assign your EditText view called "text" to the matching view in your xml layout.
The variable text is defined, however, it is never assigned a value.
Related
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.
Here's my card view activity where three dots are there as in toolbar and I want to overflow it with menu but getting this error:
java.lang.IllegalStateException: Could not find method showPopup(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatImageButton with id 'img_menu'
Here's XML :
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:layout_margin="5dp"
card_view:cardCornerRadius="2dp"
card_view:contentPadding="10dp"
android:foreground="?android:attr/selectableItemBackground">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_alignParentTop="true"/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_below="#+id/textView"/>
<ImageButton
android:id="#+id/img_menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/ic_action_navigation_more_vert"
android:layout_alignParentRight="true"
android:layout_marginTop="12dp"
android:onClick="showPopup"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
Here's activity :
public class CardViewActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private static String LOG_TAG = "CardViewActivity";
ImageButton overflowMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_view);
overflowMenu = (ImageButton) findViewById(R.id.img_menu);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyRecyclerViewAdapter(getDataSet());
mRecyclerView.setAdapter(mAdapter);
if (getSupportActionBar() != null) {
getSupportActionBar().setHomeAsUpIndicator(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void showPopup(View v) {
PopupMenu popup = new PopupMenu(this, v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.card_overflow_menu, popup.getMenu());
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.one:
//Or Some other code you want to put here.. This is just an example.
Toast.makeText(getApplicationContext(), " Clicked 1 " + " : " , Toast.LENGTH_LONG).show();
break;
case R.id.two:
Toast.makeText(getApplicationContext(), "Clicked 2 " + " : " , Toast.LENGTH_LONG).show();
break;
default:
break;
}
return true;
}
});
}
/* public void showPopup(View v) {
PopupMenu popup = new PopupMenu(CardViewActivity.this, v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.card_overflow_menu,popup.getMenu());
popup.setOnMenuItemClickListener((PopupMenu.OnMenuItemClickListener) {
public boolean onMenuClick (MenuItem item){
}
popup.show();
}}*/
/*public void showMenu(View v) {
PopupMenu popup = new PopupMenu(this, v);
// This activity implements OnMenuItemClickListener
popup.setOnMenuItemClickListener((PopupMenu.OnMenuItemClickListener)
this);
popup.inflate(R.menu.card_overflow_menu);
popup.show();
}*/
#Override
protected void onResume() {
super.onResume();
((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter
.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.i(LOG_TAG, " Clicked on Item " + position);
}
});
}
private ArrayList<DataObject> getDataSet() {
ArrayList results = new ArrayList<DataObject>();
for (int index = 0; index < 20; index++) {
DataObject obj = new DataObject("Test " + index,
"Doc number " + index);
results.add(index, obj);
}
return results;
}
}
LogCat :
java.lang.IllegalStateException: Could not find method showPopup(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatImageButton with id 'img_menu'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:325)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:4802)
at android.view.View$PerformClick.run(View.java:20101)
at android.os.Handler.handleCallback(Handler.java:810)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:189)
at android.app.ActivityThread.main(ActivityThread.java:5532)
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:950)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
You are defining onClick event on ImageButton, plus you are setting onClickListener on it too.
Use either
public void showPopup(View v)
code or
overflowMenu.setOnClickListener(new View.OnClickListener()
I suggest you to comment out your overFlowMenu clickListener code.
I have programmed a ListView at my MainActivity with an item view and a Car Class.
public class Car {
private String make;
private int year;
private int iconID;
private String condition;
public Car(String make, int year, int iconID, String condition) {
this.make = make;
this.year = year;
this.iconID = iconID;
this.condition = condition;
}
public String getMake() {return make;}
public int getYear() {return year;}
public int getIconID() {return iconID;}
public String getCondition() {return condition;}
}
My MainActivity Class looks like this:
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
ActionBar actionBar;
private List<Car> myCars = new ArrayList<Car>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyListAdapter adapter = new MyListAdapter();
toolbar = (Toolbar) findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
populateCarList();
populateListView();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
private void populateCarList() {
myCars.add(new Car("Ford", 1940, R.mipmap.ic_launcher, "Needing work"));
myCars.add(new Car("Benz", 1960, R.mipmap.ic_launcher, "Cheap"));
myCars.add(new Car("Mustang", 2000, R.mipmap.ic_launcher, "Needing new owner"));
myCars.add(new Car("BMW", 2012, R.mipmap.ic_launcher, "Needing a lot of work!"));
myCars.add(new Car("Toyota", 1940, R.mipmap.ic_launcher, "Oldtimer"));
myCars.add(new Car("VW", 2003, R.mipmap.ic_launcher, "Cool"));
myCars.add(new Car("Ferrari", 2008, R.mipmap.ic_launcher, "Nice"));
}
private void populateListView() {
ArrayAdapter<Car> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.carsListView);
TextView textView = new TextView(MainActivity.this);
textView.setText("Here you can see all the Cars!");
textView.setTextSize(15);
textView.setGravity(Gravity.CENTER_HORIZONTAL);
textView.setTypeface(null, Typeface.BOLD);
textView.setTextColor(Color.parseColor("#a60b0b"));
list.addHeaderView(textView);
list.setAdapter(adapter);
}
private class MyListAdapter extends ArrayAdapter<Car> {
public MyListAdapter() {
super(MainActivity.this, R.layout.item_view, myCars);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if(itemView == null){
itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);
}
String url;
switch(position){
case 0: url = "http://www.google.com"; break;
case 1: url = "http://www.google.com"; break;
case 2: url = "http://www.google.com"; break;
case 3: url = "http://www.google.com"; break;
case 4: url = "http://www.google.com"; break;
case 5: url = "http://www.google.com"; break;
case 6: url = "http://www.google.com"; break;
default: url = "http://www.google.com"; break;
}
Button button = (Button)itemView.findViewById(R.id.item_button);
button.setTag(url);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = (String)v.getTag();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
}
});
Car currentCar = myCars.get(position);
ImageView imageView = (ImageView) itemView.findViewById(R.id.item_icon);
imageView.setImageResource(currentCar.getIconID());
// Make:
TextView makeText = (TextView) itemView.findViewById(R.id.item_txtMake);
makeText.setText(currentCar.getMake());
// Year:
TextView yearText = (TextView) itemView.findViewById(R.id.item_txtYear);
yearText.setText("" + currentCar.getYear());
// Condition:
TextView conditionText = (TextView) itemView.findViewById(R.id.item_txtCondition);
conditionText.setText(currentCar.getCondition());
return itemView;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == android.R.id.home){
onBackPressed();
return true;
}
if (id == R.id.watchList) {
startActivity(new Intent(this, WatchListActivity.class));
}
return super.onOptionsItemSelected(item);
}
public void addCarToWatchList (View view){
Toast.makeText(MainActivity.this, "Car has been added to WatchList", Toast.LENGTH_SHORT).show();
}
}
And I also have a WatchList Class (or a FavoriteCarsList Class whatever you want to call it)
public class WatchListActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_watch_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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.action_settings) {
return true;
}
if (id == android.R.id.home){
onBackPressed();
return true;
}
if (id == R.id.watchList) {
startActivity(new Intent(this, WatchListActivity.class));
}
return super.onOptionsItemSelected(item);
}
}
The xml code for the item view looks like:
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/item_icon"
android:src="#mipmap/ic_launcher"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:layout_marginBottom="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Make shown here"
android:id="#+id/item_txtMake"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="2000"
android:id="#+id/item_txtYear"
android:layout_below="#+id/item_icon"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Condition shown Here"
android:id="#+id/item_txtCondition"
android:layout_below="#+id/item_txtYear"
android:layout_centerHorizontal="true" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy Car online!"
android:id="#+id/item_button"
android:layout_below="#+id/item_txtCondition"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="add Car to WatchList"
android:onClick="addCarToWatchList"
android:id="#+id/item_watchlist_button"
android:layout_alignTop="#+id/item_icon"
android:layout_toRightOf="#+id/item_button"
android:layout_toEndOf="#+id/item_button" />
(At first: don't get confused by the www.google.com links for the buttons or the same image (ic_launcher) for every car, I used it only for testing my code. The Button is there, to get to an Link where you can buy the Car for example.)
So everything is OK. I can run the app without an error. All Buttons working. I get a ListView at my MainActivity with the different Cars and at the ToolBar I have an Icon, which I can click and switch to the WatchList Activity. Everything is exactly as I want it.
But I can't find a solution for my next step.
First: I want to add another Button to my item_view.xml. It has to be like an "Add to WatchList"-Button. If I click that Button, the car-item has to be added to the ListView of the WatchList Activity. (the ListView at the WatchList Class doesn't exist yet)
Second: If an item is added to the WatchList, it has to be an own Layout (own item_watchlist_view.xml) which only includes (for example) the name and the image of the item_view.xml from the MainActivity. It would be also nice, if there is a delete-Button at the item_watchlist_view.xml, which could be used for deleting the Car from the WatchList if I don't want it anymore in my WatchList.
So basically the app have to run like a "shopping cart system" but the difference is that I have only cars as products and I can add them to a WatchList or FavoriteList ("Shopping cart").
I tried a lot of things for two weeks but nothing works... so I decided to sign up here at the community with hope for help.
It would be nice, if someone can give me an detailed answer!
Thank you.. and sorry for my bad English!
To pass parameters to a new Activity, call it by invoking
Intent intent = new Intent(this, WatchListActivity.class);
Bundle b = new Bundle();
b.putInt("key", 1); //Your id
intent.putExtras(b); //Put your id to your next Intent
startActivity(intent);
I want to display pie-chart in a fragment dialog box..
This is the code:--
MainActivity.java
public class MainActivity extends Activity implements
MyDialogFragment.Communicator {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#SuppressLint("NewApi")
public void showDialog(View view) {
FragmentManager manager = getFragmentManager();
MyDialogFragment1 mydialog = new MyDialogFragment1();
mydialog.show(manager, "mydialog");
}
#Override
public void message(String data) {
Toast.makeText(getApplicationContext(), data + " button clicked",
Toast.LENGTH_SHORT).show();
}
}
and the MyDialogFragment1.java
#SuppressLint({ "NewApi", "InflateParams" })
public class MyDialogFragment1 extends DialogFragment implements OnClickListener {
Button no_button;
Context context;
private static int[] COLORS = new int[] { Color.MAGENTA, Color.CYAN };
private static String[] NAME_LIST = new String[] { "A", "B" };
private CategorySeries mSeries = new CategorySeries("");
private DefaultRenderer mRenderer = new DefaultRenderer();
private GraphicalView mChartView;
private int[] VALUES = { 40, 60 };
Communicator communicator;
#SuppressLint("NewApi")
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof Communicator) {
communicator = (Communicator) getActivity();
} else {
throw new ClassCastException(activity.toString()
+ " must implemenet MyListFragment.communicator");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setCancelable(false);
getDialog().setTitle("Title");
// View view = inflater.inflate(R.layout.main, null, false);
View view = (LinearLayout) inflater.inflate(R.layout.main,container, false);
mRenderer.setApplyBackgroundColor(true);
mRenderer.setBackgroundColor(Color.argb(100, 50, 50, 50));
mRenderer.setChartTitleTextSize(20);
mRenderer.setLabelsTextSize(15);
mRenderer.setLegendTextSize(15);
mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
mRenderer.setZoomButtonsVisible(true);
mRenderer.setStartAngle(90);
for (int i = 0; i < VALUES.length; i++) {
//mSeries.add(NAME_LIST[i] + " " + VALUES[i], VALUES[i]);
mSeries.add(NAME_LIST[i] + "(" + VALUES[i]+"%)", VALUES[i]);
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[(mSeries.getItemCount() - 1) % COLORS.length]);
mRenderer.addSeriesRenderer(renderer);
}
if (mChartView != null) {
mChartView.repaint();
}
//yes_button = (Button) view.findViewById(R.id.yesbtn);
no_button = (Button) view.findViewById(R.id.nobtn);
// setting onclick listener for buttons
// yes_button.setOnClickListener(this);
no_button.setOnClickListener(this);
return view;
}
#SuppressLint("ShowToast")
#Override
public void onResume() {
super.onResume();
if (mChartView == null) {
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
mChartView = ChartFactory.getPieChartView(context, mSeries, mRenderer ) ;
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(10);
mChartView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
}
});
mChartView.setOnLongClickListener(new View.OnLongClickListener() {
#SuppressLint("ShowToast")
#Override
public boolean onLongClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
return false;
}
});
layout.addView(mChartView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
else {
mChartView.repaint();
}
}
private LinearLayout findViewById(int chart) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.nobtn :
dismiss();
communicator.message("Dialog No btn clicked");
break;
}
}
public interface Communicator {
public void message(String data);
}
}
and the xml files are:--
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp" >
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="showDialog"
android:text="Show Dialog" />
</LinearLayout>
and main.xml is :--
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/chart"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal" >
</LinearLayout>
<Button
android:id="#+id/nobtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/yesbtn"
android:layout_alignBottom="#+id/yesbtn"
android:layout_alignRight="#+id/textView1"
android:layout_marginRight="38dp"
android:text="No" />
</LinearLayout>
Now, When I run this program it shows the button,when I click the button it stops...
and showing the following error:--
FATAL EXCEPTION: main
Process: com.emple.dialog_android_example, PID: 21181
java.lang.ClassCastException: com.emple.dialog_android_example.MainActivity#41ef95b0 must implemenet MyListFragment.communicator
at com.emple.dialog_android_example.MyDialogFragment1.onAttach(MyDialogFragment1.java:64)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:849)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.BackStackRecord.run(BackStackRecord.java:698)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5324)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
where is the problem????
I think your activity is not a instance of Communicator
Check here :
#SuppressLint("NewApi")
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof Communicator) {
communicator = (Communicator) getActivity();
} else {
throw new ClassCastException(activity.toString()
+ " must implemenet MyListFragment.communicator");
}
}
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);
}