I've been searching around and tried different solutions but I can't seem to get this to work.
I have a MainActivity with a list and an "Add" button. When i click the addbutton i open a DialogFragment. In the dialog user inputs data and press "add" and i want a notification that says "xxxx has been added to list" but it never shows.
I have a seperate class for AddDialog which looks like this:
public class AddDialogFragment extends DialogFragment {
Button btnAdd;
Button btnCancel;
TextView etNewSerial, etNewBrand, etNewModel;
String newSerial, newBrand, newModel;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.dialog_add, container, false);
getDialog().setTitle("Add new serial!");
btnAdd = (Button) rootView.findViewById(R.id.btnAddNew);
etNewSerial = (TextView) rootView.findViewById(R.id.etNewSerial);
etNewBrand = (TextView) rootView.findViewById(R.id.etNewBrand);
etNewModel = (TextView) rootView.findViewById(R.id.etNewModel);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
newSerial = etNewSerial.getText().toString();
newBrand = etNewBrand.getText().toString();
newModel = etNewModel.getText().toString();
String url = "MY_VOLLEY_URL"
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
int icon = 0;
CharSequence notiText = "Item Added!";
long notiTime = System.currentTimeMillis();
CharSequence notiTitle = "Item Added!";//Titel
CharSequence notiContent = newSerial + " added!";
PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notBuilder = new NotificationCompat.Builder(getActivity());
notBuilder.setSmallIcon(icon)
.setTicker(notiText)
.setWhen(notiTime)
.setAutoCancel(true)
.setContentText(notiContent)
.setContentTitle(notiTitle)
.setContentIntent(pendingIntent);
Notification notification = notBuilder.build();
NotificationManager myNotificationManager = (NotificationManager)getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
myNotificationManager.notify(1, notification);
getDialog().dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(getActivity()).add(request);
}
});
return rootView;
}
}
But the notification never shows. I've been trying to replace the "getActivity()" with different methods for context but it doesn't seem to matter. Does anyone has some tips to make this possible?
I wonder you are getting this error because your are passing 0 as the resourceId for the small icon (setSmallIcon). Maybe, NotificationManager is ignoring this notification since it can not built properly (there's no resource with 0 as ID.
So, try to change this:
notBuilder.setSmallIcon(icon)
....
To:
notBuilder.setSmallIcon(android.R.color.transparent)
....
I use android.R.color.transparent as example since you are not interested in show any icon anyway. But you can change to any color/drawable etc...
Related
I am new to android studio.. I am building android web browser for my pleasure. Here, I'm confused about the adding new tabs. I used fragment for tabs. I created a button on mainactivity layout and when clicked the button it gonna add new fragment to fragment container..
something like this,
public void add_tab()
{
id++;
int next_id = id+1;
String tag = String.valueOf(id);
Bundle bundle = new Bundle ();
bundle.putString ("tag",tag);
bundle.putInt ("id",id);
bundle.putInt ("next_id",next_id);
final FrameLayout tab_hosting_frame = new FrameLayout(getApplicationContext ());
FrameLayout.LayoutParams layoutparams_match_parent_match_parent = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT,Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
tab_hosting_frame.setLayoutParams(layoutparams_match_parent_match_parent);
tab_hosting_frame.setBackgroundColor (Color.BLUE);
tab_hosting_frame.setId (id);
FragmentManager fragment_manager1 = getSupportFragmentManager ();
New_Tab new_tab_fragment = new New_Tab ();
FragmentTransaction fr_transaction = fragment_manager1.beginTransaction ();
fr_transaction.add ((tab_hosting_frame.getId ()),new_tab_fragment,tag);
fr_transaction.addToBackStack ("Fragment Add");
//new_tab_fragment.setArguments (bundle);
new_tab_fragment.setArguments (bundle);
fr_transaction.commit ();
tab_hosting_layout.addView (tab_hosting_frame);
//tab_hosting_layout.setVisibility (View.VISIBLE);
}
I tried this way also
public View create_tab()
{
id++;
String tag = String.valueOf(id);
linflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View tab_view = new View (getApplicationContext ());
tab_view = linflater.inflate(R.layout.new_tab_view, null);
TextView show_id = (TextView)tab_view.findViewById (R.id.tab_id);
show_id.setText (tag);
tab_hosting_layout.addView (tab_view);
return tab_view;
}
then execute then when button clicked,
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
tab_hosting_layout = (ConstraintLayout)findViewById (R.id.tab_host);
add_tab_button = (Button) findViewById (R.id.add_tab_button);
add_tab_button.setOnClickListener (
new View.OnClickListener ()
{
#Override
public void onClick(View v)
{
add_tab ();
//or
//create_tab ();
}
}
);
In 2nd methode, thing is, when I click the back button once ,all added tabs(views) are gone once. not step by step one by one..
Is this methode ok?? or is there another methode or way to create unlimited tabs like in normal web browser? I am bit confused weather iam wrong or not..
If u guys know help me with any solution...
As soon as the setOnClickListener executes I want to start another activity and transmit the variable cn.getID() to it. When inside the other activity I want to immidietaly start the method findlocation and give cn.getID() to it.
The method findLocation is not finished yet. The idea is, once it gets the ID of the other activities button, i can search with sqllite in my database for the place it belongs to, get longitude and latitude and tell mapcontroller focus the world map on this point.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.verladestellen);
final DB_Verladestellen db = new DB_Verladestellen(this);
List<DB_Place> placeList = db.getAllDBPlaces();
final LinearLayout layout = (LinearLayout) findViewById(R.id.verladestellen_liste);
for (final DB_Place cn : placeList) {
final LinearLayout row = new LinearLayout(this);
row.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
Button place = new Button(this);
place.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
place.setText(cn.getName());
place.setId(cn.getID());
row.addView(place);
row.setId(cn.getID());
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) place.getLayoutParams();
params.weight = 1.0f;
place.setLayoutParams(params);
place.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Here I want to call the method to start the other activity
//and transmit cn.getID().
openMap(null);
}
});
layout.addView(row);
}
}
//The method to start the other activity
public void openMap(View view) {
Intent intent = new Intent(this, UI_MainActivity.class);
startActivity(intent);
}
This is the method from inside the new activity I want to execute immidietaly after it has started:
public void findLocation(View view){
MapView map = (MapView) findViewById(R.id.map);
IMapController mapController = map.getController();
mapController.setZoom(17);
GeoPoint myLocation = new GeoPoint(PLACEHOLDER X , PLACEHOLDER Y);
mapController.animateTo(myLocation);
}
EDIT:
#Murat K. After some edits this is my whole class now:
public class UI_Verladestellen extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.verladestellen);
final DB_Verladestellen db = new DB_Verladestellen(this);
List<DB_Place> placeList = db.getAllDBPlaces();
final LinearLayout layout = (LinearLayout) findViewById(R.id.verladestellen_liste);
for (final DB_Place cn : placeList) {
final LinearLayout row = new LinearLayout(this);
row.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
Button place = new Button(this);
place.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
place.setText(cn.getName());
place.setId(cn.getID());
row.addView(place);
row.setId(cn.getID());
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) place.getLayoutParams();
params.weight = 1.0f;
place.setLayoutParams(params);
place.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openMap(cn.getID());
}
});
layout.addView(row);
}
}
public void openMap(int view) {
Intent intent = new Intent(UI_Verladestellen.this, UI_MainActivity.class);
intent.putExtra("findLocation", 1);
startActivity(intent);
}
}
And this is the getIntent of my onCreate method in UI_MainActivity:
int i = getIntent().getIntExtra("findlocation", 999);
if(i == 1){
findLocation(i);
}
As I edited into my earlier comment, i cant see where my Button-ID is recieved. At first i thought i would be my ID, but that wouldnt work, since The Button ID can be every number from 1 to n.
You can achieve this with an Intent e.g.
Intent i = new Intent(BaseActivity.this, YourSecondActivity.class);
intent.putExtra("METHOD_TO_CALL", 1);
startActivity(i);
and in your onCreate() method of the starting Activity you check for it.
#Override
public void onCreate(Bundle savedInstanceState) {
int i = getIntent().getIntExtra("METHOD_TO_CALL", 999);
if(i == 1){
callMethod(i);
}
EDIT:
//The method to start the other activity
public void openMap(View view) {
Intent intent = new Intent(this, UI_MainActivity.class);
intent.putExtra("METHOD_TO_CALL", 1); // the 1 is a example, put your ID here
startActivity(intent);
}
Step #1: Use putExtra() to add your ID value to the Intent that you use with startActivity()
Step #2: In the other activity, call getIntent() in onCreate() to retrieve the Intent used to create the activity instance. Call get...Extra() (where ... depends on the data type) to retrieve your ID value. If the ID value exists, call your findLocation() method.
It depends on how you want it to work. If you only want it to execute when the activity is created (when it starts or screen rotates) then call the method within the activities onCreate method. If you want it called whenever the user returns to that activity which can include them leaving the app and coming back to it sometime later then onResume would be a better spot for it. Calling the method from either should work as you hope though.
I also recommend looking over the Activity lifecycle as that will help you a lot in the future.
I've gotten my app to download content from a website but the intent asks you to open the link in the browser and downloads it from there. I wish to change that so when i tap the download button, instead of the intent directing to the browser it opens a popup in my app and shows the download progress.
How am I able to achieve this?
I have searched around stackoverflow and have only found ways that don't work for me. Here is my code -
txtLink = (EditText) findViewById(R.id.input_package);
btnOpenLink = (ImageButton) findViewById(R.id.download);
btnOpenLink.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String page = txtLink.getText().toString();
if (!TextUtils.isEmpty(page)) {
Uri uri = Uri.parse(defaultLink + page);
// Success Toast
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.custom_toast, null);
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("Your download should start shortly");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
} else {
// Fail Toast
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.custom_toast, null);
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("Please enter a package name");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.FILL_HORIZONTAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
}
});
Could someone explain what is the best way to create a popup download progress?
Because i have an input field where one can enter the second part of the url and it downloads that. Eg- download.com/ but the user enters "download" so when he taps the button it changes to download.com/download and it downloads from that url.
Thanks
You can do something like this..
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("waiting 5 minutes..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
Then write an async task to update progress..
private class DownloadZipFileTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... urls) {
//Copy you logic to calculate progress and call
publishProgress("" + progress);
}
protected void onProgressUpdate(String... progress) {
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String result) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
Write your download logic under the doInBackground method of Asynctask.This should solve your purpose and it wont even block UI tread..
Right now I am have a activity screen with edittext lines that I am obtaining user input from. When I hit the create event button on the button, the event text should populate into a news feed that I have on another activity.
Here is the portion CreateEvent activity/screen code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_event);
CreateEvent_Button = (Button)findViewById(R.id.create_event_button);
WhatEvent_Text = (EditText)findViewById(R.id.what_event);
WhenEventTime_Text = (EditText)findViewById(R.id.time_event);
WhenEventDate_Text = (EditText)findViewById(R.id.date_event);
WhereEvent_Text = (EditText)findViewById(R.id.where_event);
CreateEvent_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WhatEvent_String = WhatEvent_Text.getText().toString();
WhenEventTime_String = WhenEventTime_Text.getText().toString();
WhenEventDate_String = WhenEventDate_Text.getText().toString();
WhereEvent_String = WhereEvent_Text.getText().toString();
Log.e("What: ", WhatEvent_String);
Log.e("When_Time: ", WhenEventTime_String);
Log.e("When_Date: ", WhenEventDate_String);
Log.e("Where_Event: ", WhereEvent_String);
Intent intent = new Intent(CreateEvent.this,MainActivity.class);
intent.putExtra("WhatEvent_String", WhatEvent_String);
intent.putExtra("WhenEventTime_String", WhenEventTime_String);
intent.putExtra("WhenEventDate_String", WhenEventDate_String);
intent.putExtra("WhereEvent_String", WhereEvent_String);
startActivity(intent);
MainActivity main= new MainActivity();
//make sure you call method from other class correctly
main.addEvent();
}
});
}
When the create event button is pressed, it creates an event into the MainActivity screen/activity; however, the user input is null. I am not sure why this is happening because I believe I am using the intent methods correctly.
Here is my MainActivity screen.
Here is the getIntent method in my onCreate method in my MainActivity
Intent intent = getIntent();
if (null != intent) {
test = intent.getStringExtra("WhatEvent_String");
}
However, when I call my addEvent method:
protected void addEvent() {
// Instantiate a new "row" view.
// final ViewGroup newView = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.list_row, mContainerView, false);
// Set the text in the new row to a random country.
// Because mContainerView has android:animateLayoutChanges set to true,
// adding this view is automatically animated.
//mContainerView.addView(newView, 0);
HitupEvent hitupEvent = new HitupEvent();
hitupEvent.setTitle("Rohit "+ "wants to "+test );
hitupEvent.setThumbnailUrl(roro_photo);
//hitupEvent.setRating(30);
//hitupEvent.setYear(1995);
//hitupEvent.setThumbnailUrl(null);
ArrayList<String> singleAddress = new ArrayList<String>();
singleAddress.add("17 Fake Street");
singleAddress.add("Phoney town");
singleAddress.add("Makebelieveland");
hitupEvent.setGenre(singleAddress);
hitupEventList.add(hitupEvent);
adapter.notifyDataSetChanged();
}
The event input text is null. I am not sure why this is happening.
I tried to resolve it but no luck,
How to send string from one activity to another?
Pass a String from one Activity to another Activity in Android
Any idea as for how to resolve this?!
Thanks!
Don't use Intent to get the String you put through putExtra()
Intent intent = getIntent(); // don't use this
if (null != intent) {
test = intent.getStringExtra("WhatEvent_String");
}
Instead Use Bundle, an example snippet
Bundle extra = getIntent().getExtras();
if(extra!=null){
test= extra.getString("WhatEvent_String");
}
EDIT
I noticed just now that you're calling the method main.addEvent() from the wrong place ! Call it in the MainActivity in the onCreate() method.
Remove these lines
MainActivity main= new MainActivity();
//make sure you call method from other class correctly
main.addEvent();
and in your MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourLayout);
Bundle extra = getIntent().getExtras();
if(extra!=null){
test= extra.getString("WhatEvent_String");
}
addEvent(); // call your addEvent() method here
}
While I would like to make everything programatically whenever I can, and leave XML blank, that is not possible where I work (designers will not work with raw program code...)
So, to that extend, almost every one of my activity that I work with or built contains a large block of findViewById at the start somewhere.
This is especially painful if I had to create it from scratch and I am now allowed to programatically create an array of buttons and add it to the layout... Thankfully they will let me do that if it gets to 10+ elements and they are all the same type.
Is there a way to avoid this? Or a way to make it automatically cast it into what I am assigning it to? So I don't need to type Button mButton = (Button) findview...
If there is some way to automagically generate java instances of buttons and what nots from the XML given the layout that would be great (esp if the names were nice and autocompleteable).
Try to use Android annotations
AndroidAnnotations is an Open Source framework that speeds up Android development. It takes care of the plumbing, and lets you concentrate on what's really important. By simplifying your code, it facilitates its maintenance.
Here is a simple example of how your code can dramatically shrink, and become much easier to understand:
Before Android Annotations
public class BookmarksToClipboardActivity extends Activity {
BookmarkAdapter adapter;
ListView bookmarkList;
EditText search;
BookmarkApplication application;
Animation fadeIn;
ClipboardManager clipboardManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN);
setContentView(R.layout.bookmarks);
bookmarkList = (ListView) findViewById(R.id.bookmarkList);
search = (EditText) findViewById(R.id.search);
application = (BookmarkApplication) getApplication();
fadeIn = AnimationUtils.loadAnimation(this, anim.fade_in);
clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
View updateBookmarksButton1 = findViewById(R.id.updateBookmarksButton1);
updateBookmarksButton1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
updateBookmarksClicked();
}
});
View updateBookmarksButton2 = findViewById(R.id.updateBookmarksButton2);
updateBookmarksButton2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
updateBookmarksClicked();
}
});
bookmarkList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView p, View v, int pos, long id) {
Bookmark selectedBookmark = (Bookmark) p.getAdapter().getItem(pos);
bookmarkListItemClicked(selectedBookmark);
}
});
initBookmarkList();
}
void initBookmarkList() {
adapter = new BookmarkAdapter(this);
bookmarkList.setAdapter(adapter);
}
void updateBookmarksClicked() {
UpdateBookmarksTask task = new UpdateBookmarksTask();
task.execute(search.getText().toString(), application.getUserId());
}
private static final String BOOKMARK_URL = //
"http://www.bookmarks.com/bookmarks/{userId}?search={search}";
class UpdateBookmarksTask extends AsyncTask {
#Override
protected Bookmarks doInBackground(String... params) {
String searchString = params[0];
String userId = params[1];
RestTemplate client = new RestTemplate();
HashMap args = new HashMap();
args.put("search", searchString);
args.put("userId", userId);
HttpHeaders httpHeaders = new HttpHeaders();
HttpEntity request = new HttpEntity(httpHeaders);
ResponseEntity response = client.exchange( //
BOOKMARK_URL, HttpMethod.GET, request, Bookmarks.class, args);
Bookmarks bookmarks = response.getBody();
return bookmarks;
}
#Override
protected void onPostExecute(Bookmarks result) {
adapter.updateBookmarks(result);
bookmarkList.startAnimation(fadeIn);
}
}
void bookmarkListItemClicked(Bookmark selectedBookmark) {
clipboardManager.setText(selectedBookmark.getUrl());
}
}
After:
#NoTitle
#Fullscreen
#EActivity(R.layout.bookmarks)
public class BookmarksToClipboardActivity extends Activity {
BookmarkAdapter adapter;
#ViewById
ListView bookmarkList;
#ViewById
EditText search;
#App
BookmarkApplication application;
#RestService
BookmarkClient restClient;
#AnimationRes
Animation fadeIn;
#SystemService
ClipboardManager clipboardManager;
#AfterViews
void initBookmarkList() {
adapter = new BookmarkAdapter(this);
bookmarkList.setAdapter(adapter);
}
#Click({R.id.updateBookmarksButton1, R.id.updateBookmarksButton2})
void updateBookmarksClicked() {
searchAsync(search.getText().toString(), application.getUserId());
}
#Background
void searchAsync(String searchString, String userId) {
Bookmarks bookmarks = restClient.getBookmarks(searchString, userId);
updateBookmarks(bookmarks);
}
#UiThread
void updateBookmarks(Bookmarks bookmarks) {
adapter.updateBookmarks(bookmarks);
bookmarkList.startAnimation(fadeIn);
}
#ItemClick
void bookmarkListItemClicked(Bookmark selectedBookmark) {
clipboardManager.setText(selectedBookmark.getUrl());
}
}