Get return from AsyncTask - android

I'm trying to get a return value from the InBackground method in a way that it fetches the first time, returns right but after returns NULL, my logic was as follows: inside the onPostExecute method I call another function to set the value of a variable , however for some reason this variable becomes NULL, after receiving the data correctly. Here is my code:
public class HomeActivity extends Activity {
Button btnEntrada, btnCarregamento, btnDescarregamento;
EditText numberOF;
TextView txt;
private AlertDialog alert;
private Boolean isOnline;
private JSONArray jsonArray;
private String url = "http://192.168.1.5/ws/entradaSetor.php?numberOF=";
private MyTask task = new MyTask();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
btnEntrada = (Button) this.findViewById(R.id.btnEntrada);
btnCarregamento = (Button) this.findViewById(R.id.btnCarregamento);
btnDescarregamento = (Button) this.findViewById(R.id.btnDescarregamento);
numberOF = (EditText) this.findViewById(R.id.numberOFText);
btnEntrada.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (numberOF.getText().toString().compareTo("") == 0) {
alertDialog("la");
} else {
conecta(numberOF.getText().toString());
}
}
});
}
private void alertDialog(String numero){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Atenção");
builder.setMessage(numero);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert = builder.create();
alert.show();
}
private void func_EntryQuantity(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
final EditText edittext = new EditText(HomeActivity.this);
alert.setMessage("\nQuantidade Recebida na OF");
alert.setTitle("Digite a quantidade recebida");
alert.setView(edittext);
alert.setPositiveButton("CONFIRMAR ENTRADA", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable YouEditTextValue = edittext.getText();
}
});
alert.setNegativeButton("VOLTAR", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
alert.show();
}
private Boolean verifica(){
if(this.jsonArray.length() == 0){
return false;
}
else{
return true;
}
}
private void conecta(String numberOF){
task.execute(url + numberOF);
}
private void entradaSetor(JSONArray jsonArray){
this.jsonArray = jsonArray;
}
private class MyTask extends AsyncTask<String, Void, JSONArray>
{
#Override
protected JSONArray doInBackground(String... urls)
{
try{
URL url = new URL(urls[0]);
HttpURLConnection myConnection =
(HttpURLConnection) url.openConnection();
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader =
new InputStreamReader(responseBody, "UTF-8");
BufferedReader streamReader = new BufferedReader(new InputStreamReader(responseBody, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
JSONArray jsonArray = new JSONArray(responseStrBuilder.toString());
//myConnection.disconnect();
return jsonArray;
} else {
return null;
}
}catch (Exception e){
return null;
}
}
#Override
protected void onPostExecute(JSONArray jsonArray)
{
// Call activity method with results
entradaSetor(jsonArray);
}
}
}

I believe that a better way to provide result back to the calling code is to use an interface, like for instance:
interface RequestListener {
public onResultSuccess(JSONArray array);
public onResultFail(String error);
}
private class MyTask extends AsyncTask<String, Void, JSONArray>
{
RequestListener listener = null;
MyTask(RequestListener listener) {
this.listener = listener
}
#Override
protected JSONArray doInBackground(String... urls)
{
try{
URL url = new URL(urls[0]);
HttpURLConnection myConnection =
(HttpURLConnection) url.openConnection();
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader =
new InputStreamReader(responseBody, "UTF-8");
BufferedReader streamReader = new BufferedReader(new InputStreamReader(responseBody, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
JSONArray jsonArray = new JSONArray(responseStrBuilder.toString());
//myConnection.disconnect();
return jsonArray;
} else {
return null;
}
}catch (Exception e){
return null;
}
}
#Override
protected void onPostExecute(JSONArray jsonArray)
{
if (listener != null) {
if (jsonArray != null) {
listener.onResultSuccess(jsonArray);
} else {
listener.onResultFail(your-message);
}
}
}
}
then of course you have to provide an instance of the RequestListener interface when you instantiate the MyTask object (might be inside the onCreate)

Related

Run AsyncTask everytime button is clicked

I'm having a hard time figuring out how to implement the new MyAsyncTask().execute("") that I've searched because I have separate classes that extends Asynctask. I wanted to call the class everytime i click the button. Hope you guys can help me figure this out.
Here is my MainActivity
public class MainActivity extends AppCompatActivity {
String url = "http://192.168.254.103/dbtest/categories.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.start);
final ListView lv = (ListView) findViewById(R.id.lv);
final Downloader d = new Downloader(this,url,lv);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.execute();
}
});
}
}
Here is my Downloader.java
public class Downloader extends AsyncTask<Void,Integer, String> {
Context c;
String address;
ListView lv;
ProgressDialog pd;
public Downloader(Context c, String address, ListView lv) {
this.c = c;
this.address = address;
this.lv = lv;
}
//BEFORE JOB STARTS
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Fetch Data");
pd.setMessage("Please Wait");
pd.show();
}
#Override
protected String doInBackground(Void... params) {
String data = downloadData();
return data;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
if(s != null){
Parser p =new Parser(c,s,lv);
p.execute();
}else
{
Toast.makeText(c,"Unable to download data",Toast.LENGTH_SHORT).show();
}
}
private String downloadData(){
//connect and get a stream
InputStream is = null;
String line = null;
try{
URL url = new URL(address);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(con.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
if(br != null){
while((line = br.readLine()) != null)
{
sb.append(line+"\n");
}
}
else
{
return null;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
and my Parser.java
public class Parser extends AsyncTask<Void,Integer,Integer> {
Context c;
ListView lv;
String data;
ArrayList<String> categories = new ArrayList<>();
ProgressDialog pd;
public Parser(Context c, String data, ListView lv) {
this.c = c;
this.data = data;
this.lv = lv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Parser");
pd.setMessage("Please Wait");
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
return this.parse();
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer == 1)
{
//ADAPTER
ArrayAdapter<String> adapter = new ArrayAdapter<String>(c, android.R.layout.simple_list_item_1, categories);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}else
{
Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
}
pd.dismiss();
}
//PARSE RECEIVED DATA
private int parse(){
try
{
//ADD TGAT DATA TO JSON ARRAY FIRST
JSONArray ja = new JSONArray(data);
//CREATE JO OBJECT TO HOLD A SINGLE ITEM
JSONObject jo = null;
categories.clear();
//LOOP THROUGH ARRAY
for(int i =0 ; i<ja.length();i++)
{
jo = ja.getJSONObject(i);
//RETRIEVE NAME
String name=jo.getString("cat_name");
//ADD TO ARRAY LIST
categories.add(name);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}

asyncTask called in OptionItemSelected called at the wrong Item

I have some OptionItems with AsyncTask(with a progress dialog) called as shown
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.FilterSpeed:
GetSpeed();
break;
case R.id.FilterEvent:
GetEvents();
break;
case R.id.FilterDevice:
GetDevices();
break;
case R.id.ClearFilter:
ClearFilter();
break;
}
new GetAllUserDevices(Dashboard.this, Dashboard.this).execute(API_ServiceDev_method_url);
return true;
}
I access the Asynctask data in the 3rd item click (GetDevices) but I get the progress dialog when clicking on the 2nd item (GetEvents) even though this item have nothing to do with the AsyncTask .
how can I make the progress dialog appears on the right item choice ?
Added : GetDevices
public void GetDevices() {
DevicesNames = GetAllUserDevices.DevicesNames;
DevicesIds = GetAllUserDevices.DevicesIds;
SelectedDevicesIds = new HashSet<>();
SelectedDevices = new ArrayList<>();
isCheckedDeviceList = new boolean[DevicesIds.size()];
if (oldChecked.size() > 0) {
for (int i = 0; i < DevicesIds.size(); i++) {
isCheckedDeviceList[i] = Dashboard.oldChecked.get(i);
}
} else {
for (int i = 0; i < DevicesIds.size(); i++) {
oldChecked.add(i, Dashboard.isCheckedDeviceList[i]);
}
}
CharSequence[] DevicesNamesInChar = DevicesNames.toArray(new CharSequence[DevicesNames.size()]);
builder = new AlertDialog.Builder(Dashboard.this);
builder.setTitle(getString(R.string.Devicename))
.setMultiChoiceItems(DevicesNamesInChar, Dashboard.isCheckedDeviceList.length == DevicesIds.size() ? Dashboard.isCheckedDeviceList : null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
Dashboard.isCheckedDeviceList[which] = isChecked;
if (isChecked) {
Dashboard.SelectedDevices.add(which);
} else if (Dashboard.SelectedDevices.contains(which)) {
Dashboard.SelectedDevices.remove(Integer.valueOf(which));
}
}
})
.setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
for (int i = 0; i < Dashboard.isCheckedDeviceList.length; i++) {
boolean checked = Dashboard.isCheckedDeviceList[i];
Dashboard.oldChecked.set(i, checked);
if (checked) {
Dashboard.SelectedDevicesIds.add(String.valueOf(DevicesIds.get(i)));
}
}
Dashboard.UserEditor.putStringSet("DevicesIds", Dashboard.SelectedDevicesIds);
Dashboard.UserEditor.commit();
StopTimerTask();
StartTimer();
}
})
.setCancelable(true).show();
}
in a separated class GetAllDevices (AsyncTask) :
public class GetAllUserDevices extends AsyncTask<String, Void, String> {
//vars declaration
static SharedPreferences UserInfo;
static Context context;
static String UserToken;
static Activity activityTest;
InputToString converter;
public static Loading LoadingDialog;
static boolean IsArabic;
public static BufferedReader in;
static String inputLine;
static StringBuffer response;
public static Text_Value_Pair[] devicesList;
public static ArrayList<String> DevicesNames = new ArrayList<>();
public static ArrayList<Integer> DevicesIds = new ArrayList<>();
MoveTo moving;
public GetAllUserDevices(Context currentcontext, Activity currentActivity) {
context = currentcontext;
UserInfo = context.getSharedPreferences("Login_UserInfo", Context.MODE_PRIVATE);
converter = new InputToString();
activityTest = currentActivity;
LoadingDialog = new Loading(currentcontext);
moving = new MoveTo(context);
}
#Override
protected String doInBackground(String... urls) {
return POSTJson(urls[0]);
}
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
}
public String POSTJson(String url) {
//User Static Params
UserToken = UserInfo.getString("Token", "NoToken");
IsArabic = (new IsArabic(context).IsLangArabic());
String result = "";
URL obj;
try {
obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-type", "application/json");
con.setRequestProperty("Token", UserToken);
// Send post request
con.setDoOutput(true);
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
result = response.toString();
} catch (IOException e) {
moving.LogOffNow();
e.printStackTrace();
}
if (!result.endsWith("An error has occurred.\"}")) {
Gson gson = new Gson();
devicesList = gson.fromJson(result, Text_Value_Pair[].class);
} else {
devicesList = null;
}
if (devicesList != null) {
DevicesNames.clear();
DevicesIds.clear();
int i = 0;
while (i < devicesList.length) {
DevicesNames.add(devicesList[i].getText());
DevicesIds.add(devicesList[i].getValue());
i++;
}
}
return "Data Updated";
}
}
I guess progress dialog is appearing because of GetAllUserDevices() AsyncTask is executing after switch case is over..
Please check if you want to execute GetAllUserDevices() in all case??
if not then it should be called in particular switch case.

JSON returns data in one code and null in other

I have an app that connects to server sends sql request and get JSON answer as JsonArray.
Its Asynktask in seperate class (HTTPRequest.java is my AsyncTask class, Responce.java its my callback interface class) and it works correct.
when I use it in OrderActivity.java like below
#Override //my interface class function
public void onPostExecute(JSONArray Result) {
load(Result);
}
private void load(JSONArray json) {
for(int i=0;i<json.length();i++){
try {
JSONObject jo = json.getJSONObject(i);
Product p = new Product(
jo.getInt("ID"),
jo.getInt("parent"),
jo.getInt("category"),
jo.getString("Item"),
jo.getDouble("Price")
);
products.add(p);
} catch (JSONException e) {
e.printStackTrace();
}
}
it does work and fills product with data, but when I assign to my class variable JSONArray json
JSONArray json = new JSONArray;
.
.
.
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
json is null
//HTTPRequest.java
public class HTTPRequest extends AsyncTask<String, Void, Integer> {
private Context context;
private Responce responce;
JSONArray json;
public HTTPRequest(Context context){
this.context = context;
responce = (Responce)context;
}
#Override
protected Integer doInBackground(String... params) {
OutputStream output;
InputStream inputStream = null;
HttpURLConnection connection = null;
String charset = "UTF-8";
Integer result = 0;
try {
URL uri = new URL(params[0]);
connection = (HttpURLConnection) uri.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "text/plain; charset=" + charset);
output = connection.getOutputStream();
output.write(params[1].getBytes(charset));
output.close();
int statusCode = connection.getResponseCode();
if (statusCode == 200) {
inputStream = new BufferedInputStream(connection.getInputStream());
json = new JSONArray(getJSON(inputStream));
result = 1;
}
} catch (Exception e) {
e.getLocalizedMessage();
}
return result;
}
#Override
protected void onPostExecute(Integer i) {
super.onPostExecute(i);
if(i == 1) {
responce.onPostExecute(json);
} else {
responce.onPostExecute(null);
}
}
private String getJSON(InputStream inputStream) throws IOException, JSONException {
StringBuffer stringBuffer = new StringBuffer();
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = null;
while((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line.toString());
}
result = stringBuffer.toString();
if(null!=inputStream){
inputStream.close();
}
return result;
}
}
//Responce.java
public interface Responce {
public void onPostExecute(JSONArray Result);
}
//OrderActivity.java
public class OrderActivity extends Activity implements Responce{
ArrayList<Product> products = new ArrayList<Product>();
ProductAdapter productAdapter;
OrderItemAdapter orderItemAdapter;
ListView orderlist;
JSONArray ja;
Button btnBack;
Button btnTakeOrder;
ListView picklist;
HTTPRequest httpRequest;
String url = "http://192.168.3.125:8888/data/";
String query = "select * from vwitems order by category desc";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
orderlist =(ListView)findViewById(R.id.orderlist);
orderItemAdapter = new OrderItemAdapter(OrderActivity.this);
btnBack = (Button)findViewById(R.id.btnBack);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productAdapter.filter(0);
}
});
btnTakeOrder = (Button)findViewById(R.id.btnTakeOrder);
btnTakeOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer oid = 0;
Order order = new Order(OrderActivity.this);
oid = order.NewOrder(1, 2, 3);
Toast.makeText(OrderActivity.this," " + order.getCount(), LENGTH_SHORT).show();
}
});
orderlist.setAdapter(orderItemAdapter);
picklist = (ListView) findViewById(R.id.picklist);
picklist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int pid = 0;
if (productAdapter.getItem(position).isCategory()) {
pid = productAdapter.getItem(position).getId();
productAdapter.filter(pid);
} else {
OrderItem oi = new OrderItem();
oi.setItemId(productAdapter.getItem(position).getId());
oi.setItem(productAdapter.getItem(position).getItem());
oi.setPrice(productAdapter.getItem(position).getPrice());
search(oi);
}
}
});
httpRequest = new HTTPRequest(this);
httpRequest.execute(url, query);
}
private boolean search(OrderItem oi){
int size = orderItemAdapter.getCount();
int i = 0;
if(size != 0)
for(OrderItem o : orderItemAdapter.getAll()){
if(o.getItemId() == oi.getItemId()){
orderItemAdapter.getItem(i).setQuantity(orderItemAdapter.getItem(i).getQuantity() + 1);
orderItemAdapter.notifyDataSetChanged();
return true;
}
i++;
}
orderItemAdapter.addItem(oi);
orderItemAdapter.notifyDataSetChanged();
return false;
}
private void load(JSONArray json) {
for(int i=0;i<json.length();i++){
try {
JSONObject jo = json.getJSONObject(i);
Product p = new Product(
jo.getInt("ID"),
jo.getInt("parent"),
jo.getInt("category"),
jo.getString("Item"),
jo.getDouble("Price")
);
products.add(p);
} catch (JSONException e) {
e.printStackTrace();
}
}
productAdapter = new ProductAdapter(OrderActivity.this, products);
picklist.setAdapter(productAdapter);
productAdapter.filter(0);
}
#Override
public void onPostExecute(JSONArray Result) {
load(Result);
}
/*
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
**/
}
sorry i forgot include this one
//Order.java
public class Order implements Responce{
private Context context;
private JSONArray json = new JSONArray();
private HTTPRequest httpRequest;
private int OrderID;
private Date OrderDate;
private int OrderTable;
private int Waiter;
private byte OrderStatus;
private List<OrderItem> orderItems;
public Order(Context context){
this.context = context;
}
//some code here...
public Integer NewOrder(Integer guests, Integer waiter, Integer ordertable){
String query = "insert into orders(orderdate, guests, waiter, ordertable) VALUES(NOW()," + guests + ", " + waiter + ", " + ordertable + "); SELECT LAST_INSERT_ID() as ID;";
Integer result = 0;
Connect(query);
try {
JSONObject jo = json.getJSONObject(0);
result = jo.getInt("ID");
} catch (JSONException e) {
e.printStackTrace();
}
return result; //here i got 0 if i init result to 0, null or what ever i init my
}
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
private void Connect (String query){
httpRequest = new HTTPRequest(context);
httpRequest.execute("http://192.168.3.125:8888/data/", query);
}
}

Android web service error in http

In my project , to access the webservice am using http class which is not working properly and my project stops.
Can someone tell me an alternate way for accessing the webservice instead of using http.
Thank you in advance
class httpclass {
String result;
public String server_conn(String user_url)
{
// String user_url="";
String user_url3=user_url.replaceAll(" ","%20");
String user_url2=user_url3.replaceAll("\n","%0D");
HttpClient client = new DefaultHttpClient();
HttpGet siteRequest = new HttpGet(user_url2);
StringBuilder sb = new StringBuilder();
HttpResponse httpResponse;
try {
httpResponse = client.execute(siteRequest);
HttpEntity entity = httpResponse.getEntity();
InputStream in = entity.getContent();
String line = null;
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
result = sb.toString();
} catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
log in form
public class LoginForm extends FragmentActivity {
/** Called when the activity is first created. */
TextView txt1, txt2, err,forget;
EditText name;
EditText pass;
Button click,vend;
CheckBox savepass;
Button newuser;
Button signin;
#SuppressWarnings("unused")
private Cursor signin1;
SharedPreferences sharedPreferences=null;
public static String str1, str2;
public static String result;
public static String username;
ProgressDialog myProgressDialog = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); BugSenseHandler.initAndStartSession(this, "68640bea");
setContentView(R.layout.login);
vend=(Button)findViewById(R.id.vend);
name = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
savepass=(CheckBox)findViewById(R.id.savepass);
Button cancel = (Button) findViewById(R.id.cancel);
//Button back = (Button) findViewById(R.id.back);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent second = new Intent( LoginForm.this,canceluser.class);
startActivity(second);
finish();
}
});
sharedPreferences=PreferenceManager.getDefaultSharedPreferences(this);
String name1=sharedPreferences.getString("p_name", "");
name.setText(name1.toString());
String pass1=sharedPreferences.getString("p_pass", "");
pass.setText(pass1.toString());
//s forget=(TextView)findViewById(R.id.forget);
signin = (Button) findViewById(R.id.signin);
click = (Button) findViewById(R.id.click);
newuser = (Button) findViewById(R.id.signup);
vend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewIntent =
new Intent("android.intent.action.VIEW",
Uri.parse("http://www.iwedplanner.com/vendor/vendorhome.aspx"));
startActivity(viewIntent);
}});
click.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(LoginForm.this, forgetpwd.class);
startActivity(intent1);
finish();
}});
signin.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
if(name.getText().toString().equals(""))
{
alertbox("Message!","Enter Your Username");
name.requestFocus();
}
else if(pass.getText().toString().equals(""))
{
alertbox("Message!","Enter Your Password");
pass.requestFocus();
}
else
{
str1 = name.getText().toString();
str2 = pass.getText().toString();
boolean value = false;
// validuser();
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
value = true;
openconn(str1, str2);
}
else
{
alertbox("Message!", "No Internet Connection!");
}
}
}
});
newuser.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
newuser();
}
});
}
public void openconn(String strr1, String strr2)
{
if (!strr1.equals("") && !strr2.equals(""))
{
err = (TextView) findViewById(R.id.err);
// String user_url = "http://iwedplanner.com/mobile/MLogin.aspx?uname="+ strr1 + "&pwd=" + strr2;
String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/MLogin.aspx?uname="+ strr1 + "&pwd=" + strr2;
httpclass obj = new httpclass();
result = obj.server_conn(user_url);
// alertbox("",""+result);
if (result != null)
{
StringTokenizer st = new StringTokenizer(result, "|");
result = st.nextToken();
if (result.equals("InvalidUser "))
{
Dialog locationError = new AlertDialog.Builder(
LoginForm.this).setIcon(0).setTitle("Message!")
.setPositiveButton(R.string.yes, null).setMessage(
"Sorry, Invalid Username or Password ")
.create();
locationError.show();
name.requestFocus();
}
else if(result.equals(strr1))
{
// Toast.makeText(getBaseContext(),"Valid User",Toast.LENGTH_SHORT).show();
if(savepass.isChecked())
{
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("p_name",name.getText().toString());
//editor.putString("p_pass",pass.getText().toString());
editor.commit();
}
else
{
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("p_name", "");
editor.putString("p_pass","");
editor.commit();
}
validuser();
}
else
{
alertbox("Message!","Error in network connection");
}
}
}
}
public void validuser()
{
username=str1;
name.setText("");
pass.setText("");
Intent userintent = new Intent(this, welcomeuser1.class);
//userintent.putExtra("name5",str1);
//Intent userintent=new Intent(this,WeddingInfo.class);
startActivity(userintent);
finish();
}
public void newuser() {
Intent userintent1 = new Intent(this, newuserform.class);
startActivity(userintent1);
finish();
}
protected void alertbox(String title, String mymessage) {
new AlertDialog.Builder(this)
.setMessage(mymessage)
.setTitle(title)
.setCancelable(true)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int whichButton) {
}
}).show();
}
#Override
public void onStart() {
super.onStart();
// The rest of your onStart() code.
// // EasyTracker.getInstance(this).activityStart(this); // Add this method.
}
#Override
public void onStop() {
super.onStop();
// The rest of your onStop() code.
// EasyTracker.getInstance(this).activityStop(this); // Add this method.
}
}
Error:duplicate files during packaging of APK C:\Users\sentientit\Documents\Wed Studio\app\build\outputs\apk\app-debug-unaligned.apk
Path in archive: META-INF/LICENSE.txt
Origin 1: C:\Users\sentientit\Documents\Wed Studio\app\libs\twitter4j.jar
1 Origin 2: C:\Users\sentientit.gradle\caches\modules-2\files-2.1\joda-
time\joda-time\2.4\89e9725439adffbbd41c5f5c215c136082b34a7f\joda-time-2.4.jar
You can ignore those files in your build.gradle:
android {
packagingOptions {
exclude 'META-INF/LICENSE.txt'
}
}
Error:Execution failed for task ':app:packageDebug'.
Duplicate files copied in APK META-INF/LICENSE.txt
File 1: C:\Users\sentientit\Documents\Wed Studio\app\libs\twitter4j.jar
File 2: C:\Users\sentientit\.gradle\cache``s\modules-2\files-2.1\joda-time\joda-time\2.4\89e9725439adffbbd41c5f5c215c136082b34a7f\joda-time-2.4.jar
You can do this way:
AsyncTask for Web service:
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(AsyncExample.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("Loading...");
pdLoading.show();
}
#Override
protected Void doInBackground(Void... params) {
String serverGETResponse = getJsonDataStringFormat("Your_Url", "GET", "", "LOGIN_ACTIVITY");
String serverPOSTResponse = getJsonDataStringFormat("Your_Url", "POST", "YOUR_JSON_STRING", "LOGIN_ACTIVITY");
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//this method will be running on UI thread
pdLoading.dismiss();
}
}
Now Get Response from server in Background thread:
public static String getJsonDataStringFormat(String url, String method,String jObjStr, String tag) {
InputStream is = null;
String Root_Response = null;
HttpResponse httpResponse;
HttpParams httpParameters = new BasicHttpParams();
DefaultHttpClient httpClient;
HttpConnectionParams.setConnectionTimeout(httpParameters,connectionTimeOut);
HttpConnectionParams.setSoTimeout(httpParameters, socketTimeOut);
try {
httpClient = new DefaultHttpClient(httpParameters);
url = url.replace(" ", "%20");
if (method == "POST") {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(jObjStr));
httpResponse = httpClient.execute(httpPost);
is = httpResponse.getEntity().getContent();
} else if (method == "GET") {
HttpGet httpGet = new HttpGet(new URI(url));
httpResponse = httpClient.execute(httpGet);
is = httpResponse.getEntity().getContent();
}
Root_Response = convertStreamToString(is);
Log.i(tag, Root_Response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (URISyntaxException e) {
e.printStackTrace();
}
return Root_Response;
}
Convert Server's Response to String:
public static String convertStreamToString(InputStream inputStream)
throws IOException {
if (inputStream != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
inputStream.close();
}
return sb.toString();
} else {
return "";
}
}
Hope it will help you.
call the method server_conn() inside AsyncTask , and pass the url
private class AsyncTaskTest extends AsyncTask<String, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... strings) {
server_conn(strings[0]);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
and call the asynctastk using below syntax
new AsyncTaskTest().execute(url);
You are facing NetworkOnMainThread exception all you have to do is add this code :
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build();
StrictMode.setThreadPolicy(policy);
For more details you can check developer site.

The application crashes because it may be doing too much work on its main Thread

Maybe this is answered before but i couldnt find any identical solution to this but proposals. I am building an app in which i populate 4 ListViews from Mysql database through JSON. The work is being done at 4 fragments. The thing is that when i populate the 2 Lists from database and the other 2 just with some string array data everything works fine but when i try to populate all 4 of them at the same time then it crashes.
The Error:
01-04 11:27:25.405 3002-3017/com.order.app.order W/EGL_genymotion﹕ eglSurfaceAttrib not implemented
01-04 11:27:25.405 3002-3017/com.order.app.order W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa31ff7a0, error=EGL_SUCCESS
01-04 11:27:30.619 3002-3002/com.order.app.order I/Choreographer﹕ Skipped 307 frames! The application may be doing too much work on its main thread.
My Fragment:
private View rootView;
private ListView lv;
private ArrayAdapter<ProductList> adapter;
private String jsonResult;
private String url = "http://reservations.cretantaxiservices.gr/files/getkafedes.php";
ProgressDialog pDialog;
List<ProductList> customList;
private TextView tv1, tv2;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_coffees_fragment, container, false);
lv = (ListView)rootView.findViewById(R.id.coffeesListView);
final SwipeRefreshLayout mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.activity_main_swipe_refresh_layout);
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(getActivity().getApplicationContext().CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean network_connected = activeNetwork != null && activeNetwork.isAvailable() && activeNetwork.isConnectedOrConnecting();
if (!network_connected) {
onDetectNetworkState().show();
} else {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
accessWebService();
registerCallClickBack();
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
accessWebService();
mSwipeRefreshLayout.setRefreshing(false);
}
});
}
}
return rootView;
}
private AlertDialog onDetectNetworkState() {
AlertDialog.Builder builder1 = new AlertDialog.Builder(getActivity().getApplicationContext());
builder1.setMessage(R.string.wifi_off_message)
.setTitle(R.string.wifi_off_title)
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
getActivity().finish();
}
})
.setPositiveButton(R.string.action_settings,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
startActivityForResult((new Intent(
Settings.ACTION_WIFI_SETTINGS)), 1);
getActivity().finish();
}
});
return builder1.create();
}
private void registerCallClickBack() {
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity().getApplicationContext(), "You have chosen " + customList.get(position).getName(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (pDialog.isShowing()) {
pDialog.show();
} else {
pDialog.dismiss();
}
if (onDetectNetworkState().isShowing()
&& onDetectNetworkState() != null) {
onDetectNetworkState().show();
} else {
onDetectNetworkState().dismiss();
}
}
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
if (pDialog.isShowing()) {
pDialog.show();
} else {
pDialog.dismiss();
}
if (onDetectNetworkState().isShowing()) {
onDetectNetworkState().show();
} else {
onDetectNetworkState().dismiss();
}
}
}
public class JsonReadTask extends AsyncTask<String, Void, String> {
public JsonReadTask() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setTitle(R.string.waiting);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage(getString(R.string.get_stocks));
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.setInverseBackgroundForced(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
} catch (Exception e) {
getActivity().finish();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (Exception e) {
getActivity().finish();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrawer();
pDialog.dismiss();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
task.execute(new String[]{url});
}
public void ListDrawer() {
customList = new ArrayList<ProductList>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("kafedes");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("name");
String price = jsonChildNode.optString("price");
String image = jsonChildNode.optString("image");
customList.add(new ProductList(image, name, price));
}
} catch (Exception e) {
getActivity().finish();
}
adapter = new ProductListAdapter(getActivity().getApplicationContext(), R.layout.list_item, customList);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
}
As a matter of fact i am using 4 AsyncTasks to do this job. Any ideas???
EDIT:
I updated the code since i found something online but still the same error
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(customList == null){
accessWebService();
}else{
ListDrawer();
}
}
Any Help will be appreciated!!!
Here in this method you are actully in the UI thread
#Override
protected void onPostExecute(String result) {
ListDrawer();
pDialog.dismiss();
}
And you calling the ListDrawer(); method and it's going to do a CPU intensive task, parsing the JSON.
It throws an exception in that method and calls this getActivity().finish(); in the catch block. That's why you getting back to your previous activity.
Try parsing your JSON in the AsynckTask and it solves your problem for sure.
Update:
private View rootView;
private ListView lv;
private ArrayAdapter<ProductList> adapter;
private String jsonResult;
private String url = "http://reservations.cretantaxiservices.gr/files/getkafedes.php";
ProgressDialog pDialog;
List<ProductList> customList;
private TextView tv1, tv2;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_coffees_fragment, container, false);
lv = (ListView)rootView.findViewById(R.id.coffeesListView);
final SwipeRefreshLayout mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.activity_main_swipe_refresh_layout);
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(getActivity().getApplicationContext().CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean network_connected = activeNetwork != null && activeNetwork.isAvailable() && activeNetwork.isConnectedOrConnecting();
if (!network_connected) {
onDetectNetworkState().show();
} else {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
accessWebService();
registerCallClickBack();
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
accessWebService();
mSwipeRefreshLayout.setRefreshing(false);
}
});
}
}
return rootView;
}
private AlertDialog onDetectNetworkState() {
AlertDialog.Builder builder1 = new AlertDialog.Builder(getActivity().getApplicationContext());
builder1.setMessage(R.string.wifi_off_message)
.setTitle(R.string.wifi_off_title)
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
getActivity().finish();
}
})
.setPositiveButton(R.string.action_settings,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
startActivityForResult((new Intent(
Settings.ACTION_WIFI_SETTINGS)), 1);
getActivity().finish();
}
});
return builder1.create();
}
private void registerCallClickBack() {
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity().getApplicationContext(), "You have chosen " + customList.get(position).getName(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (pDialog.isShowing()) {
pDialog.show();
} else {
pDialog.dismiss();
}
if (onDetectNetworkState().isShowing()
&& onDetectNetworkState() != null) {
onDetectNetworkState().show();
} else {
onDetectNetworkState().dismiss();
}
}
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
if (pDialog.isShowing()) {
pDialog.show();
} else {
pDialog.dismiss();
}
if (onDetectNetworkState().isShowing()) {
onDetectNetworkState().show();
} else {
onDetectNetworkState().dismiss();
}
}
}
public class JsonReadTask extends AsyncTask<String , Void, List<ProductList>> {
public JsonReadTask() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setTitle(R.string.waiting);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage(getString(R.string.get_stocks));
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.setInverseBackgroundForced(true);
pDialog.show();
}
#Override
protected List<ProductList> doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
customList = new ArrayList<ProductList>();
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("kafedes");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("name");
String price = jsonChildNode.optString("price");
String image = jsonChildNode.optString("image");
customList.add(new ProductList(image, name, price));
}
return customList;
} catch (Exception e) {
e.printStackTrace();
getActivity().finish();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (Exception e) {
getActivity().finish();
}
return answer;
}
#Override
protected void onPostExecute(List<ProductList> customList) {
if(customList == null){
Log.d("ERORR", "No result to show.");
return;
}
ListDrawer(customList);
pDialog.dismiss();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
task.execute(new String[]{url});
}
public void ListDrawer(List<ProductList> customList) {
adapter = new ProductListAdapter(getActivity().getApplicationContext(), R.layout.list_item, customList);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
}
You are accessing the field:
private String jsonResult;
from both background thread (in doInBackground methods of your AsyncTasks) and from UI thread in ListDrawer() method in the line:
JSONObject jsonResponse = new JSONObject(jsonResult);
The most likely cause of your crash is that the UI thread doesn't see that the jsonResult value was set (since the field isn't volatile) and creating of new JSONObject throws an exception.
The solution would be to perform the parsing of the response in the doInBackground() method of your async task and return ArrayList from it (EDIT: fixed compile errors)
#Override
protected ArrayList<ProductList> doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
ArrayList<ProductList> customList = new ArrayList<ProductList>();
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("kafedes");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("name");
String price = jsonChildNode.optString("price");
String image = jsonChildNode.optString("image");
customList.add(new ProductList(image, name, price));
}
return customList;
} catch (Exception e) {
return null;
}
}
onPostExecute() method should be modified:
#Override
protected void onPostExecute(ArrayList<ProductList> result) {
pDialog.dismiss();
if(result == null) {
getActivity().finish();
} else {
adapter = new ProductListAdapter(getActivity().getApplicationContext(), R.layout.list_item, customList);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
}
}
finally the signature of your AsyncTask has to be changed:
public class JsonReadTask extends AsyncTask<ArrayList<ProductList>, Void, String> {
...
}

Categories

Resources