Tuesday, April 16, 2013

[android help] Need to access AsyncTask value in Main Class


I am facing an issue in Async task, can anyone please suggest me any solution.
I have downloaded this example from this link :
Source


My Current Structure is


  • Main Class extends MyTask and implements AsyncTaskCompleteListener interface.

  • AsyncTaskCompleteListener is an Interface contains the onTaskComplete Method .

  • MyTask extends Async Task and onPostExcute contains CallBackMethod which will return the result-set got from the doInBackground.

  • Http Class(Utils) contains the Http connection and returns the Result-set to AsyncTaskComleteListner from PostExecute.

I am trying to get my result-set Value in the main class from the interface method to perform my further operation.
I tried to get the value from static variables, static method but non of them worked, and also tried with creating a new class object to send and receive the result but every time it gives me NullPointerException . Because the statement written after the AsyncTask gets executes before getting the result.


I have also tried to get the Status of asyncTask from its method getStaus(), but it returns only Running and dose not notify when the task is completed or finished.


Here is the code sample:


Main Class Code :



package com.example.androidasynctask;


public class MainActivity extends Activity implements AsyncTaskCompleteListener {

public static String[] asyncResult;
String res[] = null;



@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void btnclick(View view) {
/*MyTask asyncTask = new MyTask(this);
String [] asyncTaskResult = asyncTask.execute("fetchCategory.php","1%Id%1");*/

//AsyncTask asyncTaskRes = new MyTask(this).execute("fetchCategory.php","1%Id%1");
//new MyTask(this).execute("fetchCategory.php","1%Id%1");
MyTask asyncTask = (MyTask) new MyTask(this).execute("fetchCategory.php","1%Id%1");

if(asyncTask.getStatus().equals(AsyncTask.Status.FINISHED) || asyncTask.getStatus().equals(AsyncTask.Status.PENDING)) {
asyncTask.execute();
}
else {

Log.v("In Else","Get Value");
}



}

@Override
public void onTaskComplete(String[] result) {
Log.v("IN ON TASK COMPLETE","VALUE = "+result[1]);


}



/*@Override
public void onTaskComplete(String result) {
System.out.println("calling onTaskComplete SIMPLE....");
System.out.println("result :: "+ result);
}*/

public static class GetAsyncResult
{
static String[] returnValues;


public GetAsyncResult()
{}
public GetAsyncResult(String[] res)
{

returnValues = res;
Log.v("getResultSetValues","returnValues"+returnValues[1]);
}


public void getResultSetValues()
{
Log.v("getResultSetValues","returnValues"+returnValues[1]);


}

}

}


Async Task Code :



public class MyTask extends AsyncTask {

private Activity activity;
private ProgressDialog dialog;
private AsyncTaskCompleteListener callback;
public String[] asyncResultSetValue = null;
public MyTask(Activity act) {
Log.v("MY TASK","ACTIVITY"+act);
this.activity = act;
this.callback = (AsyncTaskCompleteListener)act;
}

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

Log.v("MY TASK","in ON PRE EXECUTE");
dialog = new ProgressDialog(activity);
dialog.setMessage("Loading...");
dialog.show();
}

@Override
protected String[] doInBackground(String... params) {
Log.v("MY TASK","DO IN BACKGROUND");
Log.v("PARAMS"," params[0] = "+params[0]+ "| params[1]"+params[1]);
asyncResultSetValue = Utils.process_query(params[0],params[1]);
return asyncResultSetValue;
}

@Override
protected void onPostExecute(String[] result) {
super.onPostExecute(result);
Log.v("MY TASK","in ON POST EXECUTE");
if (null != dialog && dialog.isShowing()) {
dialog.dismiss();
}
callback.onTaskComplete(result);
}

}


HTTP CLASS CODE :



public class Utils {

static String result = null;
String endResult;
static java.io.InputStream is = null;
static StringBuilder sb=null;
static String delimiter = "\\|";
static String delimiter1 = "\\%";
static String[] temp = null;
static String[] temp1 = null;
static ArrayList nameValuePairs;
static Context context;
static ProgressDialog mDialog;
static HttpResponse response;
static String[] resultset_value = null;
//static String url = "http://fortuneworkinprogress.in/News_App/"; //Global URL
static String url = "http://10.0.2.2/News_App/"; //Global URL
static String query_type,parameter;

/*************** PROCESS QUERY START ***************/
public static String[] process_query(String str_url, String parameter) {
// String strval = select_parameter;
String ret_val[] = null;
String get_sel_val[] = null;
int loopcount =0;
url = url+str_url; //!!!! ######### CONCATINATING AND CREATING FULL URL ######## !!!!!!//
Log.v("PROCESS QUERY PARAMETER","URL = "+url+" | PARAMTER = "+parameter);
nameValuePairs = new ArrayList();

//Log.i("STR VAL",""+strval); //To Check which values are recieved
try
{
String strval = parameter;
get_sel_val=strval.split(delimiter1);

for(int i =0; i < get_sel_val.length ; i++)
{

loopcount = Integer.parseInt(get_sel_val[0]); // First Delimeted Value which tells the number of count
Log.i("Loopcount","cnt = "+loopcount);

}

for(int j=1;j<=(loopcount*2);j=j+2) //For Loop for making Name Values Pares Dynamic
{
nameValuePairs.add(new BasicNameValuePair(get_sel_val[j],get_sel_val[j+1]));
//Log.i("J = ["+j+"]","pairvalue1 = "+get_sel_val[j]+"pairvalue2 ="+get_sel_val[j+1]);
}
}
catch(Exception e)
{
Log.w("Exception in the getting value","Exp = "+e);
}

//nameValuePairs.add(new BasicNameValuePair("id","1"));

try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
Log.v("CONNECT URL ","Final url "+url);
Log.w("CONNECTION STATUS ",httppost.toString());
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.w("PAERSE VALUE ",nameValuePairs.toString());
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.w("1", "Connection establised succesfuly");
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
}

try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
Log.v("SB VALUE = ","sb = "+sb.toString());
String line="0";
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();

// Toast.makeText(getBaseContext(), result ,Toast.LENGTH_LONG).show();

Log.w("result", result);
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
Toast.makeText(null, "error converting response to string" ,Toast.LENGTH_LONG).show();
}

String[] temp = null;
String[] tempResult = null;

if(result!=null)
{
tempResult = result.split(delimiter); //Split the entire return string into "rows"
for(int i =0; i < tempResult.length-1 ; i++)
{
temp = null;
temp = tempResult[i].split(delimiter1); //Find columns for each row
ret_val = temp;
resultset_value=ret_val;
}
}
else
{
Toast.makeText(null, "Cannot Find Routes" ,Toast.LENGTH_LONG).show();
}

Log.v("BEFORE RETUNR = ","ret_val = "+ret_val.toString());
return ret_val; //Returning the result value array
}


/*************** PROCESS QUERY ENDS ***************/

public static boolean isNetworkAvailable(Activity activity)
{
ConnectivityManager connectivity = (ConnectivityManager) activity
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null)
{
return false;
}
else
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
{
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
}
}
return false;
}

}


Thanks in advance.



.

stackoverflow.comm

No comments:

Post a Comment

Google Voice on T-Mobile? [General]

Google Voice on T-Mobile? So I recently switched from a GNex on Verizon to a Moto X DE on T-Mobile. I had always used Google Voice for my v...