ama989
ama989

Reputation: 463

The return of AsyncTask is null. Why?

I have created an app that gets the data from mysql server. As long as I need to use the AsyncTask a lot of times. I created a class that holds the AsyncTask and then, I used a getter method to get the results from my AsyncTask class. So, First, I created AsyncTask as the followings :

public class Get_Contacts_Details extends AsyncTask<Void, Void, Boolean>
{
public String[] Names;
public String[] TheNames ;
private JSONParser jsonParser = new JSONParser();
private Context mContext ;
private JSONObject jsonObjectResult = null;
private String Contact_id ;
private String error;
private String THE_URL ;
public Get_Contacts_Details(String Contact_id, String THE_URL, Context mContext)
{
    super();

    this.Contact_id = Contact_id ;
    this.THE_URL = THE_URL ;
    this.mContext = mContext ;
}


@Override
protected void onPreExecute()
{
    super.onPreExecute();
}

@Override
protected Boolean doInBackground(Void... params)
{
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("Contact_id","'"+Contact_id+"'"));
    jsonObjectResult = jsonParser.makeHttpRequest(THE_URL, pairs);

    if (jsonObjectResult == null)
    {
        error = "Error in the connection";
        return false;
    }

    try
    {
        if (jsonObjectResult.getInt("success") == 1)
        {
            JSONArray jsonArray = jsonObjectResult.getJSONArray("posts");
            JSONObject news ;
            TheNames = new String[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++)
            {
                news = jsonArray.getJSONObject(i);
                Contacts_ListView listviewcontact  = new Contacts_ListView
                        (
                                news.getString("Names")

                        );

                TheNames[i] = listviewcontact.getContactName();
            }

            return true;
        }
        else
            error = jsonObjectResult.getString("message");

    }
    catch (Exception ex)
    {

    }

    return false;
}

@Override
protected void onPostExecute(Boolean aBoolean)
{
    super.onPostExecute(aBoolean);
    if (!aBoolean)
        Toast.makeText(getmContext(), error, Toast.LENGTH_LONG).show();
    else
    setNames(TheNames);
}


public String[] getNames() {
    return Names;
}

public void setNames(String[] names) {
    Names = names;
}
public Context getmContext() {
    return mContext;
}

}

Then I called it from another class as the followings:

public class FilesListActivity extends AppCompatActivity {
private RadioGroup ll ;
private String[] filename;

private String mURL = "Myweb.php";
private String TheNames = "";
private MyFunctionsClass myFunctionsClass;
private Get_Contacts_Details get_contacts_details ;
@Override
public String getText()
{
    String[] my ;
    myFunctionsClass = new MyFunctionsClass();
    int id_Btn = ll.getCheckedRadioButtonId() ;
    selectedRB = (RadioButton) findViewById(id_Btn) ;
    mfile_data = "THE DATA "

    get_contacts_details = new Get_Contacts_Details(
            mfile_data,mURL,FilesListActivity.this);
    get_contacts_details.execute();
        \\ my is always NULL. 

     my = get_contacts_details.getNames();
    for(int i = 0 ; i> my.length;i++)
    {
        TheNames+=my[i]+"\n";
    }
    return TheNames ; 
}

The string array my is always Null. How can I solve that ?

Upvotes: 0

Views: 50

Answers (1)

diegoveloper
diegoveloper

Reputation: 103421

Asynctask doesn't work in that way. You should update your UI/logic after onPostExecute

@Override
protected void onPostExecute(Boolean aBoolean)
{
    super.onPostExecute(aBoolean);
    if (!aBoolean)
        Toast.makeText(getmContext(), error, Toast.LENGTH_LONG).show();
    else
    setNames(TheNames);
//HERE
    String names = "";
    for(int i = 0 ; i> TheNames.length;i++)
    {
        names+=TheNames[i]+"\n";
    }

}

If you want returns data to your activity use an Interface , Refer to this documentation about the AsyncTask : https://developer.android.com/reference/android/os/AsyncTask.html

Update

Use the code below

Create this interface class:

public interface DataListener {

    void onDataListener (String[] data);
}

Modifiy your Asynctask class

public class Get_Contacts_Details extends AsyncTask<Void, Void, Boolean>
{
public String[] Names;
public String[] TheNames ;
private JSONParser jsonParser = new JSONParser();
private Context mContext ;
private JSONObject jsonObjectResult = null;
private String Contact_id ;
private String error;
private String THE_URL ;
private DataListener mListener;
public Get_Contacts_Details(String Contact_id, String THE_URL, Context mContext, DataListener mListener)
{
    super();

    this.Contact_id = Contact_id ;
    this.THE_URL = THE_URL ;
    this.mContext = mContext ;
    this.mListener = mListener;
}


@Override
protected void onPreExecute()
{
    super.onPreExecute();
}

@Override
protected Boolean doInBackground(Void... params)
{
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("Contact_id","'"+Contact_id+"'"));
    jsonObjectResult = jsonParser.makeHttpRequest(THE_URL, pairs);

    if (jsonObjectResult == null)
    {
        error = "Error in the connection";
        return false;
    }

    try
    {
        if (jsonObjectResult.getInt("success") == 1)
        {
            JSONArray jsonArray = jsonObjectResult.getJSONArray("posts");
            JSONObject news ;
            TheNames = new String[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++)
            {
                news = jsonArray.getJSONObject(i);
                Contacts_ListView listviewcontact  = new Contacts_ListView
                        (
                                news.getString("Names")

                        );

                TheNames[i] = listviewcontact.getContactName();
            }

            return true;
        }
        else
            error = jsonObjectResult.getString("message");

    }
    catch (Exception ex)
    {

    }

    return false;
}

@Override
protected void onPostExecute(Boolean aBoolean)
{
    super.onPostExecute(aBoolean);
    if (!aBoolean)
        Toast.makeText(getmContext(), error, Toast.LENGTH_LONG).show();
    else
    setNames(TheNames);

    if (mListener != null){
       mListener.onDataListener(TheNames);
    }
}


public String[] getNames() {
    return Names;
}

public void setNames(String[] names) {
    Names = names;
}
public Context getmContext() {
    return mContext;
}

}

Modify your activity class

public class FilesListActivity extends AppCompatActivity {
private RadioGroup ll ;
private String[] filename;

private String mURL = "Myweb.php";
private String TheNames = "";
private MyFunctionsClass myFunctionsClass;
private Get_Contacts_Details get_contacts_details ;
@Override
public String getText()
{
    String[] my ;
    myFunctionsClass = new MyFunctionsClass();
    int id_Btn = ll.getCheckedRadioButtonId() ;
    selectedRB = (RadioButton) findViewById(id_Btn) ;
    mfile_data = "THE DATA "

    get_contacts_details = new Get_Contacts_Details(
            mfile_data,mURL,FilesListActivity.this, listener);
    get_contacts_details.execute();

    //you can't return TheNames value here

    return TheNames ; 
}


public DataListener listener = new DataListener() {

      @Override
      public void onDataListener (String[] data) {
           for(int i = 0 ; i> data.length;i++)
            {
                TheNames+=data[i]+"\n";
            }

            //now your have the data here, use in your activity, update your UI, etc.


      }
}

}

Keep in mind that AsyncTask is used for asynchronous task, do don't expect to return your data inside your getText() method, btw who is calling to getText() method?

Upvotes: 1

Related Questions