alireza alireza - 5 months ago 17
Java Question

return value in android button

I want to return the imageUrls array for this part of code
"adapter = new LazyAdapter(this, imageUrls);" when the button click
its error say you cannot return value in void method, i dont know to use what method to return the value,

my code:

public class MainActivity extends Activity {
ListView list;
LazyAdapter adapter;
public static String res="";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn1=(Button)findViewById(R.id.button1);
list = (ListView) findViewById(R.id.listView1);
String[] imageUrls = new String[0];
adapter = new LazyAdapter(this, imageUrls);
list.setAdapter(adapter);

btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new server_side("http://192.168.1.6:81/upload/time.php","").execute();
String imageUrls[]={"http://localhost:81/upload/url.jpg"};

if (!res.equals("")) {
Toast.makeText(getApplicationContext(), "get data", Toast.LENGTH_SHORT).show();
}
return imageUrls;
}
});

}


}

Answer

Dont forget you are inside of an overriden method... the public void onClick(View v) method of the View.OnClickListener interface...

So basically you JUST CAN NOT return anything there... the most you can do is call return,

The solution to that:

you can for sure modify the logic

public class MainActivity extends Activity {
private ListView list;
private LazyAdapter adapter;
private String res = "";
//here declare as class variable....
private String[] imageUrls;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //here initialize it....
    imageUrls = new String[1];

    Button btn1=(Button)findViewById(R.id.button1);
    list = (ListView) findViewById(R.id.listView1);
    adapter = new LazyAdapter(this, imageUrls);
    list.setAdapter(adapter);

    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new server_side("http://192.168.1.6:81/upload/time.php","").execute();
            //here asign it some value....
            imageUrls[0] = {"http://localhost:81/upload/url.jpg"};
            if (!res.equals("")) {
                Toast.makeText(getApplicationContext(), "get data", Toast.LENGTH_SHORT).show();
            }
        }
    });
}
}