[Q] Populating listview from custom class - Java for Android App Development

Hello,
I'm trying to populate a listview from a custom class but i don't seem able to do it. I run the code showed below and eventhought i've got no errors on build the elements aren't shown on screen. Any help with this would be very appreaciated.
The code's below!
The main_activity.xml:
HTML:
<LinearLayout xmlns:android="link"
xmlns:tools="link" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.angelo.gamerquiz.WallpaperSelector"
android:background="@drawable/background"
android:orientation="vertical"
android:weightSum="1">
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/lista_background" />
</LinearLayout>
The single_row.xml:
HTML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="link"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/textView2" />
</LinearLayout>
And then the custom class code:
Code:
public class CustomAdapter extends BaseAdapter {
private Context mContext;
private Integer[] imgID;
public CustomAdapter(Context context, Integer[] imgID){
super();
mContext = context;
this.imgID = imgID;
}
[user=439709]@override[/user]
public int getCount() {
return 0;
}
[user=439709]@override[/user]
public Object getItem(int position) {
return null;
}
[user=439709]@override[/user]
public long getItemId(int position) {
return 0;
}
[user=439709]@override[/user]
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.single_row, null);
TextView tf = (TextView) convertView.findViewById(R.id.textView2);
tf.setText("Position " + String.valueOf(position));
return null;
}
}
And finally, the main class from where i call my custom class:
Code:
ListView listView;
Integer[] imageID = {R.drawable.ezio1_thumbnail};
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wallpaper_selector);
listView = (ListView) findViewById(R.id.lista_background);
Log.d("LVCREATED","TRUE");
CustomAdapter adapter = new CustomAdapter(this, imageID);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
[user=439709]@override[/user]
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "You clicked at position " + position, Toast.LENGTH_SHORT);
}
});
}
Thank you!
NOTE: Nevermind where it says "link" when i posted this i got the message that i wouldn't be able to post links lol

Well:
1. Why would you want to use BaseAdapter and not ArrayAdapter if the latter is easier to use?
2. If you do want to use BaseAdapter then all the methods you override should work. If getCount() always returns 0 then the listview thinks there are just no entries inside the adapter and simply aborts the creation of any list items. getCount must return the length of the array of list entries, in your case the Integer[] imgID. Then if getItem returns null this won't work either, same thing if getView simply returns null....
So:
Use ArrayAdapter, then you only have to override the getView method.
And: after you prepared your convertView, why dont you use it as a return value
--------------------
Phone: Nexus 4
OS: rooted Lollipop LRX21T
Bootloader: unlocked
stock Recovery
Recovery: TWRP 2.8.2.0

Masrepus said:
Well:
1. Why would you want to use BaseAdapter and not ArrayAdapter if the latter is easier to use?
2. If you do want to use BaseAdapter then all the methods you override should work. If getCount() always returns 0 then the listview thinks there are just no entries inside the adapter and simply aborts the creation of any list items. getCount must return the length of the array of list entries, in your case the Integer[] imgID. Then if getItem returns null this won't work either, same thing if getView simply returns null....
So:
Use ArrayAdapter, then you only have to override the getView method.
And: after you prepared your convertView, why dont you use it as a return value
--------------------
Phone: Nexus 4
OS: rooted Lollipop LRX21T
Bootloader: unlocked
stock Recovery
Recovery: TWRP 2.8.2.0
Click to expand...
Click to collapse
Thank you for your answer!
I've followed your advice and changed it to an array adapter but it still is not working. Here's my custom class code.
Code:
public class CustomAdapter extends ArrayAdapter<Integer> {
private final Context context;
private final Integer[] values;
public CustomAdapter(Context context, Integer[] values) {
super(context, R.layout.single_row);
this.context = context;
this.values = values;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.single_row, parent, false);
ImageButton imgbt = (ImageButton) rowView.findViewById(R.id.wallpaperButton);
Log.d("VALUE",String.valueOf(values[position]));
imgbt.setImageResource(values[position]);
return rowView;
}
}
Any idea why?
Two questions:
What's the parameter that an ArrayAdapter receives, which in this case is "Integer" and why the use of super in the constructor?
Thank you.

ratedam said:
Thank you for your answer!
I've followed your advice and changed it to an array adapter but it still is not working. Here's my custom class code.
Code:
public class CustomAdapter extends ArrayAdapter<Integer> {
private final Context context;
private final Integer[] values;
public CustomAdapter(Context context, Integer[] values) {
super(context, R.layout.single_row);
this.context = context;
this.values = values;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.single_row, parent, false);
ImageButton imgbt = (ImageButton) rowView.findViewById(R.id.wallpaperButton);
Log.d("VALUE",String.valueOf(values[position]));
imgbt.setImageResource(values[position]);
return rowView;
}
}
Any idea why?
Two questions:
What's the parameter that an ArrayAdapter receives, which in this case is "Integer" and why the use of super in the constructor?
Thank you.
Click to expand...
Click to collapse
Mhh.. I think the problem lies within the inflation process, try this: View rowView = View.inflate(context, R.layout.single_row, null);
There could be a problem because you try to inflate the view inside a parent view and it somehow doesn't like that.
The parameter tells the adapter what kind of array it will receive, in this case an Integer[]
It is required by the base class, but i have no idea how the super constructor works. Just take it as given or google it
--------------------
Phone: Nexus 4
OS: rooted Lollipop LRX21T
Bootloader: unlocked
Recovery: TWRP 2.8.2.0

Masrepus said:
Mhh.. I think the problem lies within the inflation process, try this: View rowView = View.inflate(context, R.layout.single_row, null);
There could be a problem because you try to inflate the view inside a parent view and it somehow doesn't like that.
The parameter tells the adapter what kind of array it will receive, in this case an Integer[]
It is required by the base class, but i have no idea how the super constructor works. Just take it as given or google it
--------------------
Phone: Nexus 4
OS: rooted Lollipop LRX21T
Bootloader: unlocked
Recovery: TWRP 2.8.2.0
Click to expand...
Click to collapse
Thank you for your prompt response,
The problem was really in the super constructor.
I changed it from this super(context, R.layout.single_row); to this super(context, R.layout.single_row, values); and it worked.
But now i have another problem, i click it but doesn't show anything. Any idea? No errors neither.
EDIT:Solved.
I removed the onitemclicklistener from the main function and inserted it on the customadapter created class like this:
Code:
ImageButton imgbt = (ImageButton) rowView.findViewById(R.id.wallpaperButton);
imgbt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("CLICKED","BUTTONCLICKED");
Log.d("cenas","cenas" + position);
}
});
And i get the pretended output.
Thank you very much for your help.

Very good! Great that i helped you
--------------------
Phone: Nexus 4
OS: rooted Lollipop LRX21T
Bootloader: unlocked
Recovery: TWRP 2.8.2.0

Related

[HOW-TO] Use Code Syntax Highlighting on XDA [Raise Awareness]

XDA is an awesome place for developers to share their knowledge and help each other, no question about it.
However, in my opinion, one of the flaws that prevent the app development forums from being more popular is the
Code:
tags.
Indeed, these tags do not provide syntax highlighting, and when people start pasting their whole Java class, the lack of proper indentation plus the lack of syntax highlighting leaves us with a very off-putting chunk of code, and even if you intend to help in the first place, having to go through this unreadable code can discourage many.
I was ranting about this in the [URL="http://forum.xda-developers.com/showpost.php?p=49938207&postcount=1976"]xda suggestions & feedback thread[/URL], when someone pointed-out the existence of the [B][PHP][/B] tags, which provide syntax highlighting for php, and, the syntaxes of PHP and Java being somewhat similar, they also do the trick for Java.
[FONT="Garamond"][I]Example:[/I][/FONT]
[PHP]
package com.androguide.recovery.emulator;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import android.util.Log;
public class CMDProcessor {
private final String TAG = getClass().getSimpleName();
private static final boolean DEBUG = false;
private Boolean can_su;
public SH sh;
public SH su;
public CMDProcessor() {
sh = new SH("sh");
su = new SH("su");
}
public SH suOrSH() {
return canSU() ? su : sh;
}
public boolean canSU() {
return canSU(false);
}
public class CommandResult {
private final String resultTag = TAG + '.' + getClass().getSimpleName();
public final String stdout;
public final String stderr;
public final Integer exit_value;
CommandResult(final Integer exit_value_in) {
this(exit_value_in, null, null);
}
CommandResult(final Integer exit_value_in, final String stdout_in,
final String stderr_in) {
exit_value = exit_value_in;
stdout = stdout_in;
stderr = stderr_in;
if (DEBUG)
Log.d(TAG, resultTag + "( exit_value=" + exit_value
+ ", stdout=" + stdout + ", stderr=" + stderr + " )");
}
public boolean success() {
return exit_value != null && exit_value == 0;
}
}
public class SH {
private String SHELL = "sh";
public SH(final String SHELL_in) {
SHELL = SHELL_in;
}
private String getStreamLines(final InputStream is) {
String out = null;
StringBuffer buffer = null;
final DataInputStream dis = new DataInputStream(is);
try {
if (dis.available() > 0) {
buffer = new StringBuffer(dis.readLine());
while (dis.available() > 0) {
buffer.append("\n").append(dis.readLine());
}
}
dis.close();
} catch (final Exception ex) {
Log.e(TAG, ex.getMessage());
}
if (buffer != null) {
out = buffer.toString();
}
return out;
}
public Process run(final String s) {
Process process = null;
try {
process = Runtime.getRuntime().exec(SHELL);
final DataOutputStream toProcess = new DataOutputStream(
process.getOutputStream());
toProcess.writeBytes("exec " + s + "\n");
toProcess.flush();
} catch (final Exception e) {
Log.e(TAG,
"Exception while trying to run: '" + s + "' "
+ e.getMessage());
process = null;
}
return process;
}
public CommandResult runWaitFor(final String s) {
if (DEBUG)
Log.d(TAG, "runWaitFor( " + s + " )");
final Process process = run(s);
Integer exit_value = null;
String stdout = null;
String stderr = null;
if (process != null) {
try {
exit_value = process.waitFor();
stdout = getStreamLines(process.getInputStream());
stderr = getStreamLines(process.getErrorStream());
} catch (final InterruptedException e) {
Log.e(TAG, "runWaitFor " + e.toString());
} catch (final NullPointerException e) {
Log.e(TAG, "runWaitFor " + e.toString());
}
}
return new CommandResult(exit_value, stdout, stderr);
}
}
public boolean canSU(final boolean force_check) {
if (can_su == null || force_check) {
final CommandResult r = su.runWaitFor("id");
final StringBuilder out = new StringBuilder();
if (r.stdout != null) {
out.append(r.stdout).append(" ; ");
}
if (r.stderr != null) {
out.append(r.stderr);
}
Log.d(TAG, "canSU() su[" + r.exit_value + "]: " + out);
can_su = r.success();
}
return can_su;
}
}
[/PHP]
Oddly enough, the [B][PHP][/B] tags also work for XML (while the [html] tags, that do exist, don't work):
[PHP]
<LinearLayout
android:id="@+id/contentLayout"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_marginLeft="8dip"
android:layout_weight="90"
android:orientation="vertical" >
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dip"
android:fontFamily="sans-serif-light"
android:textColor="#33B6EA"
android:textSize="22sp" />
<TextView
android:id="@+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="8dip"
android:layout_marginRight="8dip"
android:ellipsize="end"
android:fontFamily="sans-serif-light"
android:textColor="#232323"
android:maxLines="50"
android:textSize="16sp" />
</LinearLayout>
[/PHP]
This doesn't fix the indentation issues, but as you can see, the code is much more readable and welcoming.
By using the [B][PHP][/B] tags instead of the [strike][CODE][/strike] tags, you will be more likely to get answers to your questions involving code.
[B][SIZE="3"][CENTER]So Please, for the sake of the app development forums and the eyes of your readers:
USE THE [COLOR="RoyalBlue"][PHP][/COLOR] TAGS :victory:[/CENTER][/SIZE][/B]
[CENTER][I]Please raise awareness about this, suggest people who don't use the [B][PHP][/B] tags to use them, and together we'll make this app development forum a better place than it already is :good:[/I][/CENTER]
Whoa! Never knew about this. Nice find.
Wow, this is really cool! Thanks for finding. The only problem I have with the PHP tags is on mobile, tapatalk is obviously not supporting it at all:
SimplicityApks said:
Wow, this is really cool! Thanks for finding. The only problem I have with the PHP tags is on mobile, tapatalk is obviously not supporting it at all:
Click to expand...
Click to collapse
Too bad, thanks for reporting :good:
This obviously is just a workaround, xda could quite easily implement a dedicated syntax highlighting plugin for vBulletin as I suggested in the suggestions thread, but for the time being this is probably the closest thing we've got.
Androguide.fr said:
Too bad, thanks for reporting :good:
This obviously is just a workaround, xda could quite easily implement a dedicated syntax highlighting plugin for vBulletin as I suggested in the suggestions thread, but for the time being this is probably the closest thing we've got.
Click to expand...
Click to collapse
They've got it working way better with the CODE tags: Code syntax highlighting announcement!

[Q] Same shell command works from console and doesn't work from Activity

//sorry for my english, if any
Hi. I'm using AIDE right on my device (Xperia NeoV, 4.1.B.0.587, root)
And i'm trying to inject key events through the same shell command:
"input keyevent 25" via "su", both in AIDE Console and separated Activity.
//volume-down key is not my target, just good for tests. I've tried different keys, same result.
Part of the code:
Code:
try {
java.lang.Process p = Runtime.getRuntime().exec("su");
DataOutputStream dos = new DataOutputStream(p.getOutputStream());
dos.writeBytes("input keyevent 25\n");
dos.flush();
} catch (IOException ex) {
//log any errors
}
So, when it goes in AIDE ConsoleApp - it pushes down volume.
But when it executes from my Activity - nothing happens (no error messages in log, dos != null);
Maybe there should be some specific permission on manifest?
"android.permission.ACCESS_SUPERUSER" - no changes.
Maybe there should be some trick in code? Or(and?) i'm very stupid. Also, maybe somewhere a whole listing of _simple_ keyInjection project exists?
I managed to solve it already. I'm using this class now:
public void RunAsRoot(String[] cmds){
Process p = null;
try {
p = Runtime.getRuntime().exec("su");
} catch (IOException e) {
e.printStackTrace();
}
DataOutputStream os = new DataOutputStream(p.getOutputStream());
for (String tmpCmd : cmds) {
try {
os.writeBytes(tmpCmd+"\n");
} catch (IOException e) {
e.printStackTrace();
}
}
try {
os.writeBytes("exit\n");
} catch (IOException e) {
e.printStackTrace();
}
try {
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
Click to expand...
Click to collapse
Then simply call it via
String[] commands = {"command1", "command2", "command3", ...};
RunAsRoot(commands);
Click to expand...
Click to collapse
Thanks anyways!
Click to expand...
Click to collapse
Credits: @KrauseDroid
Our original thread i took it from:
http://forum.xda-developers.com/showthread.php?t=2725173
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk
Masrepus said:
Credits: @KrauseDroid
Our original thread i took it from:
http://forum.xda-developers.com/showthread.php?t=2725173
Click to expand...
Click to collapse
I saw that thread before creating own, and tried solutions from it. They works same way - only from ConsoleApp in AIDE.
Also, last method is the same as I'm already using, but I've tried to copy code in project - no progress.
In addition:
- superuser rights granted to both.
- test "ls" command put into dos object gives me same list of current dir in both projects, so commands seems to run.
Listing:
MainActivity:
Code:
package com.tsk.mk;
import android.app.*;
import android.content.*;
import android.os.*;
import android.widget.*;
import java.io.*;
public class MainActivity extends Activity {
public static TextView logView;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
logView = (TextView) findViewById(R.id.log);
log("creating sercice");
final MainActivity me = this;
new Thread() {
[user=439709]@override[/user]
public void run() {
log("thread.run");
startService(new Intent(me, MissedKeysService.class));
log("thread: service shoul'd be created");
}
}.start();
log("end of MA.onCreate method");
}
static void log(String message) {
logView.setText(logView.getText() + "\n" + message);
}
}
MissedKeysService:
Code:
package com.tsk.mk;
import android.app.*;
import android.content.*;
import android.graphics.*;
import android.os.*;
import android.view.*;
import java.io.*;
public class MissedKeysService extends Service {
private WindowManager windowManager;
private MissedKeysView mkv;
private WindowManager.LayoutParams params;
private DataOutputStream dos;
[user=439709]@override[/user]
public IBinder onBind(Intent intent) {
MainActivity.log("onBind called o_o");
return null;
}
[user=439709]@override[/user]
public void onCreate() {
MainActivity.log("Service.onCreate");
super.onCreate();
try {
java.lang.Process p = Runtime.getRuntime().exec("su");
dos = new DataOutputStream(p.getOutputStream());
} catch (IOException ex) {
MainActivity.log(ex.getMessage());
dos = null;
}
windowManager = (WindowManager)
getSystemService(WINDOW_SERVICE);
mkv = new MissedKeysView(this, this);
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
params.width = MissedKeysView.keySize;
params.height = MissedKeysView.keySize;
windowManager.addView(mkv, params);
MainActivity.log("Service started");
}
[user=439709]@override[/user]
public void onDestroy () {
super.onDestroy ();
if (mkv != null) windowManager.removeView(mkv);
MainActivity.log("Ssrvice is ended");
}
public void extend(boolean state) {
params.height = mkv.keySize * (state ? MissedKeysView.keys : 1);
windowManager.updateViewLayout(mkv, params);
}
public void sendKey(int code) {
if (dos == null) MainActivity.log("dos is null");
try {
dos.writeBytes("input keyevent " + code + "\n");
dos.flush();
MainActivity.log("" + code);
} catch (IOException e) {
MainActivity.log("wtf?");
}
}
}
MissedKeysView:
Code:
package com.tsk.mk;
import android.content.*;
import android.graphics.*;
import android.view.*;
import android.view.View.*;
import java.io.*;
public class MissedKeysView extends View
implements OnTouchListener {
final static int keySize = 64;
final static String[] labels = {":", "+", "-", "^", "v", "o", "<", ">"};
final private int[] codes = {-1, 24, 25, 19, 20, 23, 21, 22};
final static int keys = 3; //max shown keys
MissedKeysService mks;
Paint bgP; //background
Paint hbgP; //highlighted bg
Paint tP; //text
int selected = -1; //active key
public MissedKeysView(Context context, MissedKeysService mks) {
super(context);
this.mks = mks;
bgP = new Paint();
bgP.setARGB(64, 128, 128, 128);
hbgP = new Paint();
hbgP.setARGB(64, 255, 128, 0);
tP = new Paint();
tP.setARGB(128, 255, 255, 255);
tP.setTextSize(keySize);
tP.setTextAlign(Paint.Align.CENTER);
setOnTouchListener(this);
}
[user=439709]@override[/user]
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for(int i=0; i<getHeight()/keySize; i++) {
canvas.drawCircle(keySize/2,
keySize/2 + i*keySize, keySize/2,
(i == selected ? hbgP : bgP));
canvas.drawText(labels[i], keySize/2, i*keySize + keySize*3/4, tP);
}
}
[user=439709]@override[/user]
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
selected = (int) (event.getY()/keySize);
if (selected == 0) mks.extend((int) getHeight() <= keySize);
else mks.sendKey(codes[selected]);
break;
case MotionEvent.ACTION_UP:
selected =-1;
}
invalidate();
return super.onTouchEvent(event);
}
}
AndroidManifest:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tsk.mk"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="11" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".MainActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MissedKeysService"
android:exported="true" >
</service>
</application>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.ACCESS_SUPERUSER" />
<uses-permission android:name="android.permission.INJECT_EVENTS" />
</manifest>
@Torsionick do you have the permission INJECT_EVENTS
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk
Masrepus said:
@Torsionick do you have the permission INJECT_EVENTS
Click to expand...
Click to collapse
Thanks for participating in solving.
The reason was somewhere else - after executing "export LD_LIBRARY_PATH=/system/lib" all works fine. Thread is over.

[Q] [Solved]Calling a method of parent fragment from child fragment

TabFragment
Code:
public class TabFragment extends android.support.v4.app.Fragment
{List fragments = new Vector();
PagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
@Override
public View onCreateView (LayoutInflater inflater , ViewGroup container ,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup ) inflater .inflate(
R . layout.tabfragment , container , false );
mSectionsPagerAdapter = new ScreenSlidePagerAdapter (getActivity().getSupportFragmentManager ());
mViewPager = (ViewPager) rootView.findViewById(R.id.pager);
//for each fragment
add();
//(android.support.v4.app.Fragment.instantiate(this,Main.class.getName(),page));
mViewPager.setAdapter(mSectionsPagerAdapter);
return rootView ;
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter
{
@Override
public CharSequence getPageTitle(int position)
{return fragments.get(position).getArguments().getString("name");
}
public int getCount()
{
// TODO: Implement this method
return fragments.size();
}
public ScreenSlidePagerAdapter ( android.support.v4.app.FragmentManager fm ) {
super ( fm);
}
@Override
public android.support.v4.app.Fragment getItem ( int position ) {
android.support.v4.app.Fragment f;
f= fragments.get(position);
return f;
}
}
public void add(){
android.support.v4.app.Fragment main=new Main();
Bundle b=new Bundle();
int p=fragments.size();
b.putString("name","Sdcard");
b.putInt("pos",p);
main.setArguments(b);
fragments.add(main);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(p);
}
}
//Here "new Main()" refers to a child fragment
Now I want to execute the method "add" of above posted "TabFragment" in the child fragment "Main"
Please help for the same
Sent from my GT-S5570 using XDA Premium 4 mobile app
arpitkh96 said:
TabFragment
Code:
public class TabFragment extends android.support.v4.app.Fragment
{List<android.support.v4.app.Fragment> fragments = new Vector<android.support.v4.app.Fragment>();
PagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
@Override
public View onCreateView (LayoutInflater inflater , ViewGroup container ,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup ) inflater .inflate(
R . layout.tabfragment , container , false );
mSectionsPagerAdapter = new ScreenSlidePagerAdapter (getActivity().getSupportFragmentManager ());
mViewPager = (ViewPager) rootView.findViewById(R.id.pager);
//for each fragment
add();
//(android.support.v4.app.Fragment.instantiate(this,Main.class.getName(),page));
mViewPager.setAdapter(mSectionsPagerAdapter);
return rootView ;
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter
{
@Override
public CharSequence getPageTitle(int position)
{return fragments.get(position).getArguments().getString("name");
}
public int getCount()
{
// TODO: Implement this method
return fragments.size();
}
public ScreenSlidePagerAdapter ( android.support.v4.app.FragmentManager fm ) {
super ( fm);
}
@Override
public android.support.v4.app.Fragment getItem ( int position ) {
android.support.v4.app.Fragment f;
f= fragments.get(position);
return f;
}
}
public void add(){
android.support.v4.app.Fragment main=new Main();
Bundle b=new Bundle();
int p=fragments.size();
b.putString("name","Sdcard");
b.putInt("pos",p);
main.setArguments(b);
fragments.add(main);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(p);
}
}
//Here "new Main()" refers to a child fragment
Now I want to execute the method "add" of above posted "TabFragment" in the child fragment "Main"
Please help for the same
Sent from my GT-S5570 using XDA Premium 4 mobile app
Click to expand...
Click to collapse
You should use an EventBus for similar cases. Try Square's Otto, available on GitHub.

[Q]Problem using RootTools library

i am trying to list files of root folders using roottools libary .here is the code
Code:
public ArrayList<File> listFiles(final Context c,final String path) {
final ArrayList<File> a=new ArrayList<File>();
Command command = new Command(0, "ls "+path)
{
@Override
public void commandOutput(int i, String s) {
File f=new File(path+"/"+s);
a.add(f);}
@Override
public void commandTerminated(int i, String s) {
}
@Override
public void commandCompleted(int i, int i2) {
//want to arraylist return from here
}
};
try {
RootTools.getShell(true).add(command);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
now problem is that if i return arraylist<file> from the end of method,its size is zero,to solve it i must return the arraylist from commandCompleted
method.but i am not able to accomplish that.So please solve my problem
Maybee arraylist as static outside your function? So on top of source file? Not sure but maybee

[Q] How do I add an image picker to my app, show it in image view, then save it to pa

This is what I have:
Code:
package JEB.ssf;
import android.app.*;
import android.os.*;
import android.widget.*;
import android.view.*;
import android.view.View.*;
import com.parse.*;
import android.content.*;
import android.support.v4.app.*;
import java.util.*;
import android.widget.AdapterView.*;
import android.util.*;
import com.google.android.gms.ads.*;
import com.google.ads.mediation.*;
import com.google.ads.*;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdListener;
import android.provider.*;
import android.database.*;
import android.graphics.*;
public class ProfilePage extends Activity
{
private static int LOAD_IMAGE_RESULTS = 1;
// GUI components
private Button button; // The button
private ImageView image;// ImageView
Spinner sp1,sp2;
ArrayAdapter<String> adp1,adp2, adp3;
List<String> l1,l2, l3;
int pos;
EditText fname, lname, hf, hi, weight,
waist, wrist, hip, forearm, age, goal;
TextView userName, gender, category, unit;
String hftxt, hitxt, id, firstNameTxt, userNameTxt, posttxt, postnum;
Button share;
float obid;
int in;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_page);
getActionBar().setDisplayHomeAsUpEnabled(true);
Parse.initialize(this, "abmPl8JnnhyaqjA0Pp8ZWmptKTCeV0p8eoMEHPaL", "icKQxW5AdPXHJtsGEqSX5LwJ2Dd8zt0USKd1PNeP");
fname = (EditText) findViewById(R.id.first_name);
lname = (EditText) findViewById(R.id.last_name);
hf = (EditText) findViewById(R.id.height_feet);
hi = (EditText) findViewById(R.id.height_inch);
weight = (EditText) findViewById(R.id.weight_lbs);
waist = (EditText) findViewById(R.id.waist);
wrist = (EditText) findViewById(R.id.wrist);
hip = (EditText) findViewById(R.id.hip);
forearm = (EditText) findViewById(R.id.forearm);
age = (EditText) findViewById(R.id.age);
userName = (TextView) findViewById(R.id.user_name);
gender = (TextView) findViewById(R.id.gender);
category = (TextView) findViewById(R.id.category);
unit =(TextView) findViewById(R.id.unit);
goal =(EditText) findViewById(R.id.goal);
share = (Button) findViewById(R.id.share);
Intent i = getIntent();
userNameTxt = i.getStringExtra("user_name");
userName.setText(userNameTxt);
button = (Button)findViewById(R.id.image_pick);
image = (ImageView)findViewById(R.id.image);
gender_button();
category_button();
unit_button();
image_button();
share_button();
small_banner_ad();
final ParseQuery<ParseObject> query = ParseQuery.getQuery("profile_info");
// Restrict to cases where the author is the current user.
// Note that you should pass in a ParseUser and not the
// String reperesentation of that user
query.whereEqualTo("user_data", ParseUser.getCurrentUser());
// Run the query
query.findInBackground(new FindCallback<ParseObject>() {
public String TAG;
[user=439709]@override[/user]
public void done(List<ParseObject> postList, ParseException e) {
if (e == null) {
// If there are results, update the list of posts
// and notify the adapter
for (ParseObject profile_info : postList) {
userName.setText(profile_info.getString("user_name"));
fname.setText(profile_info.getString("first_name"));
lname.setText(profile_info.getString("last_name"));
hf.setText(profile_info.getString("height_in_feet"));
hi.setText(profile_info.getString("height_in_inches"));
weight.setText(profile_info.getString("weight"));
waist.setText(profile_info.getString("waist"));
wrist.setText(profile_info.getString("wrist"));
hip.setText(profile_info.getString("hip"));
forearm.setText(profile_info.getString("forearm"));
age.setText(profile_info.getString("age"));
gender.setText(profile_info.getString("gender"));
category.setText(profile_info.getString("category"));
unit.setText(profile_info.getString("unit"));
goal.setText(profile_info.getString("goal"));
}
} else {
Log.d("Post retrieval", "Error: " + e.getMessage());
}
}});
}
private void share_button()
{
share.setOnClickListener(new OnClickListener() {
public void onClick(View arg1) {
final ParseObject posts = new ParseObject("posts");
posts.put("user_name", userName.getText().toString());
posts.put("category", "My goal is to" + " "+category.getText()+" "+goal.getText()+" "+unit.getText().toString());
// Create an user data relationship with the current user
posts.put("user_posts", ParseUser.getCurrentUser());
// Save the post and return
posts.saveInBackground(new SaveCallback () {
[user=439709]@override[/user]
public void done(ParseException e) {
if (e == null) {
setResult(RESULT_OK);
Toast.makeText(getApplicationContext(),"post successfull",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error sharing: " + e.getMessage(),
Toast.LENGTH_SHORT)
.show();
}
}});
}
});
}
private void unit_button()
{
unit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(ProfilePage.this, unit);
//Inflating the Popup using xml file
if (category.getText().toString().equals("Loose Weight")){
popup.getMenuInflater()
.inflate(R.menu.weight_menu, popup.getMenu());
}if(category.getText().toString().equals("Target Weight")){
popup.getMenuInflater()
.inflate(R.menu.weight_menu, popup.getMenu());
}if(category.getText().toString().equals("Gain Weight")){
popup.getMenuInflater()
.inflate(R.menu.weight_menu, popup.getMenu());
}if(category.getText().toString().equals("Build Muscle")){
popup.getMenuInflater()
.inflate(R.menu.weight_menu, popup.getMenu());
}if(category.getText().toString().equals("Run")){
popup.getMenuInflater()
.inflate(R.menu.distance_menu, popup.getMenu());
}if(category.getText().toString().equals("Walk")){
popup.getMenuInflater()
.inflate(R.menu.distance_menu, popup.getMenu());
}
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.lbs:
//act for menu_item1
unit.setText("lbs");
return true;
case R.id.mile:
//act for sub_menu_item1
unit.setText("Mile");
return true;
case R.id.k:
//act for sub_menu_item1
unit.setText("K");
return true;
default:
//pass the event to parent, for options menu, use below
}
return false;
}
});
popup.show(); //showing popup menu
}
}); //closing the setOnClickListener method
}
private void category_button()
{
category.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(ProfilePage.this, category);
//Inflating the Popup using xml file
popup.getMenuInflater()
.inflate(R.menu.category_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.target_weight:
category.setText("Target Weight");
return true;
case R.id.loose_weight:
//act for menu_item1
category.setText("Loose Weight");
return true;
case R.id. gain_weight:
//act for sub_menu_item1
category.setText("Gain Weight");
return true;
case R.id. build_muscle:
//act for sub_menu_item1
category.setText("Build Muscle");
return true;
case R.id. run:
//act for sub_menu_item1
category.setText("Run");
return true;
case R.id. walk:
//act for sub_menu_item1
category.setText("Walk");
return true;
default:
//pass the event to parent, for options menu, use below
}
return false;
}
});
popup.show(); //showing popup menu
}
}); //closing the setOnClickListener method
}
private void gender_button()
{
gender.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(ProfilePage.this, gender);
//Inflating the Popup using xml file
popup.getMenuInflater()
.inflate(R.menu.gender_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id. male:
//act for menu_item1
gender.setText("Male");
return true;
case R.id. female:
//act for sub_menu_item1
gender.setText("Female");
return true;
default:
//pass the event to parent, for options menu, use below
}
return false;
}
});
popup.show(); //showing popup menu
}
}); //closing the setOnClickListener method
}
private void small_banner_ad()
{
AdView adView = (AdView) this.findViewById(R.id.adView);
//request TEST ads to avoid being disabled for clicking your own ads
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)// This is for emulators
//test mode on DEVICE (this example code must be replaced with your device uniquq ID)
.addTestDevice("15174709D5FCBF710958952E2589F20D") // Nexus 6
.build();
adView.loadAd(adRequest);
}
private void save_update_button()
{
ParseUser.getCurrentUser();
ParseQuery<ParseObject> pQuery = new ParseQuery<ParseObject>("profile_info");
pQuery.whereEqualTo("user_name", userName.getText().toString());
pQuery.getFirstInBackground(new GetCallback<ParseObject>()
{ [user=439709]@override[/user]
public void done(ParseObject update, ParseException e) {
if (e == null){
update.put("user_name", userName.getText().toString());
update.put("first_name", fname.getText().toString());
update.put("last_name", lname.getText().toString());
update.put("height_in_feet", hf.getText().toString());
update.put("height_in_inches", hi.getText().toString());
update.put("weight", weight.getText().toString());
update.put("waist", waist.getText().toString());
update.put("wrist", wrist.getText().toString());
update.put("hip", hip.getText().toString());
update.put("forearm", forearm.getText().toString());
update.put("age", age.getText().toString());
update.put("gender", gender.getText().toString());
update.put("category", category.getText().toString());
update.put("unit", unit.getText().toString());
update.put("goal", goal.getText().toString());
update.saveInBackground();
Toast.makeText(getApplicationContext(),
"Your profile has been updated",
Toast.LENGTH_SHORT)
.show();
} else {
final ParseObject profile_info = new ParseObject("profile_info");
profile_info.put("user_name", userNameTxt);
profile_info.put("first_name", fname.getText().toString());
profile_info.put("last_name", lname.getText().toString());
profile_info.put("height_in_feet", hf.getText().toString());
profile_info.put("height_in_inches", hi.getText().toString());
profile_info.put("weight", weight.getText().toString());
profile_info.put("waist", waist.getText().toString());
profile_info.put("wrist", wrist.getText().toString());
profile_info.put("hip", hip.getText().toString());
profile_info.put("forearm", forearm.getText().toString());
profile_info.put("age", age.getText().toString());
profile_info.put("gender", gender.getText().toString());
profile_info.put("category", category.getText().toString());
profile_info.put("unit", unit.getText().toString());
profile_info.put("goal", goal.getText().toString());
// Create an user data relationship with the current user
profile_info.put("user_data", ParseUser.getCurrentUser());
// Save the post and return
profile_info.saveInBackground(new SaveCallback () {
[user=439709]@override[/user]
public void done(ParseException e) {
if (e == null) {
setResult(RESULT_OK);
Toast.makeText(getApplicationContext(),"Profile saved",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error saving: " + e.getMessage(),
Toast.LENGTH_SHORT)
.show();
}
}});
}
}
});
}
//image button
public void image_button(){
image.setOnClickListener(new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
// Create the Intent for Image Gallery.
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery.
startActivityForResult(i, LOAD_IMAGE_RESULTS);
}});
}
//menu [user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.profile_menu, menu);
return super.onCreateOptionsMenu(menu);
}
[user=439709]@override[/user]
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
// Handle action buttons
switch(item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.logout:
ParseUser.logOut();
finish();
return true;
case R.id.Wall:
Intent intent = new Intent(ProfilePage.this,
Wall.class);
startActivity(intent);
return true;
case R.id.Save:
save_update_button();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
[user=439709]@override[/user]
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Here we need to check if the activity that was triggers was the Image Gallery.
// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
// Now we need to set the GUI ImageView data with data read from the picked file.
image.setImageBitmap(BitmapFactory.decodeFile(imagePath));
// At the end remember to close the cursor or you will end with the RuntimeException!
cursor.close();
}}}
[\CODE]
When I import "uri" for my on activity results at the end of my code I get a bunch of errors for everything I'm doing with parse. I been searching and trying different image picker tutorials and always end up with same results. I've checked out parse.com but only see info on saving images from the drawable folder. If I can get the image picker to work I'm pretty sure I can figure out how to save it to parse.com.
Sent from my Nexus 6 using XDA Free mobile app

Categories

Resources