Hello,
I'm new to developing software in Java, but especially with Android. I am going through a tutorial on how to create an RSS Feed Reader and so far I've got it mostly working, but I've got a few bugs I can't seem to figure out.
I wanted to post images, but it wouldn't let me, but anyway:
main activity - title, pubdate both work, as does each article's title.
after clicking on a title, the other activity is launched and the article is shown:
showdescription activity is launched - title, pubdate, link all work and display correctly.
bug: description does not always display everything or even display at all depending on the xml source.
I'm wondering if my problem is somewhere these code snippets, as this tutorial was written some time ago.
These are pretty basic, so I'm doubting the problem is in here.
RSSHandler said:
if (localName.equals("description"))
{
currentstate = RSS_DESCRIPTION;
return;
}
...
case RSS_DESCRIPTION:
_item.setDescription(theString);
currentstate = 0;
break;
Click to expand...
Click to collapse
RSSItem said:
void setDescription(String description)
{
_description = description;
}
...
String getDescription()
{
return _description;
}
Click to expand...
Click to collapse
This is where I believe the problem exists, in the onItemClick method or the ShowDescription class.
RSSReader said:
public void onItemClick(AdapterView parent, View v, int position, long id)
{
Log.i(tag,"item clicked! [" + feed.getItem(position).getTitle() + "]");
Intent itemintent = new Intent(this,ShowDescription.class);
Bundle b = new Bundle();
b.putString("title", feed.getItem(position).getTitle());
b.putString("description", feed.getItem(position).getDescription());
b.putString("link", feed.getItem(position).getLink());
b.putString("pubdate", feed.getItem(position).getPubDate());
itemintent.putExtra("android.intent.extra.INTENT", b);
//startSubActivity(itemintent, 0);
startActivity(itemintent);
}
Click to expand...
Click to collapse
ShowDescription said:
public class ShowDescription extends Activity
{
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.showdescription);
String theStory = null;
Intent startingIntent = getIntent();
if (startingIntent != null)
{
Bundle b = startingIntent.getBundleExtra("android.intent.extra.INTENT");
if (b == null)
{
theStory = "bad bundle?";
}
else
{
theStory = b.getString("title")
+ "\n\n" + b.getString("pubdate")
+ "\n\n" + b.getString("description")
+ "\n\nView Website:\n" + b.getString("link");
}
}
else
{
theStory = "Information Not Found.";
}
TextView db= (TextView) findViewById(R.id.storybox);
db.setText(theStory);
Button backbutton = (Button) findViewById(R.id.back);
backbutton.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
finish();
}
});
}
}
Click to expand...
Click to collapse
Originally the tutorial called for "startSubActivity" for starting the ShowDescription activity, but that doesn't seem to exist anymore?
The XML source I'm using can't be displayed because I can't link in outside pages, but I can PM it to you if you'd like.
I have tried using a .replaceAll("\\<.*?>","") but it didn't seem to change much about whether the <description> tag's content is displayed or not.
Anyway, if anyone takes the time to look at this, it'd be greatly appreciated, and thank you!
If you need me to post anymore code let me know.
So I think I've figured it out, well somewhat.
While stepping through the code, the <description> tag's content consists of a single < character. Then the parser goes through two more tags that contain, p and > before actually hitting the content I want.
So it looks something like this:
<description>
<
<?>
p
<?>
>
<?>
"wanted content"
</?>
</?>
</?>
</description>
Click to expand...
Click to collapse
Related
In Googles sample Notepad app (the final version using NotepadV3Solution), if you select Add Note (launching the NoteEdit activity), then just hit the back button, a blank line is then inserted into the Notepad activity, and it cannot be deleted. Does anyone know why? Below is the java code for this activity...
package com.android.demo.notepad3;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class NoteEdit extends Activity {
private EditText mTitleText;
private EditText mBodyText;
private Long mRowId;
private NotesDbAdapter mDbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.note_edit);
mTitleText = (EditText) findViewById(R.id.title);
mBodyText = (EditText) findViewById(R.id.body);
Button confirmButton = (Button) findViewById(R.id.confirm);
mRowId = savedInstanceState != null ? savedInstanceState.getLong(NotesDbAdapter.KEY_ROWID)
: null;
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
: null;
}
populateFields();
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
setResult(RESULT_OK);
finish();
}
});
}
private void populateFields() {
if (mRowId != null) {
Cursor note = mDbHelper.fetchNote(mRowId);
startManagingCursor(note);
mTitleText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
mBodyText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(NotesDbAdapter.KEY_ROWID, mRowId);
}
@Override
protected void onPause() {
super.onPause();
saveState();
}
@Override
protected void onResume() {
super.onResume();
populateFields();
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
if (mRowId == null) {
long id = mDbHelper.createNote(title, body);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateNote(mRowId, title, body);
}
}
}
When you hit the back button the onpause function is called which calls savestate. In savestate it doesn't check to see it fields title and body are blank. So it writes a record with blank or null values.
________________________________
http://ron-droid.blogspot.com
I'm still trying to figure all this java out. Any chance you could tell me specifically what I need to add to fix it?
greydarrah said:
I'm still trying to figure all this java out. Any chance you could tell me specifically what I need to add to fix it?
Click to expand...
Click to collapse
Modify the saveState() function to check to see if the body or titles are empty.
You can do something like:
Code:
if (title.isEmpty() || body.isEmpty())
return;
Which will make the save state not needlessly update or add to the db if a field is blank. This disallows you to add blank notes though (ie. notes with only a title, no body). Though I'm OK with that. But the save-state is where you want to start, because that's what's happening.
And for the love of Christ please wrap your code in code tags (select the code, hit the # sign in the top menu bar).
I'd do something like this;
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
If (title == null || title == "") return;
________________________________
http://ron-droid.blogspot.com
rigman said:
I'd do something like this;
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
If (title == null || title == "") return;
________________________________
http://ron-droid.blogspot.com
Click to expand...
Click to collapse
I'm sorry for being such an idiot, but when I put:
If (title == null || title == "") return;
in saveState, I get red mark right after the closing paren (just before return. If I hold my cursor over the red mark, it says syntax error, insert ";" to complete statement. Any idea why Eclipse doesn't like this?
Edit...A little more to the story:
The first error I got was this...
The method fi(boolean) is undefined fo rthe type NoteEdit
Quick fix: create method If(boolean)
So I did the quick fix. Now I'm thinking that I should add a ";" at the end if the if statement and put the return; in the new If(boolean) mentod. It would look like this:
Code:
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
If (title == null || title == "");
if (mRowId == null) {
long id = mDbHelper.createNote(title, body);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateNote(mRowId, title, body);
}
}
private void If(boolean b) {
// TODO Auto-generated method stub
return;
}
Is that correct, or am I totally retarded?
Well, I'm not sure what's going on in the code above, but it doesn't work...still inserts blank lines. I wish I knew more about what I'm doing.
If anyone can help me figure this out, I'm ONLY concerned with the note title (if it equals "", don't save the blank line). I don't care if the body has text in it or not.
greydarrah said:
Well, I'm not sure what's going on in the code above, but it doesn't work...still inserts blank lines. I wish I knew more about what I'm doing.
If anyone can help me figure this out, I'm ONLY concerned with the note title (if it equals "", don't save the blank line). I don't care if the body has text in it or not.
Click to expand...
Click to collapse
I'm sorry, I thought isEmpty() was a standard function of the String library in Java.
Aside from that, can I ask what your issue is with my solution?
If you don't want to check to see if the body is empty, don't. If you are only concerned with whether or not the title is empty, use Java's built in string functionality. So in your saveState function, put this after:
Code:
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
if (title.length() == 0) // if string length is 0
{
return;
}
What this will do, is if the title is empty (ie. == "") it will return from the saveState function, without updating or adding the note to the database. You CANNOT use the "==" operator, as that will run a comparison of the objects (to see if they're the same string instance), ie.:
Code:
String a = "hi";
String b = "hi";
if (a == b); // false
if (a.equals(b)); // true ([I]this calls the comparison operator on the strings, which is built into the String class[/I])
if (a == a); // true (they're the same object)
If you're checking to see if a string is empty, you can do:
Code:
if (a.equals("")) ... // checks if it's the equivalent of the empty string
OR
if (a.length() == 0) ... // Checks if size of string is 0
Either will work. Hopefully that clears it up for you, you can check if the String is empty, or you can see if it equals the empty string.
It sounds like you're new to programming in general, is this the case? Or are you just new to Android? If you are more accustomed to another language I can possibly (probably) give you better analogies from there...unless it's some weird language .
Syndacate said:
I'm sorry, I thought isEmpty() was a standard function of the String library in Java.
Aside from that, can I ask what your issue is with my solution?
If you don't want to check to see if the body is empty, don't. If you are only concerned with whether or not the title is empty, use Java's built in string functionality. So in your saveState function, put this after:
Code:
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
if (title.length() == 0) // if string length is 0
{
return;
}
Click to expand...
Click to collapse
Thanks so much. This worked perfectly. As to my programming, I'm a long time VB programmer (since VB 3), but brand new to java. In these early stages, I'm having issues getting my mind wrapped around it, but I'll get there.
I'm thankful to everyone that responded to this thread. This is how a forum should work.
greydarrah said:
As to my programming, I'm a long time VB programmer (since VB 3), but brand new to java.
Click to expand...
Click to collapse
That explains your syntax error problems above. Unlike VB, Java is case-sensitive, and you used an upper-case "If" instead of the correct lower-case "if". The compiler did not recognize this as a keyword and assumed you wanted to use a method called "If(boolean)" but forgot to define it.
So, change all capital letters in all keywords to lower case, and remove the auto-generated "If(boolean)" method again.
Cheers
tadzio
greydarrah said:
Thanks so much. This worked perfectly. As to my programming, I'm a long time VB programmer (since VB 3), but brand new to java. In these early stages, I'm having issues getting my mind wrapped around it, but I'll get there.
I'm thankful to everyone that responded to this thread. This is how a forum should work.
Click to expand...
Click to collapse
Ah, I see. Haven't used VB in forever, barely remember it, haha. Glad it works for you, though.
I'm new to using cursors to obtain data from the device. I'm working on a music player (see market link in signature) and I need to be able to list (and eventually play) the music found on the sdcard. I have some code, but I can't seem to get it to work
Here's the code I found on a website, but it leads to a force-close:
public class TestingData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView view = (TextView) findViewById(R.id.hello);
String[] projection = new String[] {
MediaStore.MediaColumns.DISPLAY_NAME
, MediaStore.MediaColumns.DATE_ADDED
, MediaStore.MediaColumns.MIME_TYPE
};
Cursor mCur = managedQuery(Media.EXTERNAL_CONTENT_URI,
projection, null, null, null
);
mCur.moveToFirst();
while (mCur.isAfterLast() == false) {
for (int i=0; i<mCur.getColumnCount(); i++) {
view.append("n" + mCur.getString(i));
}
mCur.moveToNext();
}
}
}
Here's my attempt at fixing it, which still leads to a force-close:
public class test3 extends Activity {
TextView view = (TextView) findViewById(R.id.text1);
ListView list;
private ArrayAdapter<String> adapter;
String[] projection = new String[] {
MediaStore.MediaColumns.DISPLAY_NAME
, MediaStore.MediaColumns.DATE_ADDED
, MediaStore.MediaColumns.MIME_TYPE
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = (ListView)findViewById(R.id.list);
ArrayList<String> _list = new ArrayList<String>(Arrays.asList(projection));
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,_list);
list.setAdapter(adapter);
Cursor mCur = managedQuery(Media.EXTERNAL_CONTENT_URI,
projection, null, null,
MediaStore.MediaColumns.DISPLAY_NAME + "ASC"
);
mCur.moveToFirst();
while (mCur.isAfterLast() == false) {
for (int i=0; i<mCur.getColumnCount(); i++) {
view.append("n" + mCur.getString(i));
}
mCur.moveToNext();
}
}
}
What am I doing wrong? Both codes lead to a force-close and I can't think of anything else to do. Thanks in advance.
did you set the correct permissions in the android manifest?
*slaps hand to forehead* I always forget about the manifest. Lol. Ummmm....what all am I supposed to put in there for these codes? Do both codes look like they would accomplish the same thing?
Well, I've written hundreds of Cursors in Android and I don't run my loop like you do, so, as a suggestion:
Code:
Cursror c = yada, yada;
if(c.moveToFirst()) {
do {
// TO DO HERE...
} while(c.moveToNext());
}
c.close();
Never had a problem.
Awesome! Thanks. Ill try it when I get a chance
Hi all skilled developers,
I am a newbie in coding, and I just want to make some small changes to my app.
It is a licensing feature.
1) Licensee information are stored at a very simple website. With columns for Names, IMEI and Remarks.
2) I have the following chunk of code:
Code:
if(hadLicense) {
new AlertDialog.Builder(InsuranceGuruSplash.this)
.setTitle("License")
.setMessage("Your device is registered.\nWelcome.")
.setPositiveButton("Send", new DialogInterface.OnClickListener()
Intent intent = new Intent(InsuranceGuruSplash.this, MainActivity.class);
startActivity(intent);
finish();
I want to show a toast saying,
Welcome, Shawn. Your device is registered till DD/MM/YY.
Click to expand...
Click to collapse
Can someone teach me how I can go about doing this?:silly:
You can show a toast using:
Code:
Toast.makeText(context, text, duration).show();
Just make the text String first with the text and time. For duration use Toast.LENGTH_SHORT
SimplicityApks,
Thanks for your reply. I still don't really know what you mean. how do I echo a text from a website into the app's toast?
This is the full code:
Code:
protected Void doInBackground(Void... params) {
String url_for_sale = "www(dot)heyfellas(dot)com/guru/index.php";
parseLicense(url_for_sale);
return null;
}
@Override
protected void onPostExecute(Void result) {
TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
final String imei = mngr.getDeviceId();
boolean hadLicense = false;
for(LicenseInfo license: licenses) {
if(license.phoneIMEI.equals(imei))
hadLicense = true;
}
if(hadLicense) {
Intent intent = new Intent(InsuranceGuruSplash.this, MainActivity.class);
startActivity(intent);
finish();
} else {
new AlertDialog.Builder(InsuranceGuruSplash.this)
.setTitle("License")
.setMessage("Your device is not registered.\nPlease send your details to the admin.")
.setPositiveButton("Send", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"[email protected]"});
i.putExtra(Intent.EXTRA_SUBJECT, "Request for license");
i.putExtra(Intent.EXTRA_TEXT , "UserName: \n\nPhone Number: \n\nEmail: \n\nIMEI: " + imei);
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(PropertyGuruSplash.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create().show();
}
}
}
You need
[java]
String name = ...;
String date = ....;
Toast.makeToast(Activity.this, name + ", you have registered since "+date, Toast.LENGTH_SHORT).show();[/java]
I suppose, you are strong at server side than in client programming? Then echo the result in your desired format in your php and read it in java then display it in toast. Use the below snippet:
Code:
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://www(dot)heyfellas(dot)com/guru/index.php");
HttpResponse response = httpclient.execute(httppost);
String Result = EntityUtils.toString(response.getEntity());
Toast.makeText(Context, Result, Toast.LENGTH_SHORT).show();
You are new to java development and want to get buttons working?
Maybe you are a Pro but want a reminder?
whatever you are this Guide is to help you to make buttons/check boxes...etc working and functional
Some people are distracted between guides over internet and want the easiest way to get their project working, me too
Steps :
1-Define the button :
Code:
Button btn1;
Checkbox chkbox1;
RadioButton radio1;
2- Intialize it :
Code:
btn1 = (Button) findViewById(R.id.btn1);
chkbox1= (Checkbox ) findViewById(R.id.chkbox1);
radio1= (RadioButton) findViewById(R.id.radio1);
3-Add the listener :
Button:
Code:
btn1.setOnClickListener(new OnClickListener() {
@SuppressWarnings("deprecation")
@Override
public void onClick(View arg0) {
//Write awesome code here
}
});
CheckBox :
Code:
chkbox1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (start.isChecked()) {
//if the checkbox checked
} else {
//if not checked
}
}
});
}
radio button:
Code:
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.radio1:
if (checked){
}
else{
}
break;
}
}
or use it in a radio Group :
Code:
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio1:
if (checked)
//Write code
break;
case R.id.radio2:
if (checked)
//Write code
break;
}
}
Also insted of this you can use a onCheckedChanged for a radio button (Thanks for GalaxyInABox)
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
//Code
}
}
____________________________________________________________________
____________________________________________________________________
Also you can implement a Onclicklistener for the whole class to save resources : (thanks for @Jonny )
after defining and initializing your objects add this :
Code:
OnClickListener click_listener = new OnClickListener() {
public void onClick(View view) {
int id = view.getId();
if (id == your_id) {
//do stuff for this object
} else if (id == your_id2) {
//do other stuff for diffrent object
} else if (id == your_id3) {
//and so on
}
}
};
To do list :
-add on touch listeners
-add on drag listeners
Note : you can add a click listener to almost any thing (Textview or imageView or even EditText) just using the same method of adding listener to button
also there is some other ways to add a listener but this is the fastest and less disturbing :good:
If this guide is useful, press thanks
@ OP
CheckBox and RadioButtons don't they provide a CheckedChangeListener ?
Sent from my GT-S5302 using Tapatalk 2
sak-venom1997 said:
@ OP
CheckBox and RadioButtons don't they provide a CheckedChangeListener ?
Click to expand...
Click to collapse
Yes, and now you can use
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
//Code
}
}
to get the checked button. They are pretty much the same, but you can use view.getTag() easier in the first one.
And @mohamedrashad please show how to put the listener into a inner class. Many people don't know/use it, but it's that useful!
GalaxyInABox said:
Yes, and now you can use
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
//Code
}
}
to get the checked button. They are pretty much the same, but you can use view.getTag() easier in the first one.
Click to expand...
Click to collapse
I meant that the op shuld edit this guide and use those instead of OnCickListeners
GalaxyInABox said:
And @mohamedrashad please show how to put the listener into a inner class. Many people don't know/use it, but it's that useful!
Click to expand...
Click to collapse
ya new with java8 it will be a nice usage scenario of lambadas
Sent from my GT-S5302 using Tapatalk 2
GalaxyInABox said:
Yes, and now you can use
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
//Code
}
}
to get the checked button. They are pretty much the same, but you can use view.getTag() easier in the first one.
And @mohamedrashad please show how to put the listener into a inner class. Many people don't know/use it, but it's that useful!
Click to expand...
Click to collapse
sak-venom1997 said:
@ OP
CheckBox and RadioButtons don't they provide a CheckedChangeListener ?
Sent from my GT-S5302 using Tapatalk 2
Click to expand...
Click to collapse
ok, i will add this
You can also add onClick property in XML and then handle it in a code.
Awesome tutorial! Thank you very much!
Please, you could share more related knowledge. It's really useful!
Also, an activity can be a listener. In this case:
MyActivity implements onClickListener {
btn1.setOnClickListener(this);
public void onClick (View v) {
//your code
}
}
For this kind of stuff, using some well known libraries from well known Android dev is a must.
https://github.com/JakeWharton/butterknife
Very powerfull, super easy to use, error prone and without any performance impact.
rafalniski said:
You can also add onClick property in XML and then handle it in a code.
Click to expand...
Click to collapse
SKAm69 said:
Also, an activity can be a listener. In this case:
MyActivity implements onClickListener {
btn1.setOnClickListener(this);
public void onClick (View v) {
//your code
}
}
Click to expand...
Click to collapse
will add them both, although I don't like this way
Mohamedrashad. Thanks a lot.
Sent from my P880 using Tapatalk
If you have multiple clickable objects then it's best to use just 1 onClickListener for all of them and use a switch on their ID's. This reduces resource usage as you only have 1 listener, not 5, 10 or however many you would have otherwise. It's not essential for this but it is a best practice if you want to streamline your code.
Mobile right now so I can't chuck up an example until tomorrow evening or so.
You dude had a great thread. Its helping me. Bravoo !!
Sent from my GT-I8190 using XDA Premium 4 mobile app
As @Jonny already pointed out: Use your class as a listener instead of creating a new (anonymous) inner class! Say you have a ListView, instead of doing this:
Code:
class MyFragment extends Fragment {
private void someMethod() {
((ListView) getView().findViewById(R.id.someListView)).setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Code...
}
});
}
}
you can do this:
Code:
class MyFragment extends ListFragment implements AdapterView.OnItemClickListener, View.OnClickListener {
private void someMethod() {
((ListView) getView().findViewById(R.id.someListView)).setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Code...
}
}
This may look stupid, but when you have many listeners, you can un-clutter it. In my opinion this is the best way. You can also add "this" class as listener for as many ui elements as you want(because all of them extend view, you can use one OnClickListener), then you only need to have a switch statement to distinguish between the views. And voila, you prevented cluttering the code with boilerplate stuff.
Example using code in an app I'm making - app for my school.
Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Some code here for view/layouts etc
websitebutton = (Button) view.findViewById(R.id.website_btn);
facebookbutton = (Button) view.findViewById(R.id.facebook_btn);
twitterbutton = (Button) view.findViewById(R.id.twitter_btn);
websitebutton.setOnClickListener(handler);
facebookbutton.setOnClickListener(handler);
twitterbutton.setOnClickListener(handler);
return view;
}
OnClickListener handler = new OnClickListener() {
public void onClick(View view) {
switch (view.getId()) {
case R.id.website_btn :
Uri website = Uri.parse("http://wirralgrammarboys.com/");
Intent websiteintent = new Intent(Intent.ACTION_VIEW, website);
startActivity(websiteintent);
break;
case R.id.facebook_btn :
Uri facebook = Uri.parse("https://www.facebook.com/WirralGSB");
Intent facebookintent = new Intent(Intent.ACTION_VIEW, facebook);
startActivity(facebookintent);
break;
case R.id.twitter_btn :
Uri twitter = Uri.parse("https://twitter.com/WGSB");
Intent twitterintent = new Intent(Intent.ACTION_VIEW, twitter);
startActivity(twitterintent);
break;
}
}
};
Jonny said:
Example using code in an app I'm making.
Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Some code here for view/layouts etc
websitebutton = (Button) view.findViewById(R.id.website_btn);
facebookbutton = (Button) view.findViewById(R.id.facebook_btn);
twitterbutton = (Button) view.findViewById(R.id.twitter_btn);
websitebutton.setOnClickListener(handler);
facebookbutton.setOnClickListener(handler);
twitterbutton.setOnClickListener(handler);
return view;
}
OnClickListener handler = new OnClickListener() {
public void onClick(View view) {
int id = view.getId();
if (id == R.id.website_btn) {
Uri website = Uri.parse("http://wirralgrammarboys.com/");
Intent websiteintent = new Intent(Intent.ACTION_VIEW, website);
startActivity(websiteintent);
} else if (id == R.id.facebook_btn) {
Uri facebook = Uri.parse("https://www.facebook.com/WirralGSB");
Intent facebookintent = new Intent(Intent.ACTION_VIEW, facebook);
startActivity(facebookintent);
} else if (id == R.id.twitter_btn) {
Uri twitter = Uri.parse("https://twitter.com/WGSB");
Intent twitterintent = new Intent(Intent.ACTION_VIEW, twitter);
startActivity(twitterintent);
}
}
};
Click to expand...
Click to collapse
i'm adding this to OP if you don't mind jonny
mohamedrashad said:
i'm adding this to OP if you don't mind jonny
Click to expand...
Click to collapse
That's fine - if I didn't want people to use/adapt/learn from the code then I wouldn't put it up, use it as you want :good:
Sent from my HTC One using Tapatalk
Keep it up
Great tutorials, keep em coming!
Hey what about starting a new activity with onClickListiner
Sent from my M3S_D7 using XDA Free mobile app
---------- Post added at 03:57 PM ---------- Previous post was at 03:49 PM ----------
Hey and do u mind sending a source codes.zip file
Sent from my M3S_D7 using XDA Free mobile app
Rebound.co said:
Hey what about starting a new activity with onClickListiner
Sent from my M3S_D7 using XDA Free mobile app
---------- Post added at 03:57 PM ---------- Previous post was at 03:49 PM ----------
Hey and do u mind sending a source codes.zip file
Sent from my M3S_D7 using XDA Free mobile app
Click to expand...
Click to collapse
in the onClick method just have this code:
Code:
startActivity(new Intent(this, YourActivity.class));
Hi,
currently I am developing a App.
I use the NavigationDrawer to set up a Menu (with the "Burger-Button") on the left side.
Wenn I choose a menu item, for example a PreferenceFragment i displayed.
My problem: I want to display a Tab-Layout with a PreferenceFragment in each Tab.
But I don´t know how...
In my MainActitivty-Class (AppCompatActivity) I change the content of my App (after the user clicked on a menu item) like this:
Code:
@Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentTransaction fragmentTransaction = this.getFragmentManager().beginTransaction();
int id = item.getItemId();
// Globale Eistellungen
if (id == R.id.nav_main_settings) {
fragmentTransaction.replace(R.id.containerView, new MainPreferenceMenu());
fragmentTransaction.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Whereby "MainPreferenceMenu" is a PreferenceFragment.
I tried it with this tutorial: https://guides.codepath.com/android/google-play-style-tabs-using-tablayout
First Problem: I can´t set my PreferenceFragment here:
Code:
@Override
public Fragment getItem(int position) {
return PageFragment.newInstance(position + 1);
}
Because "PreferenceFragment" is the wring Class.
Also I don´t know how to set the "ViewPager" like in the Tutorial (MainActivity).
Can anybody help me?
I hope my Problem is clear.
Using view pager for tabs is the best option as it behaves as per material guide lines.