I have a Async task like this in my app:
private class getUserSummary extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DashboardActivity.this);
pDialog.setMessage("Getting sales summary...");
//pDialog.setTitle("Getting sales summary...");
pDialog.setIndeterminate(true);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... strings) {
String JsonResponse = null;
String JsonDATA = "email=my email address";
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
ServiceUrl smf = new ServiceUrl();
URL url = new URL(smf.getUserSummaryUrl());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
// is output buffer writter
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//set headers and method
Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
writer.write(JsonDATA);
// json data
writer.close();
int responseCode = urlConnection.getResponseCode();
if (responseCode == 400) {
InputStream inputResponse = urlConnection.getErrorStream();
reader = new BufferedReader(new InputStreamReader(inputResponse));
StringBuffer errorBuffer = new StringBuffer();
String errorLine;
while ((errorLine = reader.readLine()) != null) {
errorBuffer.append(errorLine + "\n");
}
Log.i("Error text", errorBuffer.toString());
return new JSONObject(errorBuffer.toString());
}
//Log.i("Response code", String.valueOf(inputStream));
InputStream inputStream = urlConnection.getInputStream();
//input stream
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine + "\n");
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
JsonResponse = buffer.toString();
//response data
Log.i("RESPONSE", JsonResponse);
return new JSONObject(JsonResponse);
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("ERROR", "Error closing stream", e);
}
}
}
return null;
}
protected void onPostExecute(JSONObject result) {
pDialog.dismiss();
//post operation here
}
}
and calling this in onCreate() method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
ButterKnife.bind(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initCollapsingToolbar();
new getUserSummary().execute();
}
I am running this as soon as user login activity distroyed. that's why I need to call this on onCreate() method. But I am getting this error when the call this in onCreate() method
android.view.WindowLeaked: Activity softlogic.computers.softlogicsalesreward.DashboardActivity has leaked window com.android.internal.policy.PhoneWindow$DecorView{5329b90 V.E...... R......D 0,0-1002,348} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:603)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:326)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:109)
at android.app.Dialog.show(Dialog.java:505)
at softlogic.computers.softlogicsalesreward.DashboardActivity$getUserSummary.onPreExecute(DashboardActivity.java:88)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:604)
at android.os.AsyncTask.execute(AsyncTask.java:551)
at softlogic.computers.softlogicsalesreward.DashboardActivity.onResume(DashboardActivity.java:65)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1287)
at android.app.Activity.performResume(Activity.java:7015)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4210)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4323)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3426)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
is there any other event where I can call this? or what I am doing wrong?
Your asyncTask must be like this.After see your code it may possible that You may forgot some method of AsyncTask.Compare with this example to better understand.
This is complete example of asyncTask:
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
private String resp;
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
publishProgress("Sleeping..."); // Calls onProgressUpdate()
try {
int time = Integer.parseInt(params[0])*1000;
Thread.sleep(time);
resp = "Slept for " + params[0] + " seconds";
} catch (InterruptedException e) {
e.printStackTrace();
resp = e.getMessage();
} catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
progressDialog.dismiss();
finalResult.setText(result);
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this,
"ProgressDialog",
"Wait for "+time.getText().toString()+ " seconds");
}
#Override
protected void onProgressUpdate(String... text) {
finalResult.setText(text[0]);
}
}
call like this:
new AsyncTaskRunner (this).execute();
you can use thread policy for this. It's work great.
Just add two line below setcontent.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build();
StrictMode.setThreadPolicy(policy);
You Forget to call pDialog.dismiss();
in onPostExecute method of Async task
Related
So I have this little App that should only show a JSON-Object(not even parse it) in the Textview "tvJsonItem" after you push the button "btnHit". I have built in multiple Toasts to follow its procedure, but if i push the button, i only get the Toast Test1 from the onPostExecute. It seems like the Programme skips the whole try bracket.
public class MainActivity extends AppCompatActivity {
private TextView tvData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnHit = (Button) findViewById(R.id.btnHit);
tvData = (TextView) findViewById(R.id.tvJsonItem);
}
public void onClick(View view) {
new JSONTask().execute();
Toast.makeText(getApplicationContext(), "onClick", Toast.LENGTH_LONG);
}
public class JSONTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String...params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
URL url = null;
try {
url = new URL("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
Toast.makeText(MainActivity.this, "test2", Toast.LENGTH_LONG).show();
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String result = buffer.toString();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Malformed", Toast.LENGTH_LONG);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "IOException", Toast.LENGTH_LONG);
} finally {
if (connection != null) {
connection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
protected void onPostExecute(String result){
super.onPostExecute(result);
tvData.setText(result);
Toast.makeText(getApplicationContext(), "test1", Toast.LENGTH_LONG).show();
}
}
}
You can't call toast.show() in doInBackground, because toast.show() should call in Main UI Thread.
for the test, convert toast.show() to log.d()...
I'm new to Android. Don't know which part has gone wrong. The thing is I'm unable to send the data to the server in Android Studio.
This is the error I'm facing
Fatal error: Uncaught Error: Call to undefined function mysql_connect() in C:\xampp\htdocs\students\connection.php:6 Stack trace: #0 C:\xampp\htdocs\students\add_employee.php(2): include() #1 {main} thrown in C:\xampp\htdocs\students\connection.php on line 6
The code goes like this...
Main Activity
public class MainActivity extends AppCompatActivity {
Button b1;
EditText e1;
private ProgressDialog pDialog;
private JSONObject json;
private int success=0;
private HTTPURLConnection service;
private String strname ="";
//Initialize webservice URL
private String path = "http://localhost/student/add_employee.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
e1 = (EditText) findViewById(R.id.editText9);
service=new HTTPURLConnection();
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!e1.getText().toString().equals("") ) {
strname = e1.getText().toString();
//Call WebService
new PostDataTOServer().execute();
} else {
Toast.makeText(getApplicationContext(), "Please Enter all fields", Toast.LENGTH_LONG).show();
}
Intent intent = new Intent(MainActivity.this, Student1.class);
startActivity(intent);
}
});
}
private class PostDataTOServer extends AsyncTask<Void, Void, Void> {
String response = "";
//Create hashmap Object to send parameters to web service
HashMap<String, String> postDataParams;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
postDataParams=new HashMap<String, String>();
postDataParams.put("name", strname);
//Call ServerData() method to call webservice and store result in response
response= service.ServerData(path,postDataParams);
try {
json = new JSONObject(response);
//Get Values from JSONobject
System.out.println("success=" + json.get("success"));
success = json.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
if(success==1) {
Toast.makeText(getApplicationContext(), "Employee Added successfully..!", Toast.LENGTH_LONG).show();
}
}
}
}
HTTPURLConnection
public class HTTPURLConnection {
String response="";
URL url;
public String ServerData(String path,HashMap<String, String> params) {
try {
url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(params));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//Log.d("Output",br.toString());
while ((line = br.readLine()) != null) {
response += line;
Log.d("output lines", line);
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}}
My PHP code
add_employee.php
<?php
include('connection.php');
$emp_name=$_POST["name"];
$success=0;
$status="Active";
$sql = "INSERT INTO `employee` (`emp_name`)
VALUES ('$emp_name')";
if(mysql_query($sql))
{
$success=1;
}
$response["success"]=$success;
die(json_encode($response));
mysql_close($con);
?>
connection.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('student');
?>
adminpage.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mTextView = (TextView) findViewById(R.id.dataList);
Button button = (Button) findViewById(R.id.rf);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt");
new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoList.txt");
}
});
}
public static class JSONTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
StringBuffer finalBufferedData = new StringBuffer();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
String movieName = finalObject.getString("movie");
int year = finalObject.getInt("year");
finalBufferedData.append(movieName + " - " + year + "\n");
}
//JSONObject finalObject = parentArray.getJSONObject(0);
return finalBufferedData.toString();
//return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mTextView.setText(result);
}
}
So base on this what i can conclude is.
1) JSONTASK will take the url and break them in to different string and link them together and return finalBufferedData.toString();
2) The onPostExecute will take the result and set it to mTextView.
3) onclicklistener will run the function and perform step 2 and display.
Question!
I don't see anywhere in the code that call the function onPostExecute(String result) <-- what is the result?? is it the return finalBufferedData.toString()?
I am running the same function in another activity, how do i display in TextView without the onClicklistener to execute it.
1. Yes.. it is the return value(finalBufferedData.toString()).It is the output (result/return) of doInBackground method.
2. Call in onCreate or onResume for executing without onClick. eg:-
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// put the AsyncTask call here
In Logcat It Displays : Attempted to finish an input event but the input event receiver has already been disposed
In Catch Block Message Box I am Having An Error Like println needs a message. Please Help Me.
I Use Android Studio 2.0
Here is LOGCAT :
"12-13 03:48:40.598 2129-2129/com.mysqlapp.bug.mysqlapp
W/InputEventReceiver: Attempted to finish an input event but the input
event receiver has already been disposed."
public class MainActivity extends AppCompatActivity {
EditText etUserName,etPassword;
String userName,password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUserName = (EditText) findViewById(R.id.etUserName);
etPassword = (EditText) findViewById(R.id.etPassword);
}
public void btnLoginClick(View v)
{
try
{
userName = etUserName.getText().toString();
password = etPassword.getText().toString();
Log.d("Hello","Here");
MySqlDatabaseHelper sqlCls = new MySqlDatabaseHelper(this);
sqlCls.doInBackground("login",userName,password);
}
catch (Exception ex)
{
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle("Something Went Wrong");
alert.setMessage("-"+ex.getMessage()+"-");
alert.show();
}
}
}
Here is Second Class :
public class MySqlDatabaseHelper extends AsyncTask<String,Void,String> {
Context ctx;
String method,userID,userName,password,postData,result;
MySqlDatabaseHelper(Context _ctx)
{
ctx = _ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
method = params[0].toString();
if(method.equals("login"))
{
userName = params[1].toString();
password = params[2].toString();
URL url = new URL("http://10.0.2.2/Android/login.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoInput(true);
OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os,"UTF-8");
BufferedWriter bw = new BufferedWriter(osw);
postData = URLEncoder.encode("uname","UTF-8") + "=" + URLEncoder.encode(userName,"UTF-8") + "&" +
URLEncoder.encode("password","UTF-8") + "=" + URLEncoder.encode(password,"UTF-8");
bw.write(postData);
bw.flush();
bw.close();
osw.close();
os.close();
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is,"UTF-8");
BufferedReader br = new BufferedReader(isr);
String line = "";
while ((line = br.readLine()) != null)
{
result += line;
}
br.close();
isr.close();
is.close();
conn.disconnect();
return result;
}
else
{
return "NONE";
}
}
catch (Exception ex)
{
String err = (ex.getMessage() == null) ? "Error occured" : ex.getMessage();
Log.e("Err",err);
AlertDialog alert = new AlertDialog.Builder(ctx).create();
alert.setTitle("Something Went Wrong1");
alert.setMessage("-"+ex.getMessage()+"-");
alert.show();
return "ERR";
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
AlertDialog alert = new AlertDialog.Builder(ctx).create();
alert.setTitle("Successfully Worked");
alert.setMessage("-"+result+"-");
alert.show();
}
}
this is the class for reading json string from web
{
public class JSONmethod extends AsyncTask<String,String,String>
{
public String result_string;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
BufferedReader reader = null;
HttpURLConnection connection = null;
StringBuffer buffer;
try {
URL url;
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
String line= "";
buffer = new StringBuffer();
while ((line = reader.readLine())!= null)
{
buffer.append(line);
}
return buffer.toString();
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
result_string=result;
}
public String result_string_josn()
{
return result_string;
}
}
method "result_string_json()" return null string
i want to use this class frequntly for reading the json string from the web
so i made this method for return string which will returns from onPostExecute
this is the class where i want that value which is generate in post execute through method or anything else
simple.java
package com.bhatti.bis;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class simple extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple);
JSONmethod j = new JSONmethod();
j.execute("here is json string");
Toast.makeText(this,j.result_string_josn(),Toast.LENGTH_LONG).show();
}
}
Use EventBus library. It's very easy to use and will perfectly fix your problem:
First create a simple class for your Event:
public class MyEvent{
private String data;
public MyEvent(String data) {
this.data = data;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
Then in your Activity or wherever, register and unregister the EventBus, as explained in the docs.
Now post the appropriate event:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
EventBus.getDefault().post(new MyEvent(jsonArray.toString()));
}
All that's left for you to do is to listen for that event wherever you want (in another Activity, Fragment, Service - that's what makes EventBus great):
#Subscribe
public void onMyEvent(MyEvent myEvent){
String data = myEvent.getData();
//do whatever you wish with the text (e.g. make a toast, write it somewhere)
}
Async Task is asynchronous task, please read https://en.wikipedia.org/wiki/Asynchrony_%28computer_programming%29
Remove Toast just after :
JSONmethod j = new JSONmethod();
j.execute("here is json string");
And put it in onPostExecute :
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(this,result,Toast.LENGTH_LONG).show();
}
Android handles input events/tasks with a single User Interface (UI) thread and the thread is called Main thread. Main thread cannot handle concurrent operations as it handles only one event/operation at a time.For detail read this tutorials
JSONmethod jSONmethod = new JSONmethod();
jSONmethod.execute("Your json string");
public class JSONmethod extends AsyncTask<String,String,String>
{
public String result_string;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
BufferedReader reader = null;
HttpURLConnection connection = null;
StringBuffer buffer;
try {
URL url;
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
String line= "";
buffer = new StringBuffer();
while ((line = reader.readLine())!= null)
{
buffer.append(line);
}
return buffer.toString();
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("JSONmethod","result = "+result);
}
}