[Tutorial] Learn to create a Matrix Effect - Android Software Development

Hello,
I create that thread to present you a tutorial learning you how to create a Matrix Effect, also known as Digital Rain Effect, on Android. The tutorial is also available as a Youtube video :
Create a Matrix Effect on Android
Also know as Digital Rain Effect, the Matrix Effect is a classic effect featured in the Matrix series films. A green code is falling and represents the activity of the virtual reality environment of the Matrix on screen. On Android, Matrix Effect has been implemented in various applications often as a Live Wallpaper. In that tutorial, you are going to learn how to create a simple Matrix Effect.
1. Create a Matrix Effect custom View
First, you need to create a custom view named MatrixEffect :
Code:
package com.ssaurel.digitalraineffect;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import java.util.Random;
/**
* Created by ssaurel on 22/09/2016.
*/
public class MatrixEffect extends View {
private static final Random RANDOM = new Random();
private int width, height;
private Canvas canvas;
private Bitmap canvasBmp;
private int fontSize = 40;
private int columnSize;
private char[] cars = "+-*/!^'([])#@&?,=$€°|%".toCharArray();
private int[] txtPosByColumn;
private Paint paintTxt, paintBg, paintBgBmp, paintInitBg;
public MatrixEffect(Context context, AttributeSet attrs) {
super(context, attrs);
paintTxt = new Paint();
paintTxt.setStyle(Paint.Style.FILL);
paintTxt.setColor(Color.GREEN);
paintTxt.setTextSize(fontSize);
paintBg = new Paint();
paintBg.setColor(Color.BLACK);
paintBg.setAlpha(5);
paintBg.setStyle(Paint.Style.FILL);
paintBgBmp = new Paint();
paintBgBmp.setColor(Color.BLACK);
paintInitBg = new Paint();
paintInitBg.setColor(Color.BLACK);
paintInitBg.setAlpha(255);
paintInitBg.setStyle(Paint.Style.FILL);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
width = w;
height = h;
canvasBmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
canvas = new Canvas(canvasBmp);
canvas.drawRect(0, 0, width, height, paintInitBg);
columnSize = width / fontSize;
txtPosByColumn = new int[columnSize + 1];
for (int x = 0; x < columnSize; x++) {
txtPosByColumn[x] = RANDOM.nextInt(height / 2) + 1;
}
}
private void drawText() {
for (int i = 0; i < txtPosByColumn.length; i++) {
canvas.drawText("" + cars[RANDOM.nextInt(cars.length)], i * fontSize, txtPosByColumn[i] * fontSize, paintTxt);
if (txtPosByColumn[i] * fontSize > height && Math.random() > 0.975) {
txtPosByColumn[i] = 0;
}
txtPosByColumn[i]++;
}
}
private void drawCanvas() {
canvas.drawRect(0, 0, width, height, paintBg);
drawText();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(canvasBmp, 0, 0, paintBgBmp);
drawCanvas();
invalidate();
}
}
First, we define the variables for the Matrix Effect with the size of the code, the size of a column, the position of the bottom text for each column and then the caracters that will be used for the code. Note that you can put the caracters you want here or why not a custom font.
In the constructor, we initialize the paint objects. To get view width and height, we override the onSizeChanged method of the View. We initialize the position of the first caracter for each column. We use a random position between the top of the screen and the middle of the screen.
Then, we define a draw text method used to draw a random caracter for each column at the position indicated by txtPosByColumn variable.
The drawCanvas method is used to draw the background of our view and then the code.
Finally, we override the onDraw method of our custom view to call the drawCanvas method and invalidate the view to force a redraw. With that call, the Matrix Effect could progress from top to bottom in infinite mode. Note that it is not the most optimized way to manage a Matrix Effect, but for a tutorial it's sufficient.
2. Define the MatrixEffect View on the Layout
Now, we can define the MatrixEffect View on the layout of the Main Activity.
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ssaurel.digitalraineffect.MainActivity">
<com.ssaurel.digitalraineffect.MatrixEffect
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
3. Set the layout on the Main Activity
Last step is to set the layout as content view for the Main Activity.
Code:
package com.ssaurel.digitalraineffect;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
4. Demo
To enjoy the Matrix Effect, you have just to launch the application on an Android device and you sould see the following effect :
Don't hesitate to give it a try and give me your feedbacks.
Thanks.
Sylvain

Nice work mate, will give it a try.
Sent from my SM-G935F using XDA-Developers mobile app

silverrum said:
Nice work mate, will give it a try.
Sent from my SM-G935F using XDA-Developers mobile app
Click to expand...
Click to collapse
Thanks

I really like this animated wallpaper app.

Thanks for the detailed tutorial, it's always nice to see actually what the code does. :highfive:
In theory, would it be possible to take smali from the app you create and use it to create this effect on the notification screen (for example)?

Seeing the code I’m sure this app drain a lot of battery but it's very nice.

Ticklefish said:
Thanks for the detailed tutorial, it's always nice to see actually what the code does. :highfive:
In theory, would it be possible to take smali from the app you create and use it to create this effect on the notification screen (for example)?
Click to expand...
Click to collapse
Thanks.
Did you mean put the effect on the lock screen ? I thought it was not possible now to put live wallpaper on lock screen. If it's possible it could be great.

slnit said:
Seeing the code I’m sure this app drain a lot of battery but it's very nice.
Click to expand...
Click to collapse
For sure . But life is a choice, like in Matrix films, cool effect on your screen or save your battery lol

sylsau said:
Thanks.
Did you mean put the effect on the lock screen ? I thought it was not possible now to put live wallpaper on lock screen. If it's possible it could be great.
Click to expand...
Click to collapse
Should be possible to pull the AOSP lockscreen source (or the source from OEM variants that are actually available...) and replace the wallpaper code, right?

Interesting , definitely going to try it on Samsung TW later , great idea mate ..

thereassaad said:
Interesting , definitely going to try it on Samsung TW later , great idea mate ..
Click to expand...
Click to collapse
Thanks

Thanks for this tutorial With this I've started learning to work with canvas Nice job!

thereassaad said:
Interesting , definitely going to try it on Samsung TW later , great idea mate ..
Click to expand...
Click to collapse
Me too. hope it works

Excellent work.

rejm0901 said:
Me too. hope it works
Click to expand...
Click to collapse
It works mate ?

Hello! nice tutorial, everything works fine. But I would like to add buttons to change the colors of chars but i'm not able to call the method from the main activity.
I've tried this but giving errors
Code:
MatrixEffect matrixEffect = new MatrixEffect(); // this gives an error : MatrixEffect(Context, AttributSet) in MatrixEffect cannot be applied to ()
final Paint paintTxt = effetMatrix.peindreTxt;
paintTxt.setColor(Color.BLUE);
Is there a way that I can call paintTxt.setColor() to change color?
PS: Im just a noob on programming

esQmo said:
Hello! nice tutorial, everything works fine. But I would like to add buttons to change the colors of chars but i'm not able to call the method from the main activity.
I've tried this but giving errors
Code:
MatrixEffect matrixEffect = new MatrixEffect(); // this gives an error : MatrixEffect(Context, AttributSet) in MatrixEffect cannot be applied to ()
final Paint paintTxt = effetMatrix.peindreTxt;
paintTxt.setColor(Color.BLUE);
Is there a way that I can call paintTxt.setColor() to change color?
PS: Im just a noob on programming
Click to expand...
Click to collapse
If you want to add buttons to change the color of the Matrix Effect, you should work on the layout and add two buttons at the bottom of the screen under the MatrixView. The, you have to change the colors of the Matrix Effect when a user click on one of these buttons.

esQmo said:
Hello! nice tutorial, everything works fine. But I would like to add buttons to change the colors of chars but i'm not able to call the method from the main activity.
I've tried this but giving errors
Code:
MatrixEffect matrixEffect = new MatrixEffect(); // this gives an error : MatrixEffect(Context, AttributSet) in MatrixEffect cannot be applied to ()
final Paint paintTxt = effetMatrix.peindreTxt;
paintTxt.setColor(Color.BLUE);
Is there a way that I can call paintTxt.setColor() to change color?
PS: Im just a noob on programming
Click to expand...
Click to collapse
SOLVED!
---------- Post added at 11:13 PM ---------- Previous post was at 11:05 PM ----------
sylsau said:
If you want to add buttons to change the color of the Matrix Effect, you should work on the layout and add two buttons at the bottom of the screen under the MatrixView. The, you have to change the colors of the Matrix Effect when a user click on one of these buttons.
Click to expand...
Click to collapse
Already solved. I added 4 buttons for 4 colors and i used switch statement
1st, created a custom text color inside MAtrixEffect
Code:
public void setCustomTextColor(int color){
peindreTxt.setColor(color);
invalidate();
then, in mainactivity :
Code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
MatrixEffect matrixEffect;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
matrixEffect = (MatrixEffect) findViewById(R.id.arrPlan);
final Button boutton_blanc = (Button) findViewById(R.id.b_bl);
final Button boutton_bleu = (Button) findViewById(R.id.b_b);
final Button boutton_rouge = (Button) findViewById(R.id.b_r);
final Button boutton_rose = (Button) findViewById(R.id.b_ro);
if (boutton_bleu != null) {
boutton_bleu.setOnClickListener(this);
}
if (boutton_blanc != null) {
boutton_blanc.setOnClickListener(this);
}
if (boutton_rouge != null) {
boutton_rouge.setOnClickListener(this);
}
if (boutton_rose != null) {
boutton_rose.setOnClickListener(this);
}
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.b_bl:
matrixEffect.setCustomTextColor(Color.WHITE);
break;
case R.id.b_b:
matrixEffect.setCustomTextColor(Color.BLUE);
break;
case R.id.b_ro:
matrixEffectsetCustomTextColor(Color.MAGENTA);
break;
case R.id.b_r:
matrixEffect.setCustomTextColor(Color.RED);
break;
case R.id.b_def:
matrixEffect.setCustomTextColor(Color.GREEN);
break;
}
}
}
Now it works fine and i can change color while a button is pressed

esQmo said:
SOLVED!
---------- Post added at 11:13 PM ---------- Previous post was at 11:05 PM ----------
Already solved. I added 4 buttons for 4 colors and i used switch statement
1st, created a custom text color inside MAtrixEffect
Code:
public void setCustomTextColor(int color){
peindreTxt.setColor(color);
invalidate();
then, in mainactivity :
Code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
MatrixEffect matrixEffect;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
matrixEffect = (MatrixEffect) findViewById(R.id.arrPlan);
final Button boutton_blanc = (Button) findViewById(R.id.b_bl);
final Button boutton_bleu = (Button) findViewById(R.id.b_b);
final Button boutton_rouge = (Button) findViewById(R.id.b_r);
final Button boutton_rose = (Button) findViewById(R.id.b_ro);
if (boutton_bleu != null) {
boutton_bleu.setOnClickListener(this);
}
if (boutton_blanc != null) {
boutton_blanc.setOnClickListener(this);
}
if (boutton_rouge != null) {
boutton_rouge.setOnClickListener(this);
}
if (boutton_rose != null) {
boutton_rose.setOnClickListener(this);
}
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.b_bl:
matrixEffect.setCustomTextColor(Color.WHITE);
break;
case R.id.b_b:
matrixEffect.setCustomTextColor(Color.BLUE);
break;
case R.id.b_ro:
matrixEffectsetCustomTextColor(Color.MAGENTA);
break;
case R.id.b_r:
matrixEffect.setCustomTextColor(Color.RED);
break;
case R.id.b_def:
matrixEffect.setCustomTextColor(Color.GREEN);
break;
}
}
}
Now it works fine and i can change color while a button is pressed
Click to expand...
Click to collapse
Great

This is just the kind of guide that I have been waiting for! I am gonna implement this as a hidden feature in my Rom Control apk. Good lookin on the guide brother

Related

Enabling selection in textview

I am using this android:textIsSelectable and still gets the error:
Code:
TextView does not support text selection. Action mode cancelled.
Can any one please tell me what I might be doing wrong?
obscurant1st said:
I am using this android:textIsSelectable and still gets the error:
Code:
TextView does not support text selection. Action mode cancelled.
Can any one please tell me what I might be doing wrong?
Click to expand...
Click to collapse
Please post the code and also the AP version you are testing the app cant say anything without that
I believe testIsSelectable for TextViews was introduced in Honeycomb, if you want to be able to mimic that feature with lower versions of Android, here's a little workaround :
Use an EditText instead of your TextView and set android:textIsSelectable to false
In your activity's java code, override onLongClickListener and set the EditText to selectable in this method, something like this :
Code:
public class yourClass extends Activity implements onLongClickListener {
EditText yourFakeTextView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.whatever);
yourFakeTextView = (EditText) findViewById(R.id.editText1);
yourFakeTextView.setOnLongClickListener(this);
}
@Override
public boolean onLongClick(View v) {
switch (v.getId()) {
case R.id.editText1:
yourFakeTextView.setTextIsSelectable(true);
break;
default:
return;
}
return false;
}
}
This will make the EditText look like a regular TextView, and when the user long-clicks it, it will allow him to select the text (just like if it was a normal, selectable TextView).
Hope this helps.
I want to enable this feature on ICS and upper version of android. I am testing this on an ics device. There is something which is messed up. I will post the code as soon as I reach home!

How to launch an Activity on ListView Item click android

hello
I am new to android application development and i am developing and application for learning purpose.
Can any body please help me in creating an activity that launch and activity on ListView Item Click.
I am using Following code for Populating Listview Items.
filename: activity_menu.java
package com.my.android.app;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.app.LauncherActivity.ListItem;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class activity_menu extends Activity {
String[] countries = new String[] {
"Contacts",
"SMS",
"Files & Photos",
"Prefrences",
"Logout",
};
// Array of integers points to images stored in /res/drawable-ldpi/
int[] flags = new int[]{
R.drawable.phonebook,
R.drawable.sms,
R.drawable.filesphotos,
R.drawable.settings,
R.drawable.key,
};
// Array of strings to store currencies
String[] currency = new String[]{
"Manage Contacts Backup",
"Manage SMS Backup",
"Manage files & Photos Backup",
"Set your prefrences",
"Logout of Application",
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<5;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", countries);
hm.put("cur", currency);
hm.put("flag", Integer.toString(flags) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "flag","txt","cur" };
// Ids of views in listview_layout
int[] to = { R.id.flag,R.id.txt,R.id.cur};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);
// Getting a reference to listview of main.xml layout file
ListView listView = ( ListView ) findViewById(R.id.listview);
// Setting the adapter to the listView
listView.setAdapter(adapter);
}
}
Please help on this. waiting for Responses.
Try this
Code:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
// Do your action here
}
});
There are multiple ways. If using a ListFragment/ListActivity, onListItemClick can also be used. However, I think that that is used especially with a programmatically-defined ListView.
If you want to start a new Activity, do some research about Intents.
SagiLo said:
Try this
Code:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
// Do your action here
}
});
Click to expand...
Click to collapse
This. Use the position parameter if you want it to only open when a particular item is clicked (It is zero-based, if I remember correctly)
Then, to open the Intent:
Code:
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
Opening on any listitem click:
Code:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
}
});
Opening on a specific item:
Code:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
if (position == ITEM_POSITION_HERE)
{
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
}
}
});
how so i implement the code to open new activity on row cick?
cyr0s said:
This. Use the position parameter if you want it to only open when a particular item is clicked (It is zero-based, if I remember correctly)
Then, to open the Intent:
Code:
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
Opening on any listitem click:
Code:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
}
});
Opening on a specific item:
Code:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
if (position == ITEM_POSITION_HERE)
{
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
}
}
});
Click to expand...
Click to collapse
How do i implement this code in my main activity's java file?
suppose, i have a main activity which contains the listview and i have another activity "Activity_game"
and i want to open Activity_game on clicking the first row,
so i put "0" at "ITEM_POSITION_HERE" and "game" at the place of "ActivityName"
but it gives my a bunch of errors and it doesn't work
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
if (position == ITEM_POSITION_HERE)
{
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
}
}
});
nnnn1111 said:
How do i implement this code in my main activity's java file?
suppose, i have a main activity which contains the listview and i have another activity "Activity_game"
and i want to open Activity_game on clicking the first row,
so i put "0" at "ITEM_POSITION_HERE" and "game" at the place of "ActivityName"
but it gives my a bunch of errors and it doesn't work
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
if (position == ITEM_POSITION_HERE)
{
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
}
}
});
Click to expand...
Click to collapse
We need to know which errors you get.
Read this: http://forum.xda-developers.com/showthread.php?t=2439748
one question
nikwen said:
We need to know which errors you get.
Read this: http://forum.xda-developers.com/showthread.php?t=2439748
Click to expand...
Click to collapse
my problem is , when i run the app, it doesn't show any rows , not even any listview , or string
(just blank white page)
i have two activities
first one is Activity_main.xml in which ive implemented listview
here is it's java file
package com.example.desi;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
public class MainActivity extends Activity {
String[] items = { "item 1", "item 2", "item 3", "item 4", "item 5" };
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch( position )
{
case 0: Intent newActivity = new Intent(this, Munda.class);
startActivity(newActivity);
break;
}
}
}
and another activity is Activity_munda.xml
so, i want to run "Activity_munda" through on row click of listview
i also want to have many activities later in my app
my project is error free right now
do you think i have incomplete code?
nnnn1111 said:
my problem is , when i run the app, it doesn't show any rows , not even any listview , or string
(just blank white page)
i have two activities
first one is Activity_main.xml in which ive implemented listview
here is it's java file
package com.example.desi;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
public class MainActivity extends Activity {
String[] items = { "item 1", "item 2", "item 3", "item 4", "item 5" };
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch( position )
{
case 0: Intent newActivity = new Intent(this, Munda.class);
startActivity(newActivity);
break;
}
}
}
and another activity is Activity_munda.xml
so, i want to run "Activity_munda" through on row click of listview
i also want to have many activities later in my app
my project is error free right now
do you think i have incomplete code?
Click to expand...
Click to collapse
Your code is incomplete. You haven't populated the layout "activity_main.xml" here. and haven't added the list view, So it is indeed correct the app displays a blank page with no errors.
vijai2011 said:
Your code is incomplete. You haven't populated the layout "activity_main.xml" here. and haven't added the list view, So it is indeed correct the app displays a blank page with no errors.
Click to expand...
Click to collapse
Right. Read this: http://www.vogella.com/articles/AndroidListView/article.html
i already tried that
vijai2011 said:
Your code is incomplete. You haven't populated the layout "activity_main.xml" here. and haven't added the list view, So it is indeed correct the app displays a blank page with no errors.
Click to expand...
Click to collapse
but with no luck
its very complicated
can you please give me a simple tutorial ?
please dont refer to any other tutorial as i have already tried all of them,
thanks
nnnn1111 said:
but with no luck
its very complicated
can you please give me a simple tutorial ?
please dont refer to any other tutorial as i have already tried all of them,
thanks
Click to expand...
Click to collapse
Come on, you haven't tried all of them. Please don't let everyone else do the work for you. And if you can manage to do it yourself, it will be a better learning experience.
I can offer that you try the tutorial I posted and if your code doesn't work, you can post it together with a logcat and we'll check it.
haha i know
nikwen said:
Come on, you haven't tried all of them. Please don't let everyone else do the work for you. And if you can manage to do it yourself, it will be a better learning experience.
I can offer that you try the tutorial I posted and if your code doesn't work, you can post it together with a logcat and we'll check it.
Click to expand...
Click to collapse
but ive been searching for like 15 days about this problem on stack overflow , saw like 30 posts but they arent clear , please do me a favor and
tell me in few steps you will also feel good helping me.
and it will be a VERY big favor to me , trust me
nnnn1111 said:
but ive been searching for like 15 days about this problem on stack overflow , saw like 30 posts but they arent clear , please do me a favor and
tell me in few steps you will also feel good helping me.
and it will be a VERY big favor to me , trust me
Click to expand...
Click to collapse
Read this about ListActivity. It should answer your questions: http://www.vogella.com/articles/AndroidListView/article.html#listactivity
And I won't post step by step guides on how to implement ListViews. There are many great tutorials out there. I can help you if you have problems/errors with your code, but @vijai2011 has already explained what you need to do.
You cannot expect anyone to spoon feed you. We are here to help people who try to do something but run into problems. Not people who doesnt even try to understand what they do. The guides by vogella are very simple and there is no problem with the guide. You cannot simply copy paste the codes from the tutorial and expect it to compile and work.
vijai2011 said:
You cannot expect anyone to spoon feed you. We are here to help people who try to do something but run into problems. Not people who doesnt even try to understand what they do. The guides by vogella are very simple and there is no problem with the guide. You cannot simply copy paste the codes from the tutorial and expect it to compile and work.
Click to expand...
Click to collapse
i didn't find my answer on that website
nnnn1111 said:
i didn't find my answer on that website
Click to expand...
Click to collapse
Then it may mean that you dont know what you are searching for! Because the tutorial is all about what you need - ListView!

Android/Java Newbie

Hi all, im having a go at developing a simple app. i have little experience with Java and Android development. i have a little test app at the moment and have created a new class, im trying to create a new instance of this class on a button click. it fails to do so, i cant for the life of me see why so.. can someone shed any light on this?
Thanks
Debuging this shows it hitting the "LocationFactory locationf = new LocationFactory();" line and throwing an exception-
"java.lang.NullPointerException"
Main
Code:
package com.example.testapp;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends Activity {
private static final Context Context = null;
protected static final String TAG = null;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
[user=439709]@override[/user]
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 mainButton(View view) throws IOException {
try {
LocationFactory locationf = new LocationFactory();
Toast.makeText(this, locationf.getAddress(),Toast.LENGTH_LONG).show();
} catch (Exception e)
{
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
Class
Code:
package com.example.testapp;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import java.io.IOException;
import java.util.Locale;
import java.util.List;
public class LocationFactory
{
private static final Context Context = null;
Geocoder geocoder = new Geocoder(Context, Locale.getDefault());
LocationManager manager = (LocationManager) Context.getSystemService(android.content.Context.LOCATION_SERVICE);
public double Latitude = 0.0;
public double Longitude = 0.0;
public LocationFactory()
{
}
public String getAddress() throws IOException
{
String ReturnAddress = "";
String Address = "", City = "", Country = "";
List<Address> addresses = null;
if(manager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
// Use GPS Radio Location
Location GPSlocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Latitude = GPSlocation.getLatitude();
Longitude = GPSlocation.getLongitude();
}
else
{
// Use Cell Tower Location
Location NETlocation = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Latitude = NETlocation.getLatitude();
Longitude = NETlocation.getLongitude();
}
if(Latitude > 0 && Longitude > 0)
{
addresses = geocoder.getFromLocation(Latitude, Longitude, 1);
if(!addresses.isEmpty())
{
Address = addresses.get(0).getAddressLine(0);
City = addresses.get(0).getAddressLine(1);
Country = addresses.get(0).getAddressLine(2);
}
}
ReturnAddress = Address + " " + City + " " + Country;
return ReturnAddress;
}
}
I don't see anywhere in your code where you are calling the mainButton(View view) method. In the Android lifecycle, the onCreate method is the equivalent of a normal Java program's main() method, which means that code execution begins with the first line of onCreate(). Not knowing what you're trying to do, a good start would be to call your mainButton() method AFTER setContentView() in onCreate().
Side note: your mainButton() method has a View parameter that is never used. Is there a reason for that?
Android activity lifecycle: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
You have to use an intent on that button click, use the method onClickListener and define the intent in the androidmanifest.xml
e.g
Code:
Button button = (Button) findViewById(R.id.[B]button[/B]) // replace latter button with actual id defined in main xml.
button.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent("[B]com.example.packagename.CLASSNAME[/B]")); // this should be your own package name.
}
});
Also define this in android manifest under the <application> and </application>
Code:
<activity
android:name=".[B]CLASSNAME[/B]"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="[B]com.example.packagename.CLASSNAME[/B]" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Change the values of BOLD text according to your own values.
I tried to help you as far as I understood your question. Please let me know if you face any problem I would be more than happy to help you. Rest I am also in the learning phase so you can always PM me if you face any problem.
Hit thanks if I have helped you in any way.
coolbud012 said:
You have to use an intent on that button click, use the method onClickListener and define the intent in the androidmanifest.xml
Click to expand...
Click to collapse
Nope! He didn't say that he wanted to launch a new Activity when the button is clicked. He wants to create a new instance of his LocationFactory Class.
jpepin said:
Nope! He didn't say that he wanted to launch a new Activity when the button is clicked. He wants to create a new instance of his LocationFactory Class.
Click to expand...
Click to collapse
Oops yeah right read that now...I thought he want to start an activity... Anyways tried to delete my reply but not getting an option to delete.
There are many flaws in his code. And the other thing is if its his first app and if he has low level of programming experience then according to me it would be a next to impossible app for him, as per his code and what he is trying to implement.
I think he should rather start up with small apps, understand things and then move on to complex apps.
P.S - its just my opinion
Click to expand...
Click to collapse
Agreed that he should start small...which is exactly why your suggestion for creating and handling Intents makes no sense. Before that, he should first understand the activity lifecycle. Until then, he can just stick to trivial single-activity apps to gain experience.
OP: This code should be placed in the onCreate method:
Code:
Button button = (Button) findViewById(R.id.your_button_ID_here)
button.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
mainButton(); // get rid of the View parameter in this method...it's not needed
}
});
This will cause a new instance of your LocationFactory to be created, and will also cause your Toast message to be displayed.
thanks for the replies. yes you are right in that i am inexperienced, but this is just a test app for me to play around with and learn on. i tend to learn better by doing rather than constantly reading. thanks for your suggestions ill look into them
osmorgan said:
thanks for the replies. yes you are right in that i am inexperienced, but this is just a test app for me to play around with and learn on. i tend to learn better by doing rather than constantly reading. thanks for your suggestions ill look into them
Click to expand...
Click to collapse
I also believe in the same, I also keep on doing experiments and testing things out.
What I would suggest is that start with a small app and understand the insights on how android works and all...
Thanks
Potential Solution
Alright, I think I've found your problem. Have a look at where you define your variables in your LocationManager class:
Code:
private static final Context Context = null;
Geocoder geocoder = new Geocoder(Context, Locale.getDefault());
LocationManager manager = (LocationManager) Context.getSystemService(android.content.Context.LOCATION_SERVICE);
This is your problem:
Code:
Context Context = null;
If your context is null, and you use it to create a geocoder and call Context.getSystemService, you'll hit a null pointer. You're trying to access an object (the Context) that doesn't even exist
I'd recommend you pass the context in the LocationManager constructor and then instantiate your objects there. That's standard java procedure.
Code:
private Context mContext = null;
Geocoder geocoder = null;
LocationManager manager = null;
public double Latitude = 0.0;
public double Longitude = 0.0;
public LocationFactory(Context context)
{
this.mContext = context;
this.geocoder = new Geocoder(context, Locale.getDefault());
this.manager = (LocationManager) Context.getSystemService(android.content.Context.LOCATION_SERVICE);
}
I also renamed Context to mContext - it's generally a good idea to keep the instance's name separate from the class name.
Try that - it should work. Please feel free to ask any more questions - this is how I learned, and I think it's the best way!

[Guide] Listeners in Java development

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

PreferenceFragment and Tabs

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.

Categories

Resources