OkHTTP code not working - java

I have the current under my MainActivity class and i cannot see why s and post are returning errors?
public class MainActivity extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTask<String, Integer, String> (){
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
OkHttpClient client = new OkHttpClient();
s = post("https://raw.github.com/square/okhttp/master/README.md","");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e("ANSWER", "" + s);
I am not sure why its not working

Related

Error message having no message . and data is not being updated

When executing the below code I get the following in my log
05-02 02:19:34.175 8796-8810/com.example.nitikamehta.testing
I/System.out: io.cloudboost.CloudException
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CloudApp.init("vuwzaiqgwytr ", "cf358f99-1bbd-4ccc-9a4e-3370b169a50f");
myAsyncTask mTask = new myAsyncTask();
mTask.execute("abc", "10", "Hello world");
}
private class myAsyncTask extends AsyncTask<String, Integer, String> {
String mTAG = "myAsyncTask";
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg) {
CloudObject obj = new CloudObject("users");
try {
obj.set("name", "navneet");
Log.d("here", "also");
} catch (CloudException e) {
e.printStackTrace();
}
try {
obj.save(new CloudObjectCallback() {
#Override
public void done(CloudObject x,CloudException t) {
if (x != null) {
Log.d("first", "added");
}
if (t != null) {
System.out.println(""+t);
}
}
}
);
} catch (CloudException e) {
Log.d("hello", "world");
}
return "done";
}
#Override
protected void onPostExecute(String result) {
Log.d(mTAG, "Inside onPostExecute");
}
}
}

Asynctask w/ ProgressDialog

I know that have a lot of answers about this, but I can't find exactly what I need:
1) When users click on the button, shows a progress Dialog;
2) Executes a class AsyncTask and wait for the answer (it's a response using HTTPUrlConnection);
3) Dismiss Progress Dialog;
I tried a lot of things, but the progress dialog is not "appearing". My code:
public class MainActivity extends Activity implements OnTaskCompleted{
..
private ProgressDialog progressDialog;
private Button btnLogin;
..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
progressDialog = ProgressDialog.show(MainActivity.this,
"", "Scanning Please Wait", true);
try {
String param1 = "testParam1";
String param2 = "testParam2";
String response = new SyncHelper(MainActivity.this).execute("http://server.example.com/api", param1, param2).get(); //this way, my activity waits of the answer
Log.d(TAG, "Finished: " + response);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
// user didn't entered username or password
Toast.makeText(getApplicationContext(),
"Done",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
});
}
public void onTaskCompleted()
{
progressDialog.dismiss();
}
public class SyncHelper extends AsyncTask<Object, Void, String>
{
..
private OnTaskCompleted listener;
..
protected String doInBackground(Object... url) {
String response = "";
try {
response = getRequest((String) url[0],(String) url[1], (String) url[2]); //Here I make a HttpURLConnection
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPreExecute() {
}
protected void onPostExecute(String result) {
listener.onTaskCompleted();
}
}
public interface OnTaskCompleted{
void onTaskCompleted();
}
public class MainActivity extends Activity{
..
private Button btnLogin;
..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
String param1 = "testParam1";
String param2 = "testParam2";
new SyncHelper(MainActivity.this).execute("http://server.example.com/api", param1, param2); //this way, my activity waits of the answer
Log.d(TAG, "Finished: " + response);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
// user didn't entered username or password
Toast.makeText(getApplicationContext(),
"Done",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
});
}
public class SyncHelper extends AsyncTask<String, Void, String>
{
..
Context context;
private ProgressDialog pd;
..
public SyncHelper (Context c)
{
context = c;
}
#Override
protected void onPreExecute() {
pd = new ProgressDialog(context);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
protected String doInBackground(String... url) {
String response = "";
try {
response = getRequest(url[0], url[1], url[2]); //Here I make a HttpURLConnection
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
protected void onPostExecute(String result) {
// here you will be getting the response in String result.
if (pd.isShowing())
pd.dismiss();
}
}
When you are using get, using AsyncTask doesn't make any sense. Because get() will block the UI Thread, maybe thats why are not able to see the progress dialog. If you want to send the response back to the MainActivity then use the callback interface as you were using beofre.

Creating Progress dialog while switching from one activity to another

I have a custom DialogFragment. I want to show this dialog while switching my activities.
Scenario:-
1) In actvity1 I start the dialog.
2) Start a asynctask class.
3) Do some authentication in doInBackground().
4) Start new actvity from onPostExecute().
Issue:-
The dialog stops before the asynctask.
Here is my code:-
myWebView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageStarted(WebView view, String url,
Bitmap favicon)
{
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
redirected =view.getUrl();
redirected= Uri.decode(redirected);
if(redirected!=null && redirected.contains(string1))
{
myprogressDialog.show(getFragmentManager(), "Wait");
}
}
#Override
public void onPageFinished(WebView view, String url)
{
// TODO Auto-generated method stub
super.onPageFinished(view, url);
if(redirected!=null && redirected.contains(mystring) )
{
myWebView.stopLoading();
String authorizationContentString = myurl
new Authentication(Activity2.this, myprogressDialog, url).execute(authorizationString);
}
private static class ProgressDialogFragment extends DialogFragment
{
public static ProgressDialogFragment newInstance()
{
return new ProgressDialogFragment();
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_FRAME, android.R.style.Theme_Translucent);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_dialog_progress, container, false);
}
}
Authentication.java
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
/* progDia.show(man, "wait");
progDia= new Utility.ProgressDialogFragment().newInstance();*/
}
public AuthenticateDevice(Details1 myContext, ProgressDialogFragment myprogressDialog, String Url)
{
// TODO Auto-generated constructor stub
mContext = myContext;
this.progDia = myprogressDialog;
this.Url = Url;
this.mActivity = myContext;
}
#Override
protected Void doInBackground(String... params)
{
// TODO Auto-generated method stub
//Some authentication
return null;
}
#Override
protected void onPostExecute(Void result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
if(progDia!=null&&progDia.isVisible())
{
progDia.dismiss();
}
Intent myIntent = new Intent(mContext, Activity2.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(myIntent);
mActivity.finish();
}
Try following code to show progress dialog in async
ProgressDialog pd;
class MYAsync extends AsyncTask<Void , Void, String>{
#Override
protected void onPreExecute() {
// pd.setTitle("Please Wait");
pd.setMessage("Working...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String sResponse) {
pd.dismiss();
pd.cancel();
}
}
}
I tried to recreate it, it appears to be working fine. this below method has comments explaining your actions.
private void myWOrk() {
try {
final ProgressDialog Dialog = new ProgressDialog(this);
Dialog.setMessage("Loading route...");
Dialog.show();
Thread.sleep(2000);// load url and redirect
//Toast.makeText(LoginActivity.this, "redirect caught", Toast.LENGTH_SHORT).show();
new AsyncTask<Object, Object, Object>() {
protected String doInBackground(Object... params) {
try {
Thread.sleep(2000);// authenticate
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Object result) {
Toast.makeText(LoginActivity.this, "onPostExecute", Toast.LENGTH_SHORT).show();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Dialog.dismiss();// start your new activity here
};
}.execute(null, null, null);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}`

Start function inside overriden Asynctask method of the same class

I have AsyncTask class and I call it in my main class. I need to override the onPostExecute function and call inside ftpDisconnect(). But it does not work properly.
TempClass dj = new TempClass(serialnum) {
#Override
protected void onProgressUpdate(Integer... values) {
pr_bar.setProgress(values[0]);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
//dj.ftpDisconnect(); //need to make this happen
super.onPostExecute(result);
}
};
dj.execute();
My TempClass:
public class TempClass extends AsyncTask<String, Integer, String> {
public TempClass(String serialnum) {
this.serialnum = serialnum;
}
#Override
protected String doInBackground(String... params) {
//do stuff
return null;
}
public boolean ftpDisconnect() {
try {
mFTPClient.disconnect();
return true;
} catch (Exception e) {
}
return false;
}
}
You can't access that instance of dj without making it final. You should be able to call ftpDisconnect from inside the class:
#Override
protected void onPostExecute(String result) {
ftpDisconnect();
super.onPostExecute(result);
}

How can i to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

I read and apply something from this link:How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class? but I get an error NullPointerException onPostExecute on the line delegate.processFinish(result); What is the problem in my code? Here is the code:
public class MainActivity extends Activity implements AsyncResponse{
ProductConnect asyncTask =new ProductConnect();
public void processFinish(String output){
//this you will received result fired from async class of onPostExecute(result) method.
Log.v(TAG, output);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
asyncTask.delegate = this;
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
final Intent i=new Intent(MainActivity.this, second.class);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new ProductConnect().execute(true);
startActivity(i);
//startActivity(new Intent(MainActivity.this, second.class));
}
});
}
// START DATABASE CONNECTION
class ProductConnect extends AsyncTask<Boolean, String, String> {
public AsyncResponse delegate=null;
private Activity activity;
public void MyAsyncTask(Activity activity) {
this.activity = activity;
}
#Override
protected String doInBackground(Boolean... params) {
String result = null;
StringBuilder sb = new StringBuilder();
try {
// http post
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://192.168.2.245/getProducts.php");
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF8"));
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
Log.d("test", result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
t = json_data.getString("name");
delegate.processFinish(result);
}
} catch (JSONException e1) {
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
super.onPostExecute(result);
}
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Lütfen Bekleyiniz");
pd.setMessage("Authenticating..");
pd.show();
}
}
You initialize your variable to null
public AsyncResponse delegate=null;
so naturally it will give NPE when you try to use it. You give it a value in your Activity so you could pass that to the constructor of your AsyncTask and initialize it to that object.
Your are starting a new AsyncTask in this line:
new ProductConnect().execute(true);
you should execute your asyncTask change that line with this:
asyncTask.execute(true);
I think the best way to do this is using interfaces.. Create a listener for this.
[]'s
you can access asynctask() method when creating new object from it.
sample:
LoginSyncProvider syncProvider = (LoginSyncProvider) new LoginSyncProvider(){
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//TODO write something here
}
}
}.execute();
You've to pass context to that AsyncTask.
Then, on postExecute, cast context to your Activity.
Example:
((MyActivity)context).doSomethingWithResults(resultOfAsyncTask);
Edit:
Your Activity:
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
new MyAsyncTask(this).execute();
}
public void sayHello(String name){
Log.d("log","hello "+name+"!!!");
}
}
Your asynctask:
class MyAsyncTask extends AsyncTask<String,String,String>{
Context context;
public AutoPassarImatges(Context cont) {
super();
this.context = cont;
// TODO Auto-generated constructor stub
}
#Override
protected String doInBackground(String... params) {
[.......]
return null;
}
#Override
protected void onPostExecute(String result) {
((MyActivity)context).sayHello(result);
}
}

Categories

Resources