Hyunruel Cho Hyunruel Cho - 1 month ago 4
Android Question

how can I seperate method in MainActivity to other class , and call

I call a method like this.

finishedFlag = new HttpUtil().execute(url, userid, workflag).get();


and I want to seperate this method to another class.
(ex, create a class :
httpUtil
.)

how can I call, and seperate?

public class HttpUtil extends AsyncTask<String, Void, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("ing...");
pDialog.setCancelable(false);
pDialog.show();
}

@Override
public Boolean doInBackground(String... params1) {
try {

String url = params1[0];
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

if (params1[0].equals(aaa)) {
params.add(new BasicNameValuePair("time", params1[2]));
params.add(new BasicNameValuePair("userid", params1[1]));
} else if (params1[2].equals("goWork")) {
Thread.sleep(300);

params.add(new BasicNameValuePair("userid", params1[1]));
}
if (params1[2].equals("3")) {
params.add(new BasicNameValuePair("userid", params1[1]));
}

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();

InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = br.readLine()) != null) {
response.append(line);
}
br.close();

String res = response.toString();

HashMap<String, String> myHashMap = new HashMap<String, String>();
myHashMap = convertToHashMap(res);

String errmsg = "";
String errmsg2 = "";
String name = "";
String OutToWork = "";

if (params1[2].equals("goWork")) {
errmsg = myHashMap.get(" errmsg");
errmsg2 = myHashMap.get(" errmsg2");
} else if (params1[0].equals(url4end_work)) {
String outWork = loadJSONFromAsset(params1[2]);
try {
JSONObject obj1 = new JSONObject(outWork);

WIFI_CHECK_TIMER = obj1.getString("wifi-check-timer");
WIFI_AUTO_ON_TIME = obj1.getString("wifi-auto-on-time");
} catch (JSONException e) {
e.printStackTrace();
}

errmsg2 = myHashMap.get(" errmsg2");
name = myHashMap.get(" user-name");

} else {

}

OutputStreamWriter writer1 = null;
File dir = null;
File jsonFile = null;
if (params1[0].equals(url4end_work)) { jsonFile = new File(Environment.getExternalStorageDirectory(), "policy/OuttoWork.json");
} else if (params1[2].equals("3")) {
jsonFile = new File(Environment.getExternalStorageDirectory(), "policy/policy.json");
if (jsonFile.exists()) {
boolean delete = jsonFile.delete();
Log.d("Code1 ==> ", " Json !");
}
} else if (params1[2].equals("goWork")) {
jsonFile = new File(Environment.getExternalStorageDirectory(), "policy/GotoWork.json");
}
dir = new File(Environment.getExternalStorageDirectory(), "policy");
if (!dir.exists()) {
dir.mkdirs();
}
try {
writer1 = new OutputStreamWriter(new FileOutputStream(jsonFile, true), "UTF-8");
if (params1[2].equals("3")) {
writer1.write(res.toString());

} else if (params1[0].equals(url4end_work)) {
writer1.write(res.toString());
} else if (params1[2].equals("goWork")) {
writer1.write(res.toString());
}
writer1.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


if (params1[2].equals("bbb")) {
showpopup("", errmsg, errmsg2);
first_check_work--;

} else if (params1[2].equals("ccc")) {
showpopup("", errmsg, errmsg2);
first_check_work++;
} else {
}

} catch (Exception e) {
e.printStackTrace();
}
boolean a = true;
return a;

}

protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
}
}

Answer

Hey you should create class which extends async adapter to deal with background operations (you did it) and create interface callback to get your data in activity/fragment.

This is AsyncTask class:

public class HttpUtilClass extends AsyncTask<String, Void, Boolean> {

    TestListener testListener;
    Activity activity;

    public HttpUtilClass(Activity activity){
        this.activity = activity;
        testListener =(TestListener) activity;
    }

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

    @Override
    protected Boolean doInBackground(String... strings) {

        return false;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        if (testListener!=null){
            testListener.getBool(aBoolean);
        }
    }
}

This is interface:

public interface TestListener {

    void getBool(boolean bool);
}

This is your main activity

public class MainActivity extends AppCompatActivity implements TestListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        HttpUtilClass hh = new HttpUtilClass(this);
        hh.execute("test");
    }

    @Override
    public void getBool(final boolean bool) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.i("LOG", "getBool: " + bool);
            }
        });

    }
}

Good luck;)

Comments