0

I'm populating a list view with parse data and I'm querying the data. I want to show only the rows equal to a string coming from another activity.

I get the string because I have a toast that shows me the string but the string in the query.whereEqualTo is void.

How I pass the value of the string variable inside the doInBackground?

This is my code,

public class ListadoMusica extends Activity {

String año;
String artista;

// Declare Variables
ListView listview;
List<ParseObject> ob;
ProgressDialog mProgressDialog;
CustomAdapter adapter;
private List<Musica> musica = null;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from listview_main.xml
    setContentView(R.layout.activity_listado_musica);

    año = getIntent().getStringExtra("myaño");
    artista = getIntent().getStringExtra("myartista");

    Toast.makeText(getApplicationContext(),año, Toast.LENGTH_SHORT).show();

    // Execute RemoteDataTask AsyncTask
    new RemoteDataTask().execute();


}


// RemoteDataTask AsyncTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create a progressdialog
        mProgressDialog = new ProgressDialog(ListadoMusica.this);
        // Set progressdialog title
        mProgressDialog.setTitle("Cargando...");
        // Set progressdialog message
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {


        // Create the array
        musica = new ArrayList<Musica>();
        try {
            // Locate the class table named "Country" in Parse.com
            ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
                    "Musica");
            // Locate the column named "ranknum" in Parse.com and order list
            // by ascending
            //query.orderByAscending("createdAt");


            query.whereEqualTo("año", año);
            query.whereEqualTo("artista", artista);

            ob = query.find();
            for (ParseObject country : ob) {
                // Locate images in flag column
                ParseFile image = (ParseFile) country.get("imagen");

                Musica map = new Musica();
                map.setTitulo((String) country.get("titulo"));
                map.setArtista((String) country.get("artista"));
                map.setAño((String) country.get("año"));
                map.setFoto(image.getUrl());
                musica.add(map);
            }
        } catch (ParseException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // Locate the listview in listview_main.xml
        listview = (ListView) findViewById(R.id.listview);
        // Pass the results into ListViewAdapter.java
        adapter = new CustomAdapter(ListadoMusica.this,
                musica);
        // Binds the Adapter to the ListView
        listview.setAdapter(adapter);
        // Close the progressdialog
        mProgressDialog.dismiss();
    }
}

}

Thanks in advance,

Rec
  • 71
  • 1
  • 1
  • 7

2 Answers2

1

modify this line:

new RemoteDataTask().execute(año, artista );  

And this line:

private class RemoteDataTask extends AsyncTask<String, Void, Void> {

And this line:

protected Void doInBackground(String... params) {
   String año = params[0];
   String artista = params[1];
   //code
              query.whereEqualTo("año", año);

   //do whatever you need on artista 
yshahak
  • 4,996
  • 1
  • 31
  • 37
  • Thanks, yshahak, it worked perfectly but I need to query String "artista" too. I tried adding new RemoteDataTask with this string and params [1] in my query but it doesn't work. – Rec Jul 19 '15 at 15:29
  • The beuty with varargs that you could bring in hou much variables you want. See my edited answer. – yshahak Jul 19 '15 at 17:00
  • care to eaplin why this should work any better that the OP's code? – njzk2 Jul 19 '15 at 17:02
  • I can but the docs for AsyncTask will do much better job then me. You could ask more specifficaly and I will glad to try and answer:http://developer.android.com/reference/android/os/AsyncTask.html – yshahak Jul 19 '15 at 17:05
  • yshahak, with edited answer año get the value as before but artista continue void. Sorry, but I don't know how to solve it, thanks – Rec Jul 19 '15 at 17:23
  • Have you made sure that `getIntent().getStringExtra("myartista");` yields something other than `null`? I don't see a Toast like you have for *año* – Sascha Kolberg Jul 19 '15 at 17:36
  • As @Sascha Kolberg say, check your logic, the call to AsyncTask is not the problem. – yshahak Jul 19 '15 at 18:03
  • @yshahak: what I mean is, in the OP's code, ano and artista are in a scope that are visible from the asynctask, and they are accessed after they have been set. I don't see why your solution would work any better. Also, there is no reason in the OP's code that would explain the observed behaviour. – njzk2 Jul 19 '15 at 19:10
  • Basically you right that the way he wrote the code it should also work. But the problem with that approach is that we usually trying to separate the blocks of the code to have accurate control of the logic. Specifically in AyncTask the code in doInBackground() run independently from the Activity when Activity destroyed for example if you just use field instead of take parameter you may get NullPointer. Correct me if I wrong on this. – yshahak Jul 20 '15 at 03:44
  • Sascha, I wanted to test this today and as you say the value of artista comes void from my previus activity, that's the mistake, thanks. I get the value of año and artista from two spinners and año I get the value but artista stay void. I check the previous activity, – Rec Jul 20 '15 at 17:45
0

I am not exactly sure, why it is void in the code you provided, but as async task executes on another thread you cannot guarantee that your activity instance including it's contents is still valid while the task runs.

To be sure, make String año; an instance variable of RemoteDataTask and pass it to the tasks constructor.

private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
  private String año;

  RemoteDataTask(String año) {
    super();
    this.año = año;
  }
  ...
}

Also make sure your activity handles orientation changes gracefully. See this link

Community
  • 1
  • 1
Sascha Kolberg
  • 7,092
  • 1
  • 31
  • 37
  • the asynctask class is an instance class. It cannot exist itself if the activity does not exist. (in fact, it probably causes a leak of the activity in some cases) – njzk2 Jul 19 '15 at 17:03
  • You are right, my attempt at an explanation was bad as my wording was poor (at best). What I meant with *valid* is that by the time `doInBackground` is called an `onDestroy` implementation in the Activity may have left but a shell of it's former glory. No such `onDestroy` implementation is indicated in the question so, sadly, my reasoning was bad, too. – Sascha Kolberg Jul 19 '15 at 17:35