Android - ListView disappears after setContentView()? - java

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);
}

Related

Navigation drawer takes time to open and close

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.

java.lang.NullPointerException at ArrayAdapter [duplicate]

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.

json data from server is not displayed in listview

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;
}
}

List to individual item swipe

I have an activity that returns a list of information derived from Parse.com in a listview. I would want that each item on the list is shown individually on a page, and where user are able to swipe left or right or navigate through arrows left and right through the list to view other list item.
Below is the code for that produces the list:
public class MatchingActivity extends Activity {
private String currentUserId;
private ArrayAdapter<String> namesArrayAdapter;
private ArrayList<String> names;
private ListView usersListView;
private Button logoutButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.matching);
logoutButton = (Button) findViewById(R.id.logoutButton);
logoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ParseUser.logOut();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
});
setConversationsList();
}
private void setConversationsList() {
currentUserId = ParseUser.getCurrentUser().getObjectId();
names = new ArrayList<String>();
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereNotEqualTo("objectId", currentUserId);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> userList, ParseException e) {
if (e == null) {
for (int i=0; i<userList.size(); i++) {
names.add(userList.get(i).getUsername().toString());
}
usersListView = (ListView)findViewById(R.id.usersListView);
namesArrayAdapter =
new ArrayAdapter<String>(getApplicationContext(),
R.layout.user_list_item, names);
usersListView.setAdapter(namesArrayAdapter);
usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
openConversation(names, i);
}
});
} else {
Toast.makeText(getApplicationContext(),
"Error loading user list",
Toast.LENGTH_LONG).show();
}
}
});
}
public void openConversation(ArrayList<String> names, int pos) {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", names.get(pos));
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> user, ParseException e) {
if (e == null) {
Intent intent = new Intent(getApplicationContext(), MessagingActivity.class);
intent.putExtra("RECIPIENT_ID", user.get(0).getObjectId());
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(),
"Error finding that user",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
The XML layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/logout"
android:id="#+id/logoutButton"
android:gravity="center_vertical|center_horizontal"
android:layout_gravity="center_horizontal"
android:background="#color/dark_gray"
android:textSize="24sp"
android:padding="15dp"
android:textColor="#color/sinch_purple" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:textColor="#ffffff"
android:background="#drawable/bac_blue"
android:id="#+id/usersListView">
</ListView>
</RelativeLayout>
I have also have looked into http://developer.android.com/training/implementing-navigation/lateral.html, but not sure how I would incorporate that into my listview.
If you require additional information, let me know.
Try using a Viewpager, Here you have examples and documentation.

AlertDialog not be shown when receiving sms

I work on an app this sending a sms and showing the received sms as an AlertDialog but AlertDialog Not be shown when receiving SMS
here is the Code Of my project:
MainActivity:
package com.am7.masirinfo;
public class MainActivity extends Activity {
TextView tv;
SharedPreferences prefs;
Button sendBtn;
EditText txtphoneNo;
EditText txtMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton btn2 = (ImageButton) findViewById(R.id.btn2);
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
System.exit(0);
}
});
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8A0441")));
bar.show();
bar.setIcon(R.drawable.bar);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayUseLogoEnabled(true);
bar.setDisplayHomeAsUpEnabled(false);
TextView tx = (TextView)findViewById(R.id.textView1);
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/font.ttf");
tx.setTypeface(custom_font);
TextView tx1 = (TextView)findViewById(R.id.textView2);
Typeface custom_font1 = Typeface.createFromAsset(getAssets(), "fonts/gmail.ttf");
tx1.setTypeface(custom_font1);
TextView tx2 = (TextView)findViewById(R.id.textViewMessage);
tx2.setTypeface(custom_font);
TextView tx3 = (TextView)findViewById(R.id.textView3);
TextView tx4 = (TextView)findViewById(R.id.textView4);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
txtphoneNo = (EditText) findViewById(R.id.editTextPhoneNo);
txtMessage = (EditText) findViewById(R.id.editTextSMS);
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
} protected void sendSMSMessage() {
Log.i("Send SMS", "");
String phoneNo = txtphoneNo.getText().toString();
String message = txtMessage.getText().toString();
try { SmsManager smsManager =
SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
AlertDialog ad1 = new AlertDialog.Builder(this).create();
ad1.setCancelable(false);
// This blocks the 'BACK' button
ad1.setMessage("با موفقیت ارسال شد");
ad1.setTitle("انجام شد");
ad1.setButton("باش", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad1.show();
ad1.setCanceledOnTouchOutside(true);
}
catch (Exception e) {
AlertDialog ad = new AlertDialog.Builder(this).create();
ad.setCancelable(false);
// This blocks the 'BACK' button
ad.setMessage("متاسفانه ارسال نشد مجددا تلاش کنید.");
ad.setTitle("خطایی رخ داد!");
ad.setButton("خب", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad.show();
ad.setCanceledOnTouchOutside(true);
e.printStackTrace();
}
}
#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;
}
}
and this is the SmsReceiver.java :
public class SmsReceiver extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if
(bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: " + phoneNumber + "; message: " + message);
if
(TextUtils.equals(currentMessage.getDisplayOriginatingAddress(), "+981000141")) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("اطلاعات ریافت شد!");
builder.setMessage(message);
builder.setPositiveButton("HEY!", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
}
});
builder.show();
}
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
private CharSequence contains(String string) {
// TODO Auto-generated method stub
return null;
}
}
Main_layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bg"
android:orientation="vertical" >
<TextView
android:id="#+id/textViewMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/sms_label" />
<EditText
android:id="#+id/editTextSMS"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="����: 0711 0511 ���� ����� �� ����"
android:inputType="textMultiLine" >
<requestFocus />
</EditText>
<Button
android:id="#+id/btnSendSMS"
android:layout_width="fill_parent"
android:layout_height="41dp"
android:background="#drawable/abstract_877"
android:text="#string/send_sms_label" />
<EditText
android:id="#+id/editTextPhoneNo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:enabled="false"
android:inputType="phone"
android:text="+981000141"
android:visibility="invisible" />
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="����� �� ���� ��� ���� � Ӂ� �� �� � ����� �� ��� ���� �� ���� ������."
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:textColorHint="#00BD39" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="bottom|center"
android:text="AM7group#gmail.com" />
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="www.iran141.ir"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="+981000141"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageButton
android:id="#+id/btn2"
android:layout_width="match_parent"
android:layout_height="339dp"
android:background="#android:color/transparent"
android:src="#drawable/exitbtn" />
Logcat:
05-26 20:16:53.509: I/SmsReceiver(31910): senderNum: +981000141; message: عجبا
05-26 20:16:53.529: I/SmsReceiver(31356): senderNum: +981000141; message: عجبا
05-26 20:16:53.639: E/SmsReceiver(31356): Exception smsReceiverandroid.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
After along conversation with #faizal I changed the main activity but I got 2 errors once in MainActivity:
public class MainActivity extends Activity {
TextView tv;
SharedPreferences prefs;
Button sendBtn;
EditText txtphoneNo;
EditText txtMessage;
SmsReceiver BR_smsreceiver = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BR_smsreceiver = new SmsReceiver();
BR_smsreceiver.setActivityHandler(this);
IntentFilter fltr_smsreceived = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(BR_smsreceiver, fltr_smsreceived);
ImageButton btn2 = (ImageButton) findViewById(R.id.btn2);
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
System.exit(0);
}
});
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8A0441")));
bar.show();
bar.setIcon(R.drawable.bar);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayUseLogoEnabled(true);
bar.setDisplayHomeAsUpEnabled(false);
public void showAlert(string message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(" !");
builder.setMessage(message);
builder.setPositiveButton("HEY!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
}
});
builder.show();
}
TextView tx = (TextView)findViewById(R.id.textView1);
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/font.ttf");
tx.setTypeface(custom_font);
TextView tx1 = (TextView)findViewById(R.id.textView2);
Typeface custom_font1 = Typeface.createFromAsset(getAssets(), "fonts/gmail.ttf");
tx1.setTypeface(custom_font1);
TextView tx2 = (TextView)findViewById(R.id.textViewMessage);
tx2.setTypeface(custom_font);
TextView tx3 = (TextView)findViewById(R.id.textView3);
TextView tx4 = (TextView)findViewById(R.id.textView4);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
txtphoneNo = (EditText) findViewById(R.id.editTextPhoneNo);
txtMessage = (EditText) findViewById(R.id.editTextSMS);
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
} protected void sendSMSMessage() {
Log.i("Send SMS", "");
String phoneNo = txtphoneNo.getText().toString();
String message = txtMessage.getText().toString();
try { SmsManager smsManager =
SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
AlertDialog ad1 = new AlertDialog.Builder(this).create();
ad1.setCancelable(false);
// This blocks the 'BACK' button
ad1.setMessage("�� ������ ����� ��");
ad1.setTitle("����� ��");
ad1.setButton("���", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad1.show();
ad1.setCanceledOnTouchOutside(true);
}
catch (Exception e) {
AlertDialog ad = new AlertDialog.Builder(this).create();
ad.setCancelable(false);
// This blocks the 'BACK' button
ad.setMessage("�������� ����� ��� ����� ���� ����.");
ad.setTitle("����� �� ���!");
ad.setButton("��", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad.show();
ad.setCanceledOnTouchOutside(true);
e.printStackTrace();
}
}
#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;
}
}
The Error is in public void method.
And twice error is in SmsReceiver but this problem is for this problem!
Here you are #faizal
Thanks in advance
The problem is that the context being supplied to the onReceive method of the BroadcastReceiver is an application context(as opposed to activity context), which cannot be used to show a dialog box apparently. So you need to show the dialog in your running activity instead of in the broadcast receiver.
In your SmsReceiver class, create a function to receive the main activity class object :
MainActivity act = null;
void setActivityHandler(MainActivity act)
{
this.act=act;
}
Register the broadcast receiver in the main activity(instead of in the splash screen) and call setActivityHandler(). So you will have the following lines in your main activity :
SmsReceiver BR_smsreceiver = null;
onCreate(Bundle savedInstance){
....
BR_smsreceiver = new SmsReceiver();
BR_smsreceiver.setActivityHandler(this);
IntentFilter fltr_smsreceived = new
IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(BR_smsreceiver, fltr_smsreceived);
....
}
In your SmsReceiver class, remove all the AlertDialog builder lines and replace it with
act.showAlert(message);
In your main activity class, create the showAlert() :
public void showAlert(String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("اطلاعات ریافت شد!");
builder.setMessage(message);
builder.setPositiveButton("HEY!", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
}
});
builder.show();
}

Categories

Resources